01454742ee109a5458f277fae3ba9b3e0fb07227
[squirrelmail.git] / functions / strings.php
1 <?php
2
3 /**
4 * strings.php
5 *
6 * Copyright (c) 1999-2004 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 * @package squirrelmail
14 */
15
16 /**
17 * SquirrelMail version number -- DO NOT CHANGE
18 */
19 global $version;
20 $version = '1.5.1 [CVS]';
21
22 /**
23 * SquirrelMail internal version number -- DO NOT CHANGE
24 * $sm_internal_version = array (release, major, minor)
25 */
26 global $SQM_INTERNAL_VERSION;
27 $SQM_INTERNAL_VERSION = array(1,5,1);
28
29 /**
30 * There can be a circular issue with includes, where the $version string is
31 * referenced by the include of global.php, etc. before it's defined.
32 * For that reason, bring in global.php AFTER we define the version strings.
33 */
34 require_once(SM_PATH . 'functions/global.php');
35
36 /**
37 * Wraps text at $wrap characters
38 *
39 * Has a problem with special HTML characters, so call this before
40 * you do character translation.
41 *
42 * Specifically, &#039 comes up as 5 characters instead of 1.
43 * This should not add newlines to the end of lines.
44 *
45 * @param string line the line of text to wrap, by ref
46 * @param int wrap the maximum line lenth
47 * @return void
48 */
49 function sqWordWrap(&$line, $wrap) {
50 global $languages, $squirrelmail_language;
51
52 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
53 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
54 if (mb_detect_encoding($line) != 'ASCII') {
55 $line = $languages[$squirrelmail_language]['XTRA_CODE']('wordwrap', $line, $wrap);
56 return;
57 }
58 }
59
60 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
61 $beginning_spaces = $regs[1];
62 if (isset($regs[2])) {
63 $words = explode(' ', $regs[2]);
64 } else {
65 $words = '';
66 }
67
68 $i = 0;
69 $line = $beginning_spaces;
70
71 while ($i < count($words)) {
72 /* Force one word to be on a line (minimum) */
73 $line .= $words[$i];
74 $line_len = strlen($beginning_spaces) + strlen($words[$i]) + 2;
75 if (isset($words[$i + 1]))
76 $line_len += strlen($words[$i + 1]);
77 $i ++;
78
79 /* Add more words (as long as they fit) */
80 while ($line_len < $wrap && $i < count($words)) {
81 $line .= ' ' . $words[$i];
82 $i++;
83 if (isset($words[$i]))
84 $line_len += strlen($words[$i]) + 1;
85 else
86 $line_len += 1;
87 }
88
89 /* Skip spaces if they are the first thing on a continued line */
90 while (!isset($words[$i]) && $i < count($words)) {
91 $i ++;
92 }
93
94 /* Go to the next line if we have more to process */
95 if ($i < count($words)) {
96 $line .= "\n";
97 }
98 }
99 }
100
101 /**
102 * Does the opposite of sqWordWrap()
103 * @param string body the text to un-wordwrap
104 * @return void
105 */
106 function sqUnWordWrap(&$body) {
107 global $squirrelmail_language;
108
109 if ($squirrelmail_language == 'ja_JP') {
110 return;
111 }
112
113 $lines = explode("\n", $body);
114 $body = '';
115 $PreviousSpaces = '';
116 $cnt = count($lines);
117 for ($i = 0; $i < $cnt; $i ++) {
118 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
119 $CurrentSpaces = $regs[1];
120 if (isset($regs[2])) {
121 $CurrentRest = $regs[2];
122 } else {
123 $CurrentRest = '';
124 }
125
126 if ($i == 0) {
127 $PreviousSpaces = $CurrentSpaces;
128 $body = $lines[$i];
129 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
130 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
131 && strlen($CurrentRest)) { /* and there's a line to continue with */
132 $body .= ' ' . $CurrentRest;
133 } else {
134 $body .= "\n" . $lines[$i];
135 $PreviousSpaces = $CurrentSpaces;
136 }
137 }
138 $body .= "\n";
139 }
140
141 /**
142 * If $haystack is a full mailbox name and $needle is the mailbox
143 * separator character, returns the last part of the mailbox name.
144 *
145 * @param string haystack full mailbox name to search
146 * @param string needle the mailbox separator character
147 * @return string the last part of the mailbox name
148 */
149 function readShortMailboxName($haystack, $needle) {
150
151 if ($needle == '') {
152 $elem = $haystack;
153 } else {
154 $parts = explode($needle, $haystack);
155 $elem = array_pop($parts);
156 while ($elem == '' && count($parts)) {
157 $elem = array_pop($parts);
158 }
159 }
160 return( $elem );
161 }
162
163 /**
164 * Creates an URL for the page calling this function, using either the PHP global
165 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
166 *
167 * @return string the complete url for this page
168 */
169 function php_self () {
170 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
171 return $req_uri;
172 }
173
174 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
175
176 // need to add query string to end of PHP_SELF to match REQUEST_URI
177 //
178 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
179 $php_self .= '?' . $query_string;
180 }
181
182 return $php_self;
183 }
184
185 return '';
186 }
187
188
189 /**
190 * Determines the location to forward to, relative to your server.
191 * This is used in HTTP Location: redirects.
192 * If this doesnt work correctly for you (although it should), you can
193 * remove all this code except the last two lines, and have it return
194 * the right URL for your site, something like:
195 *
196 * http://www.example.com/squirrelmail/
197 *
198 * @return string the base url for this SquirrelMail installation
199 */
200 function get_location () {
201
202 global $imap_server_type;
203
204 /* Get the path, handle virtual directories */
205 if(strpos(php_self(), '?')) {
206 $path = substr(php_self(), 0, strpos(php_self(), '?'));
207 } else {
208 $path = php_self();
209 }
210 $path = substr($path, 0, strrpos($path, '/'));
211 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
212 return $full_url . $path;
213 }
214
215 /* Check if this is a HTTPS or regular HTTP request. */
216 $proto = 'http://';
217
218 /*
219 * If you have 'SSLOptions +StdEnvVars' in your apache config
220 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
221 * OR if you are on port 443
222 */
223 $getEnvVar = getenv('HTTPS');
224 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
225 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
226 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
227 $proto = 'https://';
228 }
229
230 /* Get the hostname from the Host header or server config. */
231 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
232 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
233 $host = '';
234 }
235 }
236
237 $port = '';
238 if (! strstr($host, ':')) {
239 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
240 if (($server_port != 80 && $proto == 'http://') ||
241 ($server_port != 443 && $proto == 'https://')) {
242 $port = sprintf(':%d', $server_port);
243 }
244 }
245 }
246
247 /* this is a workaround for the weird macosx caching that
248 causes Apache to return 16080 as the port number, which causes
249 SM to bail */
250
251 if ($imap_server_type == 'macosx' && $port == ':16080') {
252 $port = '';
253 }
254
255 /* Fallback is to omit the server name and use a relative */
256 /* URI, although this is not RFC 2616 compliant. */
257 $full_url = ($host ? $proto . $host . $port : '');
258 sqsession_register($full_url, 'sq_base_url');
259 return $full_url . $path;
260 }
261
262
263 /**
264 * These functions are used to encrypt the password before it is
265 * stored in a cookie. The encryption key is generated by
266 * OneTimePadCreate();
267 *
268 * @param string string the (password)string to encrypt
269 * @param string epad the encryption key
270 * @return string the base64-encoded encrypted password
271 */
272 function OneTimePadEncrypt ($string, $epad) {
273 $pad = base64_decode($epad);
274 $encrypted = '';
275 for ($i = 0; $i < strlen ($string); $i++) {
276 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
277 }
278
279 return base64_encode($encrypted);
280 }
281
282 /**
283 * Decrypt a password from the cookie, encrypted by OneTimePadEncrypt.
284 * This uses the encryption key that is stored in the session.
285 *
286 * @param string string the string to decrypt
287 * @param string epad the encryption key from the session
288 * @return string the decrypted password
289 */
290 function OneTimePadDecrypt ($string, $epad) {
291 $pad = base64_decode($epad);
292 $encrypted = base64_decode ($string);
293 $decrypted = '';
294 for ($i = 0; $i < strlen ($encrypted); $i++) {
295 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
296 }
297
298 return $decrypted;
299 }
300
301
302 /**
303 * Randomize the mt_rand() function. Toss this in strings or integers
304 * and it will seed the generator appropriately. With strings, it is
305 * better to get them long. Use md5() to lengthen smaller strings.
306 *
307 * @param mixed val a value to seed the random number generator
308 * @return void
309 */
310 function sq_mt_seed($Val) {
311 /* if mt_getrandmax() does not return a 2^n - 1 number,
312 this might not work well. This uses $Max as a bitmask. */
313 $Max = mt_getrandmax();
314
315 if (! is_int($Val)) {
316 $Val = crc32($Val);
317 }
318
319 if ($Val < 0) {
320 $Val *= -1;
321 }
322
323 if ($Val = 0) {
324 return;
325 }
326
327 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
328 }
329
330
331 /**
332 * This function initializes the random number generator fairly well.
333 * It also only initializes it once, so you don't accidentally get
334 * the same 'random' numbers twice in one session.
335 *
336 * @return void
337 */
338 function sq_mt_randomize() {
339 static $randomized;
340
341 if ($randomized) {
342 return;
343 }
344
345 /* Global. */
346 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
347 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
348 sq_mt_seed((int)((double) microtime() * 1000000));
349 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
350
351 /* getrusage */
352 if (function_exists('getrusage')) {
353 /* Avoid warnings with Win32 */
354 $dat = @getrusage();
355 if (isset($dat) && is_array($dat)) {
356 $Str = '';
357 foreach ($dat as $k => $v)
358 {
359 $Str .= $k . $v;
360 }
361 sq_mt_seed(md5($Str));
362 }
363 }
364
365 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
366 sq_mt_seed(md5($unique_id));
367 }
368
369 $randomized = 1;
370 }
371
372 /**
373 * Creates an encryption key for encrypting the password stored in the cookie.
374 * The encryption key itself is stored in the session.
375 *
376 * @param int length optional, length of the string to generate
377 * @return string the encryption key
378 */
379 function OneTimePadCreate ($length=100) {
380 sq_mt_randomize();
381
382 $pad = '';
383 for ($i = 0; $i < $length; $i++) {
384 $pad .= chr(mt_rand(0,255));
385 }
386
387 return base64_encode($pad);
388 }
389
390 /**
391 * Returns a string showing the size of the message/attachment.
392 *
393 * @param int bytes the filesize in bytes
394 * @return string the filesize in human readable format
395 */
396 function show_readable_size($bytes) {
397 $bytes /= 1024;
398 $type = 'k';
399
400 if ($bytes / 1024 > 1) {
401 $bytes /= 1024;
402 $type = 'M';
403 }
404
405 if ($bytes < 10) {
406 $bytes *= 10;
407 settype($bytes, 'integer');
408 $bytes /= 10;
409 } else {
410 settype($bytes, 'integer');
411 }
412
413 return $bytes . '<small>&nbsp;' . $type . '</small>';
414 }
415
416 /**
417 * Generates a random string from the caracter set you pass in
418 *
419 * @param int size the size of the string to generate
420 * @param string chars a string containing the characters to use
421 * @param int flags a flag to add a specific set to the characters to use:
422 * Flags:
423 * 1 = add lowercase a-z to $chars
424 * 2 = add uppercase A-Z to $chars
425 * 4 = add numbers 0-9 to $chars
426 * @return string the random string
427 */
428
429 function GenerateRandomString($size, $chars, $flags = 0) {
430 if ($flags & 0x1) {
431 $chars .= 'abcdefghijklmnopqrstuvwxyz';
432 }
433 if ($flags & 0x2) {
434 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
435 }
436 if ($flags & 0x4) {
437 $chars .= '0123456789';
438 }
439
440 if (($size < 1) || (strlen($chars) < 1)) {
441 return '';
442 }
443
444 sq_mt_randomize(); /* Initialize the random number generator */
445
446 $String = '';
447 $j = strlen( $chars ) - 1;
448 while (strlen($String) < $size) {
449 $String .= $chars{mt_rand(0, $j)};
450 }
451
452 return $String;
453 }
454
455 /**
456 * Escapes special characters for use in IMAP commands.
457 * @param string the string to escape
458 * @return string the escaped string
459 */
460 function quoteimap($str) {
461 return ereg_replace('(["\\])', '\\\\1', $str);
462 }
463
464 /**
465 * Trims every element in the array, ie. remove the first char of each element
466 * @param array array the array to trim
467 */
468 function TrimArray(&$array) {
469 foreach ($array as $k => $v) {
470 global $$k;
471 if (is_array($$k)) {
472 foreach ($$k as $k2 => $v2) {
473 $$k[$k2] = substr($v2, 1);
474 }
475 } else {
476 $$k = substr($v, 1);
477 }
478
479 /* Re-assign back to array. */
480 $array[$k] = $$k;
481 }
482 }
483
484 /**
485 * Returns a link to the compose-page, taking in consideration
486 * the compose_in_new and javascript settings.
487 * @param string url the URL to the compose page
488 * @param string text the link text, default "Compose"
489 * @return string a link to the compose page
490 */
491 function makeComposeLink($url, $text = null, $target='')
492 {
493 global $compose_new_win,$javascript_on;
494
495 if(!$text) {
496 $text = _("Compose");
497 }
498
499
500 // if not using "compose in new window", make
501 // regular link and be done with it
502 if($compose_new_win != '1') {
503 return makeInternalLink($url, $text, $target);
504 }
505
506
507 // build the compose in new window link...
508
509
510 // if javascript is on, use onClick event to handle it
511 if($javascript_on) {
512 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
513 return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
514 }
515
516
517 // otherwise, just open new window using regular HTML
518 return makeInternalLink($url, $text, '_blank');
519
520 }
521
522 /**
523 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
524 * Debugging function - does the same as print_r, but makes sure special
525 * characters are converted to htmlentities first. This will allow
526 * values like <some@email.address> to be displayed.
527 * The output is wrapped in <pre> and </pre> tags.
528 *
529 * @return void
530 */
531 function sm_print_r() {
532 ob_start(); // Buffer output
533 foreach(func_get_args() as $var) {
534 print_r($var);
535 echo "\n";
536 }
537 $buffer = ob_get_contents(); // Grab the print_r output
538 ob_end_clean(); // Silently discard the output & stop buffering
539 print '<pre>';
540 print htmlentities($buffer);
541 print '</pre>';
542 }
543
544 $PHP_SELF = php_self();
545 ?>