Possible fix for our wrapping problem. Please review it because I might have
[squirrelmail.git] / functions / strings.php
1 <?php
2
3 /**
4 * strings.php
5 *
6 * Copyright (c) 1999-2004 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 //sm_print_r($body);
120 //check for ctype support, and fake it if it doesn't exist
121 if (!function_exists('ctype_space')) {
122 function ctype_space ($string) {
123 return sm_ctype_space($string);
124 }
125 }
126
127 // the newly wrapped text
128 $outString = '';
129 // current column since the last newline in the outstring
130 $outStringCol = 0;
131 $length = strlen($body);
132 // where we are in the original string
133 $pos = 0;
134 // the number of >>> citation markers we are currently at
135 $citeLevel = 0;
136
137 // the main loop, whenever we start a newline of input text
138 // we start from here
139 while ($pos < $length) {
140 // we're at the beginning of a line, get the new cite level
141 $newCiteLevel = 0;
142
143 while (($pos < $length) && ($body{$pos} == '>')) {
144 $newCiteLevel++;
145 $pos++;
146
147 // skip over any spaces interleaved among the cite markers
148 while (($pos < $length) && ($body{$pos} == ' ')) {
149
150 $pos++;
151
152 }
153 if ($pos >= $length) {
154 break;
155 }
156 }
157
158 // special case: if this is a blank line then maintain it
159 // (i.e. try to preserve original paragraph breaks)
160 // unless they occur at the very beginning of the text
161 if (($body{$pos} == "\n" ) && (strlen($outString) != 0)) {
162 $outStringLast = $outString{strlen($outString) - 1};
163 if ($outStringLast != "\n") {
164 $outString .= "\n";
165 }
166 sqMakeCite ($outString, $newCiteLevel);
167 $outString .= "\n";
168 $pos++;
169 $outStringCol = 0;
170 continue;
171 }
172
173 // if the cite level has changed, then start a new line
174 // with the new cite level.
175 if (($citeLevel != $newCiteLevel) && ($pos > ($newCiteLevel + 1)) && ($outStringCol != 0)) {
176 sqMakeNewLine ($outString, 0, $outStringCol);
177 }
178
179 $citeLevel = $newCiteLevel;
180
181 // prepend the quote level if necessary
182 if ($outStringCol == 0) {
183 sqMakeCite ($outString, $citeLevel);
184 // if we added a citation then move the column
185 // out by citelevel + 1 (the cite markers + the space)
186 $outStringCol = $citeLevel + ($citeLevel ? 1 : 0);
187 } else if ($outStringCol > $citeLevel) {
188 // not a cite and we're not at the beginning of a line
189 // in the output. add a space to separate the new text
190 // from previous text.
191 $outString .= ' ';
192 $outStringCol++;
193 }
194
195 // find the next newline -- we don't want to go further than that
196 $nextNewline = strpos ($body, "\n", $pos);
197 if ($nextNewline === FALSE) {
198 $nextNewline = $length;
199 }
200
201 // Don't wrap unquoted lines at all. For now the textarea
202 // will work fine for this. Maybe revisit this later though
203 // (for completeness more than anything else, I think)
204 if ($citeLevel == 0) {
205 $outString .= substr ($body, $pos, ($nextNewline - $pos));
206 $outStringCol = $nextNewline - $pos;
207 if ($nextNewline != $length) {
208 sqMakeNewLine ($outString, 0, $outStringCol);
209 }
210 $pos = $nextNewline + 1;
211 continue;
212 }
213
214 // inner loop, (obviously) handles wrapping up to
215 // the next newline
216 while ($pos < $nextNewline) {
217 // skip over initial spaces
218 while (($pos < $nextNewline) && (ctype_space ($body{$pos}))) {
219 $pos++;
220 }
221
222 // if this is a short line then just append it and continue outer loop
223 if (($outStringCol + $nextNewline - $pos) <= ($wrap - $citeLevel - 1) ) {
224 // if this is the final line in the input string then include
225 // any trailing newlines
226 // echo substr($body,$pos,$wrap). "<br />";
227 if (($nextNewline + 1 == $length) && ($body{$nextNewline} == "\n")) {
228 $nextNewline++;
229 }
230
231 if (($nextNewline < $length && $body{$nextNewline} == "\n") &&
232 isset($lastRealChar)) {
233
234 // trim trailing spaces
235 $lastRealChar = $nextNewline;
236 while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space ($body{$lastRealChar}))) {
237 $lastRealChar--;
238 }
239
240 //check the first word:
241 $mypos = $nextNewline+1;
242 while (($mypos < $length) && ($body{$mypos} == '>')) {
243 $mypos++;
244
245 // skip over any spaces interleaved among the cite markers
246 while (($mypos < $length) && ($body{$mypos} == ' ')) {
247
248 $mypos++;
249
250 }
251 }
252 $firstword = substr($body,$mypos,strpos($body,' ',$mypos) - $mypos);
253 if ($firstword && ($firstword{0} == '-' ||
254 $firstword{0} == '+' ||
255 $firstword{0} == '*' ||
256 strpos($firstword,':'))) {
257 $outString .= substr($body,$pos,($lastRealChar - $pos+1));
258 $outStringCol += ($lastRealChar - $pos);
259 sqMakeNewLine($outString,$citeLevel,$outStringCol);
260 $nextNewline++;
261 $pos = $nextNewline;
262 $outStringCol--;
263 continue; //break 2;
264 }
265 }
266
267
268 // trim trailing spaces
269 $lastRealChar = $nextNewline;
270 while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space ($body{$lastRealChar}))) {
271 $lastRealChar--;
272 }
273 $outString .= substr ($body, $pos, ($lastRealChar - $pos + 1));
274 $outStringCol += ($lastRealChar - $pos);
275 $pos = $nextNewline + 1;
276 continue;
277 }
278 $eol = $pos + $wrap - $citeLevel - $outStringCol;
279 // eol is the tentative end of line.
280 // look backwards for there for a whitespace to break at.
281 // if it's already less than our current position then
282 // our current line is already too long, break immediately
283 // and restart outer loop
284 if ($eol <= $pos) {
285 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
286 continue;
287 }
288
289 // start looking backwards for whitespace to break at.
290 $breakPoint = $eol;
291 while (($breakPoint > $pos) && (! ctype_space ($body{$breakPoint}))) {
292 $breakPoint--;
293 }
294
295 // if we didn't find a breakpoint by looking backward then we
296 // need to figure out what to do about that
297 if ($breakPoint == $pos) {
298 // if we are not at the beginning then end this line
299 // and start a new loop
300 if ($outStringCol > ($citeLevel + 1)) {
301 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
302 continue;
303 } else {
304 // just hard break here. most likely we are breaking
305 // a really long URL. could also try searching
306 // forward for a break point, which is what Mozilla
307 // does. don't bother for now.
308 $breakPoint = $eol;
309 }
310 }
311
312 // special case: maybe we should have wrapped last
313 // time. if the first breakpoint here makes the
314 // current line too long and there is already text on
315 // the current line, break and loop again if at
316 // beginning of current line, don't force break
317 $SLOP = 6;
318 if ((($outStringCol + ($breakPoint - $pos)) > ($wrap + $SLOP)) && ($outStringCol > ($citeLevel + 1))) {
319 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
320 continue;
321 }
322
323 // skip newlines or whitespace at the beginning of the string
324 $substring = substr ($body, $pos, ($breakPoint - $pos));
325 $substring = rtrim ($substring); // do rtrim and ctype_space have the same ideas about whitespace?
326 $outString .= $substring;
327 $outStringCol += strlen ($substring);
328 // advance past the whitespace which caused the wrap
329 $pos = $breakPoint;
330 while (($pos < $length) && (ctype_space ($body{$pos}))) {
331 $pos++;
332 }
333 if ($pos < $length) {
334 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
335 }
336 }
337 }
338
339 return $outString;
340 }
341
342 /**
343 * Wraps text at $wrap characters
344 *
345 * Has a problem with special HTML characters, so call this before
346 * you do character translation.
347 *
348 * Specifically, &#039 comes up as 5 characters instead of 1.
349 * This should not add newlines to the end of lines.
350 *
351 * @param string line the line of text to wrap, by ref
352 * @param int wrap the maximum line lenth
353 * @return void
354 */
355 function sqWordWrap(&$line, $wrap) {
356 global $languages, $squirrelmail_language;
357
358 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
359 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
360 if (mb_detect_encoding($line) != 'ASCII') {
361 $line = $languages[$squirrelmail_language]['XTRA_CODE']('wordwrap', $line, $wrap);
362 return;
363 }
364 }
365
366 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
367 $beginning_spaces = $regs[1];
368 if (isset($regs[2])) {
369 $words = explode(' ', $regs[2]);
370 } else {
371 $words = '';
372 }
373
374 $i = 0;
375 $line = $beginning_spaces;
376
377 while ($i < count($words)) {
378 /* Force one word to be on a line (minimum) */
379 $line .= $words[$i];
380 $line_len = strlen($beginning_spaces) + strlen($words[$i]) + 2;
381 if (isset($words[$i + 1]))
382 $line_len += strlen($words[$i + 1]);
383 $i ++;
384
385 /* Add more words (as long as they fit) */
386 while ($line_len < $wrap && $i < count($words)) {
387 $line .= ' ' . $words[$i];
388 $i++;
389 if (isset($words[$i]))
390 $line_len += strlen($words[$i]) + 1;
391 else
392 $line_len += 1;
393 }
394
395 /* Skip spaces if they are the first thing on a continued line */
396 while (!isset($words[$i]) && $i < count($words)) {
397 $i ++;
398 }
399
400 /* Go to the next line if we have more to process */
401 if ($i < count($words)) {
402 $line .= "\n";
403 }
404 }
405 }
406
407 /**
408 * Does the opposite of sqWordWrap()
409 * @param string body the text to un-wordwrap
410 * @return void
411 */
412 function sqUnWordWrap(&$body) {
413 global $squirrelmail_language;
414
415 if ($squirrelmail_language == 'ja_JP') {
416 return;
417 }
418
419 $lines = explode("\n", $body);
420 $body = '';
421 $PreviousSpaces = '';
422 $cnt = count($lines);
423 for ($i = 0; $i < $cnt; $i ++) {
424 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
425 $CurrentSpaces = $regs[1];
426 if (isset($regs[2])) {
427 $CurrentRest = $regs[2];
428 } else {
429 $CurrentRest = '';
430 }
431
432 if ($i == 0) {
433 $PreviousSpaces = $CurrentSpaces;
434 $body = $lines[$i];
435 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
436 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
437 && strlen($CurrentRest)) { /* and there's a line to continue with */
438 $body .= ' ' . $CurrentRest;
439 } else {
440 $body .= "\n" . $lines[$i];
441 $PreviousSpaces = $CurrentSpaces;
442 }
443 }
444 $body .= "\n";
445 }
446
447 /**
448 * If $haystack is a full mailbox name and $needle is the mailbox
449 * separator character, returns the last part of the mailbox name.
450 *
451 * @param string haystack full mailbox name to search
452 * @param string needle the mailbox separator character
453 * @return string the last part of the mailbox name
454 */
455 function readShortMailboxName($haystack, $needle) {
456
457 if ($needle == '') {
458 $elem = $haystack;
459 } else {
460 $parts = explode($needle, $haystack);
461 $elem = array_pop($parts);
462 while ($elem == '' && count($parts)) {
463 $elem = array_pop($parts);
464 }
465 }
466 return( $elem );
467 }
468
469 /**
470 * php_self
471 *
472 * Creates an URL for the page calling this function, using either the PHP global
473 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
474 *
475 * @return string the complete url for this page
476 */
477 function php_self () {
478 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
479 return $req_uri;
480 }
481
482 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
483
484 // need to add query string to end of PHP_SELF to match REQUEST_URI
485 //
486 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
487 $php_self .= '?' . $query_string;
488 }
489
490 return $php_self;
491 }
492
493 return '';
494 }
495
496
497 /**
498 * get_location
499 *
500 * Determines the location to forward to, relative to your server.
501 * This is used in HTTP Location: redirects.
502 * If this doesnt work correctly for you (although it should), you can
503 * remove all this code except the last two lines, and have it return
504 * the right URL for your site, something like:
505 *
506 * http://www.example.com/squirrelmail/
507 *
508 * @return string the base url for this SquirrelMail installation
509 */
510 function get_location () {
511
512 global $imap_server_type;
513
514 /* Get the path, handle virtual directories */
515 if(strpos(php_self(), '?')) {
516 $path = substr(php_self(), 0, strpos(php_self(), '?'));
517 } else {
518 $path = php_self();
519 }
520 $path = substr($path, 0, strrpos($path, '/'));
521 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
522 return $full_url . $path;
523 }
524
525 /* Check if this is a HTTPS or regular HTTP request. */
526 $proto = 'http://';
527
528 /*
529 * If you have 'SSLOptions +StdEnvVars' in your apache config
530 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
531 * OR if you are on port 443
532 */
533 $getEnvVar = getenv('HTTPS');
534 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
535 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
536 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
537 $proto = 'https://';
538 }
539
540 /* Get the hostname from the Host header or server config. */
541 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
542 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
543 $host = '';
544 }
545 }
546
547 $port = '';
548 if (! strstr($host, ':')) {
549 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
550 if (($server_port != 80 && $proto == 'http://') ||
551 ($server_port != 443 && $proto == 'https://')) {
552 $port = sprintf(':%d', $server_port);
553 }
554 }
555 }
556
557 /* this is a workaround for the weird macosx caching that
558 causes Apache to return 16080 as the port number, which causes
559 SM to bail */
560
561 if ($imap_server_type == 'macosx' && $port == ':16080') {
562 $port = '';
563 }
564
565 /* Fallback is to omit the server name and use a relative */
566 /* URI, although this is not RFC 2616 compliant. */
567 $full_url = ($host ? $proto . $host . $port : '');
568 sqsession_register($full_url, 'sq_base_url');
569 return $full_url . $path;
570 }
571
572
573 /**
574 * Encrypts password
575 *
576 * These functions are used to encrypt the password before it is
577 * stored in a cookie. The encryption key is generated by
578 * OneTimePadCreate();
579 *
580 * @param string string the (password)string to encrypt
581 * @param string epad the encryption key
582 * @return string the base64-encoded encrypted password
583 */
584 function OneTimePadEncrypt ($string, $epad) {
585 $pad = base64_decode($epad);
586 $encrypted = '';
587 for ($i = 0; $i < strlen ($string); $i++) {
588 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
589 }
590
591 return base64_encode($encrypted);
592 }
593
594 /**
595 * Decrypts a password from the cookie
596 *
597 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
598 * This uses the encryption key that is stored in the session.
599 *
600 * @param string string the string to decrypt
601 * @param string epad the encryption key from the session
602 * @return string the decrypted password
603 */
604 function OneTimePadDecrypt ($string, $epad) {
605 $pad = base64_decode($epad);
606 $encrypted = base64_decode ($string);
607 $decrypted = '';
608 for ($i = 0; $i < strlen ($encrypted); $i++) {
609 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
610 }
611
612 return $decrypted;
613 }
614
615
616 /**
617 * Randomizes the mt_rand() function.
618 *
619 * Toss this in strings or integers and it will seed the generator
620 * appropriately. With strings, it is better to get them long.
621 * Use md5() to lengthen smaller strings.
622 *
623 * @param mixed val a value to seed the random number generator
624 * @return void
625 */
626 function sq_mt_seed($Val) {
627 /* if mt_getrandmax() does not return a 2^n - 1 number,
628 this might not work well. This uses $Max as a bitmask. */
629 $Max = mt_getrandmax();
630
631 if (! is_int($Val)) {
632 $Val = crc32($Val);
633 }
634
635 if ($Val < 0) {
636 $Val *= -1;
637 }
638
639 if ($Val = 0) {
640 return;
641 }
642
643 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
644 }
645
646
647 /**
648 * Init random number generator
649 *
650 * This function initializes the random number generator fairly well.
651 * It also only initializes it once, so you don't accidentally get
652 * the same 'random' numbers twice in one session.
653 *
654 * @return void
655 */
656 function sq_mt_randomize() {
657 static $randomized;
658
659 if ($randomized) {
660 return;
661 }
662
663 /* Global. */
664 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
665 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
666 sq_mt_seed((int)((double) microtime() * 1000000));
667 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
668
669 /* getrusage */
670 if (function_exists('getrusage')) {
671 /* Avoid warnings with Win32 */
672 $dat = @getrusage();
673 if (isset($dat) && is_array($dat)) {
674 $Str = '';
675 foreach ($dat as $k => $v)
676 {
677 $Str .= $k . $v;
678 }
679 sq_mt_seed(md5($Str));
680 }
681 }
682
683 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
684 sq_mt_seed(md5($unique_id));
685 }
686
687 $randomized = 1;
688 }
689
690 /**
691 * Creates encryption key
692 *
693 * Creates an encryption key for encrypting the password stored in the cookie.
694 * The encryption key itself is stored in the session.
695 *
696 * @param int length optional, length of the string to generate
697 * @return string the encryption key
698 */
699 function OneTimePadCreate ($length=100) {
700 sq_mt_randomize();
701
702 $pad = '';
703 for ($i = 0; $i < $length; $i++) {
704 $pad .= chr(mt_rand(0,255));
705 }
706
707 return base64_encode($pad);
708 }
709
710 /**
711 * Returns a string showing the size of the message/attachment.
712 *
713 * @param int bytes the filesize in bytes
714 * @return string the filesize in human readable format
715 */
716 function show_readable_size($bytes) {
717 $bytes /= 1024;
718 $type = 'k';
719
720 if ($bytes / 1024 > 1) {
721 $bytes /= 1024;
722 $type = 'M';
723 }
724
725 if ($bytes < 10) {
726 $bytes *= 10;
727 settype($bytes, 'integer');
728 $bytes /= 10;
729 } else {
730 settype($bytes, 'integer');
731 }
732
733 return $bytes . '<small>&nbsp;' . $type . '</small>';
734 }
735
736 /**
737 * Generates a random string from the caracter set you pass in
738 *
739 * @param int size the size of the string to generate
740 * @param string chars a string containing the characters to use
741 * @param int flags a flag to add a specific set to the characters to use:
742 * Flags:
743 * 1 = add lowercase a-z to $chars
744 * 2 = add uppercase A-Z to $chars
745 * 4 = add numbers 0-9 to $chars
746 * @return string the random string
747 */
748 function GenerateRandomString($size, $chars, $flags = 0) {
749 if ($flags & 0x1) {
750 $chars .= 'abcdefghijklmnopqrstuvwxyz';
751 }
752 if ($flags & 0x2) {
753 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
754 }
755 if ($flags & 0x4) {
756 $chars .= '0123456789';
757 }
758
759 if (($size < 1) || (strlen($chars) < 1)) {
760 return '';
761 }
762
763 sq_mt_randomize(); /* Initialize the random number generator */
764
765 $String = '';
766 $j = strlen( $chars ) - 1;
767 while (strlen($String) < $size) {
768 $String .= $chars{mt_rand(0, $j)};
769 }
770
771 return $String;
772 }
773
774 /**
775 * Escapes special characters for use in IMAP commands.
776 *
777 * @param string the string to escape
778 * @return string the escaped string
779 */
780 function quoteimap($str) {
781 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
782 }
783
784 /**
785 * Trims array
786 *
787 * Trims every element in the array, ie. remove the first char of each element
788 * @param array array the array to trim
789 */
790 function TrimArray(&$array) {
791 foreach ($array as $k => $v) {
792 global $$k;
793 if (is_array($$k)) {
794 foreach ($$k as $k2 => $v2) {
795 $$k[$k2] = substr($v2, 1);
796 }
797 } else {
798 $$k = substr($v, 1);
799 }
800
801 /* Re-assign back to array. */
802 $array[$k] = $$k;
803 }
804 }
805
806 /**
807 * Create compose link
808 *
809 * Returns a link to the compose-page, taking in consideration
810 * the compose_in_new and javascript settings.
811 * @param string url the URL to the compose page
812 * @param string text the link text, default "Compose"
813 * @return string a link to the compose page
814 */
815 function makeComposeLink($url, $text = null, $target='')
816 {
817 global $compose_new_win,$javascript_on;
818
819 if(!$text) {
820 $text = _("Compose");
821 }
822
823
824 // if not using "compose in new window", make
825 // regular link and be done with it
826 if($compose_new_win != '1') {
827 return makeInternalLink($url, $text, $target);
828 }
829
830
831 // build the compose in new window link...
832
833
834 // if javascript is on, use onClick event to handle it
835 if($javascript_on) {
836 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
837 return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
838 }
839
840
841 // otherwise, just open new window using regular HTML
842 return makeInternalLink($url, $text, '_blank');
843
844 }
845
846 /**
847 * Print variable
848 *
849 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
850 *
851 * Debugging function - does the same as print_r, but makes sure special
852 * characters are converted to htmlentities first. This will allow
853 * values like <some@email.address> to be displayed.
854 * The output is wrapped in <<pre>> and <</pre>> tags.
855 *
856 * @return void
857 */
858 function sm_print_r() {
859 ob_start(); // Buffer output
860 foreach(func_get_args() as $var) {
861 print_r($var);
862 echo "\n";
863 }
864 $buffer = ob_get_contents(); // Grab the print_r output
865 ob_end_clean(); // Silently discard the output & stop buffering
866 print '<pre>';
867 print htmlentities($buffer);
868 print '</pre>';
869 }
870
871 /**
872 * version of fwrite which checks for failure
873 */
874 function sq_fwrite($fp, $string) {
875 // write to file
876 $count = @fwrite($fp,$string);
877 // the number of bytes written should be the length of the string
878 if($count != strlen($string)) {
879 return FALSE;
880 }
881
882 return $count;
883 }
884
885 /**
886 * sq_get_html_translation_table
887 *
888 * Returns the translation table used by sq_htmlentities()
889 *
890 * @param integer $table html translation table. Possible values (without quotes):
891 * <ul>
892 * <li>HTML_ENTITIES - full html entities table defined by charset</li>
893 * <li>HTML_SPECIALCHARS - html special characters table</li>
894 * </ul>
895 * @param integer $quote_style quote encoding style. Possible values (without quotes):
896 * <ul>
897 * <li>ENT_COMPAT - (default) encode double quotes</li>
898 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
899 * <li>ENT_QUOTES - encode double and single quotes</li>
900 * </ul>
901 * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
902 * @return array html translation array
903 */
904 function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
905 global $default_charset;
906
907 if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
908
909 // Start array with ampersand
910 $sq_html_ent_table = array( "&" => '&amp;' );
911
912 // < and >
913 $sq_html_ent_table = array_merge($sq_html_ent_table,
914 array("<" => '&lt;',
915 ">" => '&gt;')
916 );
917 // double quotes
918 if ($quote_style == ENT_COMPAT)
919 $sq_html_ent_table = array_merge($sq_html_ent_table,
920 array("\"" => '&quot;')
921 );
922
923 // double and single quotes
924 if ($quote_style == ENT_QUOTES)
925 $sq_html_ent_table = array_merge($sq_html_ent_table,
926 array("\"" => '&quot;',
927 "'" => '&#39;')
928 );
929
930 if ($charset=='auto') $charset=$default_charset;
931
932 // add entities that depend on charset
933 switch($charset){
934 case 'iso-8859-1':
935 include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
936 break;
937 case 'utf-8':
938 include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
939 break;
940 case 'us-ascii':
941 default:
942 break;
943 }
944 // return table
945 return $sq_html_ent_table;
946 }
947
948 /**
949 * sq_htmlentities
950 *
951 * Convert all applicable characters to HTML entities.
952 * Minimal php requirement - v.4.0.5
953 *
954 * @param string $string string that has to be sanitized
955 * @param integer $quote_style quote encoding style. Possible values (without quotes):
956 * <ul>
957 * <li>ENT_COMPAT - (default) encode double quotes</li>
958 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
959 * <li>ENT_QUOTES - encode double and single quotes</li>
960 * </ul>
961 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
962 * @return string sanitized string
963 */
964 function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
965 // get translation table
966 $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
967 // convert characters
968 return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
969 }
970
971 $PHP_SELF = php_self();
972 ?>