Releasing RC2a
[squirrelmail.git] / functions / strings.php
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
15 /**
16 * SquirrelMail version number -- DO NOT CHANGE
17 */
18 global $version;
19 $version = '1.4.0 RC2a';
20
21 /**
22 * SquirrelMail internal version number -- DO NOT CHANGE
23 * $sm_internal_version = array (release, major, minor)
24 */
25 global $SQM_INTERNAL_VERSION;
26 $SQM_INTERNAL_VERSION = array(1,4,0);
27
28
29 /**
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 */
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]);
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)) {
75 $line .= "\n";
76 }
77 }
78 }
79
80 /**
81 * Does the opposite of sqWordWrap()
82 */
83 function 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];
93 } else {
94 $CurrentRest = '';
95 }
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 /**
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 */
116 function readShortMailboxName($haystack, $needle) {
117
118 if ($needle == '') {
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 }
126 }
127 return( $elem );
128 }
129
130 /**
131 * Returns an array of email addresses.
132 * Be cautious of "user@host.com"
133 */
134 function parseAddrs($text) {
135 if (trim($text) == '')
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++) {
143 $array[$i] = eregi_replace ('^.*[<]', '', $array[$i]);
144 $array[$i] = eregi_replace ('[>].*$', '', $array[$i]);
145 }
146 return $array;
147 }
148
149 /**
150 * Returns a line of comma separated email addresses from an array.
151 */
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 );
159 } else {
160 $to_line = '';
161 }
162
163 return( $to_line );
164 }
165
166 function php_self () {
167 global $PHP_SELF, $_SERVER;
168
169 if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI']) ) {
170 return $_SERVER['REQUEST_URI'];
171 }
172
173 if (isset($PHP_SELF) && !empty($PHP_SELF)) {
174 return $PHP_SELF;
175 } else if (isset($_SERVER['PHP_SELF']) &&
176 !empty($_SERVER['PHP_SELF'])) {
177 return $_SERVER['PHP_SELF'];
178 } else {
179 return '';
180 }
181 }
182
183
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 */
193 function get_location () {
194
195 global $_SERVER, $imap_server_type;
196
197 /* Get the path, handle virtual directories */
198 $path = substr(php_self(), 0, strrpos(php_self(), '/'));
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
205 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
206 * OR if you are on port 443
207 */
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)) {
214 $proto = 'https://';
215 }
216
217 /* Get the hostname from the Host header or server config. */
218 $host = '';
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'])) {
223 }
224
225
226 $port = '';
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']);
232 }
233 }
234 }
235
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
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 }
248
249
250 /**
251 * These functions are used to encrypt the passowrd before it is
252 * stored in a cookie.
253 */
254 function 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
264 function 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 }
274
275
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 */
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();
285
286 if (! is_int($Val)) {
287 $Val = crc32($Val);
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 }
300
301
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 */
307 function sq_mt_randomize() {
308 global $_SERVER;
309 static $randomized;
310
311 if ($randomized) {
312 return;
313 }
314
315 /* Global. */
316 sq_mt_seed((int)((double) microtime() * 1000000));
317 sq_mt_seed(md5($_SERVER['REMOTE_PORT'] . $_SERVER['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(isset($_SERVER['UNIQUE_ID'])) {
334 sq_mt_seed(md5($_SERVER['UNIQUE_ID']));
335 }
336
337 $randomized = 1;
338 }
339
340 function 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 * Duplicate function: obsoleted. Use check_php_version.
353 */
354 function sqCheckPHPVersion($major, $minor, $release) {
355
356 return check_php_version($major, $minor, $release);
357 }
358
359 /**
360 * Returns a string showing the size of the message/attachment.
361 */
362 function show_readable_size($bytes) {
363 $bytes /= 1024;
364 $type = 'k';
365
366 if ($bytes / 1024 > 1) {
367 $bytes /= 1024;
368 $type = 'm';
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 }
381
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 */
390
391 function 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 }
405
406 sq_mt_randomize(); /* Initialize the random number generator */
407
408 $String = '';
409 $j = strlen( $chars ) - 1;
410 while (strlen($String) < $size) {
411 $String .= $chars{mt_rand(0, $j)};
412 }
413
414 return $String;
415 }
416
417 function quoteIMAP($str) {
418 return ereg_replace('(["\\])', '\\\\1', $str);
419 }
420
421 /**
422 * Trims every element in the array
423 */
424 function 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);
430 }
431 } else {
432 $$k = substr($v, 1);
433 }
434
435 /* Re-assign back to array. */
436 $array[$k] = $$k;
437 }
438 }
439
440 /**
441 * Removes slashes from every element in the array
442 */
443 function 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);
453 }
454
455 /* Re-assign back to the array. */
456 $array[$k] = $$k;
457 }
458 }
459
460 $PHP_SELF = php_self();
461
462 ?>