information about changes
[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
598294a7 10 * used by the rest of the SquirrelMail code.
35586184 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
66239b65 36/**
c9d61baf 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
77/**
5e7ae713 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) {
c7aff938 99 if ( preg_match('/^[\x09-\x0D]|^\x20/', $string) || $string=='') {
100 return true;
101 } else {
102 return false;
103 }
5e7ae713 104}
105
106/**
c9d61baf 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
347/**
5cc0b70e 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 *
17886554 353 * Specifically, &amp;#039; comes up as 5 characters instead of 1.
5cc0b70e 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
c7aff938 358 * @param string charset name of charset used in $line string. Available since v.1.5.1.
8b096f0a 359 * @return void
5cc0b70e 360 */
c7aff938 361function sqWordWrap(&$line, $wrap, $charset='') {
e842b215 362 global $languages, $squirrelmail_language;
363
17886554 364 // Use custom wrapping function, if translation provides it
e842b215 365 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
1b45fe31 366 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap')) {
e842b215 367 if (mb_detect_encoding($line) != 'ASCII') {
1b45fe31 368 $line = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap', $line, $wrap);
e842b215 369 return;
370 }
371 }
372
5cc0b70e 373 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
374 $beginning_spaces = $regs[1];
375 if (isset($regs[2])) {
376 $words = explode(' ', $regs[2]);
377 } else {
378 $words = '';
379 }
f1ca21bd 380
5cc0b70e 381 $i = 0;
382 $line = $beginning_spaces;
f1ca21bd 383
5cc0b70e 384 while ($i < count($words)) {
385 /* Force one word to be on a line (minimum) */
386 $line .= $words[$i];
c7aff938 387 $line_len = strlen($beginning_spaces) + sq_strlen($words[$i],$charset) + 2;
5cc0b70e 388 if (isset($words[$i + 1]))
c7aff938 389 $line_len += sq_strlen($words[$i + 1],$charset);
5cc0b70e 390 $i ++;
f1ca21bd 391
5cc0b70e 392 /* Add more words (as long as they fit) */
393 while ($line_len < $wrap && $i < count($words)) {
394 $line .= ' ' . $words[$i];
395 $i++;
396 if (isset($words[$i]))
c7aff938 397 $line_len += sq_strlen($words[$i],$charset) + 1;
5cc0b70e 398 else
399 $line_len += 1;
400 }
f1ca21bd 401
5cc0b70e 402 /* Skip spaces if they are the first thing on a continued line */
403 while (!isset($words[$i]) && $i < count($words)) {
404 $i ++;
405 }
f1ca21bd 406
5cc0b70e 407 /* Go to the next line if we have more to process */
408 if ($i < count($words)) {
e0858036 409 $line .= "\n";
5cc0b70e 410 }
411 }
412}
413
414/**
341abbd6 415 * Does the opposite of sqWordWrap()
8b096f0a 416 * @param string body the text to un-wordwrap
417 * @return void
341abbd6 418 */
419function sqUnWordWrap(&$body) {
e842b215 420 global $squirrelmail_language;
f1ca21bd 421
e842b215 422 if ($squirrelmail_language == 'ja_JP') {
423 return;
424 }
425
341abbd6 426 $lines = explode("\n", $body);
427 $body = '';
428 $PreviousSpaces = '';
429 $cnt = count($lines);
430 for ($i = 0; $i < $cnt; $i ++) {
431 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
432 $CurrentSpaces = $regs[1];
433 if (isset($regs[2])) {
434 $CurrentRest = $regs[2];
1e4a4feb 435 } else {
f1ca21bd 436 $CurrentRest = '';
437 }
438
341abbd6 439 if ($i == 0) {
440 $PreviousSpaces = $CurrentSpaces;
441 $body = $lines[$i];
442 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
443 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
444 && strlen($CurrentRest)) { /* and there's a line to continue with */
445 $body .= ' ' . $CurrentRest;
446 } else {
447 $body .= "\n" . $lines[$i];
448 $PreviousSpaces = $CurrentSpaces;
449 }
450 }
451 $body .= "\n";
452}
453
454/**
66239b65 455 * If $haystack is a full mailbox name and $needle is the mailbox
456 * separator character, returns the last part of the mailbox name.
8b096f0a 457 *
458 * @param string haystack full mailbox name to search
459 * @param string needle the mailbox separator character
460 * @return string the last part of the mailbox name
66239b65 461 */
462function readShortMailboxName($haystack, $needle) {
97b1248c 463
66239b65 464 if ($needle == '') {
97b1248c 465 $elem = $haystack;
466 } else {
f1ca21bd 467 $parts = explode($needle, $haystack);
468 $elem = array_pop($parts);
469 while ($elem == '' && count($parts)) {
470 $elem = array_pop($parts);
471 }
66239b65 472 }
97b1248c 473 return( $elem );
66239b65 474}
3302d0d4 475
8b096f0a 476/**
4445e6b3 477 * php_self
478 *
8b096f0a 479 * Creates an URL for the page calling this function, using either the PHP global
480 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
481 *
482 * @return string the complete url for this page
483 */
43fdb2a4 484function php_self () {
961ca3d8 485 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
486 return $req_uri;
43fdb2a4 487 }
f1ca21bd 488
961ca3d8 489 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
f72f61d8 490
491 // need to add query string to end of PHP_SELF to match REQUEST_URI
492 //
493 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
494 $php_self .= '?' . $query_string;
495 }
496
961ca3d8 497 return $php_self;
f1ca21bd 498 }
499
961ca3d8 500 return '';
43fdb2a4 501}
502
503
66239b65 504/**
4445e6b3 505 * get_location
506 *
8b096f0a 507 * Determines the location to forward to, relative to your server.
508 * This is used in HTTP Location: redirects.
66239b65 509 * If this doesnt work correctly for you (although it should), you can
8b096f0a 510 * remove all this code except the last two lines, and have it return
511 * the right URL for your site, something like:
512 *
513 * http://www.example.com/squirrelmail/
66239b65 514 *
8b096f0a 515 * @return string the base url for this SquirrelMail installation
66239b65 516 */
517function get_location () {
f1ca21bd 518
961ca3d8 519 global $imap_server_type;
238703be 520
4deb32f1 521 /* Get the path, handle virtual directories */
f1ca21bd 522 if(strpos(php_self(), '?')) {
523 $path = substr(php_self(), 0, strpos(php_self(), '?'));
524 } else {
525 $path = php_self();
526 }
527 $path = substr($path, 0, strrpos($path, '/'));
238703be 528 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
529 return $full_url . $path;
530 }
531
66239b65 532 /* Check if this is a HTTPS or regular HTTP request. */
533 $proto = 'http://';
f1ca21bd 534
66239b65 535 /*
536 * If you have 'SSLOptions +StdEnvVars' in your apache config
44827b4d 537 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
66239b65 538 * OR if you are on port 443
539 */
540 $getEnvVar = getenv('HTTPS');
541 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
961ca3d8 542 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
543 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
8a549df2 544 $proto = 'https://';
66239b65 545 }
f1ca21bd 546
4deb32f1 547 /* Get the hostname from the Host header or server config. */
961ca3d8 548 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
549 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
550 $host = '';
551 }
66239b65 552 }
f1ca21bd 553
66239b65 554 $port = '';
555 if (! strstr($host, ':')) {
961ca3d8 556 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
f1ca21bd 557 if (($server_port != 80 && $proto == 'http://') ||
961ca3d8 558 ($server_port != 443 && $proto == 'https://')) {
559 $port = sprintf(':%d', $server_port);
66239b65 560 }
561 }
562 }
f1ca21bd 563
8de7f698 564 /* this is a workaround for the weird macosx caching that
565 causes Apache to return 16080 as the port number, which causes
566 SM to bail */
f1ca21bd 567
8de7f698 568 if ($imap_server_type == 'macosx' && $port == ':16080') {
569 $port = '';
570 }
f1ca21bd 571
238703be 572 /* Fallback is to omit the server name and use a relative */
573 /* URI, although this is not RFC 2616 compliant. */
574 $full_url = ($host ? $proto . $host . $port : '');
575 sqsession_register($full_url, 'sq_base_url');
576 return $full_url . $path;
66239b65 577}
dcaf2a49 578
9374671f 579
66239b65 580/**
4445e6b3 581 * Encrypts password
582 *
8b096f0a 583 * These functions are used to encrypt the password before it is
584 * stored in a cookie. The encryption key is generated by
585 * OneTimePadCreate();
586 *
587 * @param string string the (password)string to encrypt
588 * @param string epad the encryption key
589 * @return string the base64-encoded encrypted password
66239b65 590 */
591function OneTimePadEncrypt ($string, $epad) {
592 $pad = base64_decode($epad);
593 $encrypted = '';
594 for ($i = 0; $i < strlen ($string); $i++) {
595 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
596 }
f1ca21bd 597
66239b65 598 return base64_encode($encrypted);
599}
600
8b096f0a 601/**
4445e6b3 602 * Decrypts a password from the cookie
603 *
604 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
8b096f0a 605 * This uses the encryption key that is stored in the session.
606 *
607 * @param string string the string to decrypt
608 * @param string epad the encryption key from the session
609 * @return string the decrypted password
610 */
66239b65 611function OneTimePadDecrypt ($string, $epad) {
612 $pad = base64_decode($epad);
613 $encrypted = base64_decode ($string);
614 $decrypted = '';
615 for ($i = 0; $i < strlen ($encrypted); $i++) {
616 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
617 }
f1ca21bd 618
66239b65 619 return $decrypted;
620}
9374671f 621
9374671f 622
66239b65 623/**
4445e6b3 624 * Randomizes the mt_rand() function.
625 *
c9d61baf 626 * Toss this in strings or integers and it will seed the generator
627 * appropriately. With strings, it is better to get them long.
4445e6b3 628 * Use md5() to lengthen smaller strings.
8b096f0a 629 *
630 * @param mixed val a value to seed the random number generator
631 * @return void
66239b65 632 */
633function sq_mt_seed($Val) {
4deb32f1 634 /* if mt_getrandmax() does not return a 2^n - 1 number,
635 this might not work well. This uses $Max as a bitmask. */
66239b65 636 $Max = mt_getrandmax();
f1ca21bd 637
66239b65 638 if (! is_int($Val)) {
66239b65 639 $Val = crc32($Val);
66239b65 640 }
f1ca21bd 641
66239b65 642 if ($Val < 0) {
643 $Val *= -1;
644 }
f1ca21bd 645
8d2155e5 646 if ($Val == 0) {
66239b65 647 return;
648 }
f1ca21bd 649
66239b65 650 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
651}
9374671f 652
9374671f 653
66239b65 654/**
4445e6b3 655 * Init random number generator
656 *
66239b65 657 * This function initializes the random number generator fairly well.
658 * It also only initializes it once, so you don't accidentally get
659 * the same 'random' numbers twice in one session.
8b096f0a 660 *
661 * @return void
66239b65 662 */
663function sq_mt_randomize() {
66239b65 664 static $randomized;
f1ca21bd 665
66239b65 666 if ($randomized) {
667 return;
668 }
f1ca21bd 669
66239b65 670 /* Global. */
961ca3d8 671 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
672 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
66239b65 673 sq_mt_seed((int)((double) microtime() * 1000000));
961ca3d8 674 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
f1ca21bd 675
66239b65 676 /* getrusage */
677 if (function_exists('getrusage')) {
4deb32f1 678 /* Avoid warnings with Win32 */
66239b65 679 $dat = @getrusage();
680 if (isset($dat) && is_array($dat)) {
821a8e9c 681 $Str = '';
682 foreach ($dat as $k => $v)
66239b65 683 {
684 $Str .= $k . $v;
685 }
821a8e9c 686 sq_mt_seed(md5($Str));
66239b65 687 }
688 }
f1ca21bd 689
961ca3d8 690 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
691 sq_mt_seed(md5($unique_id));
0b97a708 692 }
f1ca21bd 693
66239b65 694 $randomized = 1;
695}
696
8b096f0a 697/**
4445e6b3 698 * Creates encryption key
699 *
8b096f0a 700 * Creates an encryption key for encrypting the password stored in the cookie.
701 * The encryption key itself is stored in the session.
702 *
703 * @param int length optional, length of the string to generate
704 * @return string the encryption key
705 */
66239b65 706function OneTimePadCreate ($length=100) {
707 sq_mt_randomize();
f1ca21bd 708
66239b65 709 $pad = '';
710 for ($i = 0; $i < $length; $i++) {
711 $pad .= chr(mt_rand(0,255));
712 }
f1ca21bd 713
66239b65 714 return base64_encode($pad);
715}
9374671f 716
66239b65 717/**
8b096f0a 718 * Returns a string showing the size of the message/attachment.
719 *
720 * @param int bytes the filesize in bytes
721 * @return string the filesize in human readable format
66239b65 722 */
723function show_readable_size($bytes) {
724 $bytes /= 1024;
725 $type = 'k';
f1ca21bd 726
66239b65 727 if ($bytes / 1024 > 1) {
728 $bytes /= 1024;
e5f1e71c 729 $type = 'M';
66239b65 730 }
f1ca21bd 731
66239b65 732 if ($bytes < 10) {
733 $bytes *= 10;
734 settype($bytes, 'integer');
735 $bytes /= 10;
736 } else {
737 settype($bytes, 'integer');
738 }
f1ca21bd 739
66239b65 740 return $bytes . '<small>&nbsp;' . $type . '</small>';
741}
9374671f 742
66239b65 743/**
c7aff938 744 * Generates a random string from the character set you pass in
66239b65 745 *
8b096f0a 746 * @param int size the size of the string to generate
747 * @param string chars a string containing the characters to use
748 * @param int flags a flag to add a specific set to the characters to use:
749 * Flags:
750 * 1 = add lowercase a-z to $chars
751 * 2 = add uppercase A-Z to $chars
752 * 4 = add numbers 0-9 to $chars
753 * @return string the random string
66239b65 754 */
66239b65 755function GenerateRandomString($size, $chars, $flags = 0) {
756 if ($flags & 0x1) {
757 $chars .= 'abcdefghijklmnopqrstuvwxyz';
758 }
759 if ($flags & 0x2) {
760 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
761 }
762 if ($flags & 0x4) {
763 $chars .= '0123456789';
764 }
f1ca21bd 765
66239b65 766 if (($size < 1) || (strlen($chars) < 1)) {
767 return '';
768 }
ff4f08ff 769
4deb32f1 770 sq_mt_randomize(); /* Initialize the random number generator */
ff4f08ff 771
4deb32f1 772 $String = '';
ff4f08ff 773 $j = strlen( $chars ) - 1;
66239b65 774 while (strlen($String) < $size) {
ff4f08ff 775 $String .= $chars{mt_rand(0, $j)};
66239b65 776 }
ff4f08ff 777
66239b65 778 return $String;
779}
9374671f 780
8b096f0a 781/**
782 * Escapes special characters for use in IMAP commands.
4445e6b3 783 *
8b096f0a 784 * @param string the string to escape
785 * @return string the escaped string
786 */
fbb76d0e 787function quoteimap($str) {
ab1df059 788 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
66239b65 789}
1899535f 790
66239b65 791/**
4445e6b3 792 * Trims array
793 *
8b096f0a 794 * Trims every element in the array, ie. remove the first char of each element
795 * @param array array the array to trim
66239b65 796 */
797function TrimArray(&$array) {
798 foreach ($array as $k => $v) {
799 global $$k;
800 if (is_array($$k)) {
801 foreach ($$k as $k2 => $v2) {
802 $$k[$k2] = substr($v2, 1);
23d6bd09 803 }
66239b65 804 } else {
805 $$k = substr($v, 1);
23d6bd09 806 }
f1ca21bd 807
4deb32f1 808 /* Re-assign back to array. */
66239b65 809 $array[$k] = $$k;
810 }
f1ca21bd 811}
23d6bd09 812
8b096f0a 813/**
4445e6b3 814 * Create compose link
815 *
8b096f0a 816 * Returns a link to the compose-page, taking in consideration
817 * the compose_in_new and javascript settings.
818 * @param string url the URL to the compose page
819 * @param string text the link text, default "Compose"
820 * @return string a link to the compose page
821 */
21a957a9 822function makeComposeLink($url, $text = null, $target='')
d62c4938 823{
824 global $compose_new_win,$javascript_on;
825
826 if(!$text) {
827 $text = _("Compose");
828 }
829
f72f61d8 830
c9d61baf 831 // if not using "compose in new window", make
f72f61d8 832 // regular link and be done with it
d62c4938 833 if($compose_new_win != '1') {
21a957a9 834 return makeInternalLink($url, $text, $target);
d62c4938 835 }
836
f72f61d8 837
c9d61baf 838 // build the compose in new window link...
f72f61d8 839
840
c435f076 841 // if javascript is on, use onclick event to handle it
d62c4938 842 if($javascript_on) {
843 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
844 return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
845 }
846
f72f61d8 847
848 // otherwise, just open new window using regular HTML
d62c4938 849 return makeInternalLink($url, $text, '_blank');
f72f61d8 850
d62c4938 851}
852
f1ca21bd 853/**
4445e6b3 854 * Print variable
855 *
8b096f0a 856 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
4445e6b3 857 *
8b096f0a 858 * Debugging function - does the same as print_r, but makes sure special
859 * characters are converted to htmlentities first. This will allow
860 * values like <some@email.address> to be displayed.
4445e6b3 861 * The output is wrapped in <<pre>> and <</pre>> tags.
8b096f0a 862 *
863 * @return void
864 */
7fe09a30 865function sm_print_r() {
50cc40fe 866 ob_start(); // Buffer output
7fe09a30 867 foreach(func_get_args() as $var) {
868 print_r($var);
869 echo "\n";
3896acce 870 // php has get_class_methods function that can print class methods
871 if (is_object($var)) {
872 // get class methods if $var is object
873 $aMethods=get_class_methods(get_class($var));
351ee7ca 874 // make sure that $aMethods is array and array is not empty
875 if (is_array($aMethods) && $aMethods!=array()) {
3896acce 876 echo "Object methods:\n";
877 foreach($aMethods as $method) {
878 echo '* ' . $method . "\n";
879 }
880 }
881 echo "\n";
882 }
7fe09a30 883 }
50cc40fe 884 $buffer = ob_get_contents(); // Grab the print_r output
885 ob_end_clean(); // Silently discard the output & stop buffering
f1ca21bd 886 print '<pre>';
50cc40fe 887 print htmlentities($buffer);
f1ca21bd 888 print '</pre>';
50cc40fe 889}
890
3ecad5e6 891/**
892 * version of fwrite which checks for failure
893 */
894function sq_fwrite($fp, $string) {
c9d61baf 895 // write to file
896 $count = @fwrite($fp,$string);
897 // the number of bytes written should be the length of the string
898 if($count != strlen($string)) {
899 return FALSE;
900 }
901
902 return $count;
3ecad5e6 903}
904
36e1180b 905/**
906 * sq_get_html_translation_table
907 *
908 * Returns the translation table used by sq_htmlentities()
909 *
910 * @param integer $table html translation table. Possible values (without quotes):
deb22cec 911 * <ul>
912 * <li>HTML_ENTITIES - full html entities table defined by charset</li>
913 * <li>HTML_SPECIALCHARS - html special characters table</li>
914 * </ul>
36e1180b 915 * @param integer $quote_style quote encoding style. Possible values (without quotes):
c9d61baf 916 * <ul>
deb22cec 917 * <li>ENT_COMPAT - (default) encode double quotes</li>
918 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
919 * <li>ENT_QUOTES - encode double and single quotes</li>
c9d61baf 920 * </ul>
36e1180b 921 * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
922 * @return array html translation array
923 */
924function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
925 global $default_charset;
926
927 if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
928
929 // Start array with ampersand
930 $sq_html_ent_table = array( "&" => '&amp;' );
931
932 // < and >
933 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 934 array("<" => '&lt;',
935 ">" => '&gt;')
936 );
36e1180b 937 // double quotes
938 if ($quote_style == ENT_COMPAT)
939 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 940 array("\"" => '&quot;')
941 );
36e1180b 942
943 // double and single quotes
944 if ($quote_style == ENT_QUOTES)
945 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 946 array("\"" => '&quot;',
947 "'" => '&#39;')
948 );
36e1180b 949
950 if ($charset=='auto') $charset=$default_charset;
951
952 // add entities that depend on charset
953 switch($charset){
954 case 'iso-8859-1':
955 include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
956 break;
957 case 'utf-8':
958 include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
959 break;
960 case 'us-ascii':
961 default:
962 break;
963 }
964 // return table
965 return $sq_html_ent_table;
966}
967
968/**
969 * sq_htmlentities
970 *
971 * Convert all applicable characters to HTML entities.
17886554 972 * Minimal php requirement - v.4.0.5.
973 *
974 * Function is designed for people that want to use full power of htmlentities() in
975 * i18n environment.
36e1180b 976 *
977 * @param string $string string that has to be sanitized
978 * @param integer $quote_style quote encoding style. Possible values (without quotes):
c9d61baf 979 * <ul>
deb22cec 980 * <li>ENT_COMPAT - (default) encode double quotes</li>
981 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
982 * <li>ENT_QUOTES - encode double and single quotes</li>
c9d61baf 983 * </ul>
36e1180b 984 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
985 * @return string sanitized string
986 */
987function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
988 // get translation table
989 $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
990 // convert characters
991 return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
992}
993
b54acf3f 994/**
995 * Tests if string contains 8bit symbols.
996 *
997 * If charset is not set, function defaults to default_charset.
91e0dccc 998 * $default_charset global must be set correctly if $charset is
b54acf3f 999 * not used.
1000 * @param string $string tested string
1001 * @param string $charset charset used in a string
1002 * @return bool true if 8bit symbols are detected
17886554 1003 * @since 1.5.1 and 1.4.4
b54acf3f 1004 */
1005function sq_is8bit($string,$charset='') {
1006 global $default_charset;
1007
1008 if ($charset=='') $charset=$default_charset;
1009
1010 /**
1011 * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
17886554 1012 * Don't use \200-\237 for iso-8859-x charsets. This range
b54acf3f 1013 * stores control symbols in those charsets.
1014 * Use preg_match instead of ereg in order to avoid problems
1015 * with mbstring overloading
1016 */
1017 if (preg_match("/^iso-8859/i",$charset)) {
1018 $needle='/\240|[\241-\377]/';
1019 } else {
1020 $needle='/[\200-\237]|\240|[\241-\377]/';
1021 }
1022 return preg_match("$needle",$string);
1023}
1024
1025/**
1026 * Replacement of mb_list_encodings function
1027 *
1028 * This function provides replacement for function that is available only
1029 * in php 5.x. Function does not test all mbstring encodings. Only the ones
1030 * that might be used in SM translations.
1031 *
17886554 1032 * Supported strings are stored in session in order to reduce number of
b54acf3f 1033 * mb_internal_encoding function calls.
1034 *
91e0dccc 1035 * If you want to test all mbstring encodings - fill $list_of_encodings
b54acf3f 1036 * array.
17886554 1037 * @return array list of encodings supported by php mbstring extension
b54acf3f 1038 * @since 1.5.1
1039 */
1040function sq_mb_list_encodings() {
1041 if (! function_exists('mb_internal_encoding'))
1042 return array();
1043
1044 // don't try to test encodings, if they are already stored in session
1045 if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION))
1046 return $mb_supported_encodings;
1047
1048 // save original encoding
1049 $orig_encoding=mb_internal_encoding();
1050
1051 $list_of_encoding=array(
1052 'pass',
1053 'auto',
1054 'ascii',
1055 'jis',
1056 'utf-8',
1057 'sjis',
1058 'euc-jp',
1059 'iso-8859-1',
1060 'iso-8859-2',
1061 'iso-8859-7',
1062 'iso-8859-9',
1063 'iso-8859-15',
1064 'koi8-r',
1065 'koi8-u',
1066 'big5',
1067 'gb2312',
1068 'windows-1251',
1069 'windows-1255',
1070 'windows-1256',
1071 'tis-620',
1072 'iso-2022-jp',
1073 'euc-kr',
1074 'utf7-imap');
1075
1076 $supported_encodings=array();
1077
1078 foreach ($list_of_encoding as $encoding) {
1079 // try setting encodings. suppress warning messages
1080 if (@mb_internal_encoding($encoding))
1081 $supported_encodings[]=$encoding;
1082 }
1083
1084 // restore original encoding
1085 mb_internal_encoding($orig_encoding);
1086
1087 // register list in session
1088 sqsession_register($supported_encodings,'mb_supported_encodings');
1089
1090 return $supported_encodings;
1091}
1092
c7aff938 1093/**
1094 * Function returns number of characters in string.
1095 *
1096 * Returned number might be different from number of bytes in string,
1097 * if $charset is multibyte charset. Currently only utf-8 charset is
1098 * supported.
1099 * @param string $str string
1100 * @param string $charset charset
1101 * @since 1.5.1
1102 * @return integer number of characters in string
1103 */
1104function sq_strlen($str, $charset=''){
1105 // default option
1106 if ($charset=='') return strlen($str);
1107
1108 // use automatic charset detection, if function call asks for it
1109 if ($charset=='auto') {
1110 global $default_charset;
1111 set_my_charset();
1112 $charset=$default_charset;
1113 }
1114
1115 // lowercase charset name
1116 $charset=strtolower($charset);
1117
1118 // set initial returned length number
1119 $real_length=0;
1120
1121 // calculate string length according to charset
1122 // function can be modulized same way we modulize decode/encode/htmlentities
1123 if ($charset=='utf-8') {
1124 if (function_exists('mb_strlen')) {
1125 $real_length = mb_strlen($str,'utf-8');
1126 } else {
1127 // function needs length of string in bytes.
1128 // mbstring overloading might break it
1129 $str_length=strlen($str);
1130 $str_index=0;
1131 while ($str_index < $str_length) {
17886554 1132 // start of internal utf-8 multibyte character detection
c7aff938 1133 if (preg_match("/[\xC0-\xDF]/",$str[$str_index]) &&
1134 isset($str[$str_index+1]) &&
1135 preg_match("/[\x80-\xBF]/",$str[$str_index+1])) {
1136 // two byte utf-8
1137 $str_index=$str_index+2;
1138 $real_length++;
1139 } elseif (preg_match("/[\xE0-\xEF]/",$str[$str_index]) &&
1140 isset($str[$str_index+2]) &&
1141 preg_match("/[\x80-\xBF][\x80-\xBF]/",$str[$str_index+1].$str[$str_index+2])) {
1142 // three byte utf-8
1143 $str_index=$str_index+3;
1144 $real_length++;
1145 } elseif (preg_match("/[\xF0-\xF7]/",$str[$str_index]) &&
1146 isset($str[$str_index+3]) &&
1147 preg_match("/[\x80-\xBF][\x80-\xBF][\x80-\xBF]/",$str[$str_index+1].$str[$str_index+2].$str[$str_index+3])) {
1148 // four byte utf-8
1149 $str_index=$str_index+4;
1150 $real_length++;
1151 } elseif (preg_match("/[\xF8-\xFB]/",$str[$str_index]) &&
1152 isset($str[$str_index+4]) &&
1153 preg_match("/[\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF]/",
1154 $str[$str_index+1].$str[$str_index+2].$str[$str_index+3].$str[$str_index+4])) {
1155 // five byte utf-8
1156 $str_index=$str_index+5;
1157 $real_length++;
1158 } elseif (preg_match("/[\xFC-\xFD]/",$str[$str_index]) &&
1159 isset($str[$str_index+5]) &&
1160 preg_match("/[\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF]/",
1161 $str[$str_index+1].$str[$str_index+2].$str[$str_index+3].$str[$str_index+4].$str[$str_index+5])) {
1162 // six byte utf-8
1163 $str_index=$str_index+6;
1164 $real_length++;
1165 } else {
1166 $str_index++;
1167 $real_length++;
1168 }
17886554 1169 // end of internal utf-8 multibyte character detection
c7aff938 1170 }
1171 }
1172 // end of utf-8 length detection
1173 } elseif ($charset=='big5') {
1174 // TODO: add big5 string length detection
1175 $real_length=strlen($str);
1176 } elseif ($charset=='gb2312') {
1177 // TODO: add gb2312 string length detection
1178 $real_length=strlen($str);
1179 } elseif ($charset=='gb18030') {
1180 // TODO: add gb18030 string length detection
1181 $real_length=strlen($str);
1182 } elseif ($charset=='euc-jp') {
1183 // TODO: add euc-jp string length detection
1184 $real_length=strlen($str);
1185 } elseif ($charset=='euc-cn') {
1186 // TODO: add euc-cn string length detection
1187 $real_length=strlen($str);
1188 } elseif ($charset=='euc-tw') {
1189 // TODO: add euc-tw string length detection
1190 $real_length=strlen($str);
1191 } elseif ($charset=='euc-kr') {
1192 // TODO: add euc-kr string length detection
1193 $real_length=strlen($str);
1194 } else {
1195 $real_length=strlen($str);
1196 }
1197 return $real_length;
1198}
1199
17886554 1200/**
1201 * string padding with multibyte support
1202 *
1203 * @link http://www.php.net/str_pad
1204 * @param string $string original string
1205 * @param integer $width padded string width
1206 * @param string $pad padding symbols
1207 * @param integer $padtype padding type
1208 * (internal php defines, see str_pad() description)
1209 * @param string $charset charset used in original string
1210 * @return string padded string
1211 */
1212function sq_str_pad($string, $width, $pad, $padtype, $charset='') {
1213
1214 $charset = strtolower($charset);
1215 $padded_string = '';
1216
1217 switch ($charset) {
1218 case 'utf-8':
1219 case 'big5':
1220 case 'gb2312':
1221 case 'euc-kr':
1222 /*
1223 * all multibyte charsets try to increase width value by
1224 * adding difference between number of bytes and real length
1225 */
1226 $width = $width - sq_strlen($string,$charset) + strlen($string);
1227 default:
1228 $padded_string=str_pad($string,$width,$pad,$padtype);
1229 }
1230 return $padded_string;
1231}
43fdb2a4 1232$PHP_SELF = php_self();
4445e6b3 1233?>