Add phpdoc doc blocks to some files.
[squirrelmail.git] / functions / strings.php
CommitLineData
59177427 1<?php
7350889b 2
f1ca21bd 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$
d6c32258 13 * @package squirrelmail
35586184 14 */
9374671f 15
35586184 16/**
17 * SquirrelMail version number -- DO NOT CHANGE
18 */
19global $version;
87d8c725 20$version = '1.5.0 [CVS]';
d068c0ec 21
f1ca21bd 22/**
97bdc607 23 * SquirrelMail internal version number -- DO NOT CHANGE
24 * $sm_internal_version = array (release, major, minor)
25 */
0567e4d5 26global $SQM_INTERNAL_VERSION;
87d8c725 27$SQM_INTERNAL_VERSION = array(1,5,0);
28
87d8c725 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 */
34require_once(SM_PATH . 'functions/global.php');
97bdc607 35
5cc0b70e 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.
8b096f0a 44 *
45 * @param string line the line of text to wrap, by ref
46 * @param int wrap the maximum line lenth
47 * @return void
5cc0b70e 48 */
49function sqWordWrap(&$line, $wrap) {
e842b215 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
5cc0b70e 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 }
f1ca21bd 67
5cc0b70e 68 $i = 0;
69 $line = $beginning_spaces;
f1ca21bd 70
5cc0b70e 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 ++;
f1ca21bd 78
5cc0b70e 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 }
f1ca21bd 88
5cc0b70e 89 /* Skip spaces if they are the first thing on a continued line */
90 while (!isset($words[$i]) && $i < count($words)) {
91 $i ++;
92 }
f1ca21bd 93
5cc0b70e 94 /* Go to the next line if we have more to process */
95 if ($i < count($words)) {
e0858036 96 $line .= "\n";
5cc0b70e 97 }
98 }
99}
100
341abbd6 101/**
102 * Does the opposite of sqWordWrap()
8b096f0a 103 * @param string body the text to un-wordwrap
104 * @return void
341abbd6 105 */
106function sqUnWordWrap(&$body) {
e842b215 107 global $squirrelmail_language;
f1ca21bd 108
e842b215 109 if ($squirrelmail_language == 'ja_JP') {
110 return;
111 }
112
341abbd6 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];
1e4a4feb 122 } else {
f1ca21bd 123 $CurrentRest = '';
124 }
125
341abbd6 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
66239b65 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.
8b096f0a 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
66239b65 148 */
149function readShortMailboxName($haystack, $needle) {
97b1248c 150
66239b65 151 if ($needle == '') {
97b1248c 152 $elem = $haystack;
153 } else {
f1ca21bd 154 $parts = explode($needle, $haystack);
155 $elem = array_pop($parts);
156 while ($elem == '' && count($parts)) {
157 $elem = array_pop($parts);
158 }
66239b65 159 }
97b1248c 160 return( $elem );
66239b65 161}
3302d0d4 162
8b096f0a 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 */
43fdb2a4 169function php_self () {
961ca3d8 170 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
171 return $req_uri;
43fdb2a4 172 }
f1ca21bd 173
961ca3d8 174 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
f72f61d8 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
961ca3d8 182 return $php_self;
f1ca21bd 183 }
184
961ca3d8 185 return '';
43fdb2a4 186}
187
188
66239b65 189/**
8b096f0a 190 * Determines the location to forward to, relative to your server.
191 * This is used in HTTP Location: redirects.
66239b65 192 * If this doesnt work correctly for you (although it should), you can
8b096f0a 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/
66239b65 197 *
8b096f0a 198 * @return string the base url for this SquirrelMail installation
66239b65 199 */
200function get_location () {
f1ca21bd 201
961ca3d8 202 global $imap_server_type;
238703be 203
4deb32f1 204 /* Get the path, handle virtual directories */
f1ca21bd 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, '/'));
238703be 211 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
212 return $full_url . $path;
213 }
214
66239b65 215 /* Check if this is a HTTPS or regular HTTP request. */
216 $proto = 'http://';
f1ca21bd 217
66239b65 218 /*
219 * If you have 'SSLOptions +StdEnvVars' in your apache config
44827b4d 220 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
66239b65 221 * OR if you are on port 443
222 */
223 $getEnvVar = getenv('HTTPS');
224 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
961ca3d8 225 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
226 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
8a549df2 227 $proto = 'https://';
66239b65 228 }
f1ca21bd 229
4deb32f1 230 /* Get the hostname from the Host header or server config. */
961ca3d8 231 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
232 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
233 $host = '';
234 }
66239b65 235 }
f1ca21bd 236
66239b65 237 $port = '';
238 if (! strstr($host, ':')) {
961ca3d8 239 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
f1ca21bd 240 if (($server_port != 80 && $proto == 'http://') ||
961ca3d8 241 ($server_port != 443 && $proto == 'https://')) {
242 $port = sprintf(':%d', $server_port);
66239b65 243 }
244 }
245 }
f1ca21bd 246
8de7f698 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 */
f1ca21bd 250
8de7f698 251 if ($imap_server_type == 'macosx' && $port == ':16080') {
252 $port = '';
253 }
f1ca21bd 254
238703be 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;
66239b65 260}
dcaf2a49 261
9374671f 262
66239b65 263/**
8b096f0a 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
66239b65 271 */
272function 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 }
f1ca21bd 278
66239b65 279 return base64_encode($encrypted);
280}
281
8b096f0a 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 */
66239b65 290function 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 }
f1ca21bd 297
66239b65 298 return $decrypted;
299}
9374671f 300
9374671f 301
66239b65 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.
8b096f0a 306 *
307 * @param mixed val a value to seed the random number generator
308 * @return void
66239b65 309 */
310function sq_mt_seed($Val) {
4deb32f1 311 /* if mt_getrandmax() does not return a 2^n - 1 number,
312 this might not work well. This uses $Max as a bitmask. */
66239b65 313 $Max = mt_getrandmax();
f1ca21bd 314
66239b65 315 if (! is_int($Val)) {
66239b65 316 $Val = crc32($Val);
66239b65 317 }
f1ca21bd 318
66239b65 319 if ($Val < 0) {
320 $Val *= -1;
321 }
f1ca21bd 322
66239b65 323 if ($Val = 0) {
324 return;
325 }
f1ca21bd 326
66239b65 327 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
328}
9374671f 329
9374671f 330
66239b65 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.
8b096f0a 335 *
336 * @return void
66239b65 337 */
338function sq_mt_randomize() {
66239b65 339 static $randomized;
f1ca21bd 340
66239b65 341 if ($randomized) {
342 return;
343 }
f1ca21bd 344
66239b65 345 /* Global. */
961ca3d8 346 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
347 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
66239b65 348 sq_mt_seed((int)((double) microtime() * 1000000));
961ca3d8 349 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
f1ca21bd 350
66239b65 351 /* getrusage */
352 if (function_exists('getrusage')) {
4deb32f1 353 /* Avoid warnings with Win32 */
66239b65 354 $dat = @getrusage();
355 if (isset($dat) && is_array($dat)) {
821a8e9c 356 $Str = '';
357 foreach ($dat as $k => $v)
66239b65 358 {
359 $Str .= $k . $v;
360 }
821a8e9c 361 sq_mt_seed(md5($Str));
66239b65 362 }
363 }
f1ca21bd 364
961ca3d8 365 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
366 sq_mt_seed(md5($unique_id));
0b97a708 367 }
f1ca21bd 368
66239b65 369 $randomized = 1;
370}
371
8b096f0a 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 */
66239b65 379function OneTimePadCreate ($length=100) {
380 sq_mt_randomize();
f1ca21bd 381
66239b65 382 $pad = '';
383 for ($i = 0; $i < $length; $i++) {
384 $pad .= chr(mt_rand(0,255));
385 }
f1ca21bd 386
66239b65 387 return base64_encode($pad);
388}
9374671f 389
66239b65 390/**
8b096f0a 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
66239b65 395 */
396function show_readable_size($bytes) {
397 $bytes /= 1024;
398 $type = 'k';
f1ca21bd 399
66239b65 400 if ($bytes / 1024 > 1) {
401 $bytes /= 1024;
e5f1e71c 402 $type = 'M';
66239b65 403 }
f1ca21bd 404
66239b65 405 if ($bytes < 10) {
406 $bytes *= 10;
407 settype($bytes, 'integer');
408 $bytes /= 10;
409 } else {
410 settype($bytes, 'integer');
411 }
f1ca21bd 412
66239b65 413 return $bytes . '<small>&nbsp;' . $type . '</small>';
414}
9374671f 415
66239b65 416/**
417 * Generates a random string from the caracter set you pass in
418 *
8b096f0a 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
66239b65 427 */
9374671f 428
66239b65 429function 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 }
f1ca21bd 439
66239b65 440 if (($size < 1) || (strlen($chars) < 1)) {
441 return '';
442 }
ff4f08ff 443
4deb32f1 444 sq_mt_randomize(); /* Initialize the random number generator */
ff4f08ff 445
4deb32f1 446 $String = '';
ff4f08ff 447 $j = strlen( $chars ) - 1;
66239b65 448 while (strlen($String) < $size) {
ff4f08ff 449 $String .= $chars{mt_rand(0, $j)};
66239b65 450 }
ff4f08ff 451
66239b65 452 return $String;
453}
9374671f 454
8b096f0a 455/**
456 * Escapes special characters for use in IMAP commands.
457 * @param string the string to escape
458 * @return string the escaped string
459 */
fbb76d0e 460function quoteimap($str) {
66239b65 461 return ereg_replace('(["\\])', '\\\\1', $str);
462}
1899535f 463
66239b65 464/**
8b096f0a 465 * Trims every element in the array, ie. remove the first char of each element
466 * @param array array the array to trim
66239b65 467 */
468function 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);
23d6bd09 474 }
66239b65 475 } else {
476 $$k = substr($v, 1);
23d6bd09 477 }
f1ca21bd 478
4deb32f1 479 /* Re-assign back to array. */
66239b65 480 $array[$k] = $$k;
481 }
f1ca21bd 482}
23d6bd09 483
8b096f0a 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 */
d62c4938 491function makeComposeLink($url, $text = null)
492{
493 global $compose_new_win,$javascript_on;
494
495 if(!$text) {
496 $text = _("Compose");
497 }
498
f72f61d8 499
500 // if not using "compose in new window", make
501 // regular link and be done with it
d62c4938 502 if($compose_new_win != '1') {
503 return makeInternalLink($url, $text, 'right');
504 }
505
f72f61d8 506
f72f61d8 507 // build the compose in new window link...
f72f61d8 508
509
510 // if javascript is on, use onClick event to handle it
d62c4938 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
f72f61d8 516
517 // otherwise, just open new window using regular HTML
d62c4938 518 return makeInternalLink($url, $text, '_blank');
f72f61d8 519
d62c4938 520}
521
f1ca21bd 522/**
8b096f0a 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 */
7fe09a30 531function sm_print_r() {
50cc40fe 532 ob_start(); // Buffer output
7fe09a30 533 foreach(func_get_args() as $var) {
534 print_r($var);
535 echo "\n";
536 }
50cc40fe 537 $buffer = ob_get_contents(); // Grab the print_r output
538 ob_end_clean(); // Silently discard the output & stop buffering
f1ca21bd 539 print '<pre>';
50cc40fe 540 print htmlentities($buffer);
f1ca21bd 541 print '</pre>';
50cc40fe 542}
543
43fdb2a4 544$PHP_SELF = php_self();
ef1932a4 545?>