Fix overlooked default parameter value
[squirrelmail.git] / functions / strings.php
CommitLineData
59177427 1<?php
7350889b 2
f1ca21bd 3/**
35586184 4 * strings.php
5 *
35586184 6 * This code provides various string manipulation functions that are
598294a7 7 * used by the rest of the SquirrelMail code.
35586184 8 *
c4faef33 9 * @copyright 1999-2020 The SquirrelMail Project Team
4b4abf93 10 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
31841a9e 11 * @version $Id$
d6c32258 12 * @package squirrelmail
35586184 13 */
9374671f 14
c56e3934 15/**
c9d61baf 16 * Appends citation markers to the string.
17 * Also appends a trailing space.
18 *
19 * @author Justus Pendleton
31310ecd 20 * @param string $str The string to append to
21 * @param int $citeLevel the number of markers to append
c9d61baf 22 * @return null
31310ecd 23 * @since 1.5.1
c9d61baf 24 */
25function 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
31310ecd 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
c9d61baf 42 * @return null
31310ecd 43 * @since 1.5.1
c9d61baf 44 */
45function 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/**
5e7ae713 57 * Checks for spaces in strings - only used if PHP doesn't have native ctype support
58 *
326727cf 59 * You might be able to rewrite the function by adding short evaluation form.
5e7ae713 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
326727cf 73 * @return bool true when only whitespace symbols are present in test string
31310ecd 74 * @since 1.5.1
5e7ae713 75 */
76function sm_ctype_space($string) {
c7aff938 77 if ( preg_match('/^[\x09-\x0D]|^\x20/', $string) || $string=='') {
78 return true;
79 } else {
80 return false;
81 }
5e7ae713 82}
83
84/**
c9d61baf 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
31310ecd 91 * @param string $body the entire body of text
92 * @param int $wrap the maximum line length
c9d61baf 93 * @return string the wrapped text
31310ecd 94 * @since 1.5.1
c9d61baf 95 */
96function &sqBodyWrap (&$body, $wrap) {
5e7ae713 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
c9d61baf 104 // the newly wrapped text
105 $outString = '';
106 // current column since the last newline in the outstring
107 $outStringCol = 0;
98abf408 108 $length = sq_strlen($body);
c9d61baf 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
98abf408 120 while (($pos < $length) && (sq_substr($body,$pos,1) == '>')) {
c9d61baf 121 $newCiteLevel++;
122 $pos++;
123
124 // skip over any spaces interleaved among the cite markers
98abf408 125 while (($pos < $length) && (sq_substr($body,$pos,1) == ' ')) {
bb977394 126
c9d61baf 127 $pos++;
bb977394 128
c9d61baf 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
98abf408 138 if ((sq_substr($body,$pos,1) == "\n" ) && (sq_strlen($outString) != 0)) {
139 $outStringLast = $outString{sq_strlen($outString) - 1};
c9d61baf 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
98abf408 173 $nextNewline = sq_strpos ($body, "\n", $pos);
c9d61baf 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) {
98abf408 182 $outString .= sq_substr ($body, $pos, ($nextNewline - $pos));
c9d61baf 183 $outStringCol = $nextNewline - $pos;
184 if ($nextNewline != $length) {
185 sqMakeNewLine ($outString, 0, $outStringCol);
186 }
187 $pos = $nextNewline + 1;
188 continue;
189 }
bb977394 190 /**
191 * Set this to false to stop appending short strings to previous lines
192 */
193 $smartwrap = true;
c9d61baf 194 // inner loop, (obviously) handles wrapping up to
195 // the next newline
196 while ($pos < $nextNewline) {
197 // skip over initial spaces
98abf408 198 while (($pos < $nextNewline) && (ctype_space (sq_substr($body,$pos,1)))) {
c9d61baf 199 $pos++;
200 }
c9d61baf 201 // if this is a short line then just append it and continue outer loop
6eaf5320 202 if (($outStringCol + $nextNewline - $pos) <= ($wrap - $citeLevel - 1) ) {
c9d61baf 203 // if this is the final line in the input string then include
204 // any trailing newlines
6eaf5320 205 // echo substr($body,$pos,$wrap). "<br />";
98abf408 206 if (($nextNewline + 1 == $length) && (sq_substr($body,$nextNewline,1) == "\n")) {
c9d61baf 207 $nextNewline++;
208 }
209
bb977394 210 // trim trailing spaces
211 $lastRealChar = $nextNewline;
98abf408 212 while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space (sq_substr($body,$lastRealChar,1)))) {
bb977394 213 $lastRealChar--;
214 }
bb977394 215 // decide if appending the short string is what we want
98abf408 216 if (($nextNewline < $length && sq_substr($body,$nextNewline,1) == "\n") &&
bb977394 217 isset($lastRealChar)) {
be86a35a 218 $mypos = $pos;
219 //check the first word:
98abf408 220 while (($mypos < $length) && (sq_substr($body,$mypos,1) == '>')) {
bb977394 221 $mypos++;
222 // skip over any spaces interleaved among the cite markers
98abf408 223 while (($mypos < $length) && (sq_substr($body,$mypos,1) == ' ')) {
6eaf5320 224 $mypos++;
bb977394 225 }
226 }
227/*
228 $ldnspacecnt = 0;
229 if ($mypos == $nextNewline+1) {
230 while (($mypos < $length) && ($body{$mypos} == ' ')) {
231 $ldnspacecnt++;
6eaf5320 232 }
bb977394 233 }
234*/
235
98abf408 236 $firstword = sq_substr($body,$mypos,sq_strpos($body,' ',$mypos) - $mypos);
bb977394 237 //if ($dowrap || $ldnspacecnt > 1 || ($firstword && (
238 if (!$smartwrap || $firstword && (
239 $firstword{0} == '-' ||
6eaf5320 240 $firstword{0} == '+' ||
241 $firstword{0} == '*' ||
98abf408 242 sq_substr($firstword,0,1) == sq_strtoupper(sq_substr($firstword,0,1)) ||
6eaf5320 243 strpos($firstword,':'))) {
98abf408 244 $outString .= sq_substr($body,$pos,($lastRealChar - $pos+1));
bb977394 245 $outStringCol += ($lastRealChar - $pos);
246 sqMakeNewLine($outString,$citeLevel,$outStringCol);
247 $nextNewline++;
248 $pos = $nextNewline;
249 $outStringCol--;
250 continue;
251 }
6eaf5320 252
c9d61baf 253 }
bb977394 254
98abf408 255 $outString .= sq_substr ($body, $pos, ($lastRealChar - $pos + 1));
c9d61baf 256 $outStringCol += ($lastRealChar - $pos);
257 $pos = $nextNewline + 1;
258 continue;
259 }
bb977394 260
c9d61baf 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) {
6eaf5320 268 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
c9d61baf 269 continue;
270 }
271
272 // start looking backwards for whitespace to break at.
273 $breakPoint = $eol;
98abf408 274 while (($breakPoint > $pos) && (! ctype_space (sq_substr($body,$breakPoint,1)))) {
c9d61baf 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
98abf408 307 $substring = sq_substr ($body, $pos, ($breakPoint - $pos));
c9d61baf 308 $substring = rtrim ($substring); // do rtrim and ctype_space have the same ideas about whitespace?
309 $outString .= $substring;
98abf408 310 $outStringCol += sq_strlen ($substring);
c9d61baf 311 // advance past the whitespace which caused the wrap
312 $pos = $breakPoint;
98abf408 313 while (($pos < $length) && (ctype_space (sq_substr($body,$pos,1)))) {
c9d61baf 314 $pos++;
315 }
316 if ($pos < $length) {
317 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
318 }
319 }
320 }
321
322 return $outString;
323}
324
325/**
5cc0b70e 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 *
17886554 331 * Specifically, &amp;#039; comes up as 5 characters instead of 1.
5cc0b70e 332 * This should not add newlines to the end of lines.
8b096f0a 333 *
31310ecd 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.
8b096f0a 337 * @return void
31310ecd 338 * @since 1.0
5cc0b70e 339 */
c7aff938 340function sqWordWrap(&$line, $wrap, $charset='') {
e842b215 341 global $languages, $squirrelmail_language;
342
17886554 343 // Use custom wrapping function, if translation provides it
e842b215 344 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
1b45fe31 345 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap')) {
e842b215 346 if (mb_detect_encoding($line) != 'ASCII') {
1b45fe31 347 $line = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap', $line, $wrap);
e842b215 348 return;
349 }
350 }
351
b7910e12 352 preg_match('/^([\t >]*)([^\t >].*)?$/', $line, $regs);
5cc0b70e 353 $beginning_spaces = $regs[1];
354 if (isset($regs[2])) {
355 $words = explode(' ', $regs[2]);
356 } else {
712a518f 357 $words = array();
5cc0b70e 358 }
f1ca21bd 359
5cc0b70e 360 $i = 0;
361 $line = $beginning_spaces;
f1ca21bd 362
5cc0b70e 363 while ($i < count($words)) {
364 /* Force one word to be on a line (minimum) */
365 $line .= $words[$i];
c7aff938 366 $line_len = strlen($beginning_spaces) + sq_strlen($words[$i],$charset) + 2;
5cc0b70e 367 if (isset($words[$i + 1]))
c7aff938 368 $line_len += sq_strlen($words[$i + 1],$charset);
5cc0b70e 369 $i ++;
f1ca21bd 370
5cc0b70e 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]))
c7aff938 376 $line_len += sq_strlen($words[$i],$charset) + 1;
5cc0b70e 377 else
378 $line_len += 1;
379 }
f1ca21bd 380
5cc0b70e 381 /* Skip spaces if they are the first thing on a continued line */
382 while (!isset($words[$i]) && $i < count($words)) {
383 $i ++;
384 }
f1ca21bd 385
5cc0b70e 386 /* Go to the next line if we have more to process */
387 if ($i < count($words)) {
e0858036 388 $line .= "\n";
5cc0b70e 389 }
390 }
391}
392
393/**
341abbd6 394 * Does the opposite of sqWordWrap()
31310ecd 395 * @param string $body the text to un-wordwrap
8b096f0a 396 * @return void
31310ecd 397 * @since 1.0
341abbd6 398 */
399function sqUnWordWrap(&$body) {
e842b215 400 global $squirrelmail_language;
f1ca21bd 401
e842b215 402 if ($squirrelmail_language == 'ja_JP') {
403 return;
404 }
405
341abbd6 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];
1e4a4feb 415 } else {
f1ca21bd 416 $CurrentRest = '';
417 }
418
341abbd6 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/**
66239b65 435 * If $haystack is a full mailbox name and $needle is the mailbox
436 * separator character, returns the last part of the mailbox name.
8b096f0a 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
31310ecd 441 * @since 1.0
66239b65 442 */
443function readShortMailboxName($haystack, $needle) {
97b1248c 444
66239b65 445 if ($needle == '') {
97b1248c 446 $elem = $haystack;
447 } else {
f1ca21bd 448 $parts = explode($needle, $haystack);
449 $elem = array_pop($parts);
450 while ($elem == '' && count($parts)) {
451 $elem = array_pop($parts);
452 }
66239b65 453 }
97b1248c 454 return( $elem );
66239b65 455}
3302d0d4 456
a9a7cda1 457
458/**
4445e6b3 459 * get_location
460 *
8b096f0a 461 * Determines the location to forward to, relative to your server.
462 * This is used in HTTP Location: redirects.
8b096f0a 463 *
74530cf4 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.
66239b65 467 *
8b096f0a 468 * @return string the base url for this SquirrelMail installation
31310ecd 469 * @since 1.0
66239b65 470 */
471function get_location () {
f1ca21bd 472
8f557b94 473 global $imap_server_type, $config_location_base,
474 $is_secure_connection, $sq_ignore_http_x_forwarded_headers;
238703be 475
4deb32f1 476 /* Get the path, handle virtual directories */
adc3ea74 477 $path = substr(php_self(FALSE), 0, strrpos(php_self(FALSE), '/'));
74530cf4 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:
238703be 484 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
485 return $full_url . $path;
486 }
74530cf4 487 // else: autodetect
238703be 488
66239b65 489 /* Check if this is a HTTPS or regular HTTP request. */
490 $proto = 'http://';
8f557b94 491 if ($is_secure_connection)
8a549df2 492 $proto = 'https://';
f1ca21bd 493
4deb32f1 494 /* Get the hostname from the Host header or server config. */
8f557b94 495 if ($sq_ignore_http_x_forwarded_headers
496 || !sqgetGlobalVar('HTTP_X_FORWARDED_HOST', $host, SQ_SERVER)
497 || empty($host)) {
0a0f05c6 498 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
499 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
500 $host = '';
501 }
502 }
66239b65 503 }
f1ca21bd 504
66239b65 505 $port = '';
506 if (! strstr($host, ':')) {
154dda4a 507 // Note: HTTP_X_FORWARDED_PROTO could be sent from the client and
01f013c1 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.
154dda4a 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 = '';
961ca3d8 517 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
f1ca21bd 518 if (($server_port != 80 && $proto == 'http://') ||
6a0c35d4 519 ($server_port != 443 && $proto == 'https://' &&
8c64fc5a 520 strcasecmp($forwarded_proto, 'https') !== 0)) {
961ca3d8 521 $port = sprintf(':%d', $server_port);
66239b65 522 }
523 }
524 }
f1ca21bd 525
74530cf4 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 */
f1ca21bd 529
74530cf4 530 if ($imap_server_type == 'macosx' && $port == ':16080') {
8de7f698 531 $port = '';
74530cf4 532 }
f1ca21bd 533
74530cf4 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;
66239b65 539}
dcaf2a49 540
9374671f 541
66239b65 542/**
c4dcda23 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 */
555function 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/**
4445e6b3 569 * Encrypts password
570 *
8b096f0a 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 *
31310ecd 575 * @param string $string the (password)string to encrypt
576 * @param string $epad the encryption key
8b096f0a 577 * @return string the base64-encoded encrypted password
31310ecd 578 * @since 1.0
66239b65 579 */
580function OneTimePadEncrypt ($string, $epad) {
581 $pad = base64_decode($epad);
432db2fc 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
66239b65 592 $encrypted = '';
593 for ($i = 0; $i < strlen ($string); $i++) {
594 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
595 }
f1ca21bd 596
66239b65 597 return base64_encode($encrypted);
598}
599
8b096f0a 600/**
4445e6b3 601 * Decrypts a password from the cookie
602 *
603 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
8b096f0a 604 * This uses the encryption key that is stored in the session.
605 *
31310ecd 606 * @param string $string the string to decrypt
607 * @param string $epad the encryption key from the session
8b096f0a 608 * @return string the decrypted password
31310ecd 609 * @since 1.0
8b096f0a 610 */
66239b65 611function OneTimePadDecrypt ($string, $epad) {
612 $pad = base64_decode($epad);
432db2fc 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
66239b65 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 }
f1ca21bd 628
66239b65 629 return $decrypted;
630}
9374671f 631
8b096f0a 632/**
4445e6b3 633 * Creates encryption key
634 *
8b096f0a 635 * Creates an encryption key for encrypting the password stored in the cookie.
636 * The encryption key itself is stored in the session.
637 *
31310ecd 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
8b096f0a 640 * @return string the encryption key
31310ecd 641 * @since 1.0
8b096f0a 642 */
66239b65 643function OneTimePadCreate ($length=100) {
66239b65 644 $pad = '';
645 for ($i = 0; $i < $length; $i++) {
646 $pad .= chr(mt_rand(0,255));
647 }
f1ca21bd 648
66239b65 649 return base64_encode($pad);
650}
9374671f 651
66239b65 652/**
fa965ffa 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
3ab5b55b 657 * @param int $filesize_divisor the divisor we'll use (OPTIONAL; default 1024)
fa965ffa 658 *
659 * @return string The size in human readable format
660 *
661 * @since 1.0
662 *
663 */
11e62dd0 664function show_readable_size($bytes, $filesize_divisor=1024) {
3ab5b55b 665 $bytes /= $filesize_divisor;
ffde32e0 666 $type = _("KiB");
f1ca21bd 667
3ab5b55b 668 if ($bytes / $filesize_divisor > 1) {
669 $bytes /= $filesize_divisor;
ffde32e0 670 $type = _("MiB");
66239b65 671 }
f1ca21bd 672
66239b65 673 if ($bytes < 10) {
674 $bytes *= 10;
675 settype($bytes, 'integer');
676 $bytes /= 10;
677 } else {
678 settype($bytes, 'integer');
679 }
f1ca21bd 680
fa965ffa 681 global $nbsp;
682 return $bytes . $nbsp . $type;
66239b65 683}
9374671f 684
66239b65 685/**
c7aff938 686 * Generates a random string from the character set you pass in
66239b65 687 *
31310ecd 688 * @param int $size the length of the string to generate
689 * @param string $chars a string containing the characters to use
690 * @param int $flags a flag to add a specific set to the characters to use:
8b096f0a 691 * Flags:
692 * 1 = add lowercase a-z to $chars
693 * 2 = add uppercase A-Z to $chars
694 * 4 = add numbers 0-9 to $chars
695 * @return string the random string
31310ecd 696 * @since 1.0
66239b65 697 */
66239b65 698function GenerateRandomString($size, $chars, $flags = 0) {
699 if ($flags & 0x1) {
700 $chars .= 'abcdefghijklmnopqrstuvwxyz';
701 }
702 if ($flags & 0x2) {
703 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
704 }
705 if ($flags & 0x4) {
706 $chars .= '0123456789';
707 }
f1ca21bd 708
66239b65 709 if (($size < 1) || (strlen($chars) < 1)) {
710 return '';
711 }
ff4f08ff 712
4deb32f1 713 $String = '';
ff4f08ff 714 $j = strlen( $chars ) - 1;
66239b65 715 while (strlen($String) < $size) {
ff4f08ff 716 $String .= $chars{mt_rand(0, $j)};
66239b65 717 }
ff4f08ff 718
66239b65 719 return $String;
720}
9374671f 721
8b096f0a 722/**
723 * Escapes special characters for use in IMAP commands.
4445e6b3 724 *
31310ecd 725 * @param string $str the string to escape
8b096f0a 726 * @return string the escaped string
31310ecd 727 * @since 1.0.3
8b096f0a 728 */
fbb76d0e 729function quoteimap($str) {
d9f83cf8 730 return str_replace(array('\\', '"'), array('\\\\', '\\"'), $str);
66239b65 731}
1899535f 732
66239b65 733/**
4445e6b3 734 * Create compose link
735 *
8b096f0a 736 * Returns a link to the compose-page, taking in consideration
737 * the compose_in_new and javascript settings.
e740a582 738 *
739 * @param string $url The URL to the compose page
740 * @param string $text The link text, default "Compose"
741 * @param string $target URL target, if any (since 1.4.3)
742 * @param string $accesskey The access key to be used, if any
743 *
8b096f0a 744 * @return string a link to the compose page
e740a582 745 *
31310ecd 746 * @since 1.4.2
8b096f0a 747 */
c12535f6 748function makeComposeLink($url, $text = null, $target='', $accesskey='NONE') {
83aff890 749 global $compose_new_win, $compose_width,
f7b996c3 750 $compose_height, $oTemplate;
d62c4938 751
752 if(!$text) {
753 $text = _("Compose");
754 }
755
c9d61baf 756 // if not using "compose in new window", make
f72f61d8 757 // regular link and be done with it
d62c4938 758 if($compose_new_win != '1') {
e740a582 759 return makeInternalLink($url, $text, $target, $accesskey);
d62c4938 760 }
761
c9d61baf 762 // build the compose in new window link...
f72f61d8 763
764
c435f076 765 // if javascript is on, use onclick event to handle it
83aff890 766 if(checkForJavascript()) {
d62c4938 767 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
cdc4d881 768 $compuri = SM_BASE_URI.$url;
769a819d 769
e740a582 770 return create_hyperlink('javascript:void(0)', $text, '',
771 "comp_in_new('$compuri','$compose_width','$compose_height')",
772 '', '', '',
c12535f6 773 ($accesskey == 'NONE'
774 ? array()
775 : array('accesskey' => $accesskey)));
d62c4938 776 }
777
f72f61d8 778 // otherwise, just open new window using regular HTML
e740a582 779 return makeInternalLink($url, $text, '_blank', $accesskey);
d62c4938 780}
781
f1ca21bd 782/**
3ecad5e6 783 * version of fwrite which checks for failure
31310ecd 784 * @param resource $fp
785 * @param string $string
786 * @return number of written bytes. false on failure
787 * @since 1.4.3
3ecad5e6 788 */
789function sq_fwrite($fp, $string) {
c9d61baf 790 // write to file
791 $count = @fwrite($fp,$string);
792 // the number of bytes written should be the length of the string
793 if($count != strlen($string)) {
794 return FALSE;
795 }
796
797 return $count;
3ecad5e6 798}
799
36e1180b 800/**
801 * sq_get_html_translation_table
802 *
803 * Returns the translation table used by sq_htmlentities()
804 *
805 * @param integer $table html translation table. Possible values (without quotes):
deb22cec 806 * <ul>
807 * <li>HTML_ENTITIES - full html entities table defined by charset</li>
808 * <li>HTML_SPECIALCHARS - html special characters table</li>
809 * </ul>
36e1180b 810 * @param integer $quote_style quote encoding style. Possible values (without quotes):
c9d61baf 811 * <ul>
deb22cec 812 * <li>ENT_COMPAT - (default) encode double quotes</li>
813 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
814 * <li>ENT_QUOTES - encode double and single quotes</li>
c9d61baf 815 * </ul>
36e1180b 816 * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
817 * @return array html translation array
31310ecd 818 * @since 1.5.1
36e1180b 819 */
820function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
821 global $default_charset;
822
823 if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
824
825 // Start array with ampersand
826 $sq_html_ent_table = array( "&" => '&amp;' );
827
828 // < and >
829 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 830 array("<" => '&lt;',
831 ">" => '&gt;')
832 );
36e1180b 833 // double quotes
834 if ($quote_style == ENT_COMPAT)
835 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 836 array("\"" => '&quot;')
837 );
36e1180b 838
839 // double and single quotes
840 if ($quote_style == ENT_QUOTES)
841 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 842 array("\"" => '&quot;',
843 "'" => '&#39;')
844 );
36e1180b 845
846 if ($charset=='auto') $charset=$default_charset;
847
848 // add entities that depend on charset
849 switch($charset){
850 case 'iso-8859-1':
851 include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
852 break;
853 case 'utf-8':
854 include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
855 break;
856 case 'us-ascii':
857 default:
858 break;
859 }
860 // return table
861 return $sq_html_ent_table;
862}
863
864/**
865 * sq_htmlentities
866 *
867 * Convert all applicable characters to HTML entities.
17886554 868 * Minimal php requirement - v.4.0.5.
869 *
870 * Function is designed for people that want to use full power of htmlentities() in
871 * i18n environment.
36e1180b 872 *
873 * @param string $string string that has to be sanitized
874 * @param integer $quote_style quote encoding style. Possible values (without quotes):
c9d61baf 875 * <ul>
deb22cec 876 * <li>ENT_COMPAT - (default) encode double quotes</li>
877 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
878 * <li>ENT_QUOTES - encode double and single quotes</li>
c9d61baf 879 * </ul>
36e1180b 880 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
881 * @return string sanitized string
31310ecd 882 * @since 1.5.1
36e1180b 883 */
884function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
885 // get translation table
886 $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
887 // convert characters
888 return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
889}
890
b54acf3f 891/**
892 * Tests if string contains 8bit symbols.
893 *
894 * If charset is not set, function defaults to default_charset.
91e0dccc 895 * $default_charset global must be set correctly if $charset is
b54acf3f 896 * not used.
897 * @param string $string tested string
898 * @param string $charset charset used in a string
899 * @return bool true if 8bit symbols are detected
17886554 900 * @since 1.5.1 and 1.4.4
b54acf3f 901 */
902function sq_is8bit($string,$charset='') {
903 global $default_charset;
904
905 if ($charset=='') $charset=$default_charset;
906
907 /**
908 * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
17886554 909 * Don't use \200-\237 for iso-8859-x charsets. This range
b54acf3f 910 * stores control symbols in those charsets.
911 * Use preg_match instead of ereg in order to avoid problems
912 * with mbstring overloading
913 */
914 if (preg_match("/^iso-8859/i",$charset)) {
915 $needle='/\240|[\241-\377]/';
916 } else {
917 $needle='/[\200-\237]|\240|[\241-\377]/';
918 }
919 return preg_match("$needle",$string);
920}
921
922/**
923 * Replacement of mb_list_encodings function
924 *
925 * This function provides replacement for function that is available only
926 * in php 5.x. Function does not test all mbstring encodings. Only the ones
927 * that might be used in SM translations.
928 *
17886554 929 * Supported strings are stored in session in order to reduce number of
b54acf3f 930 * mb_internal_encoding function calls.
931 *
91e0dccc 932 * If you want to test all mbstring encodings - fill $list_of_encodings
b54acf3f 933 * array.
17886554 934 * @return array list of encodings supported by php mbstring extension
7fe4b6ed 935 * @since 1.5.1 and 1.4.6
b54acf3f 936 */
937function sq_mb_list_encodings() {
938 if (! function_exists('mb_internal_encoding'))
939 return array();
940
31310ecd 941 // php 5+ function
942 if (function_exists('mb_list_encodings')) {
943 $ret = mb_list_encodings();
944 array_walk($ret,'sq_lowercase_array_vals');
945 return $ret;
946 }
947
b54acf3f 948 // don't try to test encodings, if they are already stored in session
949 if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION))
950 return $mb_supported_encodings;
951
952 // save original encoding
953 $orig_encoding=mb_internal_encoding();
954
955 $list_of_encoding=array(
956 'pass',
957 'auto',
958 'ascii',
959 'jis',
960 'utf-8',
961 'sjis',
962 'euc-jp',
963 'iso-8859-1',
964 'iso-8859-2',
965 'iso-8859-7',
966 'iso-8859-9',
967 'iso-8859-15',
968 'koi8-r',
969 'koi8-u',
970 'big5',
971 'gb2312',
98abf408 972 'gb18030',
b54acf3f 973 'windows-1251',
974 'windows-1255',
975 'windows-1256',
976 'tis-620',
977 'iso-2022-jp',
ba40ff8b 978 'euc-cn',
b54acf3f 979 'euc-kr',
ba40ff8b 980 'euc-tw',
981 'uhc',
b54acf3f 982 'utf7-imap');
983
984 $supported_encodings=array();
985
986 foreach ($list_of_encoding as $encoding) {
987 // try setting encodings. suppress warning messages
988 if (@mb_internal_encoding($encoding))
989 $supported_encodings[]=$encoding;
990 }
991
992 // restore original encoding
993 mb_internal_encoding($orig_encoding);
994
995 // register list in session
996 sqsession_register($supported_encodings,'mb_supported_encodings');
997
998 return $supported_encodings;
999}
1000
c7aff938 1001/**
31310ecd 1002 * Callback function used to lowercase array values.
1003 * @param string $val array value
1004 * @param mixed $key array key
7fe4b6ed 1005 * @since 1.5.1 and 1.4.6
31310ecd 1006 */
1007function sq_lowercase_array_vals(&$val,$key) {
1008 $val = strtolower($val);
1009}
1010
1011
1012/**
c7aff938 1013 * Function returns number of characters in string.
1014 *
1015 * Returned number might be different from number of bytes in string,
91c27aee 1016 * if $charset is multibyte charset. Detection depends on mbstring
98abf408 1017 * functions. If mbstring does not support tested multibyte charset,
91c27aee 1018 * vanilla string length function is used.
c7aff938 1019 * @param string $str string
1020 * @param string $charset charset
7fe4b6ed 1021 * @since 1.5.1 and 1.4.6
91c27aee 1022 * @return integer number of characters in string
c7aff938 1023 */
31310ecd 1024function sq_strlen($str, $charset=null){
c7aff938 1025 // default option
31310ecd 1026 if (is_null($charset)) return strlen($str);
1027
1028 // lowercase charset name
1029 $charset=strtolower($charset);
c7aff938 1030
1031 // use automatic charset detection, if function call asks for it
1032 if ($charset=='auto') {
37780b3e 1033 global $default_charset, $squirrelmail_language;
c7aff938 1034 set_my_charset();
1035 $charset=$default_charset;
37780b3e 1036 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
c7aff938 1037 }
1038
98abf408 1039 // Use mbstring only with listed charsets
1040 $aList_of_mb_charsets=array('utf-8','big5','gb2312','gb18030','euc-jp','euc-cn','euc-tw','euc-kr');
c7aff938 1041
1042 // calculate string length according to charset
98abf408 1043 if (in_array($charset,$aList_of_mb_charsets) && in_array($charset,sq_mb_list_encodings())) {
1044 $real_length = mb_strlen($str,$charset);
c7aff938 1045 } else {
91c27aee 1046 // own strlen detection code is removed because missing strpos,
98abf408 1047 // strtoupper and substr implementations break string wrapping.
c7aff938 1048 $real_length=strlen($str);
1049 }
1050 return $real_length;
1051}
1052
17886554 1053/**
1054 * string padding with multibyte support
1055 *
1056 * @link http://www.php.net/str_pad
1057 * @param string $string original string
1058 * @param integer $width padded string width
1059 * @param string $pad padding symbols
91c27aee 1060 * @param integer $padtype padding type
17886554 1061 * (internal php defines, see str_pad() description)
1062 * @param string $charset charset used in original string
1063 * @return string padded string
1064 */
1065function sq_str_pad($string, $width, $pad, $padtype, $charset='') {
1066
1067 $charset = strtolower($charset);
1068 $padded_string = '';
1069
1070 switch ($charset) {
1071 case 'utf-8':
1072 case 'big5':
1073 case 'gb2312':
1074 case 'euc-kr':
1075 /*
1076 * all multibyte charsets try to increase width value by
1077 * adding difference between number of bytes and real length
1078 */
1079 $width = $width - sq_strlen($string,$charset) + strlen($string);
1080 default:
1081 $padded_string=str_pad($string,$width,$pad,$padtype);
1082 }
1083 return $padded_string;
1084}
98abf408 1085
1086/**
1087 * Wrapper that is used to switch between vanilla and multibyte substr
1088 * functions.
1089 * @param string $string
1090 * @param integer $start
1091 * @param integer $length
1092 * @param string $charset
1093 * @return string
1094 * @since 1.5.1
1095 * @link http://www.php.net/substr
1096 * @link http://www.php.net/mb_substr
1097 */
c19e5483 1098function sq_substr($string,$start,$length=NULL,$charset='auto') {
1099
1100 // if $length is NULL, use the full string length...
1101 // we have to do this to mimick the use of substr()
1102 // where $length is not given
1103 //
1104 if (is_null($length))
1105 $length = sq_strlen($length);
1106
1107
98abf408 1108 // use automatic charset detection, if function call asks for it
17b097be 1109 static $charset_auto, $bUse_mb;
1110
98abf408 1111 if ($charset=='auto') {
17b097be 1112 if (!isset($charset_auto)) {
1113 global $default_charset, $squirrelmail_language;
1114 set_my_charset();
1115 $charset=$default_charset;
1116 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1117 $charset_auto = $charset;
1118 } else {
1119 $charset = $charset_auto;
1120 }
98abf408 1121 }
1122 $charset = strtolower($charset);
17b097be 1123
1124 // in_array call is expensive => do it once and use a static var for
1125 // storing the results
1126 if (!isset($bUse_mb)) {
1127 if (in_array($charset,sq_mb_list_encodings())) {
1128 $bUse_mb = true;
1129 } else {
1130 $bUse_mb = false;
1131 }
1132 }
1133
1134 if ($bUse_mb) {
98abf408 1135 return mb_substr($string,$start,$length,$charset);
1136 }
1137 // TODO: add mbstring independent code
1138
1139 // use vanilla string functions as last option
1140 return substr($string,$start,$length);
1141}
1142
1143/**
c19e5483 1144 * This is a replacement for PHP's substr_replace() that is
1145 * multibyte-aware.
1146 *
1147 * @param string $string The string to operate upon
1148 * @param string $replacement The string to be inserted
1149 * @param int $start The offset at which to begin substring replacement
1150 * @param int $length The number of characters after $start to remove
1151 * NOTE that if you need to specify a charset but
1152 * want to achieve normal substr_replace() behavior
1153 * where $length is not specified, use NULL (OPTIONAL;
1154 * default from $start to end of string)
1155 * @param string $charset The charset of the given string. A value of NULL
1156 * here will force the use of PHP's standard substr().
1157 * (OPTIONAL; default is "auto", which indicates that
1158 * the user's current charset should be used).
1159 *
1160 * @return string The manipulated string
1161 *
1162 * Of course, you can use more advanced (e.g., negative) values
1163 * for $start and $length as needed - see the PHP manual for more
1164 * information: http://www.php.net/manual/function.substr-replace.php
1165 *
1166 */
1167function sq_substr_replace($string, $replacement, $start, $length=NULL,
1168 $charset='auto')
1169{
1170
1171 // NULL charset? Just use substr_replace()
1172 //
1173 if (is_null($charset))
1174 return is_null($length) ? substr_replace($string, $replacement, $start)
1175 : substr_replace($string, $replacement, $start, $length);
1176
1177
1178 // use current character set?
1179 //
1180 if ($charset == 'auto')
1181 {
1182//FIXME: is there any reason why this cannot be a global flag used by all string wrapper functions?
1183 static $auto_charset;
1184 if (!isset($auto_charset))
1185 {
1186 global $default_charset;
1187//FIXME - do we need this?
1188global $squirrelmail_language;
1189 set_my_charset();
1190 $auto_charset = $default_charset;
1191//FIXME - do we need this?
1192if ($squirrelmail_language == 'ja_JP') $auto_charset = 'euc-jp';
1193 }
1194 $charset = $auto_charset;
1195 }
1196
1197
1198 // standardize character set name
1199 //
1200 $charset = strtolower($charset);
1201
1202
1203/* ===== 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
1204 // only use mbstring with the following character sets
1205 //
1206 $sq_substr_replace_mb_charsets = array(
1207 'utf-8',
1208 'big5',
1209 'gb2312',
1210 'gb18030',
1211 'euc-jp',
1212 'euc-cn',
1213 'euc-tw',
1214 'euc-kr'
1215 );
1216
1217
1218 // now we can use our own implementation using
1219 // mb_substr() and mb_strlen() if needed
1220 //
1221 if (in_array($charset, $sq_substr_replace_mb_charsets)
1222 && in_array($charset, sq_mb_list_encodings()))
1223===== */
1224//FIXME: is there any reason why this cannot be a global array used by all string wrapper functions?
1225 if (in_array($charset, sq_mb_list_encodings()))
1226 {
1227
1228 $string_length = mb_strlen($string, $charset);
1229
1230 if ($start < 0)
1231 $start = max(0, $string_length + $start);
1232
1233 else if ($start > $string_length)
1234 $start = $string_length;
1235
1236 if ($length < 0)
1237 $length = max(0, $string_length - $start + $length);
1238
1239 else if (is_null($length) || $length > $string_length)
1240 $length = $string_length;
1241
1242 if ($start + $length > $string_length)
1243 $length = $string_length - $start;
1244
1245 return mb_substr($string, 0, $start, $charset)
1246 . $replacement
1247 . mb_substr($string,
1248 $start + $length,
1249 $string_length, // FIXME: I can't see why this is needed: - $start - $length,
1250 $charset);
1251
1252 }
1253
1254
1255 // else use normal substr_replace()
1256 //
1257 return is_null($length) ? substr_replace($string, $replacement, $start)
1258 : substr_replace($string, $replacement, $start, $length);
1259
1260}
1261
1262/**
98abf408 1263 * Wrapper that is used to switch between vanilla and multibyte strpos
1264 * functions.
1265 * @param string $haystack
1266 * @param mixed $needle
1267 * @param integer $offset
1268 * @param string $charset
1269 * @return string
1270 * @since 1.5.1
1271 * @link http://www.php.net/strpos
1272 * @link http://www.php.net/mb_strpos
1273 */
1274function sq_strpos($haystack,$needle,$offset,$charset='auto') {
1275 // use automatic charset detection, if function call asks for it
17b097be 1276 static $charset_auto, $bUse_mb;
1277
98abf408 1278 if ($charset=='auto') {
17b097be 1279 if (!isset($charset_auto)) {
1280 global $default_charset, $squirrelmail_language;
1281 set_my_charset();
1282 $charset=$default_charset;
1283 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1284 $charset_auto = $charset;
1285 } else {
1286 $charset = $charset_auto;
1287 }
98abf408 1288 }
1289 $charset = strtolower($charset);
17b097be 1290
1291 // in_array call is expensive => do it once and use a static var for
1292 // storing the results
1293 if (!isset($bUse_mb)) {
1294 if (in_array($charset,sq_mb_list_encodings())) {
1295 $bUse_mb = true;
1296 } else {
1297 $bUse_mb = false;
1298 }
1299 }
1300 if ($bUse_mb) {
98abf408 1301 return mb_strpos($haystack,$needle,$offset,$charset);
1302 }
1303 // TODO: add mbstring independent code
1304
1305 // use vanilla string functions as last option
1306 return strpos($haystack,$needle,$offset);
1307}
1308
1309/**
1310 * Wrapper that is used to switch between vanilla and multibyte strtoupper
1311 * functions.
1312 * @param string $string
1313 * @param string $charset
1314 * @return string
1315 * @since 1.5.1
1316 * @link http://www.php.net/strtoupper
1317 * @link http://www.php.net/mb_strtoupper
1318 */
1319function sq_strtoupper($string,$charset='auto') {
1320 // use automatic charset detection, if function call asks for it
17b097be 1321 static $charset_auto, $bUse_mb;
1322
98abf408 1323 if ($charset=='auto') {
17b097be 1324 if (!isset($charset_auto)) {
1325 global $default_charset, $squirrelmail_language;
1326 set_my_charset();
1327 $charset=$default_charset;
1328 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1329 $charset_auto = $charset;
1330 } else {
1331 $charset = $charset_auto;
1332 }
98abf408 1333 }
1334 $charset = strtolower($charset);
17b097be 1335
1336 // in_array call is expensive => do it once and use a static var for
1337 // storing the results
1338 if (!isset($bUse_mb)) {
1339 if (function_exists('mb_strtoupper') &&
1340 in_array($charset,sq_mb_list_encodings())) {
1341 $bUse_mb = true;
1342 } else {
1343 $bUse_mb = false;
1344 }
1345 }
1346
1347 if ($bUse_mb) {
98abf408 1348 return mb_strtoupper($string,$charset);
1349 }
1350 // TODO: add mbstring independent code
1351
1352 // use vanilla string functions as last option
1353 return strtoupper($string);
1354}
a24cf710 1355
1356/**
1357 * Counts 8bit bytes in string
1358 * @param string $string tested string
1359 * @return integer number of 8bit bytes
1360 */
1361function sq_count8bit($string) {
1362 $count=0;
1363 for ($i=0; $i<strlen($string); $i++) {
1364 if (ord($string[$i]) > 127) $count++;
1365 }
1366 return $count;
1367}
7f62aaef 1368
86e6a9eb 1369/**
1370 * Callback function to trim whitespace from a value, to be used in array_walk
1371 * @param string $value value to trim
1372 * @since 1.5.2 and 1.4.7
1373 */
1374function sq_trim_value ( &$value ) {
1375 $value = trim($value);
1376}
199a9ab8 1377
1378/**
c19e5483 1379 * Truncates the given string so that it has at
1380 * most $max_chars characters. NOTE that a "character"
1381 * may be a multibyte character, or (optionally), an
1382 * HTML entity , so this function is different than
1383 * using substr() or mb_substr().
1384 *
1385 * NOTE that if $elipses is given and used, the returned
1386 * number of characters will be $max_chars PLUS the
1387 * length of $elipses
1388 *
1389 * @param string $string The string to truncate
1390 * @param int $max_chars The maximum allowable characters
1391 * @param string $elipses A string that will be added to
1392 * the end of the truncated string
1393 * (ONLY if it is truncated) (OPTIONAL;
1394 * default not used)
1395 * @param boolean $html_entities_as_chars Whether or not to keep
1396 * HTML entities together
1397 * (OPTIONAL; default ignore
1398 * HTML entities)
1399 *
1400 * @return string The truncated string
1401 *
1402 * @since 1.4.20 and 1.5.2 (replaced truncateWithEntities())
1403 *
1404 */
1405function sm_truncate_string($string, $max_chars, $elipses='',
1406 $html_entities_as_chars=FALSE)
1407{
1408
1409 // if the length of the string is less than
1410 // the allowable number of characters, just
1411 // return it as is (even if it contains any
1412 // HTML entities, that would just make the
1413 // actual length even smaller)
1414 //
1415 $actual_strlen = sq_strlen($string, 'auto');
1416 if ($max_chars <= 0 || $actual_strlen <= $max_chars)
1417 return $string;
1418
1419
1420 // if needed, count the number of HTML entities in
1421 // the string up to the maximum character limit,
1422 // pushing that limit up for each entity found
1423 //
1424 $adjusted_max_chars = $max_chars;
1425 if ($html_entities_as_chars)
1426 {
1427
2f3be406 1428 // $loop_count is needed to prevent an endless loop
1429 // which is caused by buggy mbstring versions that
1430 // return 0 (zero) instead of FALSE in some rare
1431 // cases. Thanks, PHP.
1432 // see: http://bugs.php.net/bug.php?id=52731
1433 // also: tracker $3053349
1434 //
1435 $loop_count = 0;
1436 $entity_pos = $entity_end_pos = -1;
1437 while ($entity_end_pos + 1 < $actual_strlen
1438 && ($entity_pos = sq_strpos($string, '&', $entity_end_pos + 1)) !== FALSE
c19e5483 1439 && ($entity_end_pos = sq_strpos($string, ';', $entity_pos)) !== FALSE
2f3be406 1440 && $entity_pos <= $adjusted_max_chars
1441 && $loop_count++ < $max_chars)
c19e5483 1442 {
1443 $adjusted_max_chars += $entity_end_pos - $entity_pos;
1444 }
1445
1446
1447 // this isn't necessary because sq_substr() would figure this
1448 // out anyway, but we can avoid a sq_substr() call and we
1449 // know that we don't have to add an elipses (this is now
1450 // an accurate comparison, since $adjusted_max_chars, like
1451 // $actual_strlen, does not take into account HTML entities)
1452 //
1453 if ($actual_strlen <= $adjusted_max_chars)
1454 return $string;
1455
1456 }
1457
1458
1459 // get the truncated string
1460 //
1461 $truncated_string = sq_substr($string, 0, $adjusted_max_chars);
1462
1463
1464 // return with added elipses
1465 //
1466 return $truncated_string . $elipses;
1467
1468}
1469
1470/**
199a9ab8 1471 * Gathers the list of secuirty tokens currently
1472 * stored in the user's preferences and optionally
1473 * purges old ones from the list.
1474 *
1475 * @param boolean $purge_old Indicates if old tokens
1476 * should be purged from the
e1bab38c 1477 * list ("old" is 2 days or
199a9ab8 1478 * older unless the administrator
1479 * overrides that value using
d20dfddd 1480 * $max_token_age_days in
199a9ab8 1481 * config/config_local.php)
1482 * (OPTIONAL; default is to always
1483 * purge old tokens)
1484 *
1485 * @return array The list of tokens
1486 *
1487 * @since 1.4.19 and 1.5.2
1488 *
1489 */
1490function sm_get_user_security_tokens($purge_old=TRUE)
1491{
1492
382075ff 1493 global $data_dir, $username, $max_token_age_days,
1494 $use_expiring_security_tokens;
199a9ab8 1495
1496 $tokens = getPref($data_dir, $username, 'security_tokens', '');
1497 if (($tokens = unserialize($tokens)) === FALSE || !is_array($tokens))
1498 $tokens = array();
1499
1500 // purge old tokens if necessary
1501 //
1502 if ($purge_old)
1503 {
e1bab38c 1504 if (empty($max_token_age_days)) $max_token_age_days = 2;
199a9ab8 1505 $now = time();
1506 $discard_token_date = $now - ($max_token_age_days * 86400);
1507 $cleaned_tokens = array();
1508 foreach ($tokens as $token => $timestamp)
1509 if ($timestamp >= $discard_token_date)
1510 $cleaned_tokens[$token] = $timestamp;
1511 $tokens = $cleaned_tokens;
1512 }
1513
1514 return $tokens;
1515
1516}
1517
1518/**
1519 * Generates a security token that is then stored in
1520 * the user's preferences with a timestamp for later
382075ff 1521 * verification/use (although session-based tokens
1522 * are not stored in user preferences).
1523 *
1524 * NOTE: By default SquirrelMail will use a single session-based
1525 * token, but if desired, user tokens can have expiration
1526 * dates associated with them and become invalid even during
1527 * the same login session. When in that mode, the note
1528 * immediately below applies, otherwise it is irrelevant.
1529 * To enable that mode, the administrator must add the
1530 * following to config/config_local.php:
1531 * $use_expiring_security_tokens = TRUE;
199a9ab8 1532 *
d20dfddd 1533 * NOTE: The administrator can force SquirrelMail to generate
1534 * a new token every time one is requested (which may increase
1535 * obscurity through token randomness at the cost of some
1536 * performance) by adding the following to
1537 * config/config_local.php: $do_not_use_single_token = TRUE;
1538 * Otherwise, only one token will be generated per user which
1539 * will change only after it expires or is used outside of the
1540 * validity period specified when calling sm_validate_security_token()
1541 *
199a9ab8 1542 * WARNING: If the administrator has turned the token system
1543 * off by setting $disable_security_tokens to TRUE in
f34bb4e3 1544 * config/config.php or the configuration tool, this
1545 * function will not store tokens in the user
1546 * preferences (but it will still generate and return
1547 * a random string).
199a9ab8 1548 *
d20dfddd 1549 * @param boolean $force_generate_new When TRUE, a new token will
1550 * always be created even if current
1551 * configuration dictates otherwise
a0fef6da 1552 * (OPTIONAL; default FALSE)
d20dfddd 1553 *
c632a9e8 1554 * @return string A security token
199a9ab8 1555 *
1556 * @since 1.4.19 and 1.5.2
1557 *
1558 */
d20dfddd 1559function sm_generate_security_token($force_generate_new=FALSE)
199a9ab8 1560{
1561
382075ff 1562 global $data_dir, $username, $disable_security_tokens, $do_not_use_single_token,
1563 $use_expiring_security_tokens;
199a9ab8 1564 $max_generation_tries = 1000;
1565
382075ff 1566 // if we're using session-based tokens, just return
1567 // the same one every time (generate it if it's not there)
1568 //
1569 if (!$use_expiring_security_tokens)
1570 {
1571 if (sqgetGlobalVar('sm_security_token', $token, SQ_SESSION))
1572 return $token;
1573
1574 // create new one since there was none in session
1575 $token = GenerateRandomString(12, '', 7);
1576 sqsession_register($token, 'sm_security_token');
1577 return $token;
1578 }
1579
199a9ab8 1580 $tokens = sm_get_user_security_tokens();
1581
d20dfddd 1582 if (!$force_generate_new && !$do_not_use_single_token && !empty($tokens))
1583 return key($tokens);
1584
199a9ab8 1585 $new_token = GenerateRandomString(12, '', 7);
1586 $count = 0;
1587 while (isset($tokens[$new_token]))
1588 {
1589 $new_token = GenerateRandomString(12, '', 7);
1590 if (++$count > $max_generation_tries)
1591 {
1592 logout_error(_("Fatal token generation error; please contact your system administrator or the SquirrelMail Team"));
1593 exit;
1594 }
1595 }
1596
1597 // is the token system enabled? CAREFUL!
1598 //
1599 if (!$disable_security_tokens)
1600 {
1601 $tokens[$new_token] = time();
1602 setPref($data_dir, $username, 'security_tokens', serialize($tokens));
1603 }
1604
1605 return $new_token;
1606
1607}
1608
1609/**
1610 * Validates a given security token and optionally remove it
1611 * from the user's preferences if it was valid. If the token
1612 * is too old but otherwise valid, it will still be rejected.
1613 *
e1bab38c 1614 * "Too old" is 2 days or older unless the administrator
d20dfddd 1615 * overrides that value using $max_token_age_days in
199a9ab8 1616 * config/config_local.php
1617 *
382075ff 1618 * Session-based tokens of course are always reused and are
1619 * valid for the lifetime of the login session.
1620 *
199a9ab8 1621 * WARNING: If the administrator has turned the token system
1622 * off by setting $disable_security_tokens to TRUE in
f34bb4e3 1623 * config/config.php or the configuration tool, this
1624 * function will always return TRUE.
199a9ab8 1625 *
1626 * @param string $token The token to validate
1627 * @param int $validity_period The number of seconds tokens are valid
1628 * for (set to zero to remove valid tokens
2cefa62a 1629 * after only one use; set to -1 to allow
1630 * indefinite re-use (but still subject to
1631 * $max_token_age_days - see elsewhere);
1632 * use 3600 to allow tokens to be reused for
1633 * an hour) (OPTIONAL; default is to only
1634 * allow tokens to be used once)
d20dfddd 1635 * NOTE this is unrelated to $max_token_age_days
1636 * or rather is an additional time constraint on
1637 * tokens that allows them to be re-used (or not)
1638 * within a more narrow timeframe
199a9ab8 1639 * @param boolean $show_error Indicates that if the token is not
1640 * valid, this function should display
1641 * a generic error, log the user out
1642 * and exit - this function will never
1643 * return in that case.
1644 * (OPTIONAL; default FALSE)
1645 *
1646 * @return boolean TRUE if the token validated; FALSE otherwise
1647 *
1648 * @since 1.4.19 and 1.5.2
1649 *
1650 */
1651function sm_validate_security_token($token, $validity_period=0, $show_error=FALSE)
1652{
1653
1654 global $data_dir, $username, $max_token_age_days,
382075ff 1655 $use_expiring_security_tokens,
199a9ab8 1656 $disable_security_tokens;
1657
1658 // bypass token validation? CAREFUL!
1659 //
1660 if ($disable_security_tokens) return TRUE;
1661
382075ff 1662 // if we're using session-based tokens, just compare
1663 // the same one every time
1664 //
1665 if (!$use_expiring_security_tokens)
1666 {
1667 if (!sqgetGlobalVar('sm_security_token', $session_token, SQ_SESSION))
1668 {
1669 if (!$show_error) return FALSE;
1670 logout_error(_("Fatal security token error; please log in again"));
1671 exit;
1672 }
1673 if ($token !== $session_token)
1674 {
1675 if (!$show_error) return FALSE;
1676 logout_error(_("The current page request appears to have originated from an untrusted source."));
1677 exit;
1678 }
1679 return TRUE;
1680 }
1681
199a9ab8 1682 // don't purge old tokens here because we already
1683 // do it when generating tokens
1684 //
1685 $tokens = sm_get_user_security_tokens(FALSE);
1686
1687 // token not found?
1688 //
1689 if (empty($tokens[$token]))
1690 {
1691 if (!$show_error) return FALSE;
1692 logout_error(_("This page request could not be verified and appears to have expired."));
1693 exit;
1694 }
1695
1696 $now = time();
1697 $timestamp = $tokens[$token];
1698
1699 // whether valid or not, we want to remove it from
2cefa62a 1700 // user prefs if it's old enough (unless requested to
1701 // bypass this (in which case $validity_period is -1))
199a9ab8 1702 //
2cefa62a 1703 if ($validity_period >= 0
1704 && $timestamp < $now - $validity_period)
199a9ab8 1705 {
1706 unset($tokens[$token]);
1707 setPref($data_dir, $username, 'security_tokens', serialize($tokens));
1708 }
1709
1710 // reject tokens that are too old
1711 //
e1bab38c 1712 if (empty($max_token_age_days)) $max_token_age_days = 2;
199a9ab8 1713 $old_token_date = $now - ($max_token_age_days * 86400);
1714 if ($timestamp < $old_token_date)
1715 {
1716 if (!$show_error) return FALSE;
1717 logout_error(_("The current page request appears to have originated from an untrusted source."));
1718 exit;
1719 }
1720
1721 // token OK!
1722 //
1723 return TRUE;
1724
1725}
1726
3047e291 1727/**
1728 * Wrapper for PHP's htmlspecialchars() that
1729 * attempts to add the correct character encoding
1730 *
1731 * @param string $string The string to be converted
1732 * @param int $flags A bitmask that controls the behavior of htmlspecialchars()
1733 * (See http://php.net/manual/function.htmlspecialchars.php )
95fde4c8 1734 * (OPTIONAL; default ENT_COMPAT, ENT_COMPAT | ENT_SUBSTITUTE for PHP >=5.4)
3047e291 1735 * @param string $encoding The character encoding to use in the conversion
1736 * (OPTIONAL; default automatic detection)
1737 * @param boolean $double_encode Whether or not to convert entities that are
1738 * already in the string (only supported in
1739 * PHP 5.2.3+) (OPTIONAL; default TRUE)
1740 *
1741 * @return string The converted text
1742 *
1743 */
1744function sm_encode_html_special_chars($string, $flags=ENT_COMPAT,
1745 $encoding=NULL, $double_encode=TRUE)
1746{
1747 if (!$encoding)
1748 {
1749 global $default_charset;
1750 if ($default_charset == 'iso-2022-jp')
1751 $default_charset = 'EUC-JP';
1752 $encoding = $default_charset;
1753 }
1754
95fde4c8 1755 if (check_php_version(5, 2, 3)) {
1756 // Replace invalid characters with a symbol instead of returning
1757 // empty string for the entire to be encoded string.
1758 if (check_php_version(5, 4, 0) && $flags == ENT_COMPAT) {
1759 $flags = $flags | ENT_SUBSTITUTE;
1760 }
3047e291 1761 return htmlspecialchars($string, $flags, $encoding, $double_encode);
95fde4c8 1762 }
3047e291 1763
1764 return htmlspecialchars($string, $flags, $encoding);
1765}
1766