6 * Copyright (c) 1999-2003 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.0 [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,0);
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 function sqWordWrap(&$line, $wrap) {
46 global $languages, $squirrelmail_language;
48 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
49 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
50 if (mb_detect_encoding($line) != 'ASCII') {
51 $line = $languages[$squirrelmail_language]['XTRA_CODE']('wordwrap', $line, $wrap);
56 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
57 $beginning_spaces = $regs[1];
58 if (isset($regs[2])) {
59 $words = explode(' ', $regs[2]);
65 $line = $beginning_spaces;
67 while ($i < count($words)) {
68 /* Force one word to be on a line (minimum) */
70 $line_len = strlen($beginning_spaces) +
strlen($words[$i]) +
2;
71 if (isset($words[$i +
1]))
72 $line_len +
= strlen($words[$i +
1]);
75 /* Add more words (as long as they fit) */
76 while ($line_len < $wrap && $i < count($words)) {
77 $line .= ' ' . $words[$i];
79 if (isset($words[$i]))
80 $line_len +
= strlen($words[$i]) +
1;
85 /* Skip spaces if they are the first thing on a continued line */
86 while (!isset($words[$i]) && $i < count($words)) {
90 /* Go to the next line if we have more to process */
91 if ($i < count($words)) {
98 * Does the opposite of sqWordWrap()
100 function sqUnWordWrap(&$body) {
101 global $squirrelmail_language;
103 if ($squirrelmail_language == 'ja_JP') {
107 $lines = explode("\n", $body);
109 $PreviousSpaces = '';
110 $cnt = count($lines);
111 for ($i = 0; $i < $cnt; $i ++
) {
112 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
113 $CurrentSpaces = $regs[1];
114 if (isset($regs[2])) {
115 $CurrentRest = $regs[2];
121 $PreviousSpaces = $CurrentSpaces;
123 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
124 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
125 && strlen($CurrentRest)) { /* and there's a line to continue with */
126 $body .= ' ' . $CurrentRest;
128 $body .= "\n" . $lines[$i];
129 $PreviousSpaces = $CurrentSpaces;
136 * If $haystack is a full mailbox name and $needle is the mailbox
137 * separator character, returns the last part of the mailbox name.
139 function readShortMailboxName($haystack, $needle) {
144 $parts = explode($needle, $haystack);
145 $elem = array_pop($parts);
146 while ($elem == '' && count($parts)) {
147 $elem = array_pop($parts);
153 function php_self () {
154 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER
) && !empty($req_uri) ) {
158 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER
) && !empty($php_self) ) {
160 // need to add query string to end of PHP_SELF to match REQUEST_URI
162 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER
) && !empty($query_string) ) {
163 $php_self .= '?' . $query_string;
174 * This determines the location to forward to relative to your server.
175 * If this doesnt work correctly for you (although it should), you can
176 * remove all this code except the last two lines, and change the header()
177 * function to look something like this, customized to the location of
178 * SquirrelMail on your server:
180 * http://www.myhost.com/squirrelmail/src/login.php
182 function get_location () {
184 global $imap_server_type;
186 /* Get the path, handle virtual directories */
187 if(strpos(php_self(), '?')) {
188 $path = substr(php_self(), 0, strpos(php_self(), '?'));
192 $path = substr($path, 0, strrpos($path, '/'));
193 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION
) ) {
194 return $full_url . $path;
197 /* Check if this is a HTTPS or regular HTTP request. */
201 * If you have 'SSLOptions +StdEnvVars' in your apache config
202 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
203 * OR if you are on port 443
205 $getEnvVar = getenv('HTTPS');
206 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
207 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER
) && !strcasecmp($https_on, 'on')) ||
208 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER
) && $server_port == 443)) {
212 /* Get the hostname from the Host header or server config. */
213 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER
) ||
empty($host) ) {
214 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER
) ||
empty($host) ) {
220 if (! strstr($host, ':')) {
221 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER
)) {
222 if (($server_port != 80 && $proto == 'http://') ||
223 ($server_port != 443 && $proto == 'https://')) {
224 $port = sprintf(':%d', $server_port);
229 /* this is a workaround for the weird macosx caching that
230 causes Apache to return 16080 as the port number, which causes
233 if ($imap_server_type == 'macosx' && $port == ':16080') {
237 /* Fallback is to omit the server name and use a relative */
238 /* URI, although this is not RFC 2616 compliant. */
239 $full_url = ($host ?
$proto . $host . $port : '');
240 sqsession_register($full_url, 'sq_base_url');
241 return $full_url . $path;
246 * These functions are used to encrypt the passowrd before it is
247 * stored in a cookie.
249 function OneTimePadEncrypt ($string, $epad) {
250 $pad = base64_decode($epad);
252 for ($i = 0; $i < strlen ($string); $i++
) {
253 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
256 return base64_encode($encrypted);
259 function OneTimePadDecrypt ($string, $epad) {
260 $pad = base64_decode($epad);
261 $encrypted = base64_decode ($string);
263 for ($i = 0; $i < strlen ($encrypted); $i++
) {
264 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
272 * Randomize the mt_rand() function. Toss this in strings or integers
273 * and it will seed the generator appropriately. With strings, it is
274 * better to get them long. Use md5() to lengthen smaller strings.
276 function sq_mt_seed($Val) {
277 /* if mt_getrandmax() does not return a 2^n - 1 number,
278 this might not work well. This uses $Max as a bitmask. */
279 $Max = mt_getrandmax();
281 if (! is_int($Val)) {
293 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
298 * This function initializes the random number generator fairly well.
299 * It also only initializes it once, so you don't accidentally get
300 * the same 'random' numbers twice in one session.
302 function sq_mt_randomize() {
310 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER
);
311 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER
);
312 sq_mt_seed((int)((double) microtime() * 1000000));
313 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
316 if (function_exists('getrusage')) {
317 /* Avoid warnings with Win32 */
319 if (isset($dat) && is_array($dat)) {
321 foreach ($dat as $k => $v)
325 sq_mt_seed(md5($Str));
329 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER
)) {
330 sq_mt_seed(md5($unique_id));
336 function OneTimePadCreate ($length=100) {
340 for ($i = 0; $i < $length; $i++
) {
341 $pad .= chr(mt_rand(0,255));
344 return base64_encode($pad);
348 * Returns a string showing the size of the message/attachment.
350 function show_readable_size($bytes) {
354 if ($bytes / 1024 > 1) {
361 settype($bytes, 'integer');
364 settype($bytes, 'integer');
367 return $bytes . '<small> ' . $type . '</small>';
371 * Generates a random string from the caracter set you pass in
374 * 1 = add lowercase a-z to $chars
375 * 2 = add uppercase A-Z to $chars
376 * 4 = add numbers 0-9 to $chars
379 function GenerateRandomString($size, $chars, $flags = 0) {
381 $chars .= 'abcdefghijklmnopqrstuvwxyz';
384 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
387 $chars .= '0123456789';
390 if (($size < 1) ||
(strlen($chars) < 1)) {
394 sq_mt_randomize(); /* Initialize the random number generator */
397 $j = strlen( $chars ) - 1;
398 while (strlen($String) < $size) {
399 $String .= $chars{mt_rand(0, $j)};
405 function quoteimap($str) {
406 return ereg_replace('(["\\])', '\\\\1', $str);
410 * Trims every element in the array
412 function TrimArray(&$array) {
413 foreach ($array as $k => $v) {
416 foreach ($
$k as $k2 => $v2) {
417 $
$k[$k2] = substr($v2, 1);
423 /* Re-assign back to array. */
428 // Returns a link to the compose-page, taking in
429 // consideration the compose_in_new and javascript
432 function makeComposeLink($url, $text = null)
434 global $compose_new_win,$javascript_on;
437 $text = _("Compose");
441 // if not using "compose in new window", make
442 // regular link and be done with it
444 if($compose_new_win != '1') {
445 return makeInternalLink($url, $text, 'right');
450 // build the compose in new window link...
454 // if javascript is on, use onClick event to handle it
457 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION
);
458 return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
462 // otherwise, just open new window using regular HTML
464 return makeInternalLink($url, $text, '_blank');
469 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
470 * Debugging function - does the same as print_r, but makes sure special
471 * characters are converted to htmlentities first. This will allow
472 * values like <some@email.address> to be displayed.
473 * The output is wrapped in <pre> and </pre> tags.
475 function sm_print_r() {
476 ob_start(); // Buffer output
477 foreach(func_get_args() as $var) {
481 $buffer = ob_get_contents(); // Grab the print_r output
482 ob_end_clean(); // Silently discard the output & stop buffering
484 print htmlentities($buffer);
488 $PHP_SELF = php_self();