Add RFC 2231 support. Thanks to Piotr Pawlow. (#2501379)
[squirrelmail.git] / functions / strings.php
1 <?php
2
3 /**
4 * strings.php
5 *
6 * This code provides various string manipulation functions that are
7 * used by the rest of the SquirrelMail code.
8 *
9 * @copyright &copy; 1999-2007 The SquirrelMail Project Team
10 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
11 * @version $Id$
12 * @package squirrelmail
13 */
14
15 /**
16 * Appends citation markers to the string.
17 * Also appends a trailing space.
18 *
19 * @author Justus Pendleton
20 * @param string $str The string to append to
21 * @param int $citeLevel the number of markers to append
22 * @return null
23 * @since 1.5.1
24 */
25 function sqMakeCite (&$str, $citeLevel) {
26 for ($i = 0; $i < $citeLevel; $i++) {
27 $str .= '>';
28 }
29 if ($citeLevel != 0) {
30 $str .= ' ';
31 }
32 }
33
34 /**
35 * Create a newline in the string, adding citation
36 * markers to the newline as necessary.
37 *
38 * @author Justus Pendleton
39 * @param string $str the string to make a newline in
40 * @param int $citeLevel the citation level the newline is at
41 * @param int $column starting column of the newline
42 * @return null
43 * @since 1.5.1
44 */
45 function sqMakeNewLine (&$str, $citeLevel, &$column) {
46 $str .= "\n";
47 $column = 0;
48 if ($citeLevel > 0) {
49 sqMakeCite ($str, $citeLevel);
50 $column = $citeLevel + 1;
51 } else {
52 $column = 0;
53 }
54 }
55
56 /**
57 * Checks for spaces in strings - only used if PHP doesn't have native ctype support
58 *
59 * You might be able to rewrite the function by adding short evaluation form.
60 *
61 * possible problems:
62 * - iso-2022-xx charsets - hex 20 might be part of other symbol. I might
63 * be wrong. 0x20 is not used in iso-2022-jp. I haven't checked iso-2022-kr
64 * and iso-2022-cn mappings.
65 *
66 * - no-break space (&nbsp;) - it is 8bit symbol, that depends on charset.
67 * there are at least three different charset groups that have nbsp in
68 * different places.
69 *
70 * I don't see any charset/nbsp options in php ctype either.
71 *
72 * @param string $string tested string
73 * @return bool true when only whitespace symbols are present in test string
74 * @since 1.5.1
75 */
76 function sm_ctype_space($string) {
77 if ( preg_match('/^[\x09-\x0D]|^\x20/', $string) || $string=='') {
78 return true;
79 } else {
80 return false;
81 }
82 }
83
84 /**
85 * Wraps text at $wrap characters. While sqWordWrap takes
86 * a single line of text and wraps it, this function works
87 * on the entire corpus at once, this allows it to be a little
88 * bit smarter and when and how to wrap.
89 *
90 * @author Justus Pendleton
91 * @param string $body the entire body of text
92 * @param int $wrap the maximum line length
93 * @return string the wrapped text
94 * @since 1.5.1
95 */
96 function &sqBodyWrap (&$body, $wrap) {
97 //check for ctype support, and fake it if it doesn't exist
98 if (!function_exists('ctype_space')) {
99 function ctype_space ($string) {
100 return sm_ctype_space($string);
101 }
102 }
103
104 // the newly wrapped text
105 $outString = '';
106 // current column since the last newline in the outstring
107 $outStringCol = 0;
108 $length = sq_strlen($body);
109 // where we are in the original string
110 $pos = 0;
111 // the number of >>> citation markers we are currently at
112 $citeLevel = 0;
113
114 // the main loop, whenever we start a newline of input text
115 // we start from here
116 while ($pos < $length) {
117 // we're at the beginning of a line, get the new cite level
118 $newCiteLevel = 0;
119
120 while (($pos < $length) && (sq_substr($body,$pos,1) == '>')) {
121 $newCiteLevel++;
122 $pos++;
123
124 // skip over any spaces interleaved among the cite markers
125 while (($pos < $length) && (sq_substr($body,$pos,1) == ' ')) {
126
127 $pos++;
128
129 }
130 if ($pos >= $length) {
131 break;
132 }
133 }
134
135 // special case: if this is a blank line then maintain it
136 // (i.e. try to preserve original paragraph breaks)
137 // unless they occur at the very beginning of the text
138 if ((sq_substr($body,$pos,1) == "\n" ) && (sq_strlen($outString) != 0)) {
139 $outStringLast = $outString{sq_strlen($outString) - 1};
140 if ($outStringLast != "\n") {
141 $outString .= "\n";
142 }
143 sqMakeCite ($outString, $newCiteLevel);
144 $outString .= "\n";
145 $pos++;
146 $outStringCol = 0;
147 continue;
148 }
149
150 // if the cite level has changed, then start a new line
151 // with the new cite level.
152 if (($citeLevel != $newCiteLevel) && ($pos > ($newCiteLevel + 1)) && ($outStringCol != 0)) {
153 sqMakeNewLine ($outString, 0, $outStringCol);
154 }
155
156 $citeLevel = $newCiteLevel;
157
158 // prepend the quote level if necessary
159 if ($outStringCol == 0) {
160 sqMakeCite ($outString, $citeLevel);
161 // if we added a citation then move the column
162 // out by citelevel + 1 (the cite markers + the space)
163 $outStringCol = $citeLevel + ($citeLevel ? 1 : 0);
164 } else if ($outStringCol > $citeLevel) {
165 // not a cite and we're not at the beginning of a line
166 // in the output. add a space to separate the new text
167 // from previous text.
168 $outString .= ' ';
169 $outStringCol++;
170 }
171
172 // find the next newline -- we don't want to go further than that
173 $nextNewline = sq_strpos ($body, "\n", $pos);
174 if ($nextNewline === FALSE) {
175 $nextNewline = $length;
176 }
177
178 // Don't wrap unquoted lines at all. For now the textarea
179 // will work fine for this. Maybe revisit this later though
180 // (for completeness more than anything else, I think)
181 if ($citeLevel == 0) {
182 $outString .= sq_substr ($body, $pos, ($nextNewline - $pos));
183 $outStringCol = $nextNewline - $pos;
184 if ($nextNewline != $length) {
185 sqMakeNewLine ($outString, 0, $outStringCol);
186 }
187 $pos = $nextNewline + 1;
188 continue;
189 }
190 /**
191 * Set this to false to stop appending short strings to previous lines
192 */
193 $smartwrap = true;
194 // inner loop, (obviously) handles wrapping up to
195 // the next newline
196 while ($pos < $nextNewline) {
197 // skip over initial spaces
198 while (($pos < $nextNewline) && (ctype_space (sq_substr($body,$pos,1)))) {
199 $pos++;
200 }
201 // if this is a short line then just append it and continue outer loop
202 if (($outStringCol + $nextNewline - $pos) <= ($wrap - $citeLevel - 1) ) {
203 // if this is the final line in the input string then include
204 // any trailing newlines
205 // echo substr($body,$pos,$wrap). "<br />";
206 if (($nextNewline + 1 == $length) && (sq_substr($body,$nextNewline,1) == "\n")) {
207 $nextNewline++;
208 }
209
210 // trim trailing spaces
211 $lastRealChar = $nextNewline;
212 while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space (sq_substr($body,$lastRealChar,1)))) {
213 $lastRealChar--;
214 }
215 // decide if appending the short string is what we want
216 if (($nextNewline < $length && sq_substr($body,$nextNewline,1) == "\n") &&
217 isset($lastRealChar)) {
218 $mypos = $pos;
219 //check the first word:
220 while (($mypos < $length) && (sq_substr($body,$mypos,1) == '>')) {
221 $mypos++;
222 // skip over any spaces interleaved among the cite markers
223 while (($mypos < $length) && (sq_substr($body,$mypos,1) == ' ')) {
224 $mypos++;
225 }
226 }
227 /*
228 $ldnspacecnt = 0;
229 if ($mypos == $nextNewline+1) {
230 while (($mypos < $length) && ($body{$mypos} == ' ')) {
231 $ldnspacecnt++;
232 }
233 }
234 */
235
236 $firstword = sq_substr($body,$mypos,sq_strpos($body,' ',$mypos) - $mypos);
237 //if ($dowrap || $ldnspacecnt > 1 || ($firstword && (
238 if (!$smartwrap || $firstword && (
239 $firstword{0} == '-' ||
240 $firstword{0} == '+' ||
241 $firstword{0} == '*' ||
242 sq_substr($firstword,0,1) == sq_strtoupper(sq_substr($firstword,0,1)) ||
243 strpos($firstword,':'))) {
244 $outString .= sq_substr($body,$pos,($lastRealChar - $pos+1));
245 $outStringCol += ($lastRealChar - $pos);
246 sqMakeNewLine($outString,$citeLevel,$outStringCol);
247 $nextNewline++;
248 $pos = $nextNewline;
249 $outStringCol--;
250 continue;
251 }
252
253 }
254
255 $outString .= sq_substr ($body, $pos, ($lastRealChar - $pos + 1));
256 $outStringCol += ($lastRealChar - $pos);
257 $pos = $nextNewline + 1;
258 continue;
259 }
260
261 $eol = $pos + $wrap - $citeLevel - $outStringCol;
262 // eol is the tentative end of line.
263 // look backwards for there for a whitespace to break at.
264 // if it's already less than our current position then
265 // our current line is already too long, break immediately
266 // and restart outer loop
267 if ($eol <= $pos) {
268 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
269 continue;
270 }
271
272 // start looking backwards for whitespace to break at.
273 $breakPoint = $eol;
274 while (($breakPoint > $pos) && (! ctype_space (sq_substr($body,$breakPoint,1)))) {
275 $breakPoint--;
276 }
277
278 // if we didn't find a breakpoint by looking backward then we
279 // need to figure out what to do about that
280 if ($breakPoint == $pos) {
281 // if we are not at the beginning then end this line
282 // and start a new loop
283 if ($outStringCol > ($citeLevel + 1)) {
284 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
285 continue;
286 } else {
287 // just hard break here. most likely we are breaking
288 // a really long URL. could also try searching
289 // forward for a break point, which is what Mozilla
290 // does. don't bother for now.
291 $breakPoint = $eol;
292 }
293 }
294
295 // special case: maybe we should have wrapped last
296 // time. if the first breakpoint here makes the
297 // current line too long and there is already text on
298 // the current line, break and loop again if at
299 // beginning of current line, don't force break
300 $SLOP = 6;
301 if ((($outStringCol + ($breakPoint - $pos)) > ($wrap + $SLOP)) && ($outStringCol > ($citeLevel + 1))) {
302 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
303 continue;
304 }
305
306 // skip newlines or whitespace at the beginning of the string
307 $substring = sq_substr ($body, $pos, ($breakPoint - $pos));
308 $substring = rtrim ($substring); // do rtrim and ctype_space have the same ideas about whitespace?
309 $outString .= $substring;
310 $outStringCol += sq_strlen ($substring);
311 // advance past the whitespace which caused the wrap
312 $pos = $breakPoint;
313 while (($pos < $length) && (ctype_space (sq_substr($body,$pos,1)))) {
314 $pos++;
315 }
316 if ($pos < $length) {
317 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
318 }
319 }
320 }
321
322 return $outString;
323 }
324
325 /**
326 * Wraps text at $wrap characters
327 *
328 * Has a problem with special HTML characters, so call this before
329 * you do character translation.
330 *
331 * Specifically, &amp;#039; comes up as 5 characters instead of 1.
332 * This should not add newlines to the end of lines.
333 *
334 * @param string $line the line of text to wrap, by ref
335 * @param int $wrap the maximum line lenth
336 * @param string $charset name of charset used in $line string. Available since v.1.5.1.
337 * @return void
338 * @since 1.0
339 */
340 function sqWordWrap(&$line, $wrap, $charset='') {
341 global $languages, $squirrelmail_language;
342
343 // Use custom wrapping function, if translation provides it
344 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
345 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap')) {
346 if (mb_detect_encoding($line) != 'ASCII') {
347 $line = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap', $line, $wrap);
348 return;
349 }
350 }
351
352 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
353 $beginning_spaces = $regs[1];
354 if (isset($regs[2])) {
355 $words = explode(' ', $regs[2]);
356 } else {
357 $words = '';
358 }
359
360 $i = 0;
361 $line = $beginning_spaces;
362
363 while ($i < count($words)) {
364 /* Force one word to be on a line (minimum) */
365 $line .= $words[$i];
366 $line_len = strlen($beginning_spaces) + sq_strlen($words[$i],$charset) + 2;
367 if (isset($words[$i + 1]))
368 $line_len += sq_strlen($words[$i + 1],$charset);
369 $i ++;
370
371 /* Add more words (as long as they fit) */
372 while ($line_len < $wrap && $i < count($words)) {
373 $line .= ' ' . $words[$i];
374 $i++;
375 if (isset($words[$i]))
376 $line_len += sq_strlen($words[$i],$charset) + 1;
377 else
378 $line_len += 1;
379 }
380
381 /* Skip spaces if they are the first thing on a continued line */
382 while (!isset($words[$i]) && $i < count($words)) {
383 $i ++;
384 }
385
386 /* Go to the next line if we have more to process */
387 if ($i < count($words)) {
388 $line .= "\n";
389 }
390 }
391 }
392
393 /**
394 * Does the opposite of sqWordWrap()
395 * @param string $body the text to un-wordwrap
396 * @return void
397 * @since 1.0
398 */
399 function sqUnWordWrap(&$body) {
400 global $squirrelmail_language;
401
402 if ($squirrelmail_language == 'ja_JP') {
403 return;
404 }
405
406 $lines = explode("\n", $body);
407 $body = '';
408 $PreviousSpaces = '';
409 $cnt = count($lines);
410 for ($i = 0; $i < $cnt; $i ++) {
411 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
412 $CurrentSpaces = $regs[1];
413 if (isset($regs[2])) {
414 $CurrentRest = $regs[2];
415 } else {
416 $CurrentRest = '';
417 }
418
419 if ($i == 0) {
420 $PreviousSpaces = $CurrentSpaces;
421 $body = $lines[$i];
422 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
423 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
424 && strlen($CurrentRest)) { /* and there's a line to continue with */
425 $body .= ' ' . $CurrentRest;
426 } else {
427 $body .= "\n" . $lines[$i];
428 $PreviousSpaces = $CurrentSpaces;
429 }
430 }
431 $body .= "\n";
432 }
433
434 /**
435 * If $haystack is a full mailbox name and $needle is the mailbox
436 * separator character, returns the last part of the mailbox name.
437 *
438 * @param string haystack full mailbox name to search
439 * @param string needle the mailbox separator character
440 * @return string the last part of the mailbox name
441 * @since 1.0
442 */
443 function readShortMailboxName($haystack, $needle) {
444
445 if ($needle == '') {
446 $elem = $haystack;
447 } else {
448 $parts = explode($needle, $haystack);
449 $elem = array_pop($parts);
450 while ($elem == '' && count($parts)) {
451 $elem = array_pop($parts);
452 }
453 }
454 return( $elem );
455 }
456
457
458 /**
459 * get_location
460 *
461 * Determines the location to forward to, relative to your server.
462 * This is used in HTTP Location: redirects.
463 *
464 * If set, it uses $config_location_base as the first part of the URL,
465 * specifically, the protocol, hostname and port parts. The path is
466 * always autodetected.
467 *
468 * @return string the base url for this SquirrelMail installation
469 * @since 1.0
470 */
471 function get_location () {
472
473 global $imap_server_type, $config_location_base,
474 $is_secure_connection, $sq_ignore_http_x_forwarded_headers;
475
476 /* Get the path, handle virtual directories */
477 if(strpos(php_self(), '?')) {
478 $path = substr(php_self(), 0, strpos(php_self(), '?'));
479 } else {
480 $path = php_self();
481 }
482 $path = substr($path, 0, strrpos($path, '/'));
483
484 // proto+host+port are already set in config:
485 if ( !empty($config_location_base) ) {
486 return $config_location_base . $path ;
487 }
488 // we computed it before, get it from the session:
489 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
490 return $full_url . $path;
491 }
492 // else: autodetect
493
494 /* Check if this is a HTTPS or regular HTTP request. */
495 $proto = 'http://';
496 if ($is_secure_connection)
497 $proto = 'https://';
498
499 /* Get the hostname from the Host header or server config. */
500 if ($sq_ignore_http_x_forwarded_headers
501 || !sqgetGlobalVar('HTTP_X_FORWARDED_HOST', $host, SQ_SERVER)
502 || empty($host)) {
503 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
504 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
505 $host = '';
506 }
507 }
508 }
509
510 $port = '';
511 if (! strstr($host, ':')) {
512 // Note: HTTP_X_FORWARDED_PROTO could be sent from the client and
513 // therefore possibly spoofed/hackable - for now, the
514 // administrator can tell SM to ignore this value by setting
515 // $sq_ignore_http_x_forwarded_headers to boolean TRUE in
516 // config/config_local.php, but in the future we may
517 // want to default this to TRUE and make administrators
518 // who use proxy systems turn it off (see 1.5.2+).
519 global $sq_ignore_http_x_forwarded_headers;
520 if ($sq_ignore_http_x_forwarded_headers
521 || !sqgetGlobalVar('HTTP_X_FORWARDED_PROTO', $forwarded_proto, SQ_SERVER))
522 $forwarded_proto = '';
523 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
524 if (($server_port != 80 && $proto == 'http://') ||
525 ($server_port != 443 && $proto == 'https://' &&
526 strcasecmp($forwarded_proto, 'https') !== 0)) {
527 $port = sprintf(':%d', $server_port);
528 }
529 }
530 }
531
532 /* this is a workaround for the weird macosx caching that
533 * causes Apache to return 16080 as the port number, which causes
534 * SM to bail */
535
536 if ($imap_server_type == 'macosx' && $port == ':16080') {
537 $port = '';
538 }
539
540 /* Fallback is to omit the server name and use a relative */
541 /* URI, although this is not RFC 2616 compliant. */
542 $full_url = ($host ? $proto . $host . $port : '');
543 sqsession_register($full_url, 'sq_base_url');
544 return $full_url . $path;
545 }
546
547
548 /**
549 * Get Message List URI
550 *
551 * @param string $mailbox Current mailbox name (unencoded/raw)
552 * @param string $startMessage The mailbox page offset
553 * @param string $what Any current search parameters (OPTIONAL;
554 * default empty string)
555 *
556 * @return string The message list URI
557 *
558 * @since 1.5.2
559 *
560 */
561 function get_message_list_uri($mailbox, $startMessage, $what='') {
562
563 global $base_uri;
564
565 $urlMailbox = urlencode($mailbox);
566
567 $list_xtra = "?where=read_body.php&what=$what&mailbox=" . $urlMailbox.
568 "&startMessage=$startMessage";
569
570 return $base_uri .'src/right_main.php'. $list_xtra;
571 }
572
573
574 /**
575 * Encrypts password
576 *
577 * These functions are used to encrypt the password before it is
578 * stored in a cookie. The encryption key is generated by
579 * OneTimePadCreate();
580 *
581 * @param string $string the (password)string to encrypt
582 * @param string $epad the encryption key
583 * @return string the base64-encoded encrypted password
584 * @since 1.0
585 */
586 function OneTimePadEncrypt ($string, $epad) {
587 $pad = base64_decode($epad);
588
589 if (strlen($pad)>0) {
590 // make sure that pad is longer than string
591 while (strlen($string)>strlen($pad)) {
592 $pad.=$pad;
593 }
594 } else {
595 // FIXME: what should we do when $epad is not base64 encoded or empty.
596 }
597
598 $encrypted = '';
599 for ($i = 0; $i < strlen ($string); $i++) {
600 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
601 }
602
603 return base64_encode($encrypted);
604 }
605
606 /**
607 * Decrypts a password from the cookie
608 *
609 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
610 * This uses the encryption key that is stored in the session.
611 *
612 * @param string $string the string to decrypt
613 * @param string $epad the encryption key from the session
614 * @return string the decrypted password
615 * @since 1.0
616 */
617 function OneTimePadDecrypt ($string, $epad) {
618 $pad = base64_decode($epad);
619
620 if (strlen($pad)>0) {
621 // make sure that pad is longer than string
622 while (strlen($string)>strlen($pad)) {
623 $pad.=$pad;
624 }
625 } else {
626 // FIXME: what should we do when $epad is not base64 encoded or empty.
627 }
628
629 $encrypted = base64_decode ($string);
630 $decrypted = '';
631 for ($i = 0; $i < strlen ($encrypted); $i++) {
632 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
633 }
634
635 return $decrypted;
636 }
637
638 /**
639 * Creates encryption key
640 *
641 * Creates an encryption key for encrypting the password stored in the cookie.
642 * The encryption key itself is stored in the session.
643 *
644 * Pad must be longer or equal to encoded string length in 1.4.4/1.5.0 and older.
645 * @param int $length optional, length of the string to generate
646 * @return string the encryption key
647 * @since 1.0
648 */
649 function OneTimePadCreate ($length=100) {
650 $pad = '';
651 for ($i = 0; $i < $length; $i++) {
652 $pad .= chr(mt_rand(0,255));
653 }
654
655 return base64_encode($pad);
656 }
657
658 /**
659 * Returns a string showing the size of the message/attachment.
660 *
661 * @param int $bytes the filesize in bytes
662 * @return string the filesize in human readable format
663 * @since 1.0
664 */
665 function show_readable_size($bytes) {
666 $bytes /= 1024;
667 $type = _("KiB");
668
669 if ($bytes / 1024 > 1) {
670 $bytes /= 1024;
671 $type = _("MiB");
672 }
673
674 if ($bytes < 10) {
675 $bytes *= 10;
676 settype($bytes, 'integer');
677 $bytes /= 10;
678 } else {
679 settype($bytes, 'integer');
680 }
681
682 return $bytes . '&nbsp;' . $type;
683 }
684
685 /**
686 * Generates a random string from the character set you pass in
687 *
688 * @param int $size the length of the string to generate
689 * @param string $chars a string containing the characters to use
690 * @param int $flags a flag to add a specific set to the characters to use:
691 * Flags:
692 * 1 = add lowercase a-z to $chars
693 * 2 = add uppercase A-Z to $chars
694 * 4 = add numbers 0-9 to $chars
695 * @return string the random string
696 * @since 1.0
697 */
698 function GenerateRandomString($size, $chars, $flags = 0) {
699 if ($flags & 0x1) {
700 $chars .= 'abcdefghijklmnopqrstuvwxyz';
701 }
702 if ($flags & 0x2) {
703 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
704 }
705 if ($flags & 0x4) {
706 $chars .= '0123456789';
707 }
708
709 if (($size < 1) || (strlen($chars) < 1)) {
710 return '';
711 }
712
713 $String = '';
714 $j = strlen( $chars ) - 1;
715 while (strlen($String) < $size) {
716 $String .= $chars{mt_rand(0, $j)};
717 }
718
719 return $String;
720 }
721
722 /**
723 * Escapes special characters for use in IMAP commands.
724 *
725 * @param string $str the string to escape
726 * @return string the escaped string
727 * @since 1.0.3
728 */
729 function quoteimap($str) {
730 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
731 }
732
733 /**
734 * Create compose link
735 *
736 * Returns a link to the compose-page, taking in consideration
737 * the compose_in_new and javascript settings.
738 *
739 * @param string $url The URL to the compose page
740 * @param string $text The link text, default "Compose"
741 * @param string $target URL target, if any (since 1.4.3)
742 * @param string $accesskey The access key to be used, if any
743 *
744 * @return string a link to the compose page
745 *
746 * @since 1.4.2
747 */
748 function makeComposeLink($url, $text = null, $target='', $accesskey='NONE') {
749 global $compose_new_win, $compose_width,
750 $compose_height, $oTemplate;
751
752 if(!$text) {
753 $text = _("Compose");
754 }
755
756 // if not using "compose in new window", make
757 // regular link and be done with it
758 if($compose_new_win != '1') {
759 return makeInternalLink($url, $text, $target, $accesskey);
760 }
761
762 // build the compose in new window link...
763
764
765 // if javascript is on, use onclick event to handle it
766 if(checkForJavascript()) {
767 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
768 $compuri = SM_BASE_URI.$url;
769
770 return create_hyperlink('javascript:void(0)', $text, '',
771 "comp_in_new('$compuri','$compose_width','$compose_height')",
772 '', '', '',
773 ($accesskey == 'NONE'
774 ? array()
775 : array('accesskey' => $accesskey)));
776 }
777
778 // otherwise, just open new window using regular HTML
779 return makeInternalLink($url, $text, '_blank', $accesskey);
780 }
781
782 /**
783 * version of fwrite which checks for failure
784 * @param resource $fp
785 * @param string $string
786 * @return number of written bytes. false on failure
787 * @since 1.4.3
788 */
789 function sq_fwrite($fp, $string) {
790 // write to file
791 $count = @fwrite($fp,$string);
792 // the number of bytes written should be the length of the string
793 if($count != strlen($string)) {
794 return FALSE;
795 }
796
797 return $count;
798 }
799
800 /**
801 * sq_get_html_translation_table
802 *
803 * Returns the translation table used by sq_htmlentities()
804 *
805 * @param integer $table html translation table. Possible values (without quotes):
806 * <ul>
807 * <li>HTML_ENTITIES - full html entities table defined by charset</li>
808 * <li>HTML_SPECIALCHARS - html special characters table</li>
809 * </ul>
810 * @param integer $quote_style quote encoding style. Possible values (without quotes):
811 * <ul>
812 * <li>ENT_COMPAT - (default) encode double quotes</li>
813 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
814 * <li>ENT_QUOTES - encode double and single quotes</li>
815 * </ul>
816 * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
817 * @return array html translation array
818 * @since 1.5.1
819 */
820 function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
821 global $default_charset;
822
823 if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
824
825 // Start array with ampersand
826 $sq_html_ent_table = array( "&" => '&amp;' );
827
828 // < and >
829 $sq_html_ent_table = array_merge($sq_html_ent_table,
830 array("<" => '&lt;',
831 ">" => '&gt;')
832 );
833 // double quotes
834 if ($quote_style == ENT_COMPAT)
835 $sq_html_ent_table = array_merge($sq_html_ent_table,
836 array("\"" => '&quot;')
837 );
838
839 // double and single quotes
840 if ($quote_style == ENT_QUOTES)
841 $sq_html_ent_table = array_merge($sq_html_ent_table,
842 array("\"" => '&quot;',
843 "'" => '&#39;')
844 );
845
846 if ($charset=='auto') $charset=$default_charset;
847
848 // add entities that depend on charset
849 switch($charset){
850 case 'iso-8859-1':
851 include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
852 break;
853 case 'utf-8':
854 include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
855 break;
856 case 'us-ascii':
857 default:
858 break;
859 }
860 // return table
861 return $sq_html_ent_table;
862 }
863
864 /**
865 * sq_htmlentities
866 *
867 * Convert all applicable characters to HTML entities.
868 * Minimal php requirement - v.4.0.5.
869 *
870 * Function is designed for people that want to use full power of htmlentities() in
871 * i18n environment.
872 *
873 * @param string $string string that has to be sanitized
874 * @param integer $quote_style quote encoding style. Possible values (without quotes):
875 * <ul>
876 * <li>ENT_COMPAT - (default) encode double quotes</li>
877 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
878 * <li>ENT_QUOTES - encode double and single quotes</li>
879 * </ul>
880 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
881 * @return string sanitized string
882 * @since 1.5.1
883 */
884 function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
885 // get translation table
886 $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
887 // convert characters
888 return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
889 }
890
891 /**
892 * Tests if string contains 8bit symbols.
893 *
894 * If charset is not set, function defaults to default_charset.
895 * $default_charset global must be set correctly if $charset is
896 * not used.
897 * @param string $string tested string
898 * @param string $charset charset used in a string
899 * @return bool true if 8bit symbols are detected
900 * @since 1.5.1 and 1.4.4
901 */
902 function sq_is8bit($string,$charset='') {
903 global $default_charset;
904
905 if ($charset=='') $charset=$default_charset;
906
907 /**
908 * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
909 * Don't use \200-\237 for iso-8859-x charsets. This range
910 * stores control symbols in those charsets.
911 * Use preg_match instead of ereg in order to avoid problems
912 * with mbstring overloading
913 */
914 if (preg_match("/^iso-8859/i",$charset)) {
915 $needle='/\240|[\241-\377]/';
916 } else {
917 $needle='/[\200-\237]|\240|[\241-\377]/';
918 }
919 return preg_match("$needle",$string);
920 }
921
922 /**
923 * Replacement of mb_list_encodings function
924 *
925 * This function provides replacement for function that is available only
926 * in php 5.x. Function does not test all mbstring encodings. Only the ones
927 * that might be used in SM translations.
928 *
929 * Supported strings are stored in session in order to reduce number of
930 * mb_internal_encoding function calls.
931 *
932 * If you want to test all mbstring encodings - fill $list_of_encodings
933 * array.
934 * @return array list of encodings supported by php mbstring extension
935 * @since 1.5.1 and 1.4.6
936 */
937 function sq_mb_list_encodings() {
938 if (! function_exists('mb_internal_encoding'))
939 return array();
940
941 // php 5+ function
942 if (function_exists('mb_list_encodings')) {
943 $ret = mb_list_encodings();
944 array_walk($ret,'sq_lowercase_array_vals');
945 return $ret;
946 }
947
948 // don't try to test encodings, if they are already stored in session
949 if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION))
950 return $mb_supported_encodings;
951
952 // save original encoding
953 $orig_encoding=mb_internal_encoding();
954
955 $list_of_encoding=array(
956 'pass',
957 'auto',
958 'ascii',
959 'jis',
960 'utf-8',
961 'sjis',
962 'euc-jp',
963 'iso-8859-1',
964 'iso-8859-2',
965 'iso-8859-7',
966 'iso-8859-9',
967 'iso-8859-15',
968 'koi8-r',
969 'koi8-u',
970 'big5',
971 'gb2312',
972 'gb18030',
973 'windows-1251',
974 'windows-1255',
975 'windows-1256',
976 'tis-620',
977 'iso-2022-jp',
978 'euc-cn',
979 'euc-kr',
980 'euc-tw',
981 'uhc',
982 'utf7-imap');
983
984 $supported_encodings=array();
985
986 foreach ($list_of_encoding as $encoding) {
987 // try setting encodings. suppress warning messages
988 if (@mb_internal_encoding($encoding))
989 $supported_encodings[]=$encoding;
990 }
991
992 // restore original encoding
993 mb_internal_encoding($orig_encoding);
994
995 // register list in session
996 sqsession_register($supported_encodings,'mb_supported_encodings');
997
998 return $supported_encodings;
999 }
1000
1001 /**
1002 * Callback function used to lowercase array values.
1003 * @param string $val array value
1004 * @param mixed $key array key
1005 * @since 1.5.1 and 1.4.6
1006 */
1007 function sq_lowercase_array_vals(&$val,$key) {
1008 $val = strtolower($val);
1009 }
1010
1011
1012 /**
1013 * Function returns number of characters in string.
1014 *
1015 * Returned number might be different from number of bytes in string,
1016 * if $charset is multibyte charset. Detection depends on mbstring
1017 * functions. If mbstring does not support tested multibyte charset,
1018 * vanilla string length function is used.
1019 * @param string $str string
1020 * @param string $charset charset
1021 * @since 1.5.1 and 1.4.6
1022 * @return integer number of characters in string
1023 */
1024 function sq_strlen($str, $charset=null){
1025 // default option
1026 if (is_null($charset)) return strlen($str);
1027
1028 // lowercase charset name
1029 $charset=strtolower($charset);
1030
1031 // use automatic charset detection, if function call asks for it
1032 if ($charset=='auto') {
1033 global $default_charset, $squirrelmail_language;
1034 set_my_charset();
1035 $charset=$default_charset;
1036 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1037 }
1038
1039 // Use mbstring only with listed charsets
1040 $aList_of_mb_charsets=array('utf-8','big5','gb2312','gb18030','euc-jp','euc-cn','euc-tw','euc-kr');
1041
1042 // calculate string length according to charset
1043 if (in_array($charset,$aList_of_mb_charsets) && in_array($charset,sq_mb_list_encodings())) {
1044 $real_length = mb_strlen($str,$charset);
1045 } else {
1046 // own strlen detection code is removed because missing strpos,
1047 // strtoupper and substr implementations break string wrapping.
1048 $real_length=strlen($str);
1049 }
1050 return $real_length;
1051 }
1052
1053 /**
1054 * string padding with multibyte support
1055 *
1056 * @link http://www.php.net/str_pad
1057 * @param string $string original string
1058 * @param integer $width padded string width
1059 * @param string $pad padding symbols
1060 * @param integer $padtype padding type
1061 * (internal php defines, see str_pad() description)
1062 * @param string $charset charset used in original string
1063 * @return string padded string
1064 */
1065 function sq_str_pad($string, $width, $pad, $padtype, $charset='') {
1066
1067 $charset = strtolower($charset);
1068 $padded_string = '';
1069
1070 switch ($charset) {
1071 case 'utf-8':
1072 case 'big5':
1073 case 'gb2312':
1074 case 'euc-kr':
1075 /*
1076 * all multibyte charsets try to increase width value by
1077 * adding difference between number of bytes and real length
1078 */
1079 $width = $width - sq_strlen($string,$charset) + strlen($string);
1080 default:
1081 $padded_string=str_pad($string,$width,$pad,$padtype);
1082 }
1083 return $padded_string;
1084 }
1085
1086 /**
1087 * Wrapper that is used to switch between vanilla and multibyte substr
1088 * functions.
1089 * @param string $string
1090 * @param integer $start
1091 * @param integer $length
1092 * @param string $charset
1093 * @return string
1094 * @since 1.5.1
1095 * @link http://www.php.net/substr
1096 * @link http://www.php.net/mb_substr
1097 */
1098 function sq_substr($string,$start,$length,$charset='auto') {
1099 // use automatic charset detection, if function call asks for it
1100 static $charset_auto, $bUse_mb;
1101
1102 if ($charset=='auto') {
1103 if (!isset($charset_auto)) {
1104 global $default_charset, $squirrelmail_language;
1105 set_my_charset();
1106 $charset=$default_charset;
1107 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1108 $charset_auto = $charset;
1109 } else {
1110 $charset = $charset_auto;
1111 }
1112 }
1113 $charset = strtolower($charset);
1114
1115 // in_array call is expensive => do it once and use a static var for
1116 // storing the results
1117 if (!isset($bUse_mb)) {
1118 if (in_array($charset,sq_mb_list_encodings())) {
1119 $bUse_mb = true;
1120 } else {
1121 $bUse_mb = false;
1122 }
1123 }
1124
1125 if ($bUse_mb) {
1126 return mb_substr($string,$start,$length,$charset);
1127 }
1128 // TODO: add mbstring independent code
1129
1130 // use vanilla string functions as last option
1131 return substr($string,$start,$length);
1132 }
1133
1134 /**
1135 * Wrapper that is used to switch between vanilla and multibyte strpos
1136 * functions.
1137 * @param string $haystack
1138 * @param mixed $needle
1139 * @param integer $offset
1140 * @param string $charset
1141 * @return string
1142 * @since 1.5.1
1143 * @link http://www.php.net/strpos
1144 * @link http://www.php.net/mb_strpos
1145 */
1146 function sq_strpos($haystack,$needle,$offset,$charset='auto') {
1147 // use automatic charset detection, if function call asks for it
1148 static $charset_auto, $bUse_mb;
1149
1150 if ($charset=='auto') {
1151 if (!isset($charset_auto)) {
1152 global $default_charset, $squirrelmail_language;
1153 set_my_charset();
1154 $charset=$default_charset;
1155 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1156 $charset_auto = $charset;
1157 } else {
1158 $charset = $charset_auto;
1159 }
1160 }
1161 $charset = strtolower($charset);
1162
1163 // in_array call is expensive => do it once and use a static var for
1164 // storing the results
1165 if (!isset($bUse_mb)) {
1166 if (in_array($charset,sq_mb_list_encodings())) {
1167 $bUse_mb = true;
1168 } else {
1169 $bUse_mb = false;
1170 }
1171 }
1172 if ($bUse_mb) {
1173 return mb_strpos($haystack,$needle,$offset,$charset);
1174 }
1175 // TODO: add mbstring independent code
1176
1177 // use vanilla string functions as last option
1178 return strpos($haystack,$needle,$offset);
1179 }
1180
1181 /**
1182 * Wrapper that is used to switch between vanilla and multibyte strtoupper
1183 * functions.
1184 * @param string $string
1185 * @param string $charset
1186 * @return string
1187 * @since 1.5.1
1188 * @link http://www.php.net/strtoupper
1189 * @link http://www.php.net/mb_strtoupper
1190 */
1191 function sq_strtoupper($string,$charset='auto') {
1192 // use automatic charset detection, if function call asks for it
1193 static $charset_auto, $bUse_mb;
1194
1195 if ($charset=='auto') {
1196 if (!isset($charset_auto)) {
1197 global $default_charset, $squirrelmail_language;
1198 set_my_charset();
1199 $charset=$default_charset;
1200 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1201 $charset_auto = $charset;
1202 } else {
1203 $charset = $charset_auto;
1204 }
1205 }
1206 $charset = strtolower($charset);
1207
1208 // in_array call is expensive => do it once and use a static var for
1209 // storing the results
1210 if (!isset($bUse_mb)) {
1211 if (function_exists('mb_strtoupper') &&
1212 in_array($charset,sq_mb_list_encodings())) {
1213 $bUse_mb = true;
1214 } else {
1215 $bUse_mb = false;
1216 }
1217 }
1218
1219 if ($bUse_mb) {
1220 return mb_strtoupper($string,$charset);
1221 }
1222 // TODO: add mbstring independent code
1223
1224 // use vanilla string functions as last option
1225 return strtoupper($string);
1226 }
1227
1228 /**
1229 * Counts 8bit bytes in string
1230 * @param string $string tested string
1231 * @return integer number of 8bit bytes
1232 */
1233 function sq_count8bit($string) {
1234 $count=0;
1235 for ($i=0; $i<strlen($string); $i++) {
1236 if (ord($string[$i]) > 127) $count++;
1237 }
1238 return $count;
1239 }
1240
1241 /**
1242 * Callback function to trim whitespace from a value, to be used in array_walk
1243 * @param string $value value to trim
1244 * @since 1.5.2 and 1.4.7
1245 */
1246 function sq_trim_value ( &$value ) {
1247 $value = trim($value);
1248 }