49addede63768e15b53622b685a6e9bb7a716551
[squirrelmail.git] / functions / strings.php
1 <?php
2
3 /**
4 * strings.php
5 *
6 * Copyright (c) 1999-2005 The SquirrelMail Project Team
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 *
12 * @version $Id$
13 * @package squirrelmail
14 */
15
16 /**
17 * SquirrelMail version number -- DO NOT CHANGE
18 */
19 global $version;
20 $version = '1.5.1 [CVS]';
21
22 /**
23 * SquirrelMail internal version number -- DO NOT CHANGE
24 * $sm_internal_version = array (release, major, minor)
25 */
26 global $SQM_INTERNAL_VERSION;
27 $SQM_INTERNAL_VERSION = array(1,5,1);
28
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 */
34 require_once(SM_PATH . 'functions/global.php');
35
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 */
46 function 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 */
66 function 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 /**
78 * Checks for spaces in strings - only used if PHP doesn't have native ctype support
79 *
80 * @author Tomas Kuliavas
81 *
82 * You might be able to rewrite the function by adding short evaluation form.
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
96 * @return bool true when only whitespace symbols are present in test string
97 */
98 function sm_ctype_space($string) {
99 if ( preg_match('/^[\x09-\x0D]|^\x20/', $string) || $string=='') {
100 return true;
101 } else {
102 return false;
103 }
104 }
105
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 */
118 function &sqBodyWrap (&$body, $wrap) {
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
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} == ' ')) {
148
149 $pos++;
150
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
160 if (($body{$pos} == "\n" ) && (strlen($outString) != 0)) {
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 }
212 /**
213 * Set this to false to stop appending short strings to previous lines
214 */
215 $smartwrap = true;
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 }
223 // if this is a short line then just append it and continue outer loop
224 if (($outStringCol + $nextNewline - $pos) <= ($wrap - $citeLevel - 1) ) {
225 // if this is the final line in the input string then include
226 // any trailing newlines
227 // echo substr($body,$pos,$wrap). "<br />";
228 if (($nextNewline + 1 == $length) && ($body{$nextNewline} == "\n")) {
229 $nextNewline++;
230 }
231
232 // trim trailing spaces
233 $lastRealChar = $nextNewline;
234 while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space ($body{$lastRealChar}))) {
235 $lastRealChar--;
236 }
237 // decide if appending the short string is what we want
238 if (($nextNewline < $length && $body{$nextNewline} == "\n") &&
239 isset($lastRealChar)) {
240 $mypos = $pos;
241 //check the first word:
242 while (($mypos < $length) && ($body{$mypos} == '>')) {
243 $mypos++;
244 // skip over any spaces interleaved among the cite markers
245 while (($mypos < $length) && ($body{$mypos} == ' ')) {
246 $mypos++;
247 }
248 }
249 /*
250 $ldnspacecnt = 0;
251 if ($mypos == $nextNewline+1) {
252 while (($mypos < $length) && ($body{$mypos} == ' ')) {
253 $ldnspacecnt++;
254 }
255 }
256 */
257
258 $firstword = substr($body,$mypos,strpos($body,' ',$mypos) - $mypos);
259 //if ($dowrap || $ldnspacecnt > 1 || ($firstword && (
260 if (!$smartwrap || $firstword && (
261 $firstword{0} == '-' ||
262 $firstword{0} == '+' ||
263 $firstword{0} == '*' ||
264 $firstword{0} == strtoupper($firstword{0}) ||
265 strpos($firstword,':'))) {
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 }
274
275 }
276
277 $outString .= substr ($body, $pos, ($lastRealChar - $pos + 1));
278 $outStringCol += ($lastRealChar - $pos);
279 $pos = $nextNewline + 1;
280 continue;
281 }
282
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) {
290 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
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 /**
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, &amp;#039; comes up as 5 characters instead of 1.
354 * This should not add newlines to the end of lines.
355 *
356 * @param string line the line of text to wrap, by ref
357 * @param int wrap the maximum line lenth
358 * @param string charset name of charset used in $line string. Available since v.1.5.1.
359 * @return void
360 */
361 function sqWordWrap(&$line, $wrap, $charset='') {
362 global $languages, $squirrelmail_language;
363
364 // Use custom wrapping function, if translation provides it
365 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
366 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap')) {
367 if (mb_detect_encoding($line) != 'ASCII') {
368 $line = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap', $line, $wrap);
369 return;
370 }
371 }
372
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 }
380
381 $i = 0;
382 $line = $beginning_spaces;
383
384 while ($i < count($words)) {
385 /* Force one word to be on a line (minimum) */
386 $line .= $words[$i];
387 $line_len = strlen($beginning_spaces) + sq_strlen($words[$i],$charset) + 2;
388 if (isset($words[$i + 1]))
389 $line_len += sq_strlen($words[$i + 1],$charset);
390 $i ++;
391
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]))
397 $line_len += sq_strlen($words[$i],$charset) + 1;
398 else
399 $line_len += 1;
400 }
401
402 /* Skip spaces if they are the first thing on a continued line */
403 while (!isset($words[$i]) && $i < count($words)) {
404 $i ++;
405 }
406
407 /* Go to the next line if we have more to process */
408 if ($i < count($words)) {
409 $line .= "\n";
410 }
411 }
412 }
413
414 /**
415 * Does the opposite of sqWordWrap()
416 * @param string body the text to un-wordwrap
417 * @return void
418 */
419 function sqUnWordWrap(&$body) {
420 global $squirrelmail_language;
421
422 if ($squirrelmail_language == 'ja_JP') {
423 return;
424 }
425
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];
435 } else {
436 $CurrentRest = '';
437 }
438
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 /**
455 * If $haystack is a full mailbox name and $needle is the mailbox
456 * separator character, returns the last part of the mailbox name.
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
461 */
462 function readShortMailboxName($haystack, $needle) {
463
464 if ($needle == '') {
465 $elem = $haystack;
466 } else {
467 $parts = explode($needle, $haystack);
468 $elem = array_pop($parts);
469 while ($elem == '' && count($parts)) {
470 $elem = array_pop($parts);
471 }
472 }
473 return( $elem );
474 }
475
476 /**
477 * php_self
478 *
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 */
484 function php_self () {
485 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
486 return $req_uri;
487 }
488
489 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
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
497 return $php_self;
498 }
499
500 return '';
501 }
502
503
504 /**
505 * get_location
506 *
507 * Determines the location to forward to, relative to your server.
508 * This is used in HTTP Location: redirects.
509 * If this doesnt work correctly for you (although it should), you can
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/
514 *
515 * @return string the base url for this SquirrelMail installation
516 */
517 function get_location () {
518
519 global $imap_server_type;
520
521 /* Get the path, handle virtual directories */
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, '/'));
528 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
529 return $full_url . $path;
530 }
531
532 /* Check if this is a HTTPS or regular HTTP request. */
533 $proto = 'http://';
534
535 /*
536 * If you have 'SSLOptions +StdEnvVars' in your apache config
537 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
538 * OR if you are on port 443
539 */
540 $getEnvVar = getenv('HTTPS');
541 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
542 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
543 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
544 $proto = 'https://';
545 }
546
547 /* Get the hostname from the Host header or server config. */
548 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
549 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
550 $host = '';
551 }
552 }
553
554 $port = '';
555 if (! strstr($host, ':')) {
556 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
557 if (($server_port != 80 && $proto == 'http://') ||
558 ($server_port != 443 && $proto == 'https://')) {
559 $port = sprintf(':%d', $server_port);
560 }
561 }
562 }
563
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 */
567
568 if ($imap_server_type == 'macosx' && $port == ':16080') {
569 $port = '';
570 }
571
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;
577 }
578
579
580 /**
581 * Encrypts password
582 *
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
590 */
591 function 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 }
597
598 return base64_encode($encrypted);
599 }
600
601 /**
602 * Decrypts a password from the cookie
603 *
604 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
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 */
611 function 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 }
618
619 return $decrypted;
620 }
621
622
623 /**
624 * Randomizes the mt_rand() function.
625 *
626 * Toss this in strings or integers and it will seed the generator
627 * appropriately. With strings, it is better to get them long.
628 * Use md5() to lengthen smaller strings.
629 *
630 * @param mixed val a value to seed the random number generator
631 * @return void
632 */
633 function sq_mt_seed($Val) {
634 /* if mt_getrandmax() does not return a 2^n - 1 number,
635 this might not work well. This uses $Max as a bitmask. */
636 $Max = mt_getrandmax();
637
638 if (! is_int($Val)) {
639 $Val = crc32($Val);
640 }
641
642 if ($Val < 0) {
643 $Val *= -1;
644 }
645
646 if ($Val == 0) {
647 return;
648 }
649
650 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
651 }
652
653
654 /**
655 * Init random number generator
656 *
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.
660 *
661 * @return void
662 */
663 function sq_mt_randomize() {
664 static $randomized;
665
666 if ($randomized) {
667 return;
668 }
669
670 /* Global. */
671 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
672 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
673 sq_mt_seed((int)((double) microtime() * 1000000));
674 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
675
676 /* getrusage */
677 if (function_exists('getrusage')) {
678 /* Avoid warnings with Win32 */
679 $dat = @getrusage();
680 if (isset($dat) && is_array($dat)) {
681 $Str = '';
682 foreach ($dat as $k => $v)
683 {
684 $Str .= $k . $v;
685 }
686 sq_mt_seed(md5($Str));
687 }
688 }
689
690 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
691 sq_mt_seed(md5($unique_id));
692 }
693
694 $randomized = 1;
695 }
696
697 /**
698 * Creates encryption key
699 *
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 */
706 function OneTimePadCreate ($length=100) {
707 sq_mt_randomize();
708
709 $pad = '';
710 for ($i = 0; $i < $length; $i++) {
711 $pad .= chr(mt_rand(0,255));
712 }
713
714 return base64_encode($pad);
715 }
716
717 /**
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
722 */
723 function show_readable_size($bytes) {
724 $bytes /= 1024;
725 $type = 'k';
726
727 if ($bytes / 1024 > 1) {
728 $bytes /= 1024;
729 $type = 'M';
730 }
731
732 if ($bytes < 10) {
733 $bytes *= 10;
734 settype($bytes, 'integer');
735 $bytes /= 10;
736 } else {
737 settype($bytes, 'integer');
738 }
739
740 return $bytes . '<small>&nbsp;' . $type . '</small>';
741 }
742
743 /**
744 * Generates a random string from the character set you pass in
745 *
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
754 */
755 function 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 }
765
766 if (($size < 1) || (strlen($chars) < 1)) {
767 return '';
768 }
769
770 sq_mt_randomize(); /* Initialize the random number generator */
771
772 $String = '';
773 $j = strlen( $chars ) - 1;
774 while (strlen($String) < $size) {
775 $String .= $chars{mt_rand(0, $j)};
776 }
777
778 return $String;
779 }
780
781 /**
782 * Escapes special characters for use in IMAP commands.
783 *
784 * @param string the string to escape
785 * @return string the escaped string
786 */
787 function quoteimap($str) {
788 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
789 }
790
791 /**
792 * Trims array
793 *
794 * Trims every element in the array, ie. remove the first char of each element
795 * @param array array the array to trim
796 */
797 function 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);
803 }
804 } else {
805 $$k = substr($v, 1);
806 }
807
808 /* Re-assign back to array. */
809 $array[$k] = $$k;
810 }
811 }
812
813 /**
814 * Create compose link
815 *
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 */
822 function makeComposeLink($url, $text = null, $target='')
823 {
824 global $compose_new_win,$javascript_on;
825
826 if(!$text) {
827 $text = _("Compose");
828 }
829
830
831 // if not using "compose in new window", make
832 // regular link and be done with it
833 if($compose_new_win != '1') {
834 return makeInternalLink($url, $text, $target);
835 }
836
837
838 // build the compose in new window link...
839
840
841 // if javascript is on, use onclick event to handle it
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
847
848 // otherwise, just open new window using regular HTML
849 return makeInternalLink($url, $text, '_blank');
850
851 }
852
853 /**
854 * Print variable
855 *
856 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
857 *
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.
861 * The output is wrapped in <<pre>> and <</pre>> tags.
862 *
863 * @return void
864 */
865 function sm_print_r() {
866 ob_start(); // Buffer output
867 foreach(func_get_args() as $var) {
868 print_r($var);
869 echo "\n";
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));
874 // make sure that $aMethods is array and array is not empty
875 if (is_array($aMethods) && $aMethods!=array()) {
876 echo "Object methods:\n";
877 foreach($aMethods as $method) {
878 echo '* ' . $method . "\n";
879 }
880 }
881 echo "\n";
882 }
883 }
884 $buffer = ob_get_contents(); // Grab the print_r output
885 ob_end_clean(); // Silently discard the output & stop buffering
886 print '<pre>';
887 print htmlentities($buffer);
888 print '</pre>';
889 }
890
891 /**
892 * version of fwrite which checks for failure
893 */
894 function sq_fwrite($fp, $string) {
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;
903 }
904
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):
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>
915 * @param integer $quote_style quote encoding style. Possible values (without quotes):
916 * <ul>
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>
920 * </ul>
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 */
924 function 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,
934 array("<" => '&lt;',
935 ">" => '&gt;')
936 );
937 // double quotes
938 if ($quote_style == ENT_COMPAT)
939 $sq_html_ent_table = array_merge($sq_html_ent_table,
940 array("\"" => '&quot;')
941 );
942
943 // double and single quotes
944 if ($quote_style == ENT_QUOTES)
945 $sq_html_ent_table = array_merge($sq_html_ent_table,
946 array("\"" => '&quot;',
947 "'" => '&#39;')
948 );
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.
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.
976 *
977 * @param string $string string that has to be sanitized
978 * @param integer $quote_style quote encoding style. Possible values (without quotes):
979 * <ul>
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>
983 * </ul>
984 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
985 * @return string sanitized string
986 */
987 function 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
994 /**
995 * Tests if string contains 8bit symbols.
996 *
997 * If charset is not set, function defaults to default_charset.
998 * $default_charset global must be set correctly if $charset is
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
1003 * @since 1.5.1 and 1.4.4
1004 */
1005 function 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.
1012 * Don't use \200-\237 for iso-8859-x charsets. This range
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 *
1032 * Supported strings are stored in session in order to reduce number of
1033 * mb_internal_encoding function calls.
1034 *
1035 * If you want to test all mbstring encodings - fill $list_of_encodings
1036 * array.
1037 * @return array list of encodings supported by php mbstring extension
1038 * @since 1.5.1
1039 */
1040 function 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
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 */
1104 function 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) {
1132 // start of internal utf-8 multibyte character detection
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 }
1169 // end of internal utf-8 multibyte character detection
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
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 */
1212 function 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 }
1232 $PHP_SELF = php_self();
1233 ?>