moved address-parsing to the displayable headers
[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
961ca3d8 15
35586184 16/**
17 * SquirrelMail version number -- DO NOT CHANGE
18 */
19global $version;
87d8c725 20$version = '1.5.0 [CVS]';
d068c0ec 21
97bdc607 22/**
23 * SquirrelMail internal version number -- DO NOT CHANGE
24 * $sm_internal_version = array (release, major, minor)
25 */
0567e4d5 26global $SQM_INTERNAL_VERSION;
87d8c725 27$SQM_INTERNAL_VERSION = array(1,5,0);
28
97bdc607 29
87d8c725 30/**
31 * There can be a circular issue with includes, where the $version string is
32 * referenced by the include of global.php, etc. before it's defined.
33 * For that reason, bring in global.php AFTER we define the version strings.
34 */
35require_once(SM_PATH . 'functions/global.php');
97bdc607 36
5cc0b70e 37/**
38 * Wraps text at $wrap characters
39 *
40 * Has a problem with special HTML characters, so call this before
41 * you do character translation.
42 *
43 * Specifically, &#039 comes up as 5 characters instead of 1.
44 * This should not add newlines to the end of lines.
45 */
46function sqWordWrap(&$line, $wrap) {
e842b215 47 global $languages, $squirrelmail_language;
48
49 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
50 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
51 if (mb_detect_encoding($line) != 'ASCII') {
52 $line = $languages[$squirrelmail_language]['XTRA_CODE']('wordwrap', $line, $wrap);
53 return;
54 }
55 }
56
5cc0b70e 57 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
58 $beginning_spaces = $regs[1];
59 if (isset($regs[2])) {
60 $words = explode(' ', $regs[2]);
61 } else {
62 $words = '';
63 }
64
65 $i = 0;
66 $line = $beginning_spaces;
67
68 while ($i < count($words)) {
69 /* Force one word to be on a line (minimum) */
70 $line .= $words[$i];
71 $line_len = strlen($beginning_spaces) + strlen($words[$i]) + 2;
72 if (isset($words[$i + 1]))
73 $line_len += strlen($words[$i + 1]);
74 $i ++;
75
76 /* Add more words (as long as they fit) */
77 while ($line_len < $wrap && $i < count($words)) {
78 $line .= ' ' . $words[$i];
79 $i++;
80 if (isset($words[$i]))
81 $line_len += strlen($words[$i]) + 1;
82 else
83 $line_len += 1;
84 }
85
86 /* Skip spaces if they are the first thing on a continued line */
87 while (!isset($words[$i]) && $i < count($words)) {
88 $i ++;
89 }
90
91 /* Go to the next line if we have more to process */
92 if ($i < count($words)) {
e0858036 93 $line .= "\n";
5cc0b70e 94 }
95 }
96}
97
341abbd6 98/**
99 * Does the opposite of sqWordWrap()
100 */
101function sqUnWordWrap(&$body) {
e842b215 102 global $squirrelmail_language;
103
104 if ($squirrelmail_language == 'ja_JP') {
105 return;
106 }
107
341abbd6 108 $lines = explode("\n", $body);
109 $body = '';
110 $PreviousSpaces = '';
111 $cnt = count($lines);
112 for ($i = 0; $i < $cnt; $i ++) {
113 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
114 $CurrentSpaces = $regs[1];
115 if (isset($regs[2])) {
116 $CurrentRest = $regs[2];
1e4a4feb 117 } else {
118 $CurrentRest = '';
119 }
341abbd6 120
121 if ($i == 0) {
122 $PreviousSpaces = $CurrentSpaces;
123 $body = $lines[$i];
124 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
125 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
126 && strlen($CurrentRest)) { /* and there's a line to continue with */
127 $body .= ' ' . $CurrentRest;
128 } else {
129 $body .= "\n" . $lines[$i];
130 $PreviousSpaces = $CurrentSpaces;
131 }
132 }
133 $body .= "\n";
134}
135
66239b65 136/**
137 * If $haystack is a full mailbox name and $needle is the mailbox
138 * separator character, returns the last part of the mailbox name.
139 */
140function readShortMailboxName($haystack, $needle) {
97b1248c 141
66239b65 142 if ($needle == '') {
97b1248c 143 $elem = $haystack;
144 } else {
145 $parts = explode($needle, $haystack);
146 $elem = array_pop($parts);
147 while ($elem == '' && count($parts)) {
148 $elem = array_pop($parts);
149 }
66239b65 150 }
97b1248c 151 return( $elem );
66239b65 152}
3302d0d4 153
66239b65 154/**
155 * Returns an array of email addresses.
156 * Be cautious of "user@host.com"
157 */
158function parseAddrs($text) {
4deb32f1 159 if (trim($text) == '')
66239b65 160 return array();
161 $text = str_replace(' ', '', $text);
162 $text = ereg_replace('"[^"]*"', '', $text);
163 $text = ereg_replace('\\([^\\)]*\\)', '', $text);
164 $text = str_replace(',', ';', $text);
165 $array = explode(';', $text);
166 for ($i = 0; $i < count ($array); $i++) {
4deb32f1 167 $array[$i] = eregi_replace ('^.*[<]', '', $array[$i]);
168 $array[$i] = eregi_replace ('[>].*$', '', $array[$i]);
66239b65 169 }
170 return $array;
171}
40ee9452 172
66239b65 173/**
174 * Returns a line of comma separated email addresses from an array.
175 */
176function getLineOfAddrs($array) {
177 if (is_array($array)) {
8a549df2 178 $to_line = implode(', ', $array);
d46b103b 179 $to_line = ereg_replace(', (, )+', ', ', $to_line);
180 $to_line = trim(ereg_replace('^, ', '', $to_line));
181 if( substr( $to_line, -1 ) == ',' )
182 $to_line = substr( $to_line, 0, -1 );
66239b65 183 } else {
8a549df2 184 $to_line = '';
66239b65 185 }
186
187 return( $to_line );
188}
189
43fdb2a4 190function php_self () {
961ca3d8 191 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
192 return $req_uri;
43fdb2a4 193 }
961ca3d8 194
195 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
196 return $php_self;
197 }
198
199 return '';
43fdb2a4 200}
201
202
66239b65 203/**
204 * This determines the location to forward to relative to your server.
205 * If this doesnt work correctly for you (although it should), you can
206 * remove all this code except the last two lines, and change the header()
207 * function to look something like this, customized to the location of
208 * SquirrelMail on your server:
209 *
210 * http://www.myhost.com/squirrelmail/src/login.php
211 */
212function get_location () {
213
961ca3d8 214 global $imap_server_type;
238703be 215
4deb32f1 216 /* Get the path, handle virtual directories */
217 $path = substr(php_self(), 0, strrpos(php_self(), '/'));
238703be 218
219 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
220 return $full_url . $path;
221 }
222
66239b65 223 /* Check if this is a HTTPS or regular HTTP request. */
224 $proto = 'http://';
225
226 /*
227 * If you have 'SSLOptions +StdEnvVars' in your apache config
44827b4d 228 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
66239b65 229 * OR if you are on port 443
230 */
231 $getEnvVar = getenv('HTTPS');
232 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
961ca3d8 233 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
234 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
8a549df2 235 $proto = 'https://';
66239b65 236 }
237
4deb32f1 238 /* Get the hostname from the Host header or server config. */
961ca3d8 239 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
240 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
241 $host = '';
242 }
66239b65 243 }
244
245 $port = '';
246 if (! strstr($host, ':')) {
961ca3d8 247 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
248 if (($server_port != 80 && $proto == 'http://') ||
249 ($server_port != 443 && $proto == 'https://')) {
250 $port = sprintf(':%d', $server_port);
66239b65 251 }
252 }
253 }
254
8de7f698 255 /* this is a workaround for the weird macosx caching that
256 causes Apache to return 16080 as the port number, which causes
257 SM to bail */
258
259 if ($imap_server_type == 'macosx' && $port == ':16080') {
260 $port = '';
261 }
262
238703be 263 /* Fallback is to omit the server name and use a relative */
264 /* URI, although this is not RFC 2616 compliant. */
265 $full_url = ($host ? $proto . $host . $port : '');
266 sqsession_register($full_url, 'sq_base_url');
267 return $full_url . $path;
66239b65 268}
dcaf2a49 269
9374671f 270
66239b65 271/**
272 * These functions are used to encrypt the passowrd before it is
273 * stored in a cookie.
274 */
275function OneTimePadEncrypt ($string, $epad) {
276 $pad = base64_decode($epad);
277 $encrypted = '';
278 for ($i = 0; $i < strlen ($string); $i++) {
279 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
280 }
281
282 return base64_encode($encrypted);
283}
284
285function OneTimePadDecrypt ($string, $epad) {
286 $pad = base64_decode($epad);
287 $encrypted = base64_decode ($string);
288 $decrypted = '';
289 for ($i = 0; $i < strlen ($encrypted); $i++) {
290 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
291 }
292
293 return $decrypted;
294}
9374671f 295
9374671f 296
66239b65 297/**
298 * Randomize the mt_rand() function. Toss this in strings or integers
299 * and it will seed the generator appropriately. With strings, it is
300 * better to get them long. Use md5() to lengthen smaller strings.
301 */
302function sq_mt_seed($Val) {
4deb32f1 303 /* if mt_getrandmax() does not return a 2^n - 1 number,
304 this might not work well. This uses $Max as a bitmask. */
66239b65 305 $Max = mt_getrandmax();
306
307 if (! is_int($Val)) {
66239b65 308 $Val = crc32($Val);
66239b65 309 }
310
311 if ($Val < 0) {
312 $Val *= -1;
313 }
314
315 if ($Val = 0) {
316 return;
317 }
318
319 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
320}
9374671f 321
9374671f 322
66239b65 323/**
324 * This function initializes the random number generator fairly well.
325 * It also only initializes it once, so you don't accidentally get
326 * the same 'random' numbers twice in one session.
327 */
328function sq_mt_randomize() {
66239b65 329 static $randomized;
330
331 if ($randomized) {
332 return;
333 }
334
335 /* Global. */
961ca3d8 336 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
337 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
66239b65 338 sq_mt_seed((int)((double) microtime() * 1000000));
961ca3d8 339 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
66239b65 340
341 /* getrusage */
342 if (function_exists('getrusage')) {
4deb32f1 343 /* Avoid warnings with Win32 */
66239b65 344 $dat = @getrusage();
345 if (isset($dat) && is_array($dat)) {
821a8e9c 346 $Str = '';
347 foreach ($dat as $k => $v)
66239b65 348 {
349 $Str .= $k . $v;
350 }
821a8e9c 351 sq_mt_seed(md5($Str));
66239b65 352 }
353 }
354
961ca3d8 355 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
356 sq_mt_seed(md5($unique_id));
0b97a708 357 }
66239b65 358
359 $randomized = 1;
360}
361
362function OneTimePadCreate ($length=100) {
363 sq_mt_randomize();
364
365 $pad = '';
366 for ($i = 0; $i < $length; $i++) {
367 $pad .= chr(mt_rand(0,255));
368 }
369
370 return base64_encode($pad);
371}
9374671f 372
66239b65 373/**
374 * Returns a string showing the size of the message/attachment.
375 */
376function show_readable_size($bytes) {
377 $bytes /= 1024;
378 $type = 'k';
379
380 if ($bytes / 1024 > 1) {
381 $bytes /= 1024;
e5f1e71c 382 $type = 'M';
66239b65 383 }
384
385 if ($bytes < 10) {
386 $bytes *= 10;
387 settype($bytes, 'integer');
388 $bytes /= 10;
389 } else {
390 settype($bytes, 'integer');
391 }
392
393 return $bytes . '<small>&nbsp;' . $type . '</small>';
394}
9374671f 395
66239b65 396/**
397 * Generates a random string from the caracter set you pass in
398 *
399 * Flags:
400 * 1 = add lowercase a-z to $chars
401 * 2 = add uppercase A-Z to $chars
402 * 4 = add numbers 0-9 to $chars
403 */
9374671f 404
66239b65 405function GenerateRandomString($size, $chars, $flags = 0) {
406 if ($flags & 0x1) {
407 $chars .= 'abcdefghijklmnopqrstuvwxyz';
408 }
409 if ($flags & 0x2) {
410 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
411 }
412 if ($flags & 0x4) {
413 $chars .= '0123456789';
414 }
415
416 if (($size < 1) || (strlen($chars) < 1)) {
417 return '';
418 }
ff4f08ff 419
4deb32f1 420 sq_mt_randomize(); /* Initialize the random number generator */
ff4f08ff 421
4deb32f1 422 $String = '';
ff4f08ff 423 $j = strlen( $chars ) - 1;
66239b65 424 while (strlen($String) < $size) {
ff4f08ff 425 $String .= $chars{mt_rand(0, $j)};
66239b65 426 }
ff4f08ff 427
66239b65 428 return $String;
429}
9374671f 430
fbb76d0e 431function quoteimap($str) {
66239b65 432 return ereg_replace('(["\\])', '\\\\1', $str);
433}
1899535f 434
66239b65 435/**
436 * Trims every element in the array
437 */
438function TrimArray(&$array) {
439 foreach ($array as $k => $v) {
440 global $$k;
441 if (is_array($$k)) {
442 foreach ($$k as $k2 => $v2) {
443 $$k[$k2] = substr($v2, 1);
23d6bd09 444 }
66239b65 445 } else {
446 $$k = substr($v, 1);
23d6bd09 447 }
66239b65 448
4deb32f1 449 /* Re-assign back to array. */
66239b65 450 $array[$k] = $$k;
451 }
452}
23d6bd09 453
66239b65 454/**
455 * Removes slashes from every element in the array
456 */
457function RemoveSlashes(&$array) {
458 foreach ($array as $k => $v) {
459 global $$k;
460 if (is_array($$k)) {
461 foreach ($$k as $k2 => $v2) {
462 $newArray[stripslashes($k2)] = stripslashes($v2);
463 }
464 $$k = $newArray;
465 } else {
466 $$k = stripslashes($v);
23d6bd09 467 }
66239b65 468
4deb32f1 469 /* Re-assign back to the array. */
66239b65 470 $array[$k] = $$k;
23d6bd09 471 }
66239b65 472}
23d6bd09 473
43fdb2a4 474$PHP_SELF = php_self();
475
ef1932a4 476?>