fix warning in case of undefined date
[squirrelmail.git] / functions / strings.php
CommitLineData
59177427 1<?php
7350889b 2
e080b080 3/**
35586184 4 * strings.php
5 *
76911253 6 * Copyright (c) 1999-2003 The SquirrelMail Project Team
35586184 7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * This code provides various string manipulation functions that are
10 * used by the rest of the Squirrelmail code.
11 *
12 * $Id$
13 */
9374671f 14
35586184 15/**
16 * SquirrelMail version number -- DO NOT CHANGE
17 */
18global $version;
89a376a2 19$version = '1.4.0 [CVS-DEVEL]';
d068c0ec 20
97bdc607 21/**
22 * SquirrelMail internal version number -- DO NOT CHANGE
23 * $sm_internal_version = array (release, major, minor)
24 */
0567e4d5 25global $SQM_INTERNAL_VERSION;
76911253 26$SQM_INTERNAL_VERSION = array(1,4,0);
97bdc607 27
28
66239b65 29/**
5cc0b70e 30 * Wraps text at $wrap characters
31 *
32 * Has a problem with special HTML characters, so call this before
33 * you do character translation.
34 *
35 * Specifically, &#039 comes up as 5 characters instead of 1.
36 * This should not add newlines to the end of lines.
37 */
38function sqWordWrap(&$line, $wrap) {
39 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
40 $beginning_spaces = $regs[1];
41 if (isset($regs[2])) {
42 $words = explode(' ', $regs[2]);
43 } else {
44 $words = '';
45 }
46
47 $i = 0;
48 $line = $beginning_spaces;
49
50 while ($i < count($words)) {
51 /* Force one word to be on a line (minimum) */
52 $line .= $words[$i];
53 $line_len = strlen($beginning_spaces) + strlen($words[$i]) + 2;
54 if (isset($words[$i + 1]))
55 $line_len += strlen($words[$i + 1]);
56 $i ++;
57
58 /* Add more words (as long as they fit) */
59 while ($line_len < $wrap && $i < count($words)) {
60 $line .= ' ' . $words[$i];
61 $i++;
62 if (isset($words[$i]))
63 $line_len += strlen($words[$i]) + 1;
64 else
65 $line_len += 1;
66 }
67
68 /* Skip spaces if they are the first thing on a continued line */
69 while (!isset($words[$i]) && $i < count($words)) {
70 $i ++;
71 }
72
73 /* Go to the next line if we have more to process */
74 if ($i < count($words)) {
e0858036 75 $line .= "\n";
5cc0b70e 76 }
77 }
78}
79
80/**
341abbd6 81 * Does the opposite of sqWordWrap()
82 */
83function sqUnWordWrap(&$body) {
84 $lines = explode("\n", $body);
85 $body = '';
86 $PreviousSpaces = '';
87 $cnt = count($lines);
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];
1e4a4feb 93 } else {
94 $CurrentRest = '';
95 }
341abbd6 96
97 if ($i == 0) {
98 $PreviousSpaces = $CurrentSpaces;
99 $body = $lines[$i];
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;
104 } else {
105 $body .= "\n" . $lines[$i];
106 $PreviousSpaces = $CurrentSpaces;
107 }
108 }
109 $body .= "\n";
110}
111
112/**
66239b65 113 * If $haystack is a full mailbox name and $needle is the mailbox
114 * separator character, returns the last part of the mailbox name.
115 */
116function readShortMailboxName($haystack, $needle) {
97b1248c 117
66239b65 118 if ($needle == '') {
97b1248c 119 $elem = $haystack;
120 } else {
121 $parts = explode($needle, $haystack);
122 $elem = array_pop($parts);
123 while ($elem == '' && count($parts)) {
124 $elem = array_pop($parts);
125 }
66239b65 126 }
97b1248c 127 return( $elem );
66239b65 128}
3302d0d4 129
66239b65 130/**
66239b65 131 * Returns an array of email addresses.
132 * Be cautious of "user@host.com"
133 */
134function parseAddrs($text) {
4deb32f1 135 if (trim($text) == '')
66239b65 136 return array();
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++) {
4deb32f1 143 $array[$i] = eregi_replace ('^.*[<]', '', $array[$i]);
144 $array[$i] = eregi_replace ('[>].*$', '', $array[$i]);
66239b65 145 }
146 return $array;
147}
40ee9452 148
66239b65 149/**
150 * Returns a line of comma separated email addresses from an array.
151 */
152function getLineOfAddrs($array) {
153 if (is_array($array)) {
8a549df2 154 $to_line = implode(', ', $array);
d46b103b 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 );
66239b65 159 } else {
8a549df2 160 $to_line = '';
66239b65 161 }
162
163 return( $to_line );
164}
165
43fdb2a4 166function php_self () {
0b97a708 167 global $PHP_SELF, $_SERVER;
43fdb2a4 168
0b97a708 169 if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI']) ) {
170 return $_SERVER['REQUEST_URI'];
4deb32f1 171 }
172
43fdb2a4 173 if (isset($PHP_SELF) && !empty($PHP_SELF)) {
174 return $PHP_SELF;
0b97a708 175 } else if (isset($_SERVER['PHP_SELF']) &&
176 !empty($_SERVER['PHP_SELF'])) {
177 return $_SERVER['PHP_SELF'];
43fdb2a4 178 } else {
179 return '';
180 }
181}
182
183
66239b65 184/**
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:
190 *
191 * http://www.myhost.com/squirrelmail/src/login.php
192 */
193function get_location () {
194
0b97a708 195 global $_SERVER, $imap_server_type;
66239b65 196
4deb32f1 197 /* Get the path, handle virtual directories */
198 $path = substr(php_self(), 0, strrpos(php_self(), '/'));
66239b65 199
200 /* Check if this is a HTTPS or regular HTTP request. */
201 $proto = 'http://';
202
203 /*
204 * If you have 'SSLOptions +StdEnvVars' in your apache config
44827b4d 205 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
66239b65 206 * OR if you are on port 443
207 */
208 $getEnvVar = getenv('HTTPS');
209 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
44827b4d 210 (isset($_SERVER['HTTPS']) &&
211 !strcasecmp($_SERVER['HTTPS'], 'on')) ||
0b97a708 212 (isset($_SERVER['SERVER_PORT']) &&
213 $_SERVER['SERVER_PORT'] == 443)) {
8a549df2 214 $proto = 'https://';
66239b65 215 }
216
4deb32f1 217 /* Get the hostname from the Host header or server config. */
66239b65 218 $host = '';
0b97a708 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'])) {
66239b65 223 }
4dc9a365 224
66239b65 225
226 $port = '';
227 if (! strstr($host, ':')) {
0b97a708 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']);
66239b65 232 }
233 }
234 }
235
8de7f698 236 /* this is a workaround for the weird macosx caching that
237 causes Apache to return 16080 as the port number, which causes
238 SM to bail */
239
240 if ($imap_server_type == 'macosx' && $port == ':16080') {
241 $port = '';
242 }
243
66239b65 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);
247}
dcaf2a49 248
9374671f 249
66239b65 250/**
251 * These functions are used to encrypt the passowrd before it is
252 * stored in a cookie.
253 */
254function OneTimePadEncrypt ($string, $epad) {
255 $pad = base64_decode($epad);
256 $encrypted = '';
257 for ($i = 0; $i < strlen ($string); $i++) {
258 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
259 }
260
261 return base64_encode($encrypted);
262}
263
264function OneTimePadDecrypt ($string, $epad) {
265 $pad = base64_decode($epad);
266 $encrypted = base64_decode ($string);
267 $decrypted = '';
268 for ($i = 0; $i < strlen ($encrypted); $i++) {
269 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
270 }
271
272 return $decrypted;
273}
9374671f 274
9374671f 275
66239b65 276/**
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.
280 */
281function sq_mt_seed($Val) {
4deb32f1 282 /* if mt_getrandmax() does not return a 2^n - 1 number,
283 this might not work well. This uses $Max as a bitmask. */
66239b65 284 $Max = mt_getrandmax();
285
286 if (! is_int($Val)) {
66239b65 287 $Val = crc32($Val);
66239b65 288 }
289
290 if ($Val < 0) {
291 $Val *= -1;
292 }
293
294 if ($Val = 0) {
295 return;
296 }
297
298 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
299}
9374671f 300
9374671f 301
66239b65 302/**
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.
306 */
307function sq_mt_randomize() {
0b97a708 308 global $_SERVER;
66239b65 309 static $randomized;
310
311 if ($randomized) {
312 return;
313 }
314
315 /* Global. */
316 sq_mt_seed((int)((double) microtime() * 1000000));
0b97a708 317 sq_mt_seed(md5($_SERVER['REMOTE_PORT'] . $_SERVER['REMOTE_ADDR'] . getmypid()));
66239b65 318
319 /* getrusage */
320 if (function_exists('getrusage')) {
4deb32f1 321 /* Avoid warnings with Win32 */
66239b65 322 $dat = @getrusage();
323 if (isset($dat) && is_array($dat)) {
821a8e9c 324 $Str = '';
325 foreach ($dat as $k => $v)
66239b65 326 {
327 $Str .= $k . $v;
328 }
821a8e9c 329 sq_mt_seed(md5($Str));
66239b65 330 }
331 }
332
0b97a708 333 if(isset($_SERVER['UNIQUE_ID'])) {
334 sq_mt_seed(md5($_SERVER['UNIQUE_ID']));
335 }
66239b65 336
337 $randomized = 1;
338}
339
340function OneTimePadCreate ($length=100) {
341 sq_mt_randomize();
342
343 $pad = '';
344 for ($i = 0; $i < $length; $i++) {
345 $pad .= chr(mt_rand(0,255));
346 }
347
348 return base64_encode($pad);
349}
9374671f 350
66239b65 351/**
787f3030 352 * Duplicate function: obsoleted. Use check_php_version.
66239b65 353 */
354function sqCheckPHPVersion($major, $minor, $release) {
787f3030 355
356 return check_php_version($major, $minor, $release);
66239b65 357}
9374671f 358
66239b65 359/**
360 * Returns a string showing the size of the message/attachment.
361 */
362function show_readable_size($bytes) {
363 $bytes /= 1024;
364 $type = 'k';
365
366 if ($bytes / 1024 > 1) {
367 $bytes /= 1024;
e5f1e71c 368 $type = 'M';
66239b65 369 }
370
371 if ($bytes < 10) {
372 $bytes *= 10;
373 settype($bytes, 'integer');
374 $bytes /= 10;
375 } else {
376 settype($bytes, 'integer');
377 }
378
379 return $bytes . '<small>&nbsp;' . $type . '</small>';
380}
9374671f 381
66239b65 382/**
383 * Generates a random string from the caracter set you pass in
384 *
385 * Flags:
386 * 1 = add lowercase a-z to $chars
387 * 2 = add uppercase A-Z to $chars
388 * 4 = add numbers 0-9 to $chars
389 */
9374671f 390
66239b65 391function GenerateRandomString($size, $chars, $flags = 0) {
392 if ($flags & 0x1) {
393 $chars .= 'abcdefghijklmnopqrstuvwxyz';
394 }
395 if ($flags & 0x2) {
396 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
397 }
398 if ($flags & 0x4) {
399 $chars .= '0123456789';
400 }
401
402 if (($size < 1) || (strlen($chars) < 1)) {
403 return '';
404 }
ff4f08ff 405
4deb32f1 406 sq_mt_randomize(); /* Initialize the random number generator */
ff4f08ff 407
4deb32f1 408 $String = '';
ff4f08ff 409 $j = strlen( $chars ) - 1;
66239b65 410 while (strlen($String) < $size) {
ff4f08ff 411 $String .= $chars{mt_rand(0, $j)};
66239b65 412 }
ff4f08ff 413
66239b65 414 return $String;
415}
9374671f 416
66239b65 417function quoteIMAP($str) {
418 return ereg_replace('(["\\])', '\\\\1', $str);
419}
1899535f 420
66239b65 421/**
422 * Trims every element in the array
423 */
424function TrimArray(&$array) {
425 foreach ($array as $k => $v) {
426 global $$k;
427 if (is_array($$k)) {
428 foreach ($$k as $k2 => $v2) {
429 $$k[$k2] = substr($v2, 1);
23d6bd09 430 }
66239b65 431 } else {
432 $$k = substr($v, 1);
23d6bd09 433 }
66239b65 434
4deb32f1 435 /* Re-assign back to array. */
66239b65 436 $array[$k] = $$k;
437 }
438}
23d6bd09 439
66239b65 440/**
441 * Removes slashes from every element in the array
442 */
443function RemoveSlashes(&$array) {
444 foreach ($array as $k => $v) {
445 global $$k;
446 if (is_array($$k)) {
447 foreach ($$k as $k2 => $v2) {
448 $newArray[stripslashes($k2)] = stripslashes($v2);
449 }
450 $$k = $newArray;
451 } else {
452 $$k = stripslashes($v);
23d6bd09 453 }
66239b65 454
4deb32f1 455 /* Re-assign back to the array. */
66239b65 456 $array[$k] = $$k;
23d6bd09 457 }
66239b65 458}
23d6bd09 459
43fdb2a4 460$PHP_SELF = php_self();
461
1885d093 462?>