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