A few more unnecessary urldecodes when not needed. Now we can view headers
[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 require_once(SM_PATH . 'functions/global.php');
16
17 /**
18 * SquirrelMail version number -- DO NOT CHANGE
19 */
20 global $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 */
27 global $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 */
40 function 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 */
85 function 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 */
118 function 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 */
136 function 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 */
154 function 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
168 function 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 */
190 function 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 /* Check if this is a HTTPS or regular HTTP request. */
198 $proto = 'http://';
199
200 /*
201 * If you have 'SSLOptions +StdEnvVars' in your apache config
202 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
203 * OR if you are on port 443
204 */
205 $getEnvVar = getenv('HTTPS');
206 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
207 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
208 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
209 $proto = 'https://';
210 }
211
212 /* Get the hostname from the Host header or server config. */
213 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
214 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
215 $host = '';
216 }
217 }
218
219 $port = '';
220 if (! strstr($host, ':')) {
221 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
222 if (($server_port != 80 && $proto == 'http://') ||
223 ($server_port != 443 && $proto == 'https://')) {
224 $port = sprintf(':%d', $server_port);
225 }
226 }
227 }
228
229 /* this is a workaround for the weird macosx caching that
230 causes Apache to return 16080 as the port number, which causes
231 SM to bail */
232
233 if ($imap_server_type == 'macosx' && $port == ':16080') {
234 $port = '';
235 }
236
237 /* Fallback is to omit the server name and use a relative */
238 /* URI, although this is not RFC 2616 compliant. */
239 return ($host ? $proto . $host . $port . $path : $path);
240 }
241
242
243 /**
244 * These functions are used to encrypt the passowrd before it is
245 * stored in a cookie.
246 */
247 function OneTimePadEncrypt ($string, $epad) {
248 $pad = base64_decode($epad);
249 $encrypted = '';
250 for ($i = 0; $i < strlen ($string); $i++) {
251 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
252 }
253
254 return base64_encode($encrypted);
255 }
256
257 function OneTimePadDecrypt ($string, $epad) {
258 $pad = base64_decode($epad);
259 $encrypted = base64_decode ($string);
260 $decrypted = '';
261 for ($i = 0; $i < strlen ($encrypted); $i++) {
262 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
263 }
264
265 return $decrypted;
266 }
267
268
269 /**
270 * Randomize the mt_rand() function. Toss this in strings or integers
271 * and it will seed the generator appropriately. With strings, it is
272 * better to get them long. Use md5() to lengthen smaller strings.
273 */
274 function sq_mt_seed($Val) {
275 /* if mt_getrandmax() does not return a 2^n - 1 number,
276 this might not work well. This uses $Max as a bitmask. */
277 $Max = mt_getrandmax();
278
279 if (! is_int($Val)) {
280 $Val = crc32($Val);
281 }
282
283 if ($Val < 0) {
284 $Val *= -1;
285 }
286
287 if ($Val = 0) {
288 return;
289 }
290
291 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
292 }
293
294
295 /**
296 * This function initializes the random number generator fairly well.
297 * It also only initializes it once, so you don't accidentally get
298 * the same 'random' numbers twice in one session.
299 */
300 function sq_mt_randomize() {
301 static $randomized;
302
303 if ($randomized) {
304 return;
305 }
306
307 /* Global. */
308 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
309 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
310 sq_mt_seed((int)((double) microtime() * 1000000));
311 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
312
313 /* getrusage */
314 if (function_exists('getrusage')) {
315 /* Avoid warnings with Win32 */
316 $dat = @getrusage();
317 if (isset($dat) && is_array($dat)) {
318 $Str = '';
319 foreach ($dat as $k => $v)
320 {
321 $Str .= $k . $v;
322 }
323 sq_mt_seed(md5($Str));
324 }
325 }
326
327 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
328 sq_mt_seed(md5($unique_id));
329 }
330
331 $randomized = 1;
332 }
333
334 function OneTimePadCreate ($length=100) {
335 sq_mt_randomize();
336
337 $pad = '';
338 for ($i = 0; $i < $length; $i++) {
339 $pad .= chr(mt_rand(0,255));
340 }
341
342 return base64_encode($pad);
343 }
344
345 /**
346 * Returns a string showing the size of the message/attachment.
347 */
348 function show_readable_size($bytes) {
349 $bytes /= 1024;
350 $type = 'k';
351
352 if ($bytes / 1024 > 1) {
353 $bytes /= 1024;
354 $type = 'M';
355 }
356
357 if ($bytes < 10) {
358 $bytes *= 10;
359 settype($bytes, 'integer');
360 $bytes /= 10;
361 } else {
362 settype($bytes, 'integer');
363 }
364
365 return $bytes . '<small>&nbsp;' . $type . '</small>';
366 }
367
368 /**
369 * Generates a random string from the caracter set you pass in
370 *
371 * Flags:
372 * 1 = add lowercase a-z to $chars
373 * 2 = add uppercase A-Z to $chars
374 * 4 = add numbers 0-9 to $chars
375 */
376
377 function GenerateRandomString($size, $chars, $flags = 0) {
378 if ($flags & 0x1) {
379 $chars .= 'abcdefghijklmnopqrstuvwxyz';
380 }
381 if ($flags & 0x2) {
382 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
383 }
384 if ($flags & 0x4) {
385 $chars .= '0123456789';
386 }
387
388 if (($size < 1) || (strlen($chars) < 1)) {
389 return '';
390 }
391
392 sq_mt_randomize(); /* Initialize the random number generator */
393
394 $String = '';
395 $j = strlen( $chars ) - 1;
396 while (strlen($String) < $size) {
397 $String .= $chars{mt_rand(0, $j)};
398 }
399
400 return $String;
401 }
402
403 function quoteIMAP($str) {
404 return ereg_replace('(["\\])', '\\\\1', $str);
405 }
406
407 /**
408 * Trims every element in the array
409 */
410 function TrimArray(&$array) {
411 foreach ($array as $k => $v) {
412 global $$k;
413 if (is_array($$k)) {
414 foreach ($$k as $k2 => $v2) {
415 $$k[$k2] = substr($v2, 1);
416 }
417 } else {
418 $$k = substr($v, 1);
419 }
420
421 /* Re-assign back to array. */
422 $array[$k] = $$k;
423 }
424 }
425
426 /**
427 * Removes slashes from every element in the array
428 */
429 function RemoveSlashes(&$array) {
430 foreach ($array as $k => $v) {
431 global $$k;
432 if (is_array($$k)) {
433 foreach ($$k as $k2 => $v2) {
434 $newArray[stripslashes($k2)] = stripslashes($v2);
435 }
436 $$k = $newArray;
437 } else {
438 $$k = stripslashes($v);
439 }
440
441 /* Re-assign back to the array. */
442 $array[$k] = $$k;
443 }
444 }
445
446 $PHP_SELF = php_self();
447
448 ?>