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