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