6 * Copyright (c) 1999-2004 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * This code provides various string manipulation functions that are
10 * used by the rest of the Squirrelmail code.
13 * @package squirrelmail
17 * SquirrelMail version number -- DO NOT CHANGE
20 $version = '1.5.1 [CVS]';
23 * SquirrelMail internal version number -- DO NOT CHANGE
24 * $sm_internal_version = array (release, major, minor)
26 global $SQM_INTERNAL_VERSION;
27 $SQM_INTERNAL_VERSION = array(1,5,1);
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.
34 require_once(SM_PATH
. 'functions/global.php');
37 * Appends citation markers to the string.
38 * Also appends a trailing space.
40 * @author Justus Pendleton
42 * @param string str The string to append to
43 * @param int citeLevel the number of markers to append
46 function sqMakeCite (&$str, $citeLevel) {
47 for ($i = 0; $i < $citeLevel; $i++
) {
50 if ($citeLevel != 0) {
56 * Create a newline in the string, adding citation
57 * markers to the newline as necessary.
59 * @author Justus Pendleton
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
66 function sqMakeNewLine (&$str, $citeLevel, &$column) {
70 sqMakeCite ($str, $citeLevel);
71 $column = $citeLevel +
1;
78 * Checks for spaces in strings - only used if PHP doesn't have native ctype support
80 * @author Tomas Kuliavas
82 * You might be able to rewrite the function by adding short evaluation form.
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.
89 * - no-break space ( ) - it is 8bit symbol, that depends on charset.
90 * there are at least three different charset groups that have nbsp in
93 * I don't see any charset/nbsp options in php ctype either.
95 * @param string $string tested string
96 * @return bool true when only whitespace symbols are present in test string
98 function sm_ctype_space($string) {
99 if ( preg_match('/^[\x09-\x0D]|^\x20/', $string) ||
$string=='') {
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.
112 * @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
118 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);
127 // the newly wrapped text
129 // current column since the last newline in the outstring
131 $length = strlen($body);
132 // where we are in the original string
134 // the number of >>> citation markers we are currently at
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
143 while (($pos < $length) && ($body{$pos} == '>')) {
147 // skip over any spaces interleaved among the cite markers
148 while (($pos < $length) && ($body{$pos} == ' ')) {
153 if ($pos >= $length) {
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") {
166 sqMakeCite ($outString, $newCiteLevel);
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);
179 $citeLevel = $newCiteLevel;
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.
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;
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);
210 $pos = $nextNewline +
1;
214 // inner loop, (obviously) handles wrapping up to
216 while ($pos < $nextNewline) {
217 // skip over initial spaces
218 while (($pos < $nextNewline) && (ctype_space ($body{$pos}))) {
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")) {
231 if (($nextNewline < $length && $body{$nextNewline} == "\n") &&
232 isset($lastRealChar)) {
234 // trim trailing spaces
235 $lastRealChar = $nextNewline;
236 while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space ($body{$lastRealChar}))) {
240 //check the first word:
241 $mypos = $nextNewline+
1;
242 while (($mypos < $length) && ($body{$mypos} == '>')) {
245 // skip over any spaces interleaved among the cite markers
246 while (($mypos < $length) && ($body{$mypos} == ' ')) {
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);
268 // trim trailing spaces
269 $lastRealChar = $nextNewline;
270 while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space ($body{$lastRealChar}))) {
273 $outString .= substr ($body, $pos, ($lastRealChar - $pos +
1));
274 $outStringCol +
= ($lastRealChar - $pos);
275 $pos = $nextNewline +
1;
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
285 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
289 // start looking backwards for whitespace to break at.
291 while (($breakPoint > $pos) && (! ctype_space ($body{$breakPoint}))) {
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);
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.
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
318 if ((($outStringCol +
($breakPoint - $pos)) > ($wrap +
$SLOP)) && ($outStringCol > ($citeLevel +
1))) {
319 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
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
330 while (($pos < $length) && (ctype_space ($body{$pos}))) {
333 if ($pos < $length) {
334 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
343 * Wraps text at $wrap characters
345 * Has a problem with special HTML characters, so call this before
346 * you do character translation.
348 * Specifically, ' comes up as 5 characters instead of 1.
349 * This should not add newlines to the end of lines.
351 * @param string line the line of text to wrap, by ref
352 * @param int wrap the maximum line lenth
355 function sqWordWrap(&$line, $wrap) {
356 global $languages, $squirrelmail_language;
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);
366 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
367 $beginning_spaces = $regs[1];
368 if (isset($regs[2])) {
369 $words = explode(' ', $regs[2]);
375 $line = $beginning_spaces;
377 while ($i < count($words)) {
378 /* Force one word to be on a line (minimum) */
380 $line_len = strlen($beginning_spaces) +
strlen($words[$i]) +
2;
381 if (isset($words[$i +
1]))
382 $line_len +
= strlen($words[$i +
1]);
385 /* Add more words (as long as they fit) */
386 while ($line_len < $wrap && $i < count($words)) {
387 $line .= ' ' . $words[$i];
389 if (isset($words[$i]))
390 $line_len +
= strlen($words[$i]) +
1;
395 /* Skip spaces if they are the first thing on a continued line */
396 while (!isset($words[$i]) && $i < count($words)) {
400 /* Go to the next line if we have more to process */
401 if ($i < count($words)) {
408 * Does the opposite of sqWordWrap()
409 * @param string body the text to un-wordwrap
412 function sqUnWordWrap(&$body) {
413 global $squirrelmail_language;
415 if ($squirrelmail_language == 'ja_JP') {
419 $lines = explode("\n", $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];
433 $PreviousSpaces = $CurrentSpaces;
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;
440 $body .= "\n" . $lines[$i];
441 $PreviousSpaces = $CurrentSpaces;
448 * If $haystack is a full mailbox name and $needle is the mailbox
449 * separator character, returns the last part of the mailbox name.
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
455 function readShortMailboxName($haystack, $needle) {
460 $parts = explode($needle, $haystack);
461 $elem = array_pop($parts);
462 while ($elem == '' && count($parts)) {
463 $elem = array_pop($parts);
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.
475 * @return string the complete url for this page
477 function php_self () {
478 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER
) && !empty($req_uri) ) {
482 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER
) && !empty($php_self) ) {
484 // need to add query string to end of PHP_SELF to match REQUEST_URI
486 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER
) && !empty($query_string) ) {
487 $php_self .= '?' . $query_string;
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:
506 * http://www.example.com/squirrelmail/
508 * @return string the base url for this SquirrelMail installation
510 function get_location () {
512 global $imap_server_type;
514 /* Get the path, handle virtual directories */
515 if(strpos(php_self(), '?')) {
516 $path = substr(php_self(), 0, strpos(php_self(), '?'));
520 $path = substr($path, 0, strrpos($path, '/'));
521 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION
) ) {
522 return $full_url . $path;
525 /* Check if this is a HTTPS or regular HTTP request. */
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
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)) {
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) ) {
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);
557 /* this is a workaround for the weird macosx caching that
558 causes Apache to return 16080 as the port number, which causes
561 if ($imap_server_type == 'macosx' && $port == ':16080') {
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;
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();
580 * @param string string the (password)string to encrypt
581 * @param string epad the encryption key
582 * @return string the base64-encoded encrypted password
584 function OneTimePadEncrypt ($string, $epad) {
585 $pad = base64_decode($epad);
587 for ($i = 0; $i < strlen ($string); $i++
) {
588 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
591 return base64_encode($encrypted);
595 * Decrypts a password from the cookie
597 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
598 * This uses the encryption key that is stored in the session.
600 * @param string string the string to decrypt
601 * @param string epad the encryption key from the session
602 * @return string the decrypted password
604 function OneTimePadDecrypt ($string, $epad) {
605 $pad = base64_decode($epad);
606 $encrypted = base64_decode ($string);
608 for ($i = 0; $i < strlen ($encrypted); $i++
) {
609 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
617 * Randomizes the mt_rand() function.
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.
623 * @param mixed val a value to seed the random number generator
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();
631 if (! is_int($Val)) {
643 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
648 * Init random number generator
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.
656 function sq_mt_randomize() {
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()));
670 if (function_exists('getrusage')) {
671 /* Avoid warnings with Win32 */
673 if (isset($dat) && is_array($dat)) {
675 foreach ($dat as $k => $v)
679 sq_mt_seed(md5($Str));
683 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER
)) {
684 sq_mt_seed(md5($unique_id));
691 * Creates encryption key
693 * Creates an encryption key for encrypting the password stored in the cookie.
694 * The encryption key itself is stored in the session.
696 * @param int length optional, length of the string to generate
697 * @return string the encryption key
699 function OneTimePadCreate ($length=100) {
703 for ($i = 0; $i < $length; $i++
) {
704 $pad .= chr(mt_rand(0,255));
707 return base64_encode($pad);
711 * Returns a string showing the size of the message/attachment.
713 * @param int bytes the filesize in bytes
714 * @return string the filesize in human readable format
716 function show_readable_size($bytes) {
720 if ($bytes / 1024 > 1) {
727 settype($bytes, 'integer');
730 settype($bytes, 'integer');
733 return $bytes . '<small> ' . $type . '</small>';
737 * Generates a random string from the caracter set you pass in
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:
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
748 function GenerateRandomString($size, $chars, $flags = 0) {
750 $chars .= 'abcdefghijklmnopqrstuvwxyz';
753 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
756 $chars .= '0123456789';
759 if (($size < 1) ||
(strlen($chars) < 1)) {
763 sq_mt_randomize(); /* Initialize the random number generator */
766 $j = strlen( $chars ) - 1;
767 while (strlen($String) < $size) {
768 $String .= $chars{mt_rand(0, $j)};
775 * Escapes special characters for use in IMAP commands.
777 * @param string the string to escape
778 * @return string the escaped string
780 function quoteimap($str) {
781 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
787 * Trims every element in the array, ie. remove the first char of each element
788 * @param array array the array to trim
790 function TrimArray(&$array) {
791 foreach ($array as $k => $v) {
794 foreach ($
$k as $k2 => $v2) {
795 $
$k[$k2] = substr($v2, 1);
801 /* Re-assign back to array. */
807 * Create compose link
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
815 function makeComposeLink($url, $text = null, $target='')
817 global $compose_new_win,$javascript_on;
820 $text = _("Compose");
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);
831 // build the compose in new window link...
834 // if javascript is on, use onClick event to handle it
836 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION
);
837 return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
841 // otherwise, just open new window using regular HTML
842 return makeInternalLink($url, $text, '_blank');
849 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
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.
858 function sm_print_r() {
859 ob_start(); // Buffer output
860 foreach(func_get_args() as $var) {
864 $buffer = ob_get_contents(); // Grab the print_r output
865 ob_end_clean(); // Silently discard the output & stop buffering
867 print htmlentities($buffer);
872 * version of fwrite which checks for failure
874 function sq_fwrite($fp, $string) {
876 $count = @fwrite
($fp,$string);
877 // the number of bytes written should be the length of the string
878 if($count != strlen($string)) {
886 * sq_get_html_translation_table
888 * Returns the translation table used by sq_htmlentities()
890 * @param integer $table html translation table. Possible values (without quotes):
892 * <li>HTML_ENTITIES - full html entities table defined by charset</li>
893 * <li>HTML_SPECIALCHARS - html special characters table</li>
895 * @param integer $quote_style quote encoding style. Possible values (without quotes):
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>
901 * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
902 * @return array html translation array
904 function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT
,$charset='us-ascii') {
905 global $default_charset;
907 if ($table == HTML_SPECIALCHARS
) $charset='us-ascii';
909 // Start array with ampersand
910 $sq_html_ent_table = array( "&" => '&' );
913 $sq_html_ent_table = array_merge($sq_html_ent_table,
918 if ($quote_style == ENT_COMPAT
)
919 $sq_html_ent_table = array_merge($sq_html_ent_table,
920 array("\"" => '"')
923 // double and single quotes
924 if ($quote_style == ENT_QUOTES
)
925 $sq_html_ent_table = array_merge($sq_html_ent_table,
926 array("\"" => '"',
930 if ($charset=='auto') $charset=$default_charset;
932 // add entities that depend on charset
935 include_once(SM_PATH
. 'functions/htmlentities/iso-8859-1.php');
938 include_once(SM_PATH
. 'functions/htmlentities/utf-8.php');
945 return $sq_html_ent_table;
951 * Convert all applicable characters to HTML entities.
952 * Minimal php requirement - v.4.0.5
954 * @param string $string string that has to be sanitized
955 * @param integer $quote_style quote encoding style. Possible values (without quotes):
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>
961 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
962 * @return string sanitized string
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);
971 $PHP_SELF = php_self();