adding str_pad replacement for multibyte charsets and some documentation fixes
[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
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) {
c7aff938 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 *
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
341abbd6 414/**
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
66239b65 454/**
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";
870 }
50cc40fe 871 $buffer = ob_get_contents(); // Grab the print_r output
872 ob_end_clean(); // Silently discard the output & stop buffering
f1ca21bd 873 print '<pre>';
50cc40fe 874 print htmlentities($buffer);
f1ca21bd 875 print '</pre>';
50cc40fe 876}
877
3ecad5e6 878/**
879 * version of fwrite which checks for failure
880 */
881function sq_fwrite($fp, $string) {
c9d61baf 882 // write to file
883 $count = @fwrite($fp,$string);
884 // the number of bytes written should be the length of the string
885 if($count != strlen($string)) {
886 return FALSE;
887 }
888
889 return $count;
3ecad5e6 890}
891
36e1180b 892/**
893 * sq_get_html_translation_table
894 *
895 * Returns the translation table used by sq_htmlentities()
896 *
897 * @param integer $table html translation table. Possible values (without quotes):
deb22cec 898 * <ul>
899 * <li>HTML_ENTITIES - full html entities table defined by charset</li>
900 * <li>HTML_SPECIALCHARS - html special characters table</li>
901 * </ul>
36e1180b 902 * @param integer $quote_style quote encoding style. Possible values (without quotes):
c9d61baf 903 * <ul>
deb22cec 904 * <li>ENT_COMPAT - (default) encode double quotes</li>
905 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
906 * <li>ENT_QUOTES - encode double and single quotes</li>
c9d61baf 907 * </ul>
36e1180b 908 * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
909 * @return array html translation array
910 */
911function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
912 global $default_charset;
913
914 if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
915
916 // Start array with ampersand
917 $sq_html_ent_table = array( "&" => '&amp;' );
918
919 // < and >
920 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 921 array("<" => '&lt;',
922 ">" => '&gt;')
923 );
36e1180b 924 // double quotes
925 if ($quote_style == ENT_COMPAT)
926 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 927 array("\"" => '&quot;')
928 );
36e1180b 929
930 // double and single quotes
931 if ($quote_style == ENT_QUOTES)
932 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 933 array("\"" => '&quot;',
934 "'" => '&#39;')
935 );
36e1180b 936
937 if ($charset=='auto') $charset=$default_charset;
938
939 // add entities that depend on charset
940 switch($charset){
941 case 'iso-8859-1':
942 include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
943 break;
944 case 'utf-8':
945 include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
946 break;
947 case 'us-ascii':
948 default:
949 break;
950 }
951 // return table
952 return $sq_html_ent_table;
953}
954
955/**
956 * sq_htmlentities
957 *
958 * Convert all applicable characters to HTML entities.
17886554 959 * Minimal php requirement - v.4.0.5.
960 *
961 * Function is designed for people that want to use full power of htmlentities() in
962 * i18n environment.
36e1180b 963 *
964 * @param string $string string that has to be sanitized
965 * @param integer $quote_style quote encoding style. Possible values (without quotes):
c9d61baf 966 * <ul>
deb22cec 967 * <li>ENT_COMPAT - (default) encode double quotes</li>
968 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
969 * <li>ENT_QUOTES - encode double and single quotes</li>
c9d61baf 970 * </ul>
36e1180b 971 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
972 * @return string sanitized string
973 */
974function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
975 // get translation table
976 $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
977 // convert characters
978 return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
979}
980
b54acf3f 981/**
982 * Tests if string contains 8bit symbols.
983 *
984 * If charset is not set, function defaults to default_charset.
91e0dccc 985 * $default_charset global must be set correctly if $charset is
b54acf3f 986 * not used.
987 * @param string $string tested string
988 * @param string $charset charset used in a string
989 * @return bool true if 8bit symbols are detected
17886554 990 * @since 1.5.1 and 1.4.4
b54acf3f 991 */
992function sq_is8bit($string,$charset='') {
993 global $default_charset;
994
995 if ($charset=='') $charset=$default_charset;
996
997 /**
998 * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
17886554 999 * Don't use \200-\237 for iso-8859-x charsets. This range
b54acf3f 1000 * stores control symbols in those charsets.
1001 * Use preg_match instead of ereg in order to avoid problems
1002 * with mbstring overloading
1003 */
1004 if (preg_match("/^iso-8859/i",$charset)) {
1005 $needle='/\240|[\241-\377]/';
1006 } else {
1007 $needle='/[\200-\237]|\240|[\241-\377]/';
1008 }
1009 return preg_match("$needle",$string);
1010}
1011
1012/**
1013 * Replacement of mb_list_encodings function
1014 *
1015 * This function provides replacement for function that is available only
1016 * in php 5.x. Function does not test all mbstring encodings. Only the ones
1017 * that might be used in SM translations.
1018 *
17886554 1019 * Supported strings are stored in session in order to reduce number of
b54acf3f 1020 * mb_internal_encoding function calls.
1021 *
91e0dccc 1022 * If you want to test all mbstring encodings - fill $list_of_encodings
b54acf3f 1023 * array.
17886554 1024 * @return array list of encodings supported by php mbstring extension
b54acf3f 1025 * @since 1.5.1
1026 */
1027function sq_mb_list_encodings() {
1028 if (! function_exists('mb_internal_encoding'))
1029 return array();
1030
1031 // don't try to test encodings, if they are already stored in session
1032 if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION))
1033 return $mb_supported_encodings;
1034
1035 // save original encoding
1036 $orig_encoding=mb_internal_encoding();
1037
1038 $list_of_encoding=array(
1039 'pass',
1040 'auto',
1041 'ascii',
1042 'jis',
1043 'utf-8',
1044 'sjis',
1045 'euc-jp',
1046 'iso-8859-1',
1047 'iso-8859-2',
1048 'iso-8859-7',
1049 'iso-8859-9',
1050 'iso-8859-15',
1051 'koi8-r',
1052 'koi8-u',
1053 'big5',
1054 'gb2312',
1055 'windows-1251',
1056 'windows-1255',
1057 'windows-1256',
1058 'tis-620',
1059 'iso-2022-jp',
1060 'euc-kr',
1061 'utf7-imap');
1062
1063 $supported_encodings=array();
1064
1065 foreach ($list_of_encoding as $encoding) {
1066 // try setting encodings. suppress warning messages
1067 if (@mb_internal_encoding($encoding))
1068 $supported_encodings[]=$encoding;
1069 }
1070
1071 // restore original encoding
1072 mb_internal_encoding($orig_encoding);
1073
1074 // register list in session
1075 sqsession_register($supported_encodings,'mb_supported_encodings');
1076
1077 return $supported_encodings;
1078}
1079
c7aff938 1080/**
1081 * Function returns number of characters in string.
1082 *
1083 * Returned number might be different from number of bytes in string,
1084 * if $charset is multibyte charset. Currently only utf-8 charset is
1085 * supported.
1086 * @param string $str string
1087 * @param string $charset charset
1088 * @since 1.5.1
1089 * @return integer number of characters in string
1090 */
1091function sq_strlen($str, $charset=''){
1092 // default option
1093 if ($charset=='') return strlen($str);
1094
1095 // use automatic charset detection, if function call asks for it
1096 if ($charset=='auto') {
1097 global $default_charset;
1098 set_my_charset();
1099 $charset=$default_charset;
1100 }
1101
1102 // lowercase charset name
1103 $charset=strtolower($charset);
1104
1105 // set initial returned length number
1106 $real_length=0;
1107
1108 // calculate string length according to charset
1109 // function can be modulized same way we modulize decode/encode/htmlentities
1110 if ($charset=='utf-8') {
1111 if (function_exists('mb_strlen')) {
1112 $real_length = mb_strlen($str,'utf-8');
1113 } else {
1114 // function needs length of string in bytes.
1115 // mbstring overloading might break it
1116 $str_length=strlen($str);
1117 $str_index=0;
1118 while ($str_index < $str_length) {
17886554 1119 // start of internal utf-8 multibyte character detection
c7aff938 1120 if (preg_match("/[\xC0-\xDF]/",$str[$str_index]) &&
1121 isset($str[$str_index+1]) &&
1122 preg_match("/[\x80-\xBF]/",$str[$str_index+1])) {
1123 // two byte utf-8
1124 $str_index=$str_index+2;
1125 $real_length++;
1126 } elseif (preg_match("/[\xE0-\xEF]/",$str[$str_index]) &&
1127 isset($str[$str_index+2]) &&
1128 preg_match("/[\x80-\xBF][\x80-\xBF]/",$str[$str_index+1].$str[$str_index+2])) {
1129 // three byte utf-8
1130 $str_index=$str_index+3;
1131 $real_length++;
1132 } elseif (preg_match("/[\xF0-\xF7]/",$str[$str_index]) &&
1133 isset($str[$str_index+3]) &&
1134 preg_match("/[\x80-\xBF][\x80-\xBF][\x80-\xBF]/",$str[$str_index+1].$str[$str_index+2].$str[$str_index+3])) {
1135 // four byte utf-8
1136 $str_index=$str_index+4;
1137 $real_length++;
1138 } elseif (preg_match("/[\xF8-\xFB]/",$str[$str_index]) &&
1139 isset($str[$str_index+4]) &&
1140 preg_match("/[\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF]/",
1141 $str[$str_index+1].$str[$str_index+2].$str[$str_index+3].$str[$str_index+4])) {
1142 // five byte utf-8
1143 $str_index=$str_index+5;
1144 $real_length++;
1145 } elseif (preg_match("/[\xFC-\xFD]/",$str[$str_index]) &&
1146 isset($str[$str_index+5]) &&
1147 preg_match("/[\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF]/",
1148 $str[$str_index+1].$str[$str_index+2].$str[$str_index+3].$str[$str_index+4].$str[$str_index+5])) {
1149 // six byte utf-8
1150 $str_index=$str_index+6;
1151 $real_length++;
1152 } else {
1153 $str_index++;
1154 $real_length++;
1155 }
17886554 1156 // end of internal utf-8 multibyte character detection
c7aff938 1157 }
1158 }
1159 // end of utf-8 length detection
1160 } elseif ($charset=='big5') {
1161 // TODO: add big5 string length detection
1162 $real_length=strlen($str);
1163 } elseif ($charset=='gb2312') {
1164 // TODO: add gb2312 string length detection
1165 $real_length=strlen($str);
1166 } elseif ($charset=='gb18030') {
1167 // TODO: add gb18030 string length detection
1168 $real_length=strlen($str);
1169 } elseif ($charset=='euc-jp') {
1170 // TODO: add euc-jp string length detection
1171 $real_length=strlen($str);
1172 } elseif ($charset=='euc-cn') {
1173 // TODO: add euc-cn string length detection
1174 $real_length=strlen($str);
1175 } elseif ($charset=='euc-tw') {
1176 // TODO: add euc-tw string length detection
1177 $real_length=strlen($str);
1178 } elseif ($charset=='euc-kr') {
1179 // TODO: add euc-kr string length detection
1180 $real_length=strlen($str);
1181 } else {
1182 $real_length=strlen($str);
1183 }
1184 return $real_length;
1185}
1186
17886554 1187/**
1188 * string padding with multibyte support
1189 *
1190 * @link http://www.php.net/str_pad
1191 * @param string $string original string
1192 * @param integer $width padded string width
1193 * @param string $pad padding symbols
1194 * @param integer $padtype padding type
1195 * (internal php defines, see str_pad() description)
1196 * @param string $charset charset used in original string
1197 * @return string padded string
1198 */
1199function sq_str_pad($string, $width, $pad, $padtype, $charset='') {
1200
1201 $charset = strtolower($charset);
1202 $padded_string = '';
1203
1204 switch ($charset) {
1205 case 'utf-8':
1206 case 'big5':
1207 case 'gb2312':
1208 case 'euc-kr':
1209 /*
1210 * all multibyte charsets try to increase width value by
1211 * adding difference between number of bytes and real length
1212 */
1213 $width = $width - sq_strlen($string,$charset) + strlen($string);
1214 default:
1215 $padded_string=str_pad($string,$width,$pad,$padtype);
1216 }
1217 return $padded_string;
1218}
43fdb2a4 1219$PHP_SELF = php_self();
4445e6b3 1220?>