phpdoc formating fixes
[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 * php_self
165 *
166 * Creates an URL for the page calling this function, using either the PHP global
167 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
168 *
169 * @return string the complete url for this page
170 */
171 function php_self () {
172 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
173 return $req_uri;
174 }
175
176 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
177
178 // need to add query string to end of PHP_SELF to match REQUEST_URI
179 //
180 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
181 $php_self .= '?' . $query_string;
182 }
183
184 return $php_self;
185 }
186
187 return '';
188 }
189
190
191 /**
192 * get_location
193 *
194 * Determines the location to forward to, relative to your server.
195 * This is used in HTTP Location: redirects.
196 * If this doesnt work correctly for you (although it should), you can
197 * remove all this code except the last two lines, and have it return
198 * the right URL for your site, something like:
199 *
200 * http://www.example.com/squirrelmail/
201 *
202 * @return string the base url for this SquirrelMail installation
203 */
204 function get_location () {
205
206 global $imap_server_type;
207
208 /* Get the path, handle virtual directories */
209 if(strpos(php_self(), '?')) {
210 $path = substr(php_self(), 0, strpos(php_self(), '?'));
211 } else {
212 $path = php_self();
213 }
214 $path = substr($path, 0, strrpos($path, '/'));
215 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
216 return $full_url . $path;
217 }
218
219 /* Check if this is a HTTPS or regular HTTP request. */
220 $proto = 'http://';
221
222 /*
223 * If you have 'SSLOptions +StdEnvVars' in your apache config
224 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
225 * OR if you are on port 443
226 */
227 $getEnvVar = getenv('HTTPS');
228 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
229 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
230 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
231 $proto = 'https://';
232 }
233
234 /* Get the hostname from the Host header or server config. */
235 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
236 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
237 $host = '';
238 }
239 }
240
241 $port = '';
242 if (! strstr($host, ':')) {
243 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
244 if (($server_port != 80 && $proto == 'http://') ||
245 ($server_port != 443 && $proto == 'https://')) {
246 $port = sprintf(':%d', $server_port);
247 }
248 }
249 }
250
251 /* this is a workaround for the weird macosx caching that
252 causes Apache to return 16080 as the port number, which causes
253 SM to bail */
254
255 if ($imap_server_type == 'macosx' && $port == ':16080') {
256 $port = '';
257 }
258
259 /* Fallback is to omit the server name and use a relative */
260 /* URI, although this is not RFC 2616 compliant. */
261 $full_url = ($host ? $proto . $host . $port : '');
262 sqsession_register($full_url, 'sq_base_url');
263 return $full_url . $path;
264 }
265
266
267 /**
268 * Encrypts password
269 *
270 * These functions are used to encrypt the password before it is
271 * stored in a cookie. The encryption key is generated by
272 * OneTimePadCreate();
273 *
274 * @param string string the (password)string to encrypt
275 * @param string epad the encryption key
276 * @return string the base64-encoded encrypted password
277 */
278 function OneTimePadEncrypt ($string, $epad) {
279 $pad = base64_decode($epad);
280 $encrypted = '';
281 for ($i = 0; $i < strlen ($string); $i++) {
282 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
283 }
284
285 return base64_encode($encrypted);
286 }
287
288 /**
289 * Decrypts a password from the cookie
290 *
291 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
292 * This uses the encryption key that is stored in the session.
293 *
294 * @param string string the string to decrypt
295 * @param string epad the encryption key from the session
296 * @return string the decrypted password
297 */
298 function OneTimePadDecrypt ($string, $epad) {
299 $pad = base64_decode($epad);
300 $encrypted = base64_decode ($string);
301 $decrypted = '';
302 for ($i = 0; $i < strlen ($encrypted); $i++) {
303 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
304 }
305
306 return $decrypted;
307 }
308
309
310 /**
311 * Randomizes the mt_rand() function.
312 *
313 * Toss this in strings or integers and it will seed the generator
314 * appropriately. With strings, it is better to get them long.
315 * Use md5() to lengthen smaller strings.
316 *
317 * @param mixed val a value to seed the random number generator
318 * @return void
319 */
320 function sq_mt_seed($Val) {
321 /* if mt_getrandmax() does not return a 2^n - 1 number,
322 this might not work well. This uses $Max as a bitmask. */
323 $Max = mt_getrandmax();
324
325 if (! is_int($Val)) {
326 $Val = crc32($Val);
327 }
328
329 if ($Val < 0) {
330 $Val *= -1;
331 }
332
333 if ($Val = 0) {
334 return;
335 }
336
337 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
338 }
339
340
341 /**
342 * Init random number generator
343 *
344 * This function initializes the random number generator fairly well.
345 * It also only initializes it once, so you don't accidentally get
346 * the same 'random' numbers twice in one session.
347 *
348 * @return void
349 */
350 function sq_mt_randomize() {
351 static $randomized;
352
353 if ($randomized) {
354 return;
355 }
356
357 /* Global. */
358 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
359 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
360 sq_mt_seed((int)((double) microtime() * 1000000));
361 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
362
363 /* getrusage */
364 if (function_exists('getrusage')) {
365 /* Avoid warnings with Win32 */
366 $dat = @getrusage();
367 if (isset($dat) && is_array($dat)) {
368 $Str = '';
369 foreach ($dat as $k => $v)
370 {
371 $Str .= $k . $v;
372 }
373 sq_mt_seed(md5($Str));
374 }
375 }
376
377 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
378 sq_mt_seed(md5($unique_id));
379 }
380
381 $randomized = 1;
382 }
383
384 /**
385 * Creates encryption key
386 *
387 * Creates an encryption key for encrypting the password stored in the cookie.
388 * The encryption key itself is stored in the session.
389 *
390 * @param int length optional, length of the string to generate
391 * @return string the encryption key
392 */
393 function OneTimePadCreate ($length=100) {
394 sq_mt_randomize();
395
396 $pad = '';
397 for ($i = 0; $i < $length; $i++) {
398 $pad .= chr(mt_rand(0,255));
399 }
400
401 return base64_encode($pad);
402 }
403
404 /**
405 * Returns a string showing the size of the message/attachment.
406 *
407 * @param int bytes the filesize in bytes
408 * @return string the filesize in human readable format
409 */
410 function show_readable_size($bytes) {
411 $bytes /= 1024;
412 $type = 'k';
413
414 if ($bytes / 1024 > 1) {
415 $bytes /= 1024;
416 $type = 'M';
417 }
418
419 if ($bytes < 10) {
420 $bytes *= 10;
421 settype($bytes, 'integer');
422 $bytes /= 10;
423 } else {
424 settype($bytes, 'integer');
425 }
426
427 return $bytes . '<small>&nbsp;' . $type . '</small>';
428 }
429
430 /**
431 * Generates a random string from the caracter set you pass in
432 *
433 * @param int size the size of the string to generate
434 * @param string chars a string containing the characters to use
435 * @param int flags a flag to add a specific set to the characters to use:
436 * Flags:
437 * 1 = add lowercase a-z to $chars
438 * 2 = add uppercase A-Z to $chars
439 * 4 = add numbers 0-9 to $chars
440 * @return string the random string
441 */
442 function GenerateRandomString($size, $chars, $flags = 0) {
443 if ($flags & 0x1) {
444 $chars .= 'abcdefghijklmnopqrstuvwxyz';
445 }
446 if ($flags & 0x2) {
447 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
448 }
449 if ($flags & 0x4) {
450 $chars .= '0123456789';
451 }
452
453 if (($size < 1) || (strlen($chars) < 1)) {
454 return '';
455 }
456
457 sq_mt_randomize(); /* Initialize the random number generator */
458
459 $String = '';
460 $j = strlen( $chars ) - 1;
461 while (strlen($String) < $size) {
462 $String .= $chars{mt_rand(0, $j)};
463 }
464
465 return $String;
466 }
467
468 /**
469 * Escapes special characters for use in IMAP commands.
470 *
471 * @param string the string to escape
472 * @return string the escaped string
473 */
474 function quoteimap($str) {
475 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
476 }
477
478 /**
479 * Trims array
480 *
481 * Trims every element in the array, ie. remove the first char of each element
482 * @param array array the array to trim
483 */
484 function TrimArray(&$array) {
485 foreach ($array as $k => $v) {
486 global $$k;
487 if (is_array($$k)) {
488 foreach ($$k as $k2 => $v2) {
489 $$k[$k2] = substr($v2, 1);
490 }
491 } else {
492 $$k = substr($v, 1);
493 }
494
495 /* Re-assign back to array. */
496 $array[$k] = $$k;
497 }
498 }
499
500 /**
501 * Create compose link
502 *
503 * Returns a link to the compose-page, taking in consideration
504 * the compose_in_new and javascript settings.
505 * @param string url the URL to the compose page
506 * @param string text the link text, default "Compose"
507 * @return string a link to the compose page
508 */
509 function makeComposeLink($url, $text = null, $target='')
510 {
511 global $compose_new_win,$javascript_on;
512
513 if(!$text) {
514 $text = _("Compose");
515 }
516
517
518 // if not using "compose in new window", make
519 // regular link and be done with it
520 if($compose_new_win != '1') {
521 return makeInternalLink($url, $text, $target);
522 }
523
524
525 // build the compose in new window link...
526
527
528 // if javascript is on, use onClick event to handle it
529 if($javascript_on) {
530 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
531 return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
532 }
533
534
535 // otherwise, just open new window using regular HTML
536 return makeInternalLink($url, $text, '_blank');
537
538 }
539
540 /**
541 * Print variable
542 *
543 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
544 *
545 * Debugging function - does the same as print_r, but makes sure special
546 * characters are converted to htmlentities first. This will allow
547 * values like <some@email.address> to be displayed.
548 * The output is wrapped in <<pre>> and <</pre>> tags.
549 *
550 * @return void
551 */
552 function sm_print_r() {
553 ob_start(); // Buffer output
554 foreach(func_get_args() as $var) {
555 print_r($var);
556 echo "\n";
557 }
558 $buffer = ob_get_contents(); // Grab the print_r output
559 ob_end_clean(); // Silently discard the output & stop buffering
560 print '<pre>';
561 print htmlentities($buffer);
562 print '</pre>';
563 }
564
565 /**
566 * version of fwrite which checks for failure
567 */
568 function sq_fwrite($fp, $string) {
569 // write to file
570 $count = @fwrite($fp,$string);
571 // the number of bytes written should be the length of the string
572 if($count != strlen($string)) {
573 return FALSE;
574 }
575
576 return $count;
577 }
578
579 $PHP_SELF = php_self();
580 ?>