4ff54b898bfeb95e145ed5deb259da559bf41aa0
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 * Wraps text at $wrap characters
39 * Has a problem with special HTML characters, so call this before
40 * you do character translation.
42 * Specifically, ' comes up as 5 characters instead of 1.
43 * This should not add newlines to the end of lines.
45 * @param string line the line of text to wrap, by ref
46 * @param int wrap the maximum line lenth
49 function sqWordWrap(&$line, $wrap) {
50 global $languages, $squirrelmail_language;
52 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
53 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
54 if (mb_detect_encoding($line) != 'ASCII') {
55 $line = $languages[$squirrelmail_language]['XTRA_CODE']('wordwrap', $line, $wrap);
60 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
61 $beginning_spaces = $regs[1];
62 if (isset($regs[2])) {
63 $words = explode(' ', $regs[2]);
69 $line = $beginning_spaces;
71 while ($i < count($words)) {
72 /* Force one word to be on a line (minimum) */
74 $line_len = strlen($beginning_spaces) +
strlen($words[$i]) +
2;
75 if (isset($words[$i +
1]))
76 $line_len +
= strlen($words[$i +
1]);
79 /* Add more words (as long as they fit) */
80 while ($line_len < $wrap && $i < count($words)) {
81 $line .= ' ' . $words[$i];
83 if (isset($words[$i]))
84 $line_len +
= strlen($words[$i]) +
1;
89 /* Skip spaces if they are the first thing on a continued line */
90 while (!isset($words[$i]) && $i < count($words)) {
94 /* Go to the next line if we have more to process */
95 if ($i < count($words)) {
102 * Does the opposite of sqWordWrap()
103 * @param string body the text to un-wordwrap
106 function sqUnWordWrap(&$body) {
107 global $squirrelmail_language;
109 if ($squirrelmail_language == 'ja_JP') {
113 $lines = explode("\n", $body);
115 $PreviousSpaces = '';
116 $cnt = count($lines);
117 for ($i = 0; $i < $cnt; $i ++
) {
118 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
119 $CurrentSpaces = $regs[1];
120 if (isset($regs[2])) {
121 $CurrentRest = $regs[2];
127 $PreviousSpaces = $CurrentSpaces;
129 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
130 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
131 && strlen($CurrentRest)) { /* and there's a line to continue with */
132 $body .= ' ' . $CurrentRest;
134 $body .= "\n" . $lines[$i];
135 $PreviousSpaces = $CurrentSpaces;
142 * If $haystack is a full mailbox name and $needle is the mailbox
143 * separator character, returns the last part of the mailbox name.
145 * @param string haystack full mailbox name to search
146 * @param string needle the mailbox separator character
147 * @return string the last part of the mailbox name
149 function readShortMailboxName($haystack, $needle) {
154 $parts = explode($needle, $haystack);
155 $elem = array_pop($parts);
156 while ($elem == '' && count($parts)) {
157 $elem = array_pop($parts);
164 * Creates an URL for the page calling this function, using either the PHP global
165 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
167 * @return string the complete url for this page
169 function php_self () {
170 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER
) && !empty($req_uri) ) {
174 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER
) && !empty($php_self) ) {
176 // need to add query string to end of PHP_SELF to match REQUEST_URI
178 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER
) && !empty($query_string) ) {
179 $php_self .= '?' . $query_string;
190 * Determines the location to forward to, relative to your server.
191 * This is used in HTTP Location: redirects.
192 * If this doesnt work correctly for you (although it should), you can
193 * remove all this code except the last two lines, and have it return
194 * the right URL for your site, something like:
196 * http://www.example.com/squirrelmail/
198 * @return string the base url for this SquirrelMail installation
200 function get_location () {
202 global $imap_server_type;
204 /* Get the path, handle virtual directories */
205 if(strpos(php_self(), '?')) {
206 $path = substr(php_self(), 0, strpos(php_self(), '?'));
210 $path = substr($path, 0, strrpos($path, '/'));
211 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION
) ) {
212 return $full_url . $path;
215 /* Check if this is a HTTPS or regular HTTP request. */
219 * If you have 'SSLOptions +StdEnvVars' in your apache config
220 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
221 * OR if you are on port 443
223 $getEnvVar = getenv('HTTPS');
224 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
225 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER
) && !strcasecmp($https_on, 'on')) ||
226 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER
) && $server_port == 443)) {
230 /* Get the hostname from the Host header or server config. */
231 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER
) ||
empty($host) ) {
232 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER
) ||
empty($host) ) {
238 if (! strstr($host, ':')) {
239 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER
)) {
240 if (($server_port != 80 && $proto == 'http://') ||
241 ($server_port != 443 && $proto == 'https://')) {
242 $port = sprintf(':%d', $server_port);
247 /* this is a workaround for the weird macosx caching that
248 causes Apache to return 16080 as the port number, which causes
251 if ($imap_server_type == 'macosx' && $port == ':16080') {
255 /* Fallback is to omit the server name and use a relative */
256 /* URI, although this is not RFC 2616 compliant. */
257 $full_url = ($host ?
$proto . $host . $port : '');
258 sqsession_register($full_url, 'sq_base_url');
259 return $full_url . $path;
264 * These functions are used to encrypt the password before it is
265 * stored in a cookie. The encryption key is generated by
266 * OneTimePadCreate();
268 * @param string string the (password)string to encrypt
269 * @param string epad the encryption key
270 * @return string the base64-encoded encrypted password
272 function OneTimePadEncrypt ($string, $epad) {
273 $pad = base64_decode($epad);
275 for ($i = 0; $i < strlen ($string); $i++
) {
276 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
279 return base64_encode($encrypted);
283 * Decrypt a password from the cookie, encrypted by OneTimePadEncrypt.
284 * This uses the encryption key that is stored in the session.
286 * @param string string the string to decrypt
287 * @param string epad the encryption key from the session
288 * @return string the decrypted password
290 function OneTimePadDecrypt ($string, $epad) {
291 $pad = base64_decode($epad);
292 $encrypted = base64_decode ($string);
294 for ($i = 0; $i < strlen ($encrypted); $i++
) {
295 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
303 * Randomize the mt_rand() function. Toss this in strings or integers
304 * and it will seed the generator appropriately. With strings, it is
305 * better to get them long. Use md5() to lengthen smaller strings.
307 * @param mixed val a value to seed the random number generator
310 function sq_mt_seed($Val) {
311 /* if mt_getrandmax() does not return a 2^n - 1 number,
312 this might not work well. This uses $Max as a bitmask. */
313 $Max = mt_getrandmax();
315 if (! is_int($Val)) {
327 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
332 * This function initializes the random number generator fairly well.
333 * It also only initializes it once, so you don't accidentally get
334 * the same 'random' numbers twice in one session.
338 function sq_mt_randomize() {
346 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER
);
347 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER
);
348 sq_mt_seed((int)((double) microtime() * 1000000));
349 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
352 if (function_exists('getrusage')) {
353 /* Avoid warnings with Win32 */
355 if (isset($dat) && is_array($dat)) {
357 foreach ($dat as $k => $v)
361 sq_mt_seed(md5($Str));
365 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER
)) {
366 sq_mt_seed(md5($unique_id));
373 * Creates an encryption key for encrypting the password stored in the cookie.
374 * The encryption key itself is stored in the session.
376 * @param int length optional, length of the string to generate
377 * @return string the encryption key
379 function OneTimePadCreate ($length=100) {
383 for ($i = 0; $i < $length; $i++
) {
384 $pad .= chr(mt_rand(0,255));
387 return base64_encode($pad);
391 * Returns a string showing the size of the message/attachment.
393 * @param int bytes the filesize in bytes
394 * @return string the filesize in human readable format
396 function show_readable_size($bytes) {
400 if ($bytes / 1024 > 1) {
407 settype($bytes, 'integer');
410 settype($bytes, 'integer');
413 return $bytes . '<small> ' . $type . '</small>';
417 * Generates a random string from the caracter set you pass in
419 * @param int size the size of the string to generate
420 * @param string chars a string containing the characters to use
421 * @param int flags a flag to add a specific set to the characters to use:
423 * 1 = add lowercase a-z to $chars
424 * 2 = add uppercase A-Z to $chars
425 * 4 = add numbers 0-9 to $chars
426 * @return string the random string
429 function GenerateRandomString($size, $chars, $flags = 0) {
431 $chars .= 'abcdefghijklmnopqrstuvwxyz';
434 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
437 $chars .= '0123456789';
440 if (($size < 1) ||
(strlen($chars) < 1)) {
444 sq_mt_randomize(); /* Initialize the random number generator */
447 $j = strlen( $chars ) - 1;
448 while (strlen($String) < $size) {
449 $String .= $chars{mt_rand(0, $j)};
456 * Escapes special characters for use in IMAP commands.
457 * @param string the string to escape
458 * @return string the escaped string
460 function quoteimap($str) {
461 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
465 * Trims every element in the array, ie. remove the first char of each element
466 * @param array array the array to trim
468 function TrimArray(&$array) {
469 foreach ($array as $k => $v) {
472 foreach ($
$k as $k2 => $v2) {
473 $
$k[$k2] = substr($v2, 1);
479 /* Re-assign back to array. */
485 * Returns a link to the compose-page, taking in consideration
486 * the compose_in_new and javascript settings.
487 * @param string url the URL to the compose page
488 * @param string text the link text, default "Compose"
489 * @return string a link to the compose page
491 function makeComposeLink($url, $text = null, $target='')
493 global $compose_new_win,$javascript_on;
496 $text = _("Compose");
500 // if not using "compose in new window", make
501 // regular link and be done with it
502 if($compose_new_win != '1') {
503 return makeInternalLink($url, $text, $target);
507 // build the compose in new window link...
510 // if javascript is on, use onClick event to handle it
512 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION
);
513 return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
517 // otherwise, just open new window using regular HTML
518 return makeInternalLink($url, $text, '_blank');
523 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
524 * Debugging function - does the same as print_r, but makes sure special
525 * characters are converted to htmlentities first. This will allow
526 * values like <some@email.address> to be displayed.
527 * The output is wrapped in <pre> and </pre> tags.
531 function sm_print_r() {
532 ob_start(); // Buffer output
533 foreach(func_get_args() as $var) {
537 $buffer = ob_get_contents(); // Grab the print_r output
538 ob_end_clean(); // Silently discard the output & stop buffering
540 print htmlentities($buffer);
545 * version of fwrite which checks for failure
547 function sq_fwrite($fp, $string) {
549 $count = @fwrite
($fp,$string);
550 // the number of bytes written should be the length of the string
551 if($count != strlen($string)) {
560 $PHP_SELF = php_self();