9e295df6dfe18fb299a7aa5e93105491596cb626
[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 1999-2020 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 preg_match('/^([\t >]*)([^\t >].*)?$/', $line, $regs);
353 $beginning_spaces = $regs[1];
354 if (isset($regs[2])) {
355 $words = explode(' ', $regs[2]);
356 } else {
357 $words = array();
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 $path = substr(php_self(FALSE), 0, strrpos(php_self(FALSE), '/'));
478
479 // proto+host+port are already set in config:
480 if ( !empty($config_location_base) ) {
481 return $config_location_base . $path ;
482 }
483 // we computed it before, get it from the session:
484 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
485 return $full_url . $path;
486 }
487 // else: autodetect
488
489 /* Check if this is a HTTPS or regular HTTP request. */
490 $proto = 'http://';
491 if ($is_secure_connection)
492 $proto = 'https://';
493
494 /* Get the hostname from the Host header or server config. */
495 if ($sq_ignore_http_x_forwarded_headers
496 || !sqgetGlobalVar('HTTP_X_FORWARDED_HOST', $host, SQ_SERVER)
497 || empty($host)) {
498 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
499 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
500 $host = '';
501 }
502 }
503 }
504
505 $port = '';
506 if (! strstr($host, ':')) {
507 // Note: HTTP_X_FORWARDED_PROTO could be sent from the client and
508 // therefore possibly spoofed/hackable. Thus, SquirrelMail
509 // ignores such headers by default. The administrator
510 // can tell SM to use such header values by setting
511 // $sq_ignore_http_x_forwarded_headers to boolean FALSE
512 // in config/config.php or by using config/conf.pl.
513 global $sq_ignore_http_x_forwarded_headers;
514 if ($sq_ignore_http_x_forwarded_headers
515 || !sqgetGlobalVar('HTTP_X_FORWARDED_PROTO', $forwarded_proto, SQ_SERVER))
516 $forwarded_proto = '';
517 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
518 if (($server_port != 80 && $proto == 'http://') ||
519 ($server_port != 443 && $proto == 'https://' &&
520 strcasecmp($forwarded_proto, 'https') !== 0)) {
521 $port = sprintf(':%d', $server_port);
522 }
523 }
524 }
525
526 /* this is a workaround for the weird macosx caching that
527 * causes Apache to return 16080 as the port number, which causes
528 * SM to bail */
529
530 if ($imap_server_type == 'macosx' && $port == ':16080') {
531 $port = '';
532 }
533
534 /* Fallback is to omit the server name and use a relative */
535 /* URI, although this is not RFC 2616 compliant. */
536 $full_url = ($host ? $proto . $host . $port : '');
537 sqsession_register($full_url, 'sq_base_url');
538 return $full_url . $path;
539 }
540
541
542 /**
543 * Get Message List URI
544 *
545 * @param string $mailbox Current mailbox name (unencoded/raw)
546 * @param string $startMessage The mailbox page offset
547 * @param string $what Any current search parameters (OPTIONAL;
548 * default empty string)
549 *
550 * @return string The message list URI
551 *
552 * @since 1.5.2
553 *
554 */
555 function get_message_list_uri($mailbox, $startMessage, $what='') {
556
557 global $base_uri;
558
559 $urlMailbox = urlencode($mailbox);
560
561 $list_xtra = "?where=read_body.php&what=$what&mailbox=" . $urlMailbox.
562 "&startMessage=$startMessage";
563
564 return $base_uri .'src/right_main.php'. $list_xtra;
565 }
566
567
568 /**
569 * Encrypts password
570 *
571 * These functions are used to encrypt the password before it is
572 * stored in a cookie. The encryption key is generated by
573 * OneTimePadCreate();
574 *
575 * @param string $string the (password)string to encrypt
576 * @param string $epad the encryption key
577 * @return string the base64-encoded encrypted password
578 * @since 1.0
579 */
580 function OneTimePadEncrypt ($string, $epad) {
581 $pad = base64_decode($epad);
582
583 if (strlen($pad)>0) {
584 // make sure that pad is longer than string
585 while (strlen($string)>strlen($pad)) {
586 $pad.=$pad;
587 }
588 } else {
589 // FIXME: what should we do when $epad is not base64 encoded or empty.
590 }
591
592 $encrypted = '';
593 for ($i = 0; $i < strlen ($string); $i++) {
594 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
595 }
596
597 return base64_encode($encrypted);
598 }
599
600 /**
601 * Decrypts a password from the cookie
602 *
603 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
604 * This uses the encryption key that is stored in the session.
605 *
606 * @param string $string the string to decrypt
607 * @param string $epad the encryption key from the session
608 * @return string the decrypted password
609 * @since 1.0
610 */
611 function OneTimePadDecrypt ($string, $epad) {
612 $pad = base64_decode($epad);
613
614 if (strlen($pad)>0) {
615 // make sure that pad is longer than string
616 while (strlen($string)>strlen($pad)) {
617 $pad.=$pad;
618 }
619 } else {
620 // FIXME: what should we do when $epad is not base64 encoded or empty.
621 }
622
623 $encrypted = base64_decode ($string);
624 $decrypted = '';
625 for ($i = 0; $i < strlen ($encrypted); $i++) {
626 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
627 }
628
629 return $decrypted;
630 }
631
632 /**
633 * Creates encryption key
634 *
635 * Creates an encryption key for encrypting the password stored in the cookie.
636 * The encryption key itself is stored in the session.
637 *
638 * Pad must be longer or equal to encoded string length in 1.4.4/1.5.0 and older.
639 * @param int $length optional, length of the string to generate
640 * @return string the encryption key
641 * @since 1.0
642 */
643 function OneTimePadCreate ($length=100) {
644 $pad = '';
645 for ($i = 0; $i < $length; $i++) {
646 $pad .= chr(mt_rand(0,255));
647 }
648
649 return base64_encode($pad);
650 }
651
652 /**
653 * Returns a string showing a byte size figure in
654 * a more easily digested (readable) format
655 *
656 * @param int $bytes the size in bytes
657 *
658 * @return string The size in human readable format
659 *
660 * @since 1.0
661 *
662 */
663 function show_readable_size($bytes) {
664 $bytes /= 1024;
665 $type = _("KiB");
666
667 if ($bytes / 1024 > 1) {
668 $bytes /= 1024;
669 $type = _("MiB");
670 }
671
672 if ($bytes < 10) {
673 $bytes *= 10;
674 settype($bytes, 'integer');
675 $bytes /= 10;
676 } else {
677 settype($bytes, 'integer');
678 }
679
680 global $nbsp;
681 return $bytes . $nbsp . $type;
682 }
683
684 /**
685 * Generates a random string from the character set you pass in
686 *
687 * @param int $size the length of the string to generate
688 * @param string $chars a string containing the characters to use
689 * @param int $flags a flag to add a specific set to the characters to use:
690 * Flags:
691 * 1 = add lowercase a-z to $chars
692 * 2 = add uppercase A-Z to $chars
693 * 4 = add numbers 0-9 to $chars
694 * @return string the random string
695 * @since 1.0
696 */
697 function GenerateRandomString($size, $chars, $flags = 0) {
698 if ($flags & 0x1) {
699 $chars .= 'abcdefghijklmnopqrstuvwxyz';
700 }
701 if ($flags & 0x2) {
702 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
703 }
704 if ($flags & 0x4) {
705 $chars .= '0123456789';
706 }
707
708 if (($size < 1) || (strlen($chars) < 1)) {
709 return '';
710 }
711
712 $String = '';
713 $j = strlen( $chars ) - 1;
714 while (strlen($String) < $size) {
715 $String .= $chars{mt_rand(0, $j)};
716 }
717
718 return $String;
719 }
720
721 /**
722 * Escapes special characters for use in IMAP commands.
723 *
724 * @param string $str the string to escape
725 * @return string the escaped string
726 * @since 1.0.3
727 */
728 function quoteimap($str) {
729 return str_replace(array('\\', '"'), array('\\\\', '\\"'), $str);
730 }
731
732 /**
733 * Create compose link
734 *
735 * Returns a link to the compose-page, taking in consideration
736 * the compose_in_new and javascript settings.
737 *
738 * @param string $url The URL to the compose page
739 * @param string $text The link text, default "Compose"
740 * @param string $target URL target, if any (since 1.4.3)
741 * @param string $accesskey The access key to be used, if any
742 *
743 * @return string a link to the compose page
744 *
745 * @since 1.4.2
746 */
747 function makeComposeLink($url, $text = null, $target='', $accesskey='NONE') {
748 global $compose_new_win, $compose_width,
749 $compose_height, $oTemplate;
750
751 if(!$text) {
752 $text = _("Compose");
753 }
754
755 // if not using "compose in new window", make
756 // regular link and be done with it
757 if($compose_new_win != '1') {
758 return makeInternalLink($url, $text, $target, $accesskey);
759 }
760
761 // build the compose in new window link...
762
763
764 // if javascript is on, use onclick event to handle it
765 if(checkForJavascript()) {
766 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
767 $compuri = SM_BASE_URI.$url;
768
769 return create_hyperlink('javascript:void(0)', $text, '',
770 "comp_in_new('$compuri','$compose_width','$compose_height')",
771 '', '', '',
772 ($accesskey == 'NONE'
773 ? array()
774 : array('accesskey' => $accesskey)));
775 }
776
777 // otherwise, just open new window using regular HTML
778 return makeInternalLink($url, $text, '_blank', $accesskey);
779 }
780
781 /**
782 * version of fwrite which checks for failure
783 * @param resource $fp
784 * @param string $string
785 * @return number of written bytes. false on failure
786 * @since 1.4.3
787 */
788 function sq_fwrite($fp, $string) {
789 // write to file
790 $count = @fwrite($fp,$string);
791 // the number of bytes written should be the length of the string
792 if($count != strlen($string)) {
793 return FALSE;
794 }
795
796 return $count;
797 }
798
799 /**
800 * sq_get_html_translation_table
801 *
802 * Returns the translation table used by sq_htmlentities()
803 *
804 * @param integer $table html translation table. Possible values (without quotes):
805 * <ul>
806 * <li>HTML_ENTITIES - full html entities table defined by charset</li>
807 * <li>HTML_SPECIALCHARS - html special characters table</li>
808 * </ul>
809 * @param integer $quote_style quote encoding style. Possible values (without quotes):
810 * <ul>
811 * <li>ENT_COMPAT - (default) encode double quotes</li>
812 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
813 * <li>ENT_QUOTES - encode double and single quotes</li>
814 * </ul>
815 * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
816 * @return array html translation array
817 * @since 1.5.1
818 */
819 function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
820 global $default_charset;
821
822 if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
823
824 // Start array with ampersand
825 $sq_html_ent_table = array( "&" => '&amp;' );
826
827 // < and >
828 $sq_html_ent_table = array_merge($sq_html_ent_table,
829 array("<" => '&lt;',
830 ">" => '&gt;')
831 );
832 // double quotes
833 if ($quote_style == ENT_COMPAT)
834 $sq_html_ent_table = array_merge($sq_html_ent_table,
835 array("\"" => '&quot;')
836 );
837
838 // double and single quotes
839 if ($quote_style == ENT_QUOTES)
840 $sq_html_ent_table = array_merge($sq_html_ent_table,
841 array("\"" => '&quot;',
842 "'" => '&#39;')
843 );
844
845 if ($charset=='auto') $charset=$default_charset;
846
847 // add entities that depend on charset
848 switch($charset){
849 case 'iso-8859-1':
850 include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
851 break;
852 case 'utf-8':
853 include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
854 break;
855 case 'us-ascii':
856 default:
857 break;
858 }
859 // return table
860 return $sq_html_ent_table;
861 }
862
863 /**
864 * sq_htmlentities
865 *
866 * Convert all applicable characters to HTML entities.
867 * Minimal php requirement - v.4.0.5.
868 *
869 * Function is designed for people that want to use full power of htmlentities() in
870 * i18n environment.
871 *
872 * @param string $string string that has to be sanitized
873 * @param integer $quote_style quote encoding style. Possible values (without quotes):
874 * <ul>
875 * <li>ENT_COMPAT - (default) encode double quotes</li>
876 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
877 * <li>ENT_QUOTES - encode double and single quotes</li>
878 * </ul>
879 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
880 * @return string sanitized string
881 * @since 1.5.1
882 */
883 function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
884 // get translation table
885 $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
886 // convert characters
887 return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
888 }
889
890 /**
891 * Tests if string contains 8bit symbols.
892 *
893 * If charset is not set, function defaults to default_charset.
894 * $default_charset global must be set correctly if $charset is
895 * not used.
896 * @param string $string tested string
897 * @param string $charset charset used in a string
898 * @return bool true if 8bit symbols are detected
899 * @since 1.5.1 and 1.4.4
900 */
901 function sq_is8bit($string,$charset='') {
902 global $default_charset;
903
904 if ($charset=='') $charset=$default_charset;
905
906 /**
907 * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
908 * Don't use \200-\237 for iso-8859-x charsets. This range
909 * stores control symbols in those charsets.
910 * Use preg_match instead of ereg in order to avoid problems
911 * with mbstring overloading
912 */
913 if (preg_match("/^iso-8859/i",$charset)) {
914 $needle='/\240|[\241-\377]/';
915 } else {
916 $needle='/[\200-\237]|\240|[\241-\377]/';
917 }
918 return preg_match("$needle",$string);
919 }
920
921 /**
922 * Replacement of mb_list_encodings function
923 *
924 * This function provides replacement for function that is available only
925 * in php 5.x. Function does not test all mbstring encodings. Only the ones
926 * that might be used in SM translations.
927 *
928 * Supported strings are stored in session in order to reduce number of
929 * mb_internal_encoding function calls.
930 *
931 * If you want to test all mbstring encodings - fill $list_of_encodings
932 * array.
933 * @return array list of encodings supported by php mbstring extension
934 * @since 1.5.1 and 1.4.6
935 */
936 function sq_mb_list_encodings() {
937 if (! function_exists('mb_internal_encoding'))
938 return array();
939
940 // php 5+ function
941 if (function_exists('mb_list_encodings')) {
942 $ret = mb_list_encodings();
943 array_walk($ret,'sq_lowercase_array_vals');
944 return $ret;
945 }
946
947 // don't try to test encodings, if they are already stored in session
948 if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION))
949 return $mb_supported_encodings;
950
951 // save original encoding
952 $orig_encoding=mb_internal_encoding();
953
954 $list_of_encoding=array(
955 'pass',
956 'auto',
957 'ascii',
958 'jis',
959 'utf-8',
960 'sjis',
961 'euc-jp',
962 'iso-8859-1',
963 'iso-8859-2',
964 'iso-8859-7',
965 'iso-8859-9',
966 'iso-8859-15',
967 'koi8-r',
968 'koi8-u',
969 'big5',
970 'gb2312',
971 'gb18030',
972 'windows-1251',
973 'windows-1255',
974 'windows-1256',
975 'tis-620',
976 'iso-2022-jp',
977 'euc-cn',
978 'euc-kr',
979 'euc-tw',
980 'uhc',
981 'utf7-imap');
982
983 $supported_encodings=array();
984
985 foreach ($list_of_encoding as $encoding) {
986 // try setting encodings. suppress warning messages
987 if (@mb_internal_encoding($encoding))
988 $supported_encodings[]=$encoding;
989 }
990
991 // restore original encoding
992 mb_internal_encoding($orig_encoding);
993
994 // register list in session
995 sqsession_register($supported_encodings,'mb_supported_encodings');
996
997 return $supported_encodings;
998 }
999
1000 /**
1001 * Callback function used to lowercase array values.
1002 * @param string $val array value
1003 * @param mixed $key array key
1004 * @since 1.5.1 and 1.4.6
1005 */
1006 function sq_lowercase_array_vals(&$val,$key) {
1007 $val = strtolower($val);
1008 }
1009
1010
1011 /**
1012 * Function returns number of characters in string.
1013 *
1014 * Returned number might be different from number of bytes in string,
1015 * if $charset is multibyte charset. Detection depends on mbstring
1016 * functions. If mbstring does not support tested multibyte charset,
1017 * vanilla string length function is used.
1018 * @param string $str string
1019 * @param string $charset charset
1020 * @since 1.5.1 and 1.4.6
1021 * @return integer number of characters in string
1022 */
1023 function sq_strlen($str, $charset=null){
1024 // default option
1025 if (is_null($charset)) return strlen($str);
1026
1027 // lowercase charset name
1028 $charset=strtolower($charset);
1029
1030 // use automatic charset detection, if function call asks for it
1031 if ($charset=='auto') {
1032 global $default_charset, $squirrelmail_language;
1033 set_my_charset();
1034 $charset=$default_charset;
1035 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1036 }
1037
1038 // Use mbstring only with listed charsets
1039 $aList_of_mb_charsets=array('utf-8','big5','gb2312','gb18030','euc-jp','euc-cn','euc-tw','euc-kr');
1040
1041 // calculate string length according to charset
1042 if (in_array($charset,$aList_of_mb_charsets) && in_array($charset,sq_mb_list_encodings())) {
1043 $real_length = mb_strlen($str,$charset);
1044 } else {
1045 // own strlen detection code is removed because missing strpos,
1046 // strtoupper and substr implementations break string wrapping.
1047 $real_length=strlen($str);
1048 }
1049 return $real_length;
1050 }
1051
1052 /**
1053 * string padding with multibyte support
1054 *
1055 * @link http://www.php.net/str_pad
1056 * @param string $string original string
1057 * @param integer $width padded string width
1058 * @param string $pad padding symbols
1059 * @param integer $padtype padding type
1060 * (internal php defines, see str_pad() description)
1061 * @param string $charset charset used in original string
1062 * @return string padded string
1063 */
1064 function sq_str_pad($string, $width, $pad, $padtype, $charset='') {
1065
1066 $charset = strtolower($charset);
1067 $padded_string = '';
1068
1069 switch ($charset) {
1070 case 'utf-8':
1071 case 'big5':
1072 case 'gb2312':
1073 case 'euc-kr':
1074 /*
1075 * all multibyte charsets try to increase width value by
1076 * adding difference between number of bytes and real length
1077 */
1078 $width = $width - sq_strlen($string,$charset) + strlen($string);
1079 default:
1080 $padded_string=str_pad($string,$width,$pad,$padtype);
1081 }
1082 return $padded_string;
1083 }
1084
1085 /**
1086 * Wrapper that is used to switch between vanilla and multibyte substr
1087 * functions.
1088 * @param string $string
1089 * @param integer $start
1090 * @param integer $length
1091 * @param string $charset
1092 * @return string
1093 * @since 1.5.1
1094 * @link http://www.php.net/substr
1095 * @link http://www.php.net/mb_substr
1096 */
1097 function sq_substr($string,$start,$length=NULL,$charset='auto') {
1098
1099 // if $length is NULL, use the full string length...
1100 // we have to do this to mimick the use of substr()
1101 // where $length is not given
1102 //
1103 if (is_null($length))
1104 $length = sq_strlen($length);
1105
1106
1107 // use automatic charset detection, if function call asks for it
1108 static $charset_auto, $bUse_mb;
1109
1110 if ($charset=='auto') {
1111 if (!isset($charset_auto)) {
1112 global $default_charset, $squirrelmail_language;
1113 set_my_charset();
1114 $charset=$default_charset;
1115 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1116 $charset_auto = $charset;
1117 } else {
1118 $charset = $charset_auto;
1119 }
1120 }
1121 $charset = strtolower($charset);
1122
1123 // in_array call is expensive => do it once and use a static var for
1124 // storing the results
1125 if (!isset($bUse_mb)) {
1126 if (in_array($charset,sq_mb_list_encodings())) {
1127 $bUse_mb = true;
1128 } else {
1129 $bUse_mb = false;
1130 }
1131 }
1132
1133 if ($bUse_mb) {
1134 return mb_substr($string,$start,$length,$charset);
1135 }
1136 // TODO: add mbstring independent code
1137
1138 // use vanilla string functions as last option
1139 return substr($string,$start,$length);
1140 }
1141
1142 /**
1143 * This is a replacement for PHP's substr_replace() that is
1144 * multibyte-aware.
1145 *
1146 * @param string $string The string to operate upon
1147 * @param string $replacement The string to be inserted
1148 * @param int $start The offset at which to begin substring replacement
1149 * @param int $length The number of characters after $start to remove
1150 * NOTE that if you need to specify a charset but
1151 * want to achieve normal substr_replace() behavior
1152 * where $length is not specified, use NULL (OPTIONAL;
1153 * default from $start to end of string)
1154 * @param string $charset The charset of the given string. A value of NULL
1155 * here will force the use of PHP's standard substr().
1156 * (OPTIONAL; default is "auto", which indicates that
1157 * the user's current charset should be used).
1158 *
1159 * @return string The manipulated string
1160 *
1161 * Of course, you can use more advanced (e.g., negative) values
1162 * for $start and $length as needed - see the PHP manual for more
1163 * information: http://www.php.net/manual/function.substr-replace.php
1164 *
1165 */
1166 function sq_substr_replace($string, $replacement, $start, $length=NULL,
1167 $charset='auto')
1168 {
1169
1170 // NULL charset? Just use substr_replace()
1171 //
1172 if (is_null($charset))
1173 return is_null($length) ? substr_replace($string, $replacement, $start)
1174 : substr_replace($string, $replacement, $start, $length);
1175
1176
1177 // use current character set?
1178 //
1179 if ($charset == 'auto')
1180 {
1181 //FIXME: is there any reason why this cannot be a global flag used by all string wrapper functions?
1182 static $auto_charset;
1183 if (!isset($auto_charset))
1184 {
1185 global $default_charset;
1186 //FIXME - do we need this?
1187 global $squirrelmail_language;
1188 set_my_charset();
1189 $auto_charset = $default_charset;
1190 //FIXME - do we need this?
1191 if ($squirrelmail_language == 'ja_JP') $auto_charset = 'euc-jp';
1192 }
1193 $charset = $auto_charset;
1194 }
1195
1196
1197 // standardize character set name
1198 //
1199 $charset = strtolower($charset);
1200
1201
1202 /* ===== FIXME: this list is not used in 1.5.x, but if we need it, unless this differs between all our string function wrappers, we should store this info in the session
1203 // only use mbstring with the following character sets
1204 //
1205 $sq_substr_replace_mb_charsets = array(
1206 'utf-8',
1207 'big5',
1208 'gb2312',
1209 'gb18030',
1210 'euc-jp',
1211 'euc-cn',
1212 'euc-tw',
1213 'euc-kr'
1214 );
1215
1216
1217 // now we can use our own implementation using
1218 // mb_substr() and mb_strlen() if needed
1219 //
1220 if (in_array($charset, $sq_substr_replace_mb_charsets)
1221 && in_array($charset, sq_mb_list_encodings()))
1222 ===== */
1223 //FIXME: is there any reason why this cannot be a global array used by all string wrapper functions?
1224 if (in_array($charset, sq_mb_list_encodings()))
1225 {
1226
1227 $string_length = mb_strlen($string, $charset);
1228
1229 if ($start < 0)
1230 $start = max(0, $string_length + $start);
1231
1232 else if ($start > $string_length)
1233 $start = $string_length;
1234
1235 if ($length < 0)
1236 $length = max(0, $string_length - $start + $length);
1237
1238 else if (is_null($length) || $length > $string_length)
1239 $length = $string_length;
1240
1241 if ($start + $length > $string_length)
1242 $length = $string_length - $start;
1243
1244 return mb_substr($string, 0, $start, $charset)
1245 . $replacement
1246 . mb_substr($string,
1247 $start + $length,
1248 $string_length, // FIXME: I can't see why this is needed: - $start - $length,
1249 $charset);
1250
1251 }
1252
1253
1254 // else use normal substr_replace()
1255 //
1256 return is_null($length) ? substr_replace($string, $replacement, $start)
1257 : substr_replace($string, $replacement, $start, $length);
1258
1259 }
1260
1261 /**
1262 * Wrapper that is used to switch between vanilla and multibyte strpos
1263 * functions.
1264 * @param string $haystack
1265 * @param mixed $needle
1266 * @param integer $offset
1267 * @param string $charset
1268 * @return string
1269 * @since 1.5.1
1270 * @link http://www.php.net/strpos
1271 * @link http://www.php.net/mb_strpos
1272 */
1273 function sq_strpos($haystack,$needle,$offset,$charset='auto') {
1274 // use automatic charset detection, if function call asks for it
1275 static $charset_auto, $bUse_mb;
1276
1277 if ($charset=='auto') {
1278 if (!isset($charset_auto)) {
1279 global $default_charset, $squirrelmail_language;
1280 set_my_charset();
1281 $charset=$default_charset;
1282 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1283 $charset_auto = $charset;
1284 } else {
1285 $charset = $charset_auto;
1286 }
1287 }
1288 $charset = strtolower($charset);
1289
1290 // in_array call is expensive => do it once and use a static var for
1291 // storing the results
1292 if (!isset($bUse_mb)) {
1293 if (in_array($charset,sq_mb_list_encodings())) {
1294 $bUse_mb = true;
1295 } else {
1296 $bUse_mb = false;
1297 }
1298 }
1299 if ($bUse_mb) {
1300 return mb_strpos($haystack,$needle,$offset,$charset);
1301 }
1302 // TODO: add mbstring independent code
1303
1304 // use vanilla string functions as last option
1305 return strpos($haystack,$needle,$offset);
1306 }
1307
1308 /**
1309 * Wrapper that is used to switch between vanilla and multibyte strtoupper
1310 * functions.
1311 * @param string $string
1312 * @param string $charset
1313 * @return string
1314 * @since 1.5.1
1315 * @link http://www.php.net/strtoupper
1316 * @link http://www.php.net/mb_strtoupper
1317 */
1318 function sq_strtoupper($string,$charset='auto') {
1319 // use automatic charset detection, if function call asks for it
1320 static $charset_auto, $bUse_mb;
1321
1322 if ($charset=='auto') {
1323 if (!isset($charset_auto)) {
1324 global $default_charset, $squirrelmail_language;
1325 set_my_charset();
1326 $charset=$default_charset;
1327 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1328 $charset_auto = $charset;
1329 } else {
1330 $charset = $charset_auto;
1331 }
1332 }
1333 $charset = strtolower($charset);
1334
1335 // in_array call is expensive => do it once and use a static var for
1336 // storing the results
1337 if (!isset($bUse_mb)) {
1338 if (function_exists('mb_strtoupper') &&
1339 in_array($charset,sq_mb_list_encodings())) {
1340 $bUse_mb = true;
1341 } else {
1342 $bUse_mb = false;
1343 }
1344 }
1345
1346 if ($bUse_mb) {
1347 return mb_strtoupper($string,$charset);
1348 }
1349 // TODO: add mbstring independent code
1350
1351 // use vanilla string functions as last option
1352 return strtoupper($string);
1353 }
1354
1355 /**
1356 * Counts 8bit bytes in string
1357 * @param string $string tested string
1358 * @return integer number of 8bit bytes
1359 */
1360 function sq_count8bit($string) {
1361 $count=0;
1362 for ($i=0; $i<strlen($string); $i++) {
1363 if (ord($string[$i]) > 127) $count++;
1364 }
1365 return $count;
1366 }
1367
1368 /**
1369 * Callback function to trim whitespace from a value, to be used in array_walk
1370 * @param string $value value to trim
1371 * @since 1.5.2 and 1.4.7
1372 */
1373 function sq_trim_value ( &$value ) {
1374 $value = trim($value);
1375 }
1376
1377 /**
1378 * Truncates the given string so that it has at
1379 * most $max_chars characters. NOTE that a "character"
1380 * may be a multibyte character, or (optionally), an
1381 * HTML entity , so this function is different than
1382 * using substr() or mb_substr().
1383 *
1384 * NOTE that if $elipses is given and used, the returned
1385 * number of characters will be $max_chars PLUS the
1386 * length of $elipses
1387 *
1388 * @param string $string The string to truncate
1389 * @param int $max_chars The maximum allowable characters
1390 * @param string $elipses A string that will be added to
1391 * the end of the truncated string
1392 * (ONLY if it is truncated) (OPTIONAL;
1393 * default not used)
1394 * @param boolean $html_entities_as_chars Whether or not to keep
1395 * HTML entities together
1396 * (OPTIONAL; default ignore
1397 * HTML entities)
1398 *
1399 * @return string The truncated string
1400 *
1401 * @since 1.4.20 and 1.5.2 (replaced truncateWithEntities())
1402 *
1403 */
1404 function sm_truncate_string($string, $max_chars, $elipses='',
1405 $html_entities_as_chars=FALSE)
1406 {
1407
1408 // if the length of the string is less than
1409 // the allowable number of characters, just
1410 // return it as is (even if it contains any
1411 // HTML entities, that would just make the
1412 // actual length even smaller)
1413 //
1414 $actual_strlen = sq_strlen($string, 'auto');
1415 if ($max_chars <= 0 || $actual_strlen <= $max_chars)
1416 return $string;
1417
1418
1419 // if needed, count the number of HTML entities in
1420 // the string up to the maximum character limit,
1421 // pushing that limit up for each entity found
1422 //
1423 $adjusted_max_chars = $max_chars;
1424 if ($html_entities_as_chars)
1425 {
1426
1427 // $loop_count is needed to prevent an endless loop
1428 // which is caused by buggy mbstring versions that
1429 // return 0 (zero) instead of FALSE in some rare
1430 // cases. Thanks, PHP.
1431 // see: http://bugs.php.net/bug.php?id=52731
1432 // also: tracker $3053349
1433 //
1434 $loop_count = 0;
1435 $entity_pos = $entity_end_pos = -1;
1436 while ($entity_end_pos + 1 < $actual_strlen
1437 && ($entity_pos = sq_strpos($string, '&', $entity_end_pos + 1)) !== FALSE
1438 && ($entity_end_pos = sq_strpos($string, ';', $entity_pos)) !== FALSE
1439 && $entity_pos <= $adjusted_max_chars
1440 && $loop_count++ < $max_chars)
1441 {
1442 $adjusted_max_chars += $entity_end_pos - $entity_pos;
1443 }
1444
1445
1446 // this isn't necessary because sq_substr() would figure this
1447 // out anyway, but we can avoid a sq_substr() call and we
1448 // know that we don't have to add an elipses (this is now
1449 // an accurate comparison, since $adjusted_max_chars, like
1450 // $actual_strlen, does not take into account HTML entities)
1451 //
1452 if ($actual_strlen <= $adjusted_max_chars)
1453 return $string;
1454
1455 }
1456
1457
1458 // get the truncated string
1459 //
1460 $truncated_string = sq_substr($string, 0, $adjusted_max_chars);
1461
1462
1463 // return with added elipses
1464 //
1465 return $truncated_string . $elipses;
1466
1467 }
1468
1469 /**
1470 * Gathers the list of secuirty tokens currently
1471 * stored in the user's preferences and optionally
1472 * purges old ones from the list.
1473 *
1474 * @param boolean $purge_old Indicates if old tokens
1475 * should be purged from the
1476 * list ("old" is 2 days or
1477 * older unless the administrator
1478 * overrides that value using
1479 * $max_token_age_days in
1480 * config/config_local.php)
1481 * (OPTIONAL; default is to always
1482 * purge old tokens)
1483 *
1484 * @return array The list of tokens
1485 *
1486 * @since 1.4.19 and 1.5.2
1487 *
1488 */
1489 function sm_get_user_security_tokens($purge_old=TRUE)
1490 {
1491
1492 global $data_dir, $username, $max_token_age_days,
1493 $use_expiring_security_tokens;
1494
1495 $tokens = getPref($data_dir, $username, 'security_tokens', '');
1496 if (($tokens = unserialize($tokens)) === FALSE || !is_array($tokens))
1497 $tokens = array();
1498
1499 // purge old tokens if necessary
1500 //
1501 if ($purge_old)
1502 {
1503 if (empty($max_token_age_days)) $max_token_age_days = 2;
1504 $now = time();
1505 $discard_token_date = $now - ($max_token_age_days * 86400);
1506 $cleaned_tokens = array();
1507 foreach ($tokens as $token => $timestamp)
1508 if ($timestamp >= $discard_token_date)
1509 $cleaned_tokens[$token] = $timestamp;
1510 $tokens = $cleaned_tokens;
1511 }
1512
1513 return $tokens;
1514
1515 }
1516
1517 /**
1518 * Generates a security token that is then stored in
1519 * the user's preferences with a timestamp for later
1520 * verification/use (although session-based tokens
1521 * are not stored in user preferences).
1522 *
1523 * NOTE: By default SquirrelMail will use a single session-based
1524 * token, but if desired, user tokens can have expiration
1525 * dates associated with them and become invalid even during
1526 * the same login session. When in that mode, the note
1527 * immediately below applies, otherwise it is irrelevant.
1528 * To enable that mode, the administrator must add the
1529 * following to config/config_local.php:
1530 * $use_expiring_security_tokens = TRUE;
1531 *
1532 * NOTE: The administrator can force SquirrelMail to generate
1533 * a new token every time one is requested (which may increase
1534 * obscurity through token randomness at the cost of some
1535 * performance) by adding the following to
1536 * config/config_local.php: $do_not_use_single_token = TRUE;
1537 * Otherwise, only one token will be generated per user which
1538 * will change only after it expires or is used outside of the
1539 * validity period specified when calling sm_validate_security_token()
1540 *
1541 * WARNING: If the administrator has turned the token system
1542 * off by setting $disable_security_tokens to TRUE in
1543 * config/config.php or the configuration tool, this
1544 * function will not store tokens in the user
1545 * preferences (but it will still generate and return
1546 * a random string).
1547 *
1548 * @param boolean $force_generate_new When TRUE, a new token will
1549 * always be created even if current
1550 * configuration dictates otherwise
1551 * (OPTIONAL; default FALSE)
1552 *
1553 * @return string A security token
1554 *
1555 * @since 1.4.19 and 1.5.2
1556 *
1557 */
1558 function sm_generate_security_token($force_generate_new=FALSE)
1559 {
1560
1561 global $data_dir, $username, $disable_security_tokens, $do_not_use_single_token,
1562 $use_expiring_security_tokens;
1563 $max_generation_tries = 1000;
1564
1565 // if we're using session-based tokens, just return
1566 // the same one every time (generate it if it's not there)
1567 //
1568 if (!$use_expiring_security_tokens)
1569 {
1570 if (sqgetGlobalVar('sm_security_token', $token, SQ_SESSION))
1571 return $token;
1572
1573 // create new one since there was none in session
1574 $token = GenerateRandomString(12, '', 7);
1575 sqsession_register($token, 'sm_security_token');
1576 return $token;
1577 }
1578
1579 $tokens = sm_get_user_security_tokens();
1580
1581 if (!$force_generate_new && !$do_not_use_single_token && !empty($tokens))
1582 return key($tokens);
1583
1584 $new_token = GenerateRandomString(12, '', 7);
1585 $count = 0;
1586 while (isset($tokens[$new_token]))
1587 {
1588 $new_token = GenerateRandomString(12, '', 7);
1589 if (++$count > $max_generation_tries)
1590 {
1591 logout_error(_("Fatal token generation error; please contact your system administrator or the SquirrelMail Team"));
1592 exit;
1593 }
1594 }
1595
1596 // is the token system enabled? CAREFUL!
1597 //
1598 if (!$disable_security_tokens)
1599 {
1600 $tokens[$new_token] = time();
1601 setPref($data_dir, $username, 'security_tokens', serialize($tokens));
1602 }
1603
1604 return $new_token;
1605
1606 }
1607
1608 /**
1609 * Validates a given security token and optionally remove it
1610 * from the user's preferences if it was valid. If the token
1611 * is too old but otherwise valid, it will still be rejected.
1612 *
1613 * "Too old" is 2 days or older unless the administrator
1614 * overrides that value using $max_token_age_days in
1615 * config/config_local.php
1616 *
1617 * Session-based tokens of course are always reused and are
1618 * valid for the lifetime of the login session.
1619 *
1620 * WARNING: If the administrator has turned the token system
1621 * off by setting $disable_security_tokens to TRUE in
1622 * config/config.php or the configuration tool, this
1623 * function will always return TRUE.
1624 *
1625 * @param string $token The token to validate
1626 * @param int $validity_period The number of seconds tokens are valid
1627 * for (set to zero to remove valid tokens
1628 * after only one use; set to -1 to allow
1629 * indefinite re-use (but still subject to
1630 * $max_token_age_days - see elsewhere);
1631 * use 3600 to allow tokens to be reused for
1632 * an hour) (OPTIONAL; default is to only
1633 * allow tokens to be used once)
1634 * NOTE this is unrelated to $max_token_age_days
1635 * or rather is an additional time constraint on
1636 * tokens that allows them to be re-used (or not)
1637 * within a more narrow timeframe
1638 * @param boolean $show_error Indicates that if the token is not
1639 * valid, this function should display
1640 * a generic error, log the user out
1641 * and exit - this function will never
1642 * return in that case.
1643 * (OPTIONAL; default FALSE)
1644 *
1645 * @return boolean TRUE if the token validated; FALSE otherwise
1646 *
1647 * @since 1.4.19 and 1.5.2
1648 *
1649 */
1650 function sm_validate_security_token($token, $validity_period=0, $show_error=FALSE)
1651 {
1652
1653 global $data_dir, $username, $max_token_age_days,
1654 $use_expiring_security_tokens,
1655 $disable_security_tokens;
1656
1657 // bypass token validation? CAREFUL!
1658 //
1659 if ($disable_security_tokens) return TRUE;
1660
1661 // if we're using session-based tokens, just compare
1662 // the same one every time
1663 //
1664 if (!$use_expiring_security_tokens)
1665 {
1666 if (!sqgetGlobalVar('sm_security_token', $session_token, SQ_SESSION))
1667 {
1668 if (!$show_error) return FALSE;
1669 logout_error(_("Fatal security token error; please log in again"));
1670 exit;
1671 }
1672 if ($token !== $session_token)
1673 {
1674 if (!$show_error) return FALSE;
1675 logout_error(_("The current page request appears to have originated from an untrusted source."));
1676 exit;
1677 }
1678 return TRUE;
1679 }
1680
1681 // don't purge old tokens here because we already
1682 // do it when generating tokens
1683 //
1684 $tokens = sm_get_user_security_tokens(FALSE);
1685
1686 // token not found?
1687 //
1688 if (empty($tokens[$token]))
1689 {
1690 if (!$show_error) return FALSE;
1691 logout_error(_("This page request could not be verified and appears to have expired."));
1692 exit;
1693 }
1694
1695 $now = time();
1696 $timestamp = $tokens[$token];
1697
1698 // whether valid or not, we want to remove it from
1699 // user prefs if it's old enough (unless requested to
1700 // bypass this (in which case $validity_period is -1))
1701 //
1702 if ($validity_period >= 0
1703 && $timestamp < $now - $validity_period)
1704 {
1705 unset($tokens[$token]);
1706 setPref($data_dir, $username, 'security_tokens', serialize($tokens));
1707 }
1708
1709 // reject tokens that are too old
1710 //
1711 if (empty($max_token_age_days)) $max_token_age_days = 2;
1712 $old_token_date = $now - ($max_token_age_days * 86400);
1713 if ($timestamp < $old_token_date)
1714 {
1715 if (!$show_error) return FALSE;
1716 logout_error(_("The current page request appears to have originated from an untrusted source."));
1717 exit;
1718 }
1719
1720 // token OK!
1721 //
1722 return TRUE;
1723
1724 }
1725
1726 /**
1727 * Wrapper for PHP's htmlspecialchars() that
1728 * attempts to add the correct character encoding
1729 *
1730 * @param string $string The string to be converted
1731 * @param int $flags A bitmask that controls the behavior of htmlspecialchars()
1732 * (See http://php.net/manual/function.htmlspecialchars.php )
1733 * (OPTIONAL; default ENT_COMPAT, ENT_COMPAT | ENT_SUBSTITUTE for PHP >=5.4)
1734 * @param string $encoding The character encoding to use in the conversion
1735 * (OPTIONAL; default automatic detection)
1736 * @param boolean $double_encode Whether or not to convert entities that are
1737 * already in the string (only supported in
1738 * PHP 5.2.3+) (OPTIONAL; default TRUE)
1739 *
1740 * @return string The converted text
1741 *
1742 */
1743 function sm_encode_html_special_chars($string, $flags=ENT_COMPAT,
1744 $encoding=NULL, $double_encode=TRUE)
1745 {
1746 if (!$encoding)
1747 {
1748 global $default_charset;
1749 if ($default_charset == 'iso-2022-jp')
1750 $default_charset = 'EUC-JP';
1751 $encoding = $default_charset;
1752 }
1753
1754 if (check_php_version(5, 2, 3)) {
1755 // Replace invalid characters with a symbol instead of returning
1756 // empty string for the entire to be encoded string.
1757 if (check_php_version(5, 4, 0) && $flags == ENT_COMPAT) {
1758 $flags = $flags | ENT_SUBSTITUTE;
1759 }
1760 return htmlspecialchars($string, $flags, $encoding, $double_encode);
1761 }
1762
1763 return htmlspecialchars($string, $flags, $encoding);
1764 }
1765