Fix for infinite loop when trying to decode multi-part mime attachments
[squirrelmail.git] / functions / strings.php
... / ...
CommitLineData
1<?php
2
3/**
4 * strings.php
5 *
6 * Copyright (c) 1999-2003 The SquirrelMail Project Team
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 */
14
15require_once(SM_PATH . 'functions/global.php');
16
17/**
18 * SquirrelMail version number -- DO NOT CHANGE
19 */
20global $version;
21$version = '1.4.0 [CVS-DEVEL]';
22
23/**
24 * SquirrelMail internal version number -- DO NOT CHANGE
25 * $sm_internal_version = array (release, major, minor)
26 */
27global $SQM_INTERNAL_VERSION;
28$SQM_INTERNAL_VERSION = array(1,4,0);
29
30
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)) {
77 $line .= "\n";
78 }
79 }
80}
81
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];
95 } else {
96 $CurrentRest = '';
97 }
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
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) {
119
120 if ($needle == '') {
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 }
128 }
129 return( $elem );
130}
131
132/**
133 * Returns an array of email addresses.
134 * Be cautious of "user@host.com"
135 */
136function parseAddrs($text) {
137 if (trim($text) == '')
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++) {
145 $array[$i] = eregi_replace ('^.*[<]', '', $array[$i]);
146 $array[$i] = eregi_replace ('[>].*$', '', $array[$i]);
147 }
148 return $array;
149}
150
151/**
152 * Returns a line of comma separated email addresses from an array.
153 */
154function getLineOfAddrs($array) {
155 if (is_array($array)) {
156 $to_line = implode(', ', $array);
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 );
161 } else {
162 $to_line = '';
163 }
164
165 return( $to_line );
166}
167
168function php_self () {
169 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
170 return $req_uri;
171 }
172
173 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
174 return $php_self;
175 }
176
177 return '';
178}
179
180
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
192 global $imap_server_type;
193
194 /* Get the path, handle virtual directories */
195 $path = substr(php_self(), 0, strrpos(php_self(), '/'));
196
197 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
198 return $full_url . $path;
199 }
200
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
206 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
207 * OR if you are on port 443
208 */
209 $getEnvVar = getenv('HTTPS');
210 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
211 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
212 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
213 $proto = 'https://';
214 }
215
216 /* Get the hostname from the Host header or server config. */
217 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
218 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
219 $host = '';
220 }
221 }
222
223 $port = '';
224 if (! strstr($host, ':')) {
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);
229 }
230 }
231 }
232
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
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;
246}
247
248
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}
273
274
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) {
281 /* if mt_getrandmax() does not return a 2^n - 1 number,
282 this might not work well. This uses $Max as a bitmask. */
283 $Max = mt_getrandmax();
284
285 if (! is_int($Val)) {
286 $Val = crc32($Val);
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}
299
300
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() {
307 static $randomized;
308
309 if ($randomized) {
310 return;
311 }
312
313 /* Global. */
314 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
315 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
316 sq_mt_seed((int)((double) microtime() * 1000000));
317 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
318
319 /* getrusage */
320 if (function_exists('getrusage')) {
321 /* Avoid warnings with Win32 */
322 $dat = @getrusage();
323 if (isset($dat) && is_array($dat)) {
324 $Str = '';
325 foreach ($dat as $k => $v)
326 {
327 $Str .= $k . $v;
328 }
329 sq_mt_seed(md5($Str));
330 }
331 }
332
333 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
334 sq_mt_seed(md5($unique_id));
335 }
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}
350
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;
360 $type = 'M';
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}
373
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 */
382
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 }
397
398 sq_mt_randomize(); /* Initialize the random number generator */
399
400 $String = '';
401 $j = strlen( $chars ) - 1;
402 while (strlen($String) < $size) {
403 $String .= $chars{mt_rand(0, $j)};
404 }
405
406 return $String;
407}
408
409function quoteimap($str) {
410 return ereg_replace('(["\\])', '\\\\1', $str);
411}
412
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);
422 }
423 } else {
424 $$k = substr($v, 1);
425 }
426
427 /* Re-assign back to array. */
428 $array[$k] = $$k;
429 }
430}
431
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);
445 }
446
447 /* Re-assign back to the array. */
448 $array[$k] = $$k;
449 }
450}
451
452$PHP_SELF = php_self();
453
454?>