Increment year in copyright notice.
[squirrelmail.git] / functions / strings.php
CommitLineData
59177427 1<?php
7350889b 2
f1ca21bd 3/**
35586184 4 * strings.php
5 *
6c84ba1e 6 * Copyright (c) 1999-2005 The SquirrelMail Project Team
35586184 7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * This code provides various string manipulation functions that are
10 * used by the rest of the Squirrelmail code.
11 *
31841a9e 12 * @version $Id$
d6c32258 13 * @package squirrelmail
35586184 14 */
9374671f 15
35586184 16/**
17 * SquirrelMail version number -- DO NOT CHANGE
18 */
19global $version;
509fc585 20$version = '1.5.1 [CVS]';
d068c0ec 21
f1ca21bd 22/**
97bdc607 23 * SquirrelMail internal version number -- DO NOT CHANGE
24 * $sm_internal_version = array (release, major, minor)
25 */
0567e4d5 26global $SQM_INTERNAL_VERSION;
a959e855 27$SQM_INTERNAL_VERSION = array(1,5,1);
87d8c725 28
87d8c725 29/**
30 * There can be a circular issue with includes, where the $version string is
31 * referenced by the include of global.php, etc. before it's defined.
32 * For that reason, bring in global.php AFTER we define the version strings.
33 */
34require_once(SM_PATH . 'functions/global.php');
97bdc607 35
c9d61baf 36/**
37 * Appends citation markers to the string.
38 * Also appends a trailing space.
39 *
40 * @author Justus Pendleton
41 *
42 * @param string str The string to append to
43 * @param int citeLevel the number of markers to append
44 * @return null
45 */
46function sqMakeCite (&$str, $citeLevel) {
47 for ($i = 0; $i < $citeLevel; $i++) {
48 $str .= '>';
49 }
50 if ($citeLevel != 0) {
51 $str .= ' ';
52 }
53}
54
55/**
56 * Create a newline in the string, adding citation
57 * markers to the newline as necessary.
58 *
59 * @author Justus Pendleton
60 *
61 * @param string str the string to make a newline in
62 * @param int citeLevel the citation level the newline is at
63 * @param int column starting column of the newline
64 * @return null
65 */
66function sqMakeNewLine (&$str, $citeLevel, &$column) {
67 $str .= "\n";
68 $column = 0;
69 if ($citeLevel > 0) {
70 sqMakeCite ($str, $citeLevel);
71 $column = $citeLevel + 1;
72 } else {
73 $column = 0;
74 }
75}
76
5e7ae713 77/**
78 * Checks for spaces in strings - only used if PHP doesn't have native ctype support
79 *
80 * @author Tomas Kuliavas
326727cf 81 *
82 * You might be able to rewrite the function by adding short evaluation form.
5e7ae713 83 *
84 * possible problems:
85 * - iso-2022-xx charsets - hex 20 might be part of other symbol. I might
86 * be wrong. 0x20 is not used in iso-2022-jp. I haven't checked iso-2022-kr
87 * and iso-2022-cn mappings.
88 *
89 * - no-break space (&nbsp;) - it is 8bit symbol, that depends on charset.
90 * there are at least three different charset groups that have nbsp in
91 * different places.
92 *
93 * I don't see any charset/nbsp options in php ctype either.
94 *
95 * @param string $string tested string
326727cf 96 * @return bool true when only whitespace symbols are present in test string
5e7ae713 97 */
98function sm_ctype_space($string) {
326727cf 99 if ( preg_match('/^[\x09-\x0D]|^\x20/', $string) || $string=='') {
100 return true;
101 } else {
102 return false;
103 }
5e7ae713 104}
105
c9d61baf 106/**
107 * Wraps text at $wrap characters. While sqWordWrap takes
108 * a single line of text and wraps it, this function works
109 * on the entire corpus at once, this allows it to be a little
110 * bit smarter and when and how to wrap.
111 *
112 * @author Justus Pendleton
113 *
114 * @param string body the entire body of text
115 * @param int wrap the maximum line length
116 * @return string the wrapped text
117 */
118function &sqBodyWrap (&$body, $wrap) {
5e7ae713 119 //check for ctype support, and fake it if it doesn't exist
120 if (!function_exists('ctype_space')) {
121 function ctype_space ($string) {
122 return sm_ctype_space($string);
123 }
124 }
125
c9d61baf 126 // the newly wrapped text
127 $outString = '';
128 // current column since the last newline in the outstring
129 $outStringCol = 0;
130 $length = strlen($body);
131 // where we are in the original string
132 $pos = 0;
133 // the number of >>> citation markers we are currently at
134 $citeLevel = 0;
135
136 // the main loop, whenever we start a newline of input text
137 // we start from here
138 while ($pos < $length) {
139 // we're at the beginning of a line, get the new cite level
140 $newCiteLevel = 0;
141
142 while (($pos < $length) && ($body{$pos} == '>')) {
143 $newCiteLevel++;
144 $pos++;
145
146 // skip over any spaces interleaved among the cite markers
147 while (($pos < $length) && ($body{$pos} == ' ')) {
bb977394 148
c9d61baf 149 $pos++;
bb977394 150
c9d61baf 151 }
152 if ($pos >= $length) {
153 break;
154 }
155 }
156
157 // special case: if this is a blank line then maintain it
158 // (i.e. try to preserve original paragraph breaks)
159 // unless they occur at the very beginning of the text
6eaf5320 160 if (($body{$pos} == "\n" ) && (strlen($outString) != 0)) {
c9d61baf 161 $outStringLast = $outString{strlen($outString) - 1};
162 if ($outStringLast != "\n") {
163 $outString .= "\n";
164 }
165 sqMakeCite ($outString, $newCiteLevel);
166 $outString .= "\n";
167 $pos++;
168 $outStringCol = 0;
169 continue;
170 }
171
172 // if the cite level has changed, then start a new line
173 // with the new cite level.
174 if (($citeLevel != $newCiteLevel) && ($pos > ($newCiteLevel + 1)) && ($outStringCol != 0)) {
175 sqMakeNewLine ($outString, 0, $outStringCol);
176 }
177
178 $citeLevel = $newCiteLevel;
179
180 // prepend the quote level if necessary
181 if ($outStringCol == 0) {
182 sqMakeCite ($outString, $citeLevel);
183 // if we added a citation then move the column
184 // out by citelevel + 1 (the cite markers + the space)
185 $outStringCol = $citeLevel + ($citeLevel ? 1 : 0);
186 } else if ($outStringCol > $citeLevel) {
187 // not a cite and we're not at the beginning of a line
188 // in the output. add a space to separate the new text
189 // from previous text.
190 $outString .= ' ';
191 $outStringCol++;
192 }
193
194 // find the next newline -- we don't want to go further than that
195 $nextNewline = strpos ($body, "\n", $pos);
196 if ($nextNewline === FALSE) {
197 $nextNewline = $length;
198 }
199
200 // Don't wrap unquoted lines at all. For now the textarea
201 // will work fine for this. Maybe revisit this later though
202 // (for completeness more than anything else, I think)
203 if ($citeLevel == 0) {
204 $outString .= substr ($body, $pos, ($nextNewline - $pos));
205 $outStringCol = $nextNewline - $pos;
206 if ($nextNewline != $length) {
207 sqMakeNewLine ($outString, 0, $outStringCol);
208 }
209 $pos = $nextNewline + 1;
210 continue;
211 }
bb977394 212 /**
213 * Set this to false to stop appending short strings to previous lines
214 */
215 $smartwrap = true;
c9d61baf 216 // inner loop, (obviously) handles wrapping up to
217 // the next newline
218 while ($pos < $nextNewline) {
219 // skip over initial spaces
220 while (($pos < $nextNewline) && (ctype_space ($body{$pos}))) {
221 $pos++;
222 }
c9d61baf 223 // if this is a short line then just append it and continue outer loop
6eaf5320 224 if (($outStringCol + $nextNewline - $pos) <= ($wrap - $citeLevel - 1) ) {
c9d61baf 225 // if this is the final line in the input string then include
226 // any trailing newlines
6eaf5320 227 // echo substr($body,$pos,$wrap). "<br />";
c9d61baf 228 if (($nextNewline + 1 == $length) && ($body{$nextNewline} == "\n")) {
229 $nextNewline++;
230 }
231
bb977394 232 // trim trailing spaces
233 $lastRealChar = $nextNewline;
234 while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space ($body{$lastRealChar}))) {
235 $lastRealChar--;
236 }
bb977394 237 // decide if appending the short string is what we want
238 if (($nextNewline < $length && $body{$nextNewline} == "\n") &&
239 isset($lastRealChar)) {
be86a35a 240 $mypos = $pos;
241 //check the first word:
bb977394 242 while (($mypos < $length) && ($body{$mypos} == '>')) {
243 $mypos++;
244 // skip over any spaces interleaved among the cite markers
245 while (($mypos < $length) && ($body{$mypos} == ' ')) {
6eaf5320 246 $mypos++;
bb977394 247 }
248 }
249/*
250 $ldnspacecnt = 0;
251 if ($mypos == $nextNewline+1) {
252 while (($mypos < $length) && ($body{$mypos} == ' ')) {
253 $ldnspacecnt++;
6eaf5320 254 }
bb977394 255 }
256*/
257
258 $firstword = substr($body,$mypos,strpos($body,' ',$mypos) - $mypos);
bb977394 259 //if ($dowrap || $ldnspacecnt > 1 || ($firstword && (
260 if (!$smartwrap || $firstword && (
261 $firstword{0} == '-' ||
6eaf5320 262 $firstword{0} == '+' ||
263 $firstword{0} == '*' ||
bb977394 264 $firstword{0} == strtoupper($firstword{0}) ||
6eaf5320 265 strpos($firstword,':'))) {
bb977394 266 $outString .= substr($body,$pos,($lastRealChar - $pos+1));
267 $outStringCol += ($lastRealChar - $pos);
268 sqMakeNewLine($outString,$citeLevel,$outStringCol);
269 $nextNewline++;
270 $pos = $nextNewline;
271 $outStringCol--;
272 continue;
273 }
6eaf5320 274
c9d61baf 275 }
bb977394 276
c9d61baf 277 $outString .= substr ($body, $pos, ($lastRealChar - $pos + 1));
278 $outStringCol += ($lastRealChar - $pos);
279 $pos = $nextNewline + 1;
280 continue;
281 }
bb977394 282
c9d61baf 283 $eol = $pos + $wrap - $citeLevel - $outStringCol;
284 // eol is the tentative end of line.
285 // look backwards for there for a whitespace to break at.
286 // if it's already less than our current position then
287 // our current line is already too long, break immediately
288 // and restart outer loop
289 if ($eol <= $pos) {
6eaf5320 290 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
c9d61baf 291 continue;
292 }
293
294 // start looking backwards for whitespace to break at.
295 $breakPoint = $eol;
296 while (($breakPoint > $pos) && (! ctype_space ($body{$breakPoint}))) {
297 $breakPoint--;
298 }
299
300 // if we didn't find a breakpoint by looking backward then we
301 // need to figure out what to do about that
302 if ($breakPoint == $pos) {
303 // if we are not at the beginning then end this line
304 // and start a new loop
305 if ($outStringCol > ($citeLevel + 1)) {
306 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
307 continue;
308 } else {
309 // just hard break here. most likely we are breaking
310 // a really long URL. could also try searching
311 // forward for a break point, which is what Mozilla
312 // does. don't bother for now.
313 $breakPoint = $eol;
314 }
315 }
316
317 // special case: maybe we should have wrapped last
318 // time. if the first breakpoint here makes the
319 // current line too long and there is already text on
320 // the current line, break and loop again if at
321 // beginning of current line, don't force break
322 $SLOP = 6;
323 if ((($outStringCol + ($breakPoint - $pos)) > ($wrap + $SLOP)) && ($outStringCol > ($citeLevel + 1))) {
324 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
325 continue;
326 }
327
328 // skip newlines or whitespace at the beginning of the string
329 $substring = substr ($body, $pos, ($breakPoint - $pos));
330 $substring = rtrim ($substring); // do rtrim and ctype_space have the same ideas about whitespace?
331 $outString .= $substring;
332 $outStringCol += strlen ($substring);
333 // advance past the whitespace which caused the wrap
334 $pos = $breakPoint;
335 while (($pos < $length) && (ctype_space ($body{$pos}))) {
336 $pos++;
337 }
338 if ($pos < $length) {
339 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
340 }
341 }
342 }
343
344 return $outString;
345}
346
5cc0b70e 347/**
348 * Wraps text at $wrap characters
349 *
350 * Has a problem with special HTML characters, so call this before
351 * you do character translation.
352 *
353 * Specifically, &#039 comes up as 5 characters instead of 1.
354 * This should not add newlines to the end of lines.
8b096f0a 355 *
356 * @param string line the line of text to wrap, by ref
357 * @param int wrap the maximum line lenth
358 * @return void
5cc0b70e 359 */
360function sqWordWrap(&$line, $wrap) {
e842b215 361 global $languages, $squirrelmail_language;
362
363 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
1b45fe31 364 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap')) {
e842b215 365 if (mb_detect_encoding($line) != 'ASCII') {
1b45fe31 366 $line = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap', $line, $wrap);
e842b215 367 return;
368 }
369 }
370
5cc0b70e 371 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
372 $beginning_spaces = $regs[1];
373 if (isset($regs[2])) {
374 $words = explode(' ', $regs[2]);
375 } else {
376 $words = '';
377 }
f1ca21bd 378
5cc0b70e 379 $i = 0;
380 $line = $beginning_spaces;
f1ca21bd 381
5cc0b70e 382 while ($i < count($words)) {
383 /* Force one word to be on a line (minimum) */
384 $line .= $words[$i];
385 $line_len = strlen($beginning_spaces) + strlen($words[$i]) + 2;
386 if (isset($words[$i + 1]))
387 $line_len += strlen($words[$i + 1]);
388 $i ++;
f1ca21bd 389
5cc0b70e 390 /* Add more words (as long as they fit) */
391 while ($line_len < $wrap && $i < count($words)) {
392 $line .= ' ' . $words[$i];
393 $i++;
394 if (isset($words[$i]))
395 $line_len += strlen($words[$i]) + 1;
396 else
397 $line_len += 1;
398 }
f1ca21bd 399
5cc0b70e 400 /* Skip spaces if they are the first thing on a continued line */
401 while (!isset($words[$i]) && $i < count($words)) {
402 $i ++;
403 }
f1ca21bd 404
5cc0b70e 405 /* Go to the next line if we have more to process */
406 if ($i < count($words)) {
e0858036 407 $line .= "\n";
5cc0b70e 408 }
409 }
410}
411
341abbd6 412/**
413 * Does the opposite of sqWordWrap()
8b096f0a 414 * @param string body the text to un-wordwrap
415 * @return void
341abbd6 416 */
417function sqUnWordWrap(&$body) {
e842b215 418 global $squirrelmail_language;
f1ca21bd 419
e842b215 420 if ($squirrelmail_language == 'ja_JP') {
421 return;
422 }
423
341abbd6 424 $lines = explode("\n", $body);
425 $body = '';
426 $PreviousSpaces = '';
427 $cnt = count($lines);
428 for ($i = 0; $i < $cnt; $i ++) {
429 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
430 $CurrentSpaces = $regs[1];
431 if (isset($regs[2])) {
432 $CurrentRest = $regs[2];
1e4a4feb 433 } else {
f1ca21bd 434 $CurrentRest = '';
435 }
436
341abbd6 437 if ($i == 0) {
438 $PreviousSpaces = $CurrentSpaces;
439 $body = $lines[$i];
440 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
441 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
442 && strlen($CurrentRest)) { /* and there's a line to continue with */
443 $body .= ' ' . $CurrentRest;
444 } else {
445 $body .= "\n" . $lines[$i];
446 $PreviousSpaces = $CurrentSpaces;
447 }
448 }
449 $body .= "\n";
450}
451
66239b65 452/**
453 * If $haystack is a full mailbox name and $needle is the mailbox
454 * separator character, returns the last part of the mailbox name.
8b096f0a 455 *
456 * @param string haystack full mailbox name to search
457 * @param string needle the mailbox separator character
458 * @return string the last part of the mailbox name
66239b65 459 */
460function readShortMailboxName($haystack, $needle) {
97b1248c 461
66239b65 462 if ($needle == '') {
97b1248c 463 $elem = $haystack;
464 } else {
f1ca21bd 465 $parts = explode($needle, $haystack);
466 $elem = array_pop($parts);
467 while ($elem == '' && count($parts)) {
468 $elem = array_pop($parts);
469 }
66239b65 470 }
97b1248c 471 return( $elem );
66239b65 472}
3302d0d4 473
8b096f0a 474/**
4445e6b3 475 * php_self
476 *
8b096f0a 477 * Creates an URL for the page calling this function, using either the PHP global
478 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
479 *
480 * @return string the complete url for this page
481 */
43fdb2a4 482function php_self () {
961ca3d8 483 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
484 return $req_uri;
43fdb2a4 485 }
f1ca21bd 486
961ca3d8 487 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
f72f61d8 488
489 // need to add query string to end of PHP_SELF to match REQUEST_URI
490 //
491 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
492 $php_self .= '?' . $query_string;
493 }
494
961ca3d8 495 return $php_self;
f1ca21bd 496 }
497
961ca3d8 498 return '';
43fdb2a4 499}
500
501
66239b65 502/**
4445e6b3 503 * get_location
504 *
8b096f0a 505 * Determines the location to forward to, relative to your server.
506 * This is used in HTTP Location: redirects.
66239b65 507 * If this doesnt work correctly for you (although it should), you can
8b096f0a 508 * remove all this code except the last two lines, and have it return
509 * the right URL for your site, something like:
510 *
511 * http://www.example.com/squirrelmail/
66239b65 512 *
8b096f0a 513 * @return string the base url for this SquirrelMail installation
66239b65 514 */
515function get_location () {
f1ca21bd 516
961ca3d8 517 global $imap_server_type;
238703be 518
4deb32f1 519 /* Get the path, handle virtual directories */
f1ca21bd 520 if(strpos(php_self(), '?')) {
521 $path = substr(php_self(), 0, strpos(php_self(), '?'));
522 } else {
523 $path = php_self();
524 }
525 $path = substr($path, 0, strrpos($path, '/'));
238703be 526 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
527 return $full_url . $path;
528 }
529
66239b65 530 /* Check if this is a HTTPS or regular HTTP request. */
531 $proto = 'http://';
f1ca21bd 532
66239b65 533 /*
534 * If you have 'SSLOptions +StdEnvVars' in your apache config
44827b4d 535 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
66239b65 536 * OR if you are on port 443
537 */
538 $getEnvVar = getenv('HTTPS');
539 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
961ca3d8 540 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
541 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
8a549df2 542 $proto = 'https://';
66239b65 543 }
f1ca21bd 544
4deb32f1 545 /* Get the hostname from the Host header or server config. */
961ca3d8 546 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
547 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
548 $host = '';
549 }
66239b65 550 }
f1ca21bd 551
66239b65 552 $port = '';
553 if (! strstr($host, ':')) {
961ca3d8 554 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
f1ca21bd 555 if (($server_port != 80 && $proto == 'http://') ||
961ca3d8 556 ($server_port != 443 && $proto == 'https://')) {
557 $port = sprintf(':%d', $server_port);
66239b65 558 }
559 }
560 }
f1ca21bd 561
8de7f698 562 /* this is a workaround for the weird macosx caching that
563 causes Apache to return 16080 as the port number, which causes
564 SM to bail */
f1ca21bd 565
8de7f698 566 if ($imap_server_type == 'macosx' && $port == ':16080') {
567 $port = '';
568 }
f1ca21bd 569
238703be 570 /* Fallback is to omit the server name and use a relative */
571 /* URI, although this is not RFC 2616 compliant. */
572 $full_url = ($host ? $proto . $host . $port : '');
573 sqsession_register($full_url, 'sq_base_url');
574 return $full_url . $path;
66239b65 575}
dcaf2a49 576
9374671f 577
66239b65 578/**
4445e6b3 579 * Encrypts password
580 *
8b096f0a 581 * These functions are used to encrypt the password before it is
582 * stored in a cookie. The encryption key is generated by
583 * OneTimePadCreate();
584 *
585 * @param string string the (password)string to encrypt
586 * @param string epad the encryption key
587 * @return string the base64-encoded encrypted password
66239b65 588 */
589function OneTimePadEncrypt ($string, $epad) {
590 $pad = base64_decode($epad);
591 $encrypted = '';
592 for ($i = 0; $i < strlen ($string); $i++) {
593 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
594 }
f1ca21bd 595
66239b65 596 return base64_encode($encrypted);
597}
598
8b096f0a 599/**
4445e6b3 600 * Decrypts a password from the cookie
601 *
602 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
8b096f0a 603 * This uses the encryption key that is stored in the session.
604 *
605 * @param string string the string to decrypt
606 * @param string epad the encryption key from the session
607 * @return string the decrypted password
608 */
66239b65 609function OneTimePadDecrypt ($string, $epad) {
610 $pad = base64_decode($epad);
611 $encrypted = base64_decode ($string);
612 $decrypted = '';
613 for ($i = 0; $i < strlen ($encrypted); $i++) {
614 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
615 }
f1ca21bd 616
66239b65 617 return $decrypted;
618}
9374671f 619
9374671f 620
66239b65 621/**
4445e6b3 622 * Randomizes the mt_rand() function.
623 *
c9d61baf 624 * Toss this in strings or integers and it will seed the generator
625 * appropriately. With strings, it is better to get them long.
4445e6b3 626 * Use md5() to lengthen smaller strings.
8b096f0a 627 *
628 * @param mixed val a value to seed the random number generator
629 * @return void
66239b65 630 */
631function sq_mt_seed($Val) {
4deb32f1 632 /* if mt_getrandmax() does not return a 2^n - 1 number,
633 this might not work well. This uses $Max as a bitmask. */
66239b65 634 $Max = mt_getrandmax();
f1ca21bd 635
66239b65 636 if (! is_int($Val)) {
66239b65 637 $Val = crc32($Val);
66239b65 638 }
f1ca21bd 639
66239b65 640 if ($Val < 0) {
641 $Val *= -1;
642 }
f1ca21bd 643
8d2155e5 644 if ($Val == 0) {
66239b65 645 return;
646 }
f1ca21bd 647
66239b65 648 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
649}
9374671f 650
9374671f 651
66239b65 652/**
4445e6b3 653 * Init random number generator
654 *
66239b65 655 * This function initializes the random number generator fairly well.
656 * It also only initializes it once, so you don't accidentally get
657 * the same 'random' numbers twice in one session.
8b096f0a 658 *
659 * @return void
66239b65 660 */
661function sq_mt_randomize() {
66239b65 662 static $randomized;
f1ca21bd 663
66239b65 664 if ($randomized) {
665 return;
666 }
f1ca21bd 667
66239b65 668 /* Global. */
961ca3d8 669 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
670 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
66239b65 671 sq_mt_seed((int)((double) microtime() * 1000000));
961ca3d8 672 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
f1ca21bd 673
66239b65 674 /* getrusage */
675 if (function_exists('getrusage')) {
4deb32f1 676 /* Avoid warnings with Win32 */
66239b65 677 $dat = @getrusage();
678 if (isset($dat) && is_array($dat)) {
821a8e9c 679 $Str = '';
680 foreach ($dat as $k => $v)
66239b65 681 {
682 $Str .= $k . $v;
683 }
821a8e9c 684 sq_mt_seed(md5($Str));
66239b65 685 }
686 }
f1ca21bd 687
961ca3d8 688 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
689 sq_mt_seed(md5($unique_id));
0b97a708 690 }
f1ca21bd 691
66239b65 692 $randomized = 1;
693}
694
8b096f0a 695/**
4445e6b3 696 * Creates encryption key
697 *
8b096f0a 698 * Creates an encryption key for encrypting the password stored in the cookie.
699 * The encryption key itself is stored in the session.
700 *
701 * @param int length optional, length of the string to generate
702 * @return string the encryption key
703 */
66239b65 704function OneTimePadCreate ($length=100) {
705 sq_mt_randomize();
f1ca21bd 706
66239b65 707 $pad = '';
708 for ($i = 0; $i < $length; $i++) {
709 $pad .= chr(mt_rand(0,255));
710 }
f1ca21bd 711
66239b65 712 return base64_encode($pad);
713}
9374671f 714
66239b65 715/**
8b096f0a 716 * Returns a string showing the size of the message/attachment.
717 *
718 * @param int bytes the filesize in bytes
719 * @return string the filesize in human readable format
66239b65 720 */
721function show_readable_size($bytes) {
722 $bytes /= 1024;
723 $type = 'k';
f1ca21bd 724
66239b65 725 if ($bytes / 1024 > 1) {
726 $bytes /= 1024;
e5f1e71c 727 $type = 'M';
66239b65 728 }
f1ca21bd 729
66239b65 730 if ($bytes < 10) {
731 $bytes *= 10;
732 settype($bytes, 'integer');
733 $bytes /= 10;
734 } else {
735 settype($bytes, 'integer');
736 }
f1ca21bd 737
66239b65 738 return $bytes . '<small>&nbsp;' . $type . '</small>';
739}
9374671f 740
66239b65 741/**
742 * Generates a random string from the caracter set you pass in
743 *
8b096f0a 744 * @param int size the size of the string to generate
745 * @param string chars a string containing the characters to use
746 * @param int flags a flag to add a specific set to the characters to use:
747 * Flags:
748 * 1 = add lowercase a-z to $chars
749 * 2 = add uppercase A-Z to $chars
750 * 4 = add numbers 0-9 to $chars
751 * @return string the random string
66239b65 752 */
66239b65 753function GenerateRandomString($size, $chars, $flags = 0) {
754 if ($flags & 0x1) {
755 $chars .= 'abcdefghijklmnopqrstuvwxyz';
756 }
757 if ($flags & 0x2) {
758 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
759 }
760 if ($flags & 0x4) {
761 $chars .= '0123456789';
762 }
f1ca21bd 763
66239b65 764 if (($size < 1) || (strlen($chars) < 1)) {
765 return '';
766 }
ff4f08ff 767
4deb32f1 768 sq_mt_randomize(); /* Initialize the random number generator */
ff4f08ff 769
4deb32f1 770 $String = '';
ff4f08ff 771 $j = strlen( $chars ) - 1;
66239b65 772 while (strlen($String) < $size) {
ff4f08ff 773 $String .= $chars{mt_rand(0, $j)};
66239b65 774 }
ff4f08ff 775
66239b65 776 return $String;
777}
9374671f 778
8b096f0a 779/**
780 * Escapes special characters for use in IMAP commands.
4445e6b3 781 *
8b096f0a 782 * @param string the string to escape
783 * @return string the escaped string
784 */
fbb76d0e 785function quoteimap($str) {
ab1df059 786 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
66239b65 787}
1899535f 788
66239b65 789/**
4445e6b3 790 * Trims array
791 *
8b096f0a 792 * Trims every element in the array, ie. remove the first char of each element
793 * @param array array the array to trim
66239b65 794 */
795function TrimArray(&$array) {
796 foreach ($array as $k => $v) {
797 global $$k;
798 if (is_array($$k)) {
799 foreach ($$k as $k2 => $v2) {
800 $$k[$k2] = substr($v2, 1);
23d6bd09 801 }
66239b65 802 } else {
803 $$k = substr($v, 1);
23d6bd09 804 }
f1ca21bd 805
4deb32f1 806 /* Re-assign back to array. */
66239b65 807 $array[$k] = $$k;
808 }
f1ca21bd 809}
23d6bd09 810
8b096f0a 811/**
4445e6b3 812 * Create compose link
813 *
8b096f0a 814 * Returns a link to the compose-page, taking in consideration
815 * the compose_in_new and javascript settings.
816 * @param string url the URL to the compose page
817 * @param string text the link text, default "Compose"
818 * @return string a link to the compose page
819 */
21a957a9 820function makeComposeLink($url, $text = null, $target='')
d62c4938 821{
822 global $compose_new_win,$javascript_on;
823
824 if(!$text) {
825 $text = _("Compose");
826 }
827
f72f61d8 828
c9d61baf 829 // if not using "compose in new window", make
f72f61d8 830 // regular link and be done with it
d62c4938 831 if($compose_new_win != '1') {
21a957a9 832 return makeInternalLink($url, $text, $target);
d62c4938 833 }
834
f72f61d8 835
c9d61baf 836 // build the compose in new window link...
f72f61d8 837
838
c435f076 839 // if javascript is on, use onclick event to handle it
d62c4938 840 if($javascript_on) {
841 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
842 return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
843 }
844
f72f61d8 845
846 // otherwise, just open new window using regular HTML
d62c4938 847 return makeInternalLink($url, $text, '_blank');
f72f61d8 848
d62c4938 849}
850
f1ca21bd 851/**
4445e6b3 852 * Print variable
853 *
8b096f0a 854 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
4445e6b3 855 *
8b096f0a 856 * Debugging function - does the same as print_r, but makes sure special
857 * characters are converted to htmlentities first. This will allow
858 * values like <some@email.address> to be displayed.
4445e6b3 859 * The output is wrapped in <<pre>> and <</pre>> tags.
8b096f0a 860 *
861 * @return void
862 */
7fe09a30 863function sm_print_r() {
50cc40fe 864 ob_start(); // Buffer output
7fe09a30 865 foreach(func_get_args() as $var) {
866 print_r($var);
867 echo "\n";
868 }
50cc40fe 869 $buffer = ob_get_contents(); // Grab the print_r output
870 ob_end_clean(); // Silently discard the output & stop buffering
f1ca21bd 871 print '<pre>';
50cc40fe 872 print htmlentities($buffer);
f1ca21bd 873 print '</pre>';
50cc40fe 874}
875
3ecad5e6 876/**
877 * version of fwrite which checks for failure
878 */
879function sq_fwrite($fp, $string) {
c9d61baf 880 // write to file
881 $count = @fwrite($fp,$string);
882 // the number of bytes written should be the length of the string
883 if($count != strlen($string)) {
884 return FALSE;
885 }
886
887 return $count;
3ecad5e6 888}
889
36e1180b 890/**
891 * sq_get_html_translation_table
892 *
893 * Returns the translation table used by sq_htmlentities()
894 *
895 * @param integer $table html translation table. Possible values (without quotes):
deb22cec 896 * <ul>
897 * <li>HTML_ENTITIES - full html entities table defined by charset</li>
898 * <li>HTML_SPECIALCHARS - html special characters table</li>
899 * </ul>
36e1180b 900 * @param integer $quote_style quote encoding style. Possible values (without quotes):
c9d61baf 901 * <ul>
deb22cec 902 * <li>ENT_COMPAT - (default) encode double quotes</li>
903 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
904 * <li>ENT_QUOTES - encode double and single quotes</li>
c9d61baf 905 * </ul>
36e1180b 906 * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
907 * @return array html translation array
908 */
909function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
910 global $default_charset;
911
912 if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
913
914 // Start array with ampersand
915 $sq_html_ent_table = array( "&" => '&amp;' );
916
917 // < and >
918 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 919 array("<" => '&lt;',
920 ">" => '&gt;')
921 );
36e1180b 922 // double quotes
923 if ($quote_style == ENT_COMPAT)
924 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 925 array("\"" => '&quot;')
926 );
36e1180b 927
928 // double and single quotes
929 if ($quote_style == ENT_QUOTES)
930 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 931 array("\"" => '&quot;',
932 "'" => '&#39;')
933 );
36e1180b 934
935 if ($charset=='auto') $charset=$default_charset;
936
937 // add entities that depend on charset
938 switch($charset){
939 case 'iso-8859-1':
940 include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
941 break;
942 case 'utf-8':
943 include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
944 break;
945 case 'us-ascii':
946 default:
947 break;
948 }
949 // return table
950 return $sq_html_ent_table;
951}
952
953/**
954 * sq_htmlentities
955 *
956 * Convert all applicable characters to HTML entities.
957 * Minimal php requirement - v.4.0.5
958 *
959 * @param string $string string that has to be sanitized
960 * @param integer $quote_style quote encoding style. Possible values (without quotes):
c9d61baf 961 * <ul>
deb22cec 962 * <li>ENT_COMPAT - (default) encode double quotes</li>
963 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
964 * <li>ENT_QUOTES - encode double and single quotes</li>
c9d61baf 965 * </ul>
36e1180b 966 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
967 * @return string sanitized string
968 */
969function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
970 // get translation table
971 $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
972 // convert characters
973 return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
974}
975
b54acf3f 976/**
977 * Tests if string contains 8bit symbols.
978 *
979 * If charset is not set, function defaults to default_charset.
91e0dccc 980 * $default_charset global must be set correctly if $charset is
b54acf3f 981 * not used.
982 * @param string $string tested string
983 * @param string $charset charset used in a string
984 * @return bool true if 8bit symbols are detected
985 * @since 1.5.1
986 */
987function sq_is8bit($string,$charset='') {
988 global $default_charset;
989
990 if ($charset=='') $charset=$default_charset;
991
992 /**
993 * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
91e0dccc 994 * Don't use \200-\237 for iso-8859-x charsets. This ranges
b54acf3f 995 * stores control symbols in those charsets.
996 * Use preg_match instead of ereg in order to avoid problems
997 * with mbstring overloading
998 */
999 if (preg_match("/^iso-8859/i",$charset)) {
1000 $needle='/\240|[\241-\377]/';
1001 } else {
1002 $needle='/[\200-\237]|\240|[\241-\377]/';
1003 }
1004 return preg_match("$needle",$string);
1005}
1006
1007/**
1008 * Replacement of mb_list_encodings function
1009 *
1010 * This function provides replacement for function that is available only
1011 * in php 5.x. Function does not test all mbstring encodings. Only the ones
1012 * that might be used in SM translations.
1013 *
91e0dccc 1014 * Supported arrays are stored in session in order to reduce number of
b54acf3f 1015 * mb_internal_encoding function calls.
1016 *
91e0dccc 1017 * If you want to test all mbstring encodings - fill $list_of_encodings
b54acf3f 1018 * array.
1019 * @return array list of encodings supported by mbstring
1020 * @since 1.5.1
1021 */
1022function sq_mb_list_encodings() {
1023 if (! function_exists('mb_internal_encoding'))
1024 return array();
1025
1026 // don't try to test encodings, if they are already stored in session
1027 if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION))
1028 return $mb_supported_encodings;
1029
1030 // save original encoding
1031 $orig_encoding=mb_internal_encoding();
1032
1033 $list_of_encoding=array(
1034 'pass',
1035 'auto',
1036 'ascii',
1037 'jis',
1038 'utf-8',
1039 'sjis',
1040 'euc-jp',
1041 'iso-8859-1',
1042 'iso-8859-2',
1043 'iso-8859-7',
1044 'iso-8859-9',
1045 'iso-8859-15',
1046 'koi8-r',
1047 'koi8-u',
1048 'big5',
1049 'gb2312',
1050 'windows-1251',
1051 'windows-1255',
1052 'windows-1256',
1053 'tis-620',
1054 'iso-2022-jp',
1055 'euc-kr',
1056 'utf7-imap');
1057
1058 $supported_encodings=array();
1059
1060 foreach ($list_of_encoding as $encoding) {
1061 // try setting encodings. suppress warning messages
1062 if (@mb_internal_encoding($encoding))
1063 $supported_encodings[]=$encoding;
1064 }
1065
1066 // restore original encoding
1067 mb_internal_encoding($orig_encoding);
1068
1069 // register list in session
1070 sqsession_register($supported_encodings,'mb_supported_encodings');
1071
1072 return $supported_encodings;
1073}
1074
43fdb2a4 1075$PHP_SELF = php_self();
4445e6b3 1076?>