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.
16 * SquirrelMail version number -- DO NOT CHANGE
19 $version = '1.4.0 [CVS-DEVEL]';
22 * SquirrelMail internal version number -- DO NOT CHANGE
23 * $sm_internal_version = array (release, major, minor)
25 global $SQM_INTERNAL_VERSION;
26 $SQM_INTERNAL_VERSION = array(1,4,0);
30 * Wraps text at $wrap characters
32 * Has a problem with special HTML characters, so call this before
33 * you do character translation.
35 * Specifically, ' comes up as 5 characters instead of 1.
36 * This should not add newlines to the end of lines.
38 function sqWordWrap(&$line, $wrap) {
39 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
40 $beginning_spaces = $regs[1];
41 if (isset($regs[2])) {
42 $words = explode(' ', $regs[2]);
48 $line = $beginning_spaces;
50 while ($i < count($words)) {
51 /* Force one word to be on a line (minimum) */
53 $line_len = strlen($beginning_spaces) +
strlen($words[$i]) +
2;
54 if (isset($words[$i +
1]))
55 $line_len +
= strlen($words[$i +
1]);
58 /* Add more words (as long as they fit) */
59 while ($line_len < $wrap && $i < count($words)) {
60 $line .= ' ' . $words[$i];
62 if (isset($words[$i]))
63 $line_len +
= strlen($words[$i]) +
1;
68 /* Skip spaces if they are the first thing on a continued line */
69 while (!isset($words[$i]) && $i < count($words)) {
73 /* Go to the next line if we have more to process */
74 if ($i < count($words)) {
81 * Does the opposite of sqWordWrap()
83 function sqUnWordWrap(&$body) {
84 $lines = explode("\n", $body);
88 for ($i = 0; $i < $cnt; $i ++
) {
89 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
90 $CurrentSpaces = $regs[1];
91 if (isset($regs[2])) {
92 $CurrentRest = $regs[2];
98 $PreviousSpaces = $CurrentSpaces;
100 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
101 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
102 && strlen($CurrentRest)) { /* and there's a line to continue with */
103 $body .= ' ' . $CurrentRest;
105 $body .= "\n" . $lines[$i];
106 $PreviousSpaces = $CurrentSpaces;
113 * If $haystack is a full mailbox name and $needle is the mailbox
114 * separator character, returns the last part of the mailbox name.
116 function readShortMailboxName($haystack, $needle) {
121 $parts = explode($needle, $haystack);
122 $elem = array_pop($parts);
123 while ($elem == '' && count($parts)) {
124 $elem = array_pop($parts);
131 * Returns an array of email addresses.
132 * Be cautious of "user@host.com"
134 function parseAddrs($text) {
135 if (trim($text) == '')
137 $text = str_replace(' ', '', $text);
138 $text = ereg_replace('"[^"]*"', '', $text);
139 $text = ereg_replace('\\([^\\)]*\\)', '', $text);
140 $text = str_replace(',', ';', $text);
141 $array = explode(';', $text);
142 for ($i = 0; $i < count ($array); $i++
) {
143 $array[$i] = eregi_replace ('^.*[<]', '', $array[$i]);
144 $array[$i] = eregi_replace ('[>].*$', '', $array[$i]);
150 * Returns a line of comma separated email addresses from an array.
152 function getLineOfAddrs($array) {
153 if (is_array($array)) {
154 $to_line = implode(', ', $array);
155 $to_line = ereg_replace(', (, )+', ', ', $to_line);
156 $to_line = trim(ereg_replace('^, ', '', $to_line));
157 if( substr( $to_line, -1 ) == ',' )
158 $to_line = substr( $to_line, 0, -1 );
166 function php_self () {
167 global $PHP_SELF, $_SERVER;
169 if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI']) ) {
170 return $_SERVER['REQUEST_URI'];
173 if (isset($PHP_SELF) && !empty($PHP_SELF)) {
175 } else if (isset($_SERVER['PHP_SELF']) &&
176 !empty($_SERVER['PHP_SELF'])) {
177 return $_SERVER['PHP_SELF'];
185 * This determines the location to forward to relative to your server.
186 * If this doesnt work correctly for you (although it should), you can
187 * remove all this code except the last two lines, and change the header()
188 * function to look something like this, customized to the location of
189 * SquirrelMail on your server:
191 * http://www.myhost.com/squirrelmail/src/login.php
193 function get_location () {
195 global $_SERVER, $imap_server_type;
197 /* Get the path, handle virtual directories */
198 $path = substr(php_self(), 0, strrpos(php_self(), '/'));
200 /* Check if this is a HTTPS or regular HTTP request. */
204 * If you have 'SSLOptions +StdEnvVars' in your apache config
205 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
206 * OR if you are on port 443
208 $getEnvVar = getenv('HTTPS');
209 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
210 (isset($_SERVER['HTTPS']) &&
211 !strcasecmp($_SERVER['HTTPS'], 'on')) ||
212 (isset($_SERVER['SERVER_PORT']) &&
213 $_SERVER['SERVER_PORT'] == 443)) {
217 /* Get the hostname from the Host header or server config. */
219 if (isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])) {
220 $host = $_SERVER['HTTP_HOST'];
221 } else if (isset($_SERVER['SERVER_NAME']) &&
222 !empty($_SERVER['SERVER_NAME'])) {
227 if (! strstr($host, ':')) {
228 if (isset($_SERVER['SERVER_PORT'])) {
229 if (($_SERVER['SERVER_PORT'] != 80 && $proto == 'http://')
230 ||
($_SERVER['SERVER_PORT'] != 443 && $proto == 'https://')) {
231 $port = sprintf(':%d', $_SERVER['SERVER_PORT']);
236 /* this is a workaround for the weird macosx caching that
237 causes Apache to return 16080 as the port number, which causes
240 if ($imap_server_type == 'macosx' && $port == ':16080') {
244 /* Fallback is to omit the server name and use a relative */
245 /* URI, although this is not RFC 2616 compliant. */
246 return ($host ?
$proto . $host . $port . $path : $path);
251 * These functions are used to encrypt the passowrd before it is
252 * stored in a cookie.
254 function OneTimePadEncrypt ($string, $epad) {
255 $pad = base64_decode($epad);
257 for ($i = 0; $i < strlen ($string); $i++
) {
258 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
261 return base64_encode($encrypted);
264 function OneTimePadDecrypt ($string, $epad) {
265 $pad = base64_decode($epad);
266 $encrypted = base64_decode ($string);
268 for ($i = 0; $i < strlen ($encrypted); $i++
) {
269 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
277 * Randomize the mt_rand() function. Toss this in strings or integers
278 * and it will seed the generator appropriately. With strings, it is
279 * better to get them long. Use md5() to lengthen smaller strings.
281 function sq_mt_seed($Val) {
282 /* if mt_getrandmax() does not return a 2^n - 1 number,
283 this might not work well. This uses $Max as a bitmask. */
284 $Max = mt_getrandmax();
286 if (! is_int($Val)) {
298 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
303 * This function initializes the random number generator fairly well.
304 * It also only initializes it once, so you don't accidentally get
305 * the same 'random' numbers twice in one session.
307 function sq_mt_randomize() {
316 sq_mt_seed((int)((double) microtime() * 1000000));
317 sq_mt_seed(md5($_SERVER['REMOTE_PORT'] . $_SERVER['REMOTE_ADDR'] . getmypid()));
320 if (function_exists('getrusage')) {
321 /* Avoid warnings with Win32 */
323 if (isset($dat) && is_array($dat)) {
325 foreach ($dat as $k => $v)
329 sq_mt_seed(md5($Str));
333 if(isset($_SERVER['UNIQUE_ID'])) {
334 sq_mt_seed(md5($_SERVER['UNIQUE_ID']));
340 function OneTimePadCreate ($length=100) {
344 for ($i = 0; $i < $length; $i++
) {
345 $pad .= chr(mt_rand(0,255));
348 return base64_encode($pad);
352 * Check if we have a required PHP-version. Return TRUE if we do,
353 * or FALSE if we don't.
355 * To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
356 * To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
358 * Does not handle betas like 4.0.1b1 or development versions
360 function sqCheckPHPVersion($major, $minor, $release) {
363 eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
365 /* Parse the version string. */
366 $vmajor = strval($regs[1]);
367 $vminor = strval($regs[2]);
369 if($vrel[0] == '.') {
370 $vrel = strval(substr($vrel, 1));
372 if($vrel[0] == 'b' ||
$vrel[0] == 'B') {
373 $vrel = - strval(substr($vrel, 1));
375 if($vrel[0] == 'r' ||
$vrel[0] == 'R') {
376 $vrel = - strval(substr($vrel, 2))/10;
379 /* Compare major version. */
380 if ($vmajor < $major) { return false; }
381 if ($vmajor > $major) { return true; }
383 /* Major is the same. Compare minor. */
384 if ($vminor < $minor) { return false; }
385 if ($vminor > $minor) { return true; }
387 /* Major and minor is the same as the required one. Compare release */
388 if ($vrel >= 0 && $release >= 0) { /* Neither are beta */
389 if($vrel < $release) return false;
390 } else if($vrel >= 0 && $release < 0) { /* This is not beta, required is beta */
392 } else if($vrel < 0 && $release >= 0){ /* This is beta, require not beta */
394 } else { /* Both are beta */
395 if($vrel > $release) return false;
402 * Returns a string showing the size of the message/attachment.
404 function show_readable_size($bytes) {
408 if ($bytes / 1024 > 1) {
415 settype($bytes, 'integer');
418 settype($bytes, 'integer');
421 return $bytes . '<small> ' . $type . '</small>';
425 * Generates a random string from the caracter set you pass in
428 * 1 = add lowercase a-z to $chars
429 * 2 = add uppercase A-Z to $chars
430 * 4 = add numbers 0-9 to $chars
433 function GenerateRandomString($size, $chars, $flags = 0) {
435 $chars .= 'abcdefghijklmnopqrstuvwxyz';
438 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
441 $chars .= '0123456789';
444 if (($size < 1) ||
(strlen($chars) < 1)) {
448 sq_mt_randomize(); /* Initialize the random number generator */
451 $j = strlen( $chars ) - 1;
452 while (strlen($String) < $size) {
453 $String .= $chars{mt_rand(0, $j)};
459 function quoteIMAP($str) {
460 return ereg_replace('(["\\])', '\\\\1', $str);
464 * Trims every element in the array
466 function TrimArray(&$array) {
467 foreach ($array as $k => $v) {
470 foreach ($
$k as $k2 => $v2) {
471 $
$k[$k2] = substr($v2, 1);
477 /* Re-assign back to array. */
483 * Removes slashes from every element in the array
485 function RemoveSlashes(&$array) {
486 foreach ($array as $k => $v) {
489 foreach ($
$k as $k2 => $v2) {
490 $newArray[stripslashes($k2)] = stripslashes($v2);
494 $
$k = stripslashes($v);
497 /* Re-assign back to the array. */
502 $PHP_SELF = php_self();