Stop using session_unregister()
[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 *
d4e46166 9 * @copyright &copy; 1999-2009 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
c9d61baf 15/**
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
5e7ae713 56/**
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
c9d61baf 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
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
5cc0b70e 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 *
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
5cc0b70e 352 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
353 $beginning_spaces = $regs[1];
354 if (isset($regs[2])) {
355 $words = explode(' ', $regs[2]);
356 } else {
357 $words = '';
358 }
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
341abbd6 393/**
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
66239b65 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.
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
66239b65 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 */
f1ca21bd 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, '/'));
74530cf4 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:
238703be 489 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
490 return $full_url . $path;
491 }
74530cf4 492 // else: autodetect
238703be 493
66239b65 494 /* Check if this is a HTTPS or regular HTTP request. */
495 $proto = 'http://';
8f557b94 496 if ($is_secure_connection)
8a549df2 497 $proto = 'https://';
f1ca21bd 498
4deb32f1 499 /* Get the hostname from the Host header or server config. */
8f557b94 500 if ($sq_ignore_http_x_forwarded_headers
501 || !sqgetGlobalVar('HTTP_X_FORWARDED_HOST', $host, SQ_SERVER)
502 || empty($host)) {
0a0f05c6 503 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
504 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
505 $host = '';
506 }
507 }
66239b65 508 }
f1ca21bd 509
66239b65 510 $port = '';
511 if (! strstr($host, ':')) {
154dda4a 512 // Note: HTTP_X_FORWARDED_PROTO could be sent from the client and
01f013c1 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.
154dda4a 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 = '';
961ca3d8 522 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
f1ca21bd 523 if (($server_port != 80 && $proto == 'http://') ||
6a0c35d4 524 ($server_port != 443 && $proto == 'https://' &&
8c64fc5a 525 strcasecmp($forwarded_proto, 'https') !== 0)) {
961ca3d8 526 $port = sprintf(':%d', $server_port);
66239b65 527 }
528 }
529 }
f1ca21bd 530
74530cf4 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 */
f1ca21bd 534
74530cf4 535 if ($imap_server_type == 'macosx' && $port == ':16080') {
8de7f698 536 $port = '';
74530cf4 537 }
f1ca21bd 538
74530cf4 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;
66239b65 544}
dcaf2a49 545
9374671f 546
c4dcda23 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 */
560function 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
66239b65 573/**
4445e6b3 574 * Encrypts password
575 *
8b096f0a 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 *
31310ecd 580 * @param string $string the (password)string to encrypt
581 * @param string $epad the encryption key
8b096f0a 582 * @return string the base64-encoded encrypted password
31310ecd 583 * @since 1.0
66239b65 584 */
585function OneTimePadEncrypt ($string, $epad) {
586 $pad = base64_decode($epad);
432db2fc 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
66239b65 597 $encrypted = '';
598 for ($i = 0; $i < strlen ($string); $i++) {
599 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
600 }
f1ca21bd 601
66239b65 602 return base64_encode($encrypted);
603}
604
8b096f0a 605/**
4445e6b3 606 * Decrypts a password from the cookie
607 *
608 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
8b096f0a 609 * This uses the encryption key that is stored in the session.
610 *
31310ecd 611 * @param string $string the string to decrypt
612 * @param string $epad the encryption key from the session
8b096f0a 613 * @return string the decrypted password
31310ecd 614 * @since 1.0
8b096f0a 615 */
66239b65 616function OneTimePadDecrypt ($string, $epad) {
617 $pad = base64_decode($epad);
432db2fc 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
66239b65 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 }
f1ca21bd 633
66239b65 634 return $decrypted;
635}
9374671f 636
8b096f0a 637/**
4445e6b3 638 * Creates encryption key
639 *
8b096f0a 640 * Creates an encryption key for encrypting the password stored in the cookie.
641 * The encryption key itself is stored in the session.
642 *
31310ecd 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
8b096f0a 645 * @return string the encryption key
31310ecd 646 * @since 1.0
8b096f0a 647 */
66239b65 648function OneTimePadCreate ($length=100) {
66239b65 649 $pad = '';
650 for ($i = 0; $i < $length; $i++) {
651 $pad .= chr(mt_rand(0,255));
652 }
f1ca21bd 653
66239b65 654 return base64_encode($pad);
655}
9374671f 656
66239b65 657/**
8b096f0a 658 * Returns a string showing the size of the message/attachment.
659 *
31310ecd 660 * @param int $bytes the filesize in bytes
8b096f0a 661 * @return string the filesize in human readable format
31310ecd 662 * @since 1.0
66239b65 663 */
664function show_readable_size($bytes) {
665 $bytes /= 1024;
ffde32e0 666 $type = _("KiB");
f1ca21bd 667
66239b65 668 if ($bytes / 1024 > 1) {
669 $bytes /= 1024;
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
91c27aee 681 return $bytes . '&nbsp;' . $type;
66239b65 682}
9374671f 683
66239b65 684/**
c7aff938 685 * Generates a random string from the character set you pass in
66239b65 686 *
31310ecd 687 * @param int $size the length of the string to generate
688 * @param string $chars a string containing the characters to use
689 * @param int $flags a flag to add a specific set to the characters to use:
8b096f0a 690 * Flags:
691 * 1 = add lowercase a-z to $chars
692 * 2 = add uppercase A-Z to $chars
693 * 4 = add numbers 0-9 to $chars
694 * @return string the random string
31310ecd 695 * @since 1.0
66239b65 696 */
66239b65 697function GenerateRandomString($size, $chars, $flags = 0) {
698 if ($flags & 0x1) {
699 $chars .= 'abcdefghijklmnopqrstuvwxyz';
700 }
701 if ($flags & 0x2) {
702 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
703 }
704 if ($flags & 0x4) {
705 $chars .= '0123456789';
706 }
f1ca21bd 707
66239b65 708 if (($size < 1) || (strlen($chars) < 1)) {
709 return '';
710 }
ff4f08ff 711
4deb32f1 712 $String = '';
ff4f08ff 713 $j = strlen( $chars ) - 1;
66239b65 714 while (strlen($String) < $size) {
ff4f08ff 715 $String .= $chars{mt_rand(0, $j)};
66239b65 716 }
ff4f08ff 717
66239b65 718 return $String;
719}
9374671f 720
8b096f0a 721/**
722 * Escapes special characters for use in IMAP commands.
4445e6b3 723 *
31310ecd 724 * @param string $str the string to escape
8b096f0a 725 * @return string the escaped string
31310ecd 726 * @since 1.0.3
8b096f0a 727 */
fbb76d0e 728function quoteimap($str) {
ab1df059 729 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
66239b65 730}
1899535f 731
8b096f0a 732/**
4445e6b3 733 * Create compose link
734 *
8b096f0a 735 * Returns a link to the compose-page, taking in consideration
736 * the compose_in_new and javascript settings.
e740a582 737 *
738 * @param string $url The URL to the compose page
739 * @param string $text The link text, default "Compose"
740 * @param string $target URL target, if any (since 1.4.3)
741 * @param string $accesskey The access key to be used, if any
742 *
8b096f0a 743 * @return string a link to the compose page
e740a582 744 *
31310ecd 745 * @since 1.4.2
8b096f0a 746 */
c12535f6 747function makeComposeLink($url, $text = null, $target='', $accesskey='NONE') {
83aff890 748 global $compose_new_win, $compose_width,
f7b996c3 749 $compose_height, $oTemplate;
d62c4938 750
751 if(!$text) {
752 $text = _("Compose");
753 }
754
c9d61baf 755 // if not using "compose in new window", make
f72f61d8 756 // regular link and be done with it
d62c4938 757 if($compose_new_win != '1') {
e740a582 758 return makeInternalLink($url, $text, $target, $accesskey);
d62c4938 759 }
760
c9d61baf 761 // build the compose in new window link...
f72f61d8 762
763
c435f076 764 // if javascript is on, use onclick event to handle it
83aff890 765 if(checkForJavascript()) {
d62c4938 766 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
cdc4d881 767 $compuri = SM_BASE_URI.$url;
769a819d 768
e740a582 769 return create_hyperlink('javascript:void(0)', $text, '',
770 "comp_in_new('$compuri','$compose_width','$compose_height')",
771 '', '', '',
c12535f6 772 ($accesskey == 'NONE'
773 ? array()
774 : array('accesskey' => $accesskey)));
d62c4938 775 }
776
f72f61d8 777 // otherwise, just open new window using regular HTML
e740a582 778 return makeInternalLink($url, $text, '_blank', $accesskey);
d62c4938 779}
780
3ecad5e6 781/**
782 * version of fwrite which checks for failure
31310ecd 783 * @param resource $fp
784 * @param string $string
785 * @return number of written bytes. false on failure
786 * @since 1.4.3
3ecad5e6 787 */
788function sq_fwrite($fp, $string) {
c9d61baf 789 // write to file
790 $count = @fwrite($fp,$string);
791 // the number of bytes written should be the length of the string
792 if($count != strlen($string)) {
793 return FALSE;
794 }
795
796 return $count;
3ecad5e6 797}
798
36e1180b 799/**
800 * sq_get_html_translation_table
801 *
802 * Returns the translation table used by sq_htmlentities()
803 *
804 * @param integer $table html translation table. Possible values (without quotes):
deb22cec 805 * <ul>
806 * <li>HTML_ENTITIES - full html entities table defined by charset</li>
807 * <li>HTML_SPECIALCHARS - html special characters table</li>
808 * </ul>
36e1180b 809 * @param integer $quote_style quote encoding style. Possible values (without quotes):
c9d61baf 810 * <ul>
deb22cec 811 * <li>ENT_COMPAT - (default) encode double quotes</li>
812 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
813 * <li>ENT_QUOTES - encode double and single quotes</li>
c9d61baf 814 * </ul>
36e1180b 815 * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
816 * @return array html translation array
31310ecd 817 * @since 1.5.1
36e1180b 818 */
819function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
820 global $default_charset;
821
822 if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
823
824 // Start array with ampersand
825 $sq_html_ent_table = array( "&" => '&amp;' );
826
827 // < and >
828 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 829 array("<" => '&lt;',
830 ">" => '&gt;')
831 );
36e1180b 832 // double quotes
833 if ($quote_style == ENT_COMPAT)
834 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 835 array("\"" => '&quot;')
836 );
36e1180b 837
838 // double and single quotes
839 if ($quote_style == ENT_QUOTES)
840 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 841 array("\"" => '&quot;',
842 "'" => '&#39;')
843 );
36e1180b 844
845 if ($charset=='auto') $charset=$default_charset;
846
847 // add entities that depend on charset
848 switch($charset){
849 case 'iso-8859-1':
850 include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
851 break;
852 case 'utf-8':
853 include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
854 break;
855 case 'us-ascii':
856 default:
857 break;
858 }
859 // return table
860 return $sq_html_ent_table;
861}
862
863/**
864 * sq_htmlentities
865 *
866 * Convert all applicable characters to HTML entities.
17886554 867 * Minimal php requirement - v.4.0.5.
868 *
869 * Function is designed for people that want to use full power of htmlentities() in
870 * i18n environment.
36e1180b 871 *
872 * @param string $string string that has to be sanitized
873 * @param integer $quote_style quote encoding style. Possible values (without quotes):
c9d61baf 874 * <ul>
deb22cec 875 * <li>ENT_COMPAT - (default) encode double quotes</li>
876 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
877 * <li>ENT_QUOTES - encode double and single quotes</li>
c9d61baf 878 * </ul>
36e1180b 879 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
880 * @return string sanitized string
31310ecd 881 * @since 1.5.1
36e1180b 882 */
883function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
884 // get translation table
885 $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
886 // convert characters
887 return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
888}
889
b54acf3f 890/**
891 * Tests if string contains 8bit symbols.
892 *
893 * If charset is not set, function defaults to default_charset.
91e0dccc 894 * $default_charset global must be set correctly if $charset is
b54acf3f 895 * not used.
896 * @param string $string tested string
897 * @param string $charset charset used in a string
898 * @return bool true if 8bit symbols are detected
17886554 899 * @since 1.5.1 and 1.4.4
b54acf3f 900 */
901function sq_is8bit($string,$charset='') {
902 global $default_charset;
903
904 if ($charset=='') $charset=$default_charset;
905
906 /**
907 * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
17886554 908 * Don't use \200-\237 for iso-8859-x charsets. This range
b54acf3f 909 * stores control symbols in those charsets.
910 * Use preg_match instead of ereg in order to avoid problems
911 * with mbstring overloading
912 */
913 if (preg_match("/^iso-8859/i",$charset)) {
914 $needle='/\240|[\241-\377]/';
915 } else {
916 $needle='/[\200-\237]|\240|[\241-\377]/';
917 }
918 return preg_match("$needle",$string);
919}
920
921/**
922 * Replacement of mb_list_encodings function
923 *
924 * This function provides replacement for function that is available only
925 * in php 5.x. Function does not test all mbstring encodings. Only the ones
926 * that might be used in SM translations.
927 *
17886554 928 * Supported strings are stored in session in order to reduce number of
b54acf3f 929 * mb_internal_encoding function calls.
930 *
91e0dccc 931 * If you want to test all mbstring encodings - fill $list_of_encodings
b54acf3f 932 * array.
17886554 933 * @return array list of encodings supported by php mbstring extension
7fe4b6ed 934 * @since 1.5.1 and 1.4.6
b54acf3f 935 */
936function sq_mb_list_encodings() {
937 if (! function_exists('mb_internal_encoding'))
938 return array();
939
31310ecd 940 // php 5+ function
941 if (function_exists('mb_list_encodings')) {
942 $ret = mb_list_encodings();
943 array_walk($ret,'sq_lowercase_array_vals');
944 return $ret;
945 }
946
b54acf3f 947 // don't try to test encodings, if they are already stored in session
948 if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION))
949 return $mb_supported_encodings;
950
951 // save original encoding
952 $orig_encoding=mb_internal_encoding();
953
954 $list_of_encoding=array(
955 'pass',
956 'auto',
957 'ascii',
958 'jis',
959 'utf-8',
960 'sjis',
961 'euc-jp',
962 'iso-8859-1',
963 'iso-8859-2',
964 'iso-8859-7',
965 'iso-8859-9',
966 'iso-8859-15',
967 'koi8-r',
968 'koi8-u',
969 'big5',
970 'gb2312',
98abf408 971 'gb18030',
b54acf3f 972 'windows-1251',
973 'windows-1255',
974 'windows-1256',
975 'tis-620',
976 'iso-2022-jp',
ba40ff8b 977 'euc-cn',
b54acf3f 978 'euc-kr',
ba40ff8b 979 'euc-tw',
980 'uhc',
b54acf3f 981 'utf7-imap');
982
983 $supported_encodings=array();
984
985 foreach ($list_of_encoding as $encoding) {
986 // try setting encodings. suppress warning messages
987 if (@mb_internal_encoding($encoding))
988 $supported_encodings[]=$encoding;
989 }
990
991 // restore original encoding
992 mb_internal_encoding($orig_encoding);
993
994 // register list in session
995 sqsession_register($supported_encodings,'mb_supported_encodings');
996
997 return $supported_encodings;
998}
999
31310ecd 1000/**
1001 * Callback function used to lowercase array values.
1002 * @param string $val array value
1003 * @param mixed $key array key
7fe4b6ed 1004 * @since 1.5.1 and 1.4.6
31310ecd 1005 */
1006function sq_lowercase_array_vals(&$val,$key) {
1007 $val = strtolower($val);
1008}
1009
1010
c7aff938 1011/**
1012 * Function returns number of characters in string.
1013 *
1014 * Returned number might be different from number of bytes in string,
91c27aee 1015 * if $charset is multibyte charset. Detection depends on mbstring
98abf408 1016 * functions. If mbstring does not support tested multibyte charset,
91c27aee 1017 * vanilla string length function is used.
c7aff938 1018 * @param string $str string
1019 * @param string $charset charset
7fe4b6ed 1020 * @since 1.5.1 and 1.4.6
91c27aee 1021 * @return integer number of characters in string
c7aff938 1022 */
31310ecd 1023function sq_strlen($str, $charset=null){
c7aff938 1024 // default option
31310ecd 1025 if (is_null($charset)) return strlen($str);
1026
1027 // lowercase charset name
1028 $charset=strtolower($charset);
c7aff938 1029
1030 // use automatic charset detection, if function call asks for it
1031 if ($charset=='auto') {
37780b3e 1032 global $default_charset, $squirrelmail_language;
c7aff938 1033 set_my_charset();
1034 $charset=$default_charset;
37780b3e 1035 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
c7aff938 1036 }
1037
98abf408 1038 // Use mbstring only with listed charsets
1039 $aList_of_mb_charsets=array('utf-8','big5','gb2312','gb18030','euc-jp','euc-cn','euc-tw','euc-kr');
c7aff938 1040
1041 // calculate string length according to charset
98abf408 1042 if (in_array($charset,$aList_of_mb_charsets) && in_array($charset,sq_mb_list_encodings())) {
1043 $real_length = mb_strlen($str,$charset);
c7aff938 1044 } else {
91c27aee 1045 // own strlen detection code is removed because missing strpos,
98abf408 1046 // strtoupper and substr implementations break string wrapping.
c7aff938 1047 $real_length=strlen($str);
1048 }
1049 return $real_length;
1050}
1051
17886554 1052/**
1053 * string padding with multibyte support
1054 *
1055 * @link http://www.php.net/str_pad
1056 * @param string $string original string
1057 * @param integer $width padded string width
1058 * @param string $pad padding symbols
91c27aee 1059 * @param integer $padtype padding type
17886554 1060 * (internal php defines, see str_pad() description)
1061 * @param string $charset charset used in original string
1062 * @return string padded string
1063 */
1064function sq_str_pad($string, $width, $pad, $padtype, $charset='') {
1065
1066 $charset = strtolower($charset);
1067 $padded_string = '';
1068
1069 switch ($charset) {
1070 case 'utf-8':
1071 case 'big5':
1072 case 'gb2312':
1073 case 'euc-kr':
1074 /*
1075 * all multibyte charsets try to increase width value by
1076 * adding difference between number of bytes and real length
1077 */
1078 $width = $width - sq_strlen($string,$charset) + strlen($string);
1079 default:
1080 $padded_string=str_pad($string,$width,$pad,$padtype);
1081 }
1082 return $padded_string;
1083}
98abf408 1084
1085/**
1086 * Wrapper that is used to switch between vanilla and multibyte substr
1087 * functions.
1088 * @param string $string
1089 * @param integer $start
1090 * @param integer $length
1091 * @param string $charset
1092 * @return string
1093 * @since 1.5.1
1094 * @link http://www.php.net/substr
1095 * @link http://www.php.net/mb_substr
1096 */
1097function sq_substr($string,$start,$length,$charset='auto') {
1098 // use automatic charset detection, if function call asks for it
17b097be 1099 static $charset_auto, $bUse_mb;
1100
98abf408 1101 if ($charset=='auto') {
17b097be 1102 if (!isset($charset_auto)) {
1103 global $default_charset, $squirrelmail_language;
1104 set_my_charset();
1105 $charset=$default_charset;
1106 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1107 $charset_auto = $charset;
1108 } else {
1109 $charset = $charset_auto;
1110 }
98abf408 1111 }
1112 $charset = strtolower($charset);
17b097be 1113
1114 // in_array call is expensive => do it once and use a static var for
1115 // storing the results
1116 if (!isset($bUse_mb)) {
1117 if (in_array($charset,sq_mb_list_encodings())) {
1118 $bUse_mb = true;
1119 } else {
1120 $bUse_mb = false;
1121 }
1122 }
1123
1124 if ($bUse_mb) {
98abf408 1125 return mb_substr($string,$start,$length,$charset);
1126 }
1127 // TODO: add mbstring independent code
1128
1129 // use vanilla string functions as last option
1130 return substr($string,$start,$length);
1131}
1132
1133/**
1134 * Wrapper that is used to switch between vanilla and multibyte strpos
1135 * functions.
1136 * @param string $haystack
1137 * @param mixed $needle
1138 * @param integer $offset
1139 * @param string $charset
1140 * @return string
1141 * @since 1.5.1
1142 * @link http://www.php.net/strpos
1143 * @link http://www.php.net/mb_strpos
1144 */
1145function sq_strpos($haystack,$needle,$offset,$charset='auto') {
1146 // use automatic charset detection, if function call asks for it
17b097be 1147 static $charset_auto, $bUse_mb;
1148
98abf408 1149 if ($charset=='auto') {
17b097be 1150 if (!isset($charset_auto)) {
1151 global $default_charset, $squirrelmail_language;
1152 set_my_charset();
1153 $charset=$default_charset;
1154 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1155 $charset_auto = $charset;
1156 } else {
1157 $charset = $charset_auto;
1158 }
98abf408 1159 }
1160 $charset = strtolower($charset);
17b097be 1161
1162 // in_array call is expensive => do it once and use a static var for
1163 // storing the results
1164 if (!isset($bUse_mb)) {
1165 if (in_array($charset,sq_mb_list_encodings())) {
1166 $bUse_mb = true;
1167 } else {
1168 $bUse_mb = false;
1169 }
1170 }
1171 if ($bUse_mb) {
98abf408 1172 return mb_strpos($haystack,$needle,$offset,$charset);
1173 }
1174 // TODO: add mbstring independent code
1175
1176 // use vanilla string functions as last option
1177 return strpos($haystack,$needle,$offset);
1178}
1179
1180/**
1181 * Wrapper that is used to switch between vanilla and multibyte strtoupper
1182 * functions.
1183 * @param string $string
1184 * @param string $charset
1185 * @return string
1186 * @since 1.5.1
1187 * @link http://www.php.net/strtoupper
1188 * @link http://www.php.net/mb_strtoupper
1189 */
1190function sq_strtoupper($string,$charset='auto') {
1191 // use automatic charset detection, if function call asks for it
17b097be 1192 static $charset_auto, $bUse_mb;
1193
98abf408 1194 if ($charset=='auto') {
17b097be 1195 if (!isset($charset_auto)) {
1196 global $default_charset, $squirrelmail_language;
1197 set_my_charset();
1198 $charset=$default_charset;
1199 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1200 $charset_auto = $charset;
1201 } else {
1202 $charset = $charset_auto;
1203 }
98abf408 1204 }
1205 $charset = strtolower($charset);
17b097be 1206
1207 // in_array call is expensive => do it once and use a static var for
1208 // storing the results
1209 if (!isset($bUse_mb)) {
1210 if (function_exists('mb_strtoupper') &&
1211 in_array($charset,sq_mb_list_encodings())) {
1212 $bUse_mb = true;
1213 } else {
1214 $bUse_mb = false;
1215 }
1216 }
1217
1218 if ($bUse_mb) {
98abf408 1219 return mb_strtoupper($string,$charset);
1220 }
1221 // TODO: add mbstring independent code
1222
1223 // use vanilla string functions as last option
1224 return strtoupper($string);
1225}
a24cf710 1226
1227/**
1228 * Counts 8bit bytes in string
1229 * @param string $string tested string
1230 * @return integer number of 8bit bytes
1231 */
1232function sq_count8bit($string) {
1233 $count=0;
1234 for ($i=0; $i<strlen($string); $i++) {
1235 if (ord($string[$i]) > 127) $count++;
1236 }
1237 return $count;
1238}
7f62aaef 1239
86e6a9eb 1240/**
1241 * Callback function to trim whitespace from a value, to be used in array_walk
1242 * @param string $value value to trim
1243 * @since 1.5.2 and 1.4.7
1244 */
1245function sq_trim_value ( &$value ) {
1246 $value = trim($value);
1247}