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 * Wraps text at $wrap characters. While sqWordWrap takes
79 * a single line of text and wraps it, this function works
80 * on the entire corpus at once, this allows it to be a little
81 * bit smarter and when and how to wrap.
83 * @author Justus Pendleton
85 * @param string body the entire body of text
86 * @param int wrap the maximum line length
87 * @return string the wrapped text
89 function &sqBodyWrap (&$body, $wrap) {
90 // the newly wrapped text
92 // current column since the last newline in the outstring
94 $length = strlen($body);
95 // where we are in the original string
97 // the number of >>> citation markers we are currently at
100 // the main loop, whenever we start a newline of input text
101 // we start from here
102 while ($pos < $length) {
103 // we're at the beginning of a line, get the new cite level
106 while (($pos < $length) && ($body{$pos} == '>')) {
110 // skip over any spaces interleaved among the cite markers
111 while (($pos < $length) && ($body{$pos} == ' ')) {
114 if ($pos >= $length) {
119 // special case: if this is a blank line then maintain it
120 // (i.e. try to preserve original paragraph breaks)
121 // unless they occur at the very beginning of the text
122 if (($body{$pos} == "\n") && (strlen($outString) != 0)) {
123 $outStringLast = $outString{strlen($outString) - 1};
124 if ($outStringLast != "\n") {
127 sqMakeCite ($outString, $newCiteLevel);
134 // if the cite level has changed, then start a new line
135 // with the new cite level.
136 if (($citeLevel != $newCiteLevel) && ($pos > ($newCiteLevel +
1)) && ($outStringCol != 0)) {
137 sqMakeNewLine ($outString, 0, $outStringCol);
140 $citeLevel = $newCiteLevel;
142 // prepend the quote level if necessary
143 if ($outStringCol == 0) {
144 sqMakeCite ($outString, $citeLevel);
145 // if we added a citation then move the column
146 // out by citelevel + 1 (the cite markers + the space)
147 $outStringCol = $citeLevel +
($citeLevel ?
1 : 0);
148 } else if ($outStringCol > $citeLevel) {
149 // not a cite and we're not at the beginning of a line
150 // in the output. add a space to separate the new text
151 // from previous text.
156 // find the next newline -- we don't want to go further than that
157 $nextNewline = strpos ($body, "\n", $pos);
158 if ($nextNewline === FALSE) {
159 $nextNewline = $length;
162 // Don't wrap unquoted lines at all. For now the textarea
163 // will work fine for this. Maybe revisit this later though
164 // (for completeness more than anything else, I think)
165 if ($citeLevel == 0) {
166 $outString .= substr ($body, $pos, ($nextNewline - $pos));
167 $outStringCol = $nextNewline - $pos;
168 if ($nextNewline != $length) {
169 sqMakeNewLine ($outString, 0, $outStringCol);
171 $pos = $nextNewline +
1;
175 // inner loop, (obviously) handles wrapping up to
177 while ($pos < $nextNewline) {
178 // skip over initial spaces
179 while (($pos < $nextNewline) && (ctype_space ($body{$pos}))) {
183 // if this is a short line then just append it and continue outer loop
184 if (($outStringCol +
$nextNewline - $pos) <= ($wrap - $citeLevel - 1)) {
185 // if this is the final line in the input string then include
186 // any trailing newlines
187 if (($nextNewline +
1 == $length) && ($body{$nextNewline} == "\n")) {
191 // trim trailing spaces
192 $lastRealChar = $nextNewline;
193 while (($lastRealChar > $pos) && (ctype_space ($body{$lastRealChar}))) {
197 $outString .= substr ($body, $pos, ($lastRealChar - $pos +
1));
198 $outStringCol +
= ($lastRealChar - $pos);
199 $pos = $nextNewline +
1;
203 $eol = $pos +
$wrap - $citeLevel - $outStringCol;
204 // eol is the tentative end of line.
205 // look backwards for there for a whitespace to break at.
206 // if it's already less than our current position then
207 // our current line is already too long, break immediately
208 // and restart outer loop
210 sqMakeNewLine ($outString, $citeLeve, $outStringCol);
214 // start looking backwards for whitespace to break at.
216 while (($breakPoint > $pos) && (! ctype_space ($body{$breakPoint}))) {
220 // if we didn't find a breakpoint by looking backward then we
221 // need to figure out what to do about that
222 if ($breakPoint == $pos) {
223 // if we are not at the beginning then end this line
224 // and start a new loop
225 if ($outStringCol > ($citeLevel +
1)) {
226 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
229 // just hard break here. most likely we are breaking
230 // a really long URL. could also try searching
231 // forward for a break point, which is what Mozilla
232 // does. don't bother for now.
237 // special case: maybe we should have wrapped last
238 // time. if the first breakpoint here makes the
239 // current line too long and there is already text on
240 // the current line, break and loop again if at
241 // beginning of current line, don't force break
243 if ((($outStringCol +
($breakPoint - $pos)) > ($wrap +
$SLOP)) && ($outStringCol > ($citeLevel +
1))) {
244 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
248 // skip newlines or whitespace at the beginning of the string
249 $substring = substr ($body, $pos, ($breakPoint - $pos));
250 $substring = rtrim ($substring); // do rtrim and ctype_space have the same ideas about whitespace?
251 $outString .= $substring;
252 $outStringCol +
= strlen ($substring);
253 // advance past the whitespace which caused the wrap
255 while (($pos < $length) && (ctype_space ($body{$pos}))) {
258 if ($pos < $length) {
259 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
268 * Wraps text at $wrap characters
270 * Has a problem with special HTML characters, so call this before
271 * you do character translation.
273 * Specifically, ' comes up as 5 characters instead of 1.
274 * This should not add newlines to the end of lines.
276 * @param string line the line of text to wrap, by ref
277 * @param int wrap the maximum line lenth
280 function sqWordWrap(&$line, $wrap) {
281 global $languages, $squirrelmail_language;
283 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
284 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
285 if (mb_detect_encoding($line) != 'ASCII') {
286 $line = $languages[$squirrelmail_language]['XTRA_CODE']('wordwrap', $line, $wrap);
291 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
292 $beginning_spaces = $regs[1];
293 if (isset($regs[2])) {
294 $words = explode(' ', $regs[2]);
300 $line = $beginning_spaces;
302 while ($i < count($words)) {
303 /* Force one word to be on a line (minimum) */
305 $line_len = strlen($beginning_spaces) +
strlen($words[$i]) +
2;
306 if (isset($words[$i +
1]))
307 $line_len +
= strlen($words[$i +
1]);
310 /* Add more words (as long as they fit) */
311 while ($line_len < $wrap && $i < count($words)) {
312 $line .= ' ' . $words[$i];
314 if (isset($words[$i]))
315 $line_len +
= strlen($words[$i]) +
1;
320 /* Skip spaces if they are the first thing on a continued line */
321 while (!isset($words[$i]) && $i < count($words)) {
325 /* Go to the next line if we have more to process */
326 if ($i < count($words)) {
333 * Does the opposite of sqWordWrap()
334 * @param string body the text to un-wordwrap
337 function sqUnWordWrap(&$body) {
338 global $squirrelmail_language;
340 if ($squirrelmail_language == 'ja_JP') {
344 $lines = explode("\n", $body);
346 $PreviousSpaces = '';
347 $cnt = count($lines);
348 for ($i = 0; $i < $cnt; $i ++
) {
349 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
350 $CurrentSpaces = $regs[1];
351 if (isset($regs[2])) {
352 $CurrentRest = $regs[2];
358 $PreviousSpaces = $CurrentSpaces;
360 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
361 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
362 && strlen($CurrentRest)) { /* and there's a line to continue with */
363 $body .= ' ' . $CurrentRest;
365 $body .= "\n" . $lines[$i];
366 $PreviousSpaces = $CurrentSpaces;
373 * If $haystack is a full mailbox name and $needle is the mailbox
374 * separator character, returns the last part of the mailbox name.
376 * @param string haystack full mailbox name to search
377 * @param string needle the mailbox separator character
378 * @return string the last part of the mailbox name
380 function readShortMailboxName($haystack, $needle) {
385 $parts = explode($needle, $haystack);
386 $elem = array_pop($parts);
387 while ($elem == '' && count($parts)) {
388 $elem = array_pop($parts);
397 * Creates an URL for the page calling this function, using either the PHP global
398 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
400 * @return string the complete url for this page
402 function php_self () {
403 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER
) && !empty($req_uri) ) {
407 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER
) && !empty($php_self) ) {
409 // need to add query string to end of PHP_SELF to match REQUEST_URI
411 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER
) && !empty($query_string) ) {
412 $php_self .= '?' . $query_string;
425 * Determines the location to forward to, relative to your server.
426 * This is used in HTTP Location: redirects.
427 * If this doesnt work correctly for you (although it should), you can
428 * remove all this code except the last two lines, and have it return
429 * the right URL for your site, something like:
431 * http://www.example.com/squirrelmail/
433 * @return string the base url for this SquirrelMail installation
435 function get_location () {
437 global $imap_server_type;
439 /* Get the path, handle virtual directories */
440 if(strpos(php_self(), '?')) {
441 $path = substr(php_self(), 0, strpos(php_self(), '?'));
445 $path = substr($path, 0, strrpos($path, '/'));
446 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION
) ) {
447 return $full_url . $path;
450 /* Check if this is a HTTPS or regular HTTP request. */
454 * If you have 'SSLOptions +StdEnvVars' in your apache config
455 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
456 * OR if you are on port 443
458 $getEnvVar = getenv('HTTPS');
459 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
460 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER
) && !strcasecmp($https_on, 'on')) ||
461 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER
) && $server_port == 443)) {
465 /* Get the hostname from the Host header or server config. */
466 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER
) ||
empty($host) ) {
467 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER
) ||
empty($host) ) {
473 if (! strstr($host, ':')) {
474 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER
)) {
475 if (($server_port != 80 && $proto == 'http://') ||
476 ($server_port != 443 && $proto == 'https://')) {
477 $port = sprintf(':%d', $server_port);
482 /* this is a workaround for the weird macosx caching that
483 causes Apache to return 16080 as the port number, which causes
486 if ($imap_server_type == 'macosx' && $port == ':16080') {
490 /* Fallback is to omit the server name and use a relative */
491 /* URI, although this is not RFC 2616 compliant. */
492 $full_url = ($host ?
$proto . $host . $port : '');
493 sqsession_register($full_url, 'sq_base_url');
494 return $full_url . $path;
501 * These functions are used to encrypt the password before it is
502 * stored in a cookie. The encryption key is generated by
503 * OneTimePadCreate();
505 * @param string string the (password)string to encrypt
506 * @param string epad the encryption key
507 * @return string the base64-encoded encrypted password
509 function OneTimePadEncrypt ($string, $epad) {
510 $pad = base64_decode($epad);
512 for ($i = 0; $i < strlen ($string); $i++
) {
513 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
516 return base64_encode($encrypted);
520 * Decrypts a password from the cookie
522 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
523 * This uses the encryption key that is stored in the session.
525 * @param string string the string to decrypt
526 * @param string epad the encryption key from the session
527 * @return string the decrypted password
529 function OneTimePadDecrypt ($string, $epad) {
530 $pad = base64_decode($epad);
531 $encrypted = base64_decode ($string);
533 for ($i = 0; $i < strlen ($encrypted); $i++
) {
534 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
542 * Randomizes the mt_rand() function.
544 * Toss this in strings or integers and it will seed the generator
545 * appropriately. With strings, it is better to get them long.
546 * Use md5() to lengthen smaller strings.
548 * @param mixed val a value to seed the random number generator
551 function sq_mt_seed($Val) {
552 /* if mt_getrandmax() does not return a 2^n - 1 number,
553 this might not work well. This uses $Max as a bitmask. */
554 $Max = mt_getrandmax();
556 if (! is_int($Val)) {
568 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
573 * Init random number generator
575 * This function initializes the random number generator fairly well.
576 * It also only initializes it once, so you don't accidentally get
577 * the same 'random' numbers twice in one session.
581 function sq_mt_randomize() {
589 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER
);
590 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER
);
591 sq_mt_seed((int)((double) microtime() * 1000000));
592 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
595 if (function_exists('getrusage')) {
596 /* Avoid warnings with Win32 */
598 if (isset($dat) && is_array($dat)) {
600 foreach ($dat as $k => $v)
604 sq_mt_seed(md5($Str));
608 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER
)) {
609 sq_mt_seed(md5($unique_id));
616 * Creates encryption key
618 * Creates an encryption key for encrypting the password stored in the cookie.
619 * The encryption key itself is stored in the session.
621 * @param int length optional, length of the string to generate
622 * @return string the encryption key
624 function OneTimePadCreate ($length=100) {
628 for ($i = 0; $i < $length; $i++
) {
629 $pad .= chr(mt_rand(0,255));
632 return base64_encode($pad);
636 * Returns a string showing the size of the message/attachment.
638 * @param int bytes the filesize in bytes
639 * @return string the filesize in human readable format
641 function show_readable_size($bytes) {
645 if ($bytes / 1024 > 1) {
652 settype($bytes, 'integer');
655 settype($bytes, 'integer');
658 return $bytes . '<small> ' . $type . '</small>';
662 * Generates a random string from the caracter set you pass in
664 * @param int size the size of the string to generate
665 * @param string chars a string containing the characters to use
666 * @param int flags a flag to add a specific set to the characters to use:
668 * 1 = add lowercase a-z to $chars
669 * 2 = add uppercase A-Z to $chars
670 * 4 = add numbers 0-9 to $chars
671 * @return string the random string
673 function GenerateRandomString($size, $chars, $flags = 0) {
675 $chars .= 'abcdefghijklmnopqrstuvwxyz';
678 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
681 $chars .= '0123456789';
684 if (($size < 1) ||
(strlen($chars) < 1)) {
688 sq_mt_randomize(); /* Initialize the random number generator */
691 $j = strlen( $chars ) - 1;
692 while (strlen($String) < $size) {
693 $String .= $chars{mt_rand(0, $j)};
700 * Escapes special characters for use in IMAP commands.
702 * @param string the string to escape
703 * @return string the escaped string
705 function quoteimap($str) {
706 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
712 * Trims every element in the array, ie. remove the first char of each element
713 * @param array array the array to trim
715 function TrimArray(&$array) {
716 foreach ($array as $k => $v) {
719 foreach ($
$k as $k2 => $v2) {
720 $
$k[$k2] = substr($v2, 1);
726 /* Re-assign back to array. */
732 * Create compose link
734 * Returns a link to the compose-page, taking in consideration
735 * the compose_in_new and javascript settings.
736 * @param string url the URL to the compose page
737 * @param string text the link text, default "Compose"
738 * @return string a link to the compose page
740 function makeComposeLink($url, $text = null, $target='')
742 global $compose_new_win,$javascript_on;
745 $text = _("Compose");
749 // if not using "compose in new window", make
750 // regular link and be done with it
751 if($compose_new_win != '1') {
752 return makeInternalLink($url, $text, $target);
756 // build the compose in new window link...
759 // if javascript is on, use onClick event to handle it
761 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION
);
762 return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
766 // otherwise, just open new window using regular HTML
767 return makeInternalLink($url, $text, '_blank');
774 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
776 * Debugging function - does the same as print_r, but makes sure special
777 * characters are converted to htmlentities first. This will allow
778 * values like <some@email.address> to be displayed.
779 * The output is wrapped in <<pre>> and <</pre>> tags.
783 function sm_print_r() {
784 ob_start(); // Buffer output
785 foreach(func_get_args() as $var) {
789 $buffer = ob_get_contents(); // Grab the print_r output
790 ob_end_clean(); // Silently discard the output & stop buffering
792 print htmlentities($buffer);
797 * version of fwrite which checks for failure
799 function sq_fwrite($fp, $string) {
801 $count = @fwrite
($fp,$string);
802 // the number of bytes written should be the length of the string
803 if($count != strlen($string)) {
811 * sq_get_html_translation_table
813 * Returns the translation table used by sq_htmlentities()
815 * @param integer $table html translation table. Possible values (without quotes):
817 * <li>HTML_ENTITIES - full html entities table defined by charset</li>
818 * <li>HTML_SPECIALCHARS - html special characters table</li>
820 * @param integer $quote_style quote encoding style. Possible values (without quotes):
822 * <li>ENT_COMPAT - (default) encode double quotes</li>
823 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
824 * <li>ENT_QUOTES - encode double and single quotes</li>
826 * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
827 * @return array html translation array
829 function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT
,$charset='us-ascii') {
830 global $default_charset;
832 if ($table == HTML_SPECIALCHARS
) $charset='us-ascii';
834 // Start array with ampersand
835 $sq_html_ent_table = array( "&" => '&' );
838 $sq_html_ent_table = array_merge($sq_html_ent_table,
843 if ($quote_style == ENT_COMPAT
)
844 $sq_html_ent_table = array_merge($sq_html_ent_table,
845 array("\"" => '"')
848 // double and single quotes
849 if ($quote_style == ENT_QUOTES
)
850 $sq_html_ent_table = array_merge($sq_html_ent_table,
851 array("\"" => '"',
855 if ($charset=='auto') $charset=$default_charset;
857 // add entities that depend on charset
860 include_once(SM_PATH
. 'functions/htmlentities/iso-8859-1.php');
863 include_once(SM_PATH
. 'functions/htmlentities/utf-8.php');
870 return $sq_html_ent_table;
876 * Convert all applicable characters to HTML entities.
877 * Minimal php requirement - v.4.0.5
879 * @param string $string string that has to be sanitized
880 * @param integer $quote_style quote encoding style. Possible values (without quotes):
882 * <li>ENT_COMPAT - (default) encode double quotes</li>
883 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
884 * <li>ENT_QUOTES - encode double and single quotes</li>
886 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
887 * @return string sanitized string
889 function sq_htmlentities($string,$quote_style=ENT_COMPAT
,$charset='us-ascii') {
890 // get translation table
891 $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES
,$quote_style,$charset);
892 // convert characters
893 return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
896 $PHP_SELF = php_self();