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