8f2cfa7c38a5ce0e270977998388a99ddc37754f
[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 * @package squirrelmail
14 */
15
16 /**
17 * SquirrelMail version number -- DO NOT CHANGE
18 */
19 global $version;
20 $version = '1.5.0 [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,0);
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 function sqWordWrap(&$line, $wrap) {
46 global $languages, $squirrelmail_language;
47
48 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
49 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
50 if (mb_detect_encoding($line) != 'ASCII') {
51 $line = $languages[$squirrelmail_language]['XTRA_CODE']('wordwrap', $line, $wrap);
52 return;
53 }
54 }
55
56 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
57 $beginning_spaces = $regs[1];
58 if (isset($regs[2])) {
59 $words = explode(' ', $regs[2]);
60 } else {
61 $words = '';
62 }
63
64 $i = 0;
65 $line = $beginning_spaces;
66
67 while ($i < count($words)) {
68 /* Force one word to be on a line (minimum) */
69 $line .= $words[$i];
70 $line_len = strlen($beginning_spaces) + strlen($words[$i]) + 2;
71 if (isset($words[$i + 1]))
72 $line_len += strlen($words[$i + 1]);
73 $i ++;
74
75 /* Add more words (as long as they fit) */
76 while ($line_len < $wrap && $i < count($words)) {
77 $line .= ' ' . $words[$i];
78 $i++;
79 if (isset($words[$i]))
80 $line_len += strlen($words[$i]) + 1;
81 else
82 $line_len += 1;
83 }
84
85 /* Skip spaces if they are the first thing on a continued line */
86 while (!isset($words[$i]) && $i < count($words)) {
87 $i ++;
88 }
89
90 /* Go to the next line if we have more to process */
91 if ($i < count($words)) {
92 $line .= "\n";
93 }
94 }
95 }
96
97 /**
98 * Does the opposite of sqWordWrap()
99 */
100 function sqUnWordWrap(&$body) {
101 global $squirrelmail_language;
102
103 if ($squirrelmail_language == 'ja_JP') {
104 return;
105 }
106
107 $lines = explode("\n", $body);
108 $body = '';
109 $PreviousSpaces = '';
110 $cnt = count($lines);
111 for ($i = 0; $i < $cnt; $i ++) {
112 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
113 $CurrentSpaces = $regs[1];
114 if (isset($regs[2])) {
115 $CurrentRest = $regs[2];
116 } else {
117 $CurrentRest = '';
118 }
119
120 if ($i == 0) {
121 $PreviousSpaces = $CurrentSpaces;
122 $body = $lines[$i];
123 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
124 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
125 && strlen($CurrentRest)) { /* and there's a line to continue with */
126 $body .= ' ' . $CurrentRest;
127 } else {
128 $body .= "\n" . $lines[$i];
129 $PreviousSpaces = $CurrentSpaces;
130 }
131 }
132 $body .= "\n";
133 }
134
135 /**
136 * If $haystack is a full mailbox name and $needle is the mailbox
137 * separator character, returns the last part of the mailbox name.
138 */
139 function readShortMailboxName($haystack, $needle) {
140
141 if ($needle == '') {
142 $elem = $haystack;
143 } else {
144 $parts = explode($needle, $haystack);
145 $elem = array_pop($parts);
146 while ($elem == '' && count($parts)) {
147 $elem = array_pop($parts);
148 }
149 }
150 return( $elem );
151 }
152
153 function php_self () {
154 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
155 return $req_uri;
156 }
157
158 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
159
160 // need to add query string to end of PHP_SELF to match REQUEST_URI
161 //
162 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
163 $php_self .= '?' . $query_string;
164 }
165
166 return $php_self;
167 }
168
169 return '';
170 }
171
172
173 /**
174 * This determines the location to forward to relative to your server.
175 * If this doesnt work correctly for you (although it should), you can
176 * remove all this code except the last two lines, and change the header()
177 * function to look something like this, customized to the location of
178 * SquirrelMail on your server:
179 *
180 * http://www.myhost.com/squirrelmail/src/login.php
181 */
182 function get_location () {
183
184 global $imap_server_type;
185
186 /* Get the path, handle virtual directories */
187 if(strpos(php_self(), '?')) {
188 $path = substr(php_self(), 0, strpos(php_self(), '?'));
189 } else {
190 $path = php_self();
191 }
192 $path = substr($path, 0, strrpos($path, '/'));
193 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
194 return $full_url . $path;
195 }
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 $full_url = ($host ? $proto . $host . $port : '');
240 sqsession_register($full_url, 'sq_base_url');
241 return $full_url . $path;
242 }
243
244
245 /**
246 * These functions are used to encrypt the passowrd before it is
247 * stored in a cookie.
248 */
249 function OneTimePadEncrypt ($string, $epad) {
250 $pad = base64_decode($epad);
251 $encrypted = '';
252 for ($i = 0; $i < strlen ($string); $i++) {
253 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
254 }
255
256 return base64_encode($encrypted);
257 }
258
259 function OneTimePadDecrypt ($string, $epad) {
260 $pad = base64_decode($epad);
261 $encrypted = base64_decode ($string);
262 $decrypted = '';
263 for ($i = 0; $i < strlen ($encrypted); $i++) {
264 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
265 }
266
267 return $decrypted;
268 }
269
270
271 /**
272 * Randomize the mt_rand() function. Toss this in strings or integers
273 * and it will seed the generator appropriately. With strings, it is
274 * better to get them long. Use md5() to lengthen smaller strings.
275 */
276 function sq_mt_seed($Val) {
277 /* if mt_getrandmax() does not return a 2^n - 1 number,
278 this might not work well. This uses $Max as a bitmask. */
279 $Max = mt_getrandmax();
280
281 if (! is_int($Val)) {
282 $Val = crc32($Val);
283 }
284
285 if ($Val < 0) {
286 $Val *= -1;
287 }
288
289 if ($Val = 0) {
290 return;
291 }
292
293 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
294 }
295
296
297 /**
298 * This function initializes the random number generator fairly well.
299 * It also only initializes it once, so you don't accidentally get
300 * the same 'random' numbers twice in one session.
301 */
302 function sq_mt_randomize() {
303 static $randomized;
304
305 if ($randomized) {
306 return;
307 }
308
309 /* Global. */
310 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
311 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
312 sq_mt_seed((int)((double) microtime() * 1000000));
313 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
314
315 /* getrusage */
316 if (function_exists('getrusage')) {
317 /* Avoid warnings with Win32 */
318 $dat = @getrusage();
319 if (isset($dat) && is_array($dat)) {
320 $Str = '';
321 foreach ($dat as $k => $v)
322 {
323 $Str .= $k . $v;
324 }
325 sq_mt_seed(md5($Str));
326 }
327 }
328
329 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
330 sq_mt_seed(md5($unique_id));
331 }
332
333 $randomized = 1;
334 }
335
336 function OneTimePadCreate ($length=100) {
337 sq_mt_randomize();
338
339 $pad = '';
340 for ($i = 0; $i < $length; $i++) {
341 $pad .= chr(mt_rand(0,255));
342 }
343
344 return base64_encode($pad);
345 }
346
347 /**
348 * Returns a string showing the size of the message/attachment.
349 */
350 function show_readable_size($bytes) {
351 $bytes /= 1024;
352 $type = 'k';
353
354 if ($bytes / 1024 > 1) {
355 $bytes /= 1024;
356 $type = 'M';
357 }
358
359 if ($bytes < 10) {
360 $bytes *= 10;
361 settype($bytes, 'integer');
362 $bytes /= 10;
363 } else {
364 settype($bytes, 'integer');
365 }
366
367 return $bytes . '<small>&nbsp;' . $type . '</small>';
368 }
369
370 /**
371 * Generates a random string from the caracter set you pass in
372 *
373 * Flags:
374 * 1 = add lowercase a-z to $chars
375 * 2 = add uppercase A-Z to $chars
376 * 4 = add numbers 0-9 to $chars
377 */
378
379 function GenerateRandomString($size, $chars, $flags = 0) {
380 if ($flags & 0x1) {
381 $chars .= 'abcdefghijklmnopqrstuvwxyz';
382 }
383 if ($flags & 0x2) {
384 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
385 }
386 if ($flags & 0x4) {
387 $chars .= '0123456789';
388 }
389
390 if (($size < 1) || (strlen($chars) < 1)) {
391 return '';
392 }
393
394 sq_mt_randomize(); /* Initialize the random number generator */
395
396 $String = '';
397 $j = strlen( $chars ) - 1;
398 while (strlen($String) < $size) {
399 $String .= $chars{mt_rand(0, $j)};
400 }
401
402 return $String;
403 }
404
405 function quoteimap($str) {
406 return ereg_replace('(["\\])', '\\\\1', $str);
407 }
408
409 /**
410 * Trims every element in the array
411 */
412 function TrimArray(&$array) {
413 foreach ($array as $k => $v) {
414 global $$k;
415 if (is_array($$k)) {
416 foreach ($$k as $k2 => $v2) {
417 $$k[$k2] = substr($v2, 1);
418 }
419 } else {
420 $$k = substr($v, 1);
421 }
422
423 /* Re-assign back to array. */
424 $array[$k] = $$k;
425 }
426 }
427
428 // Returns a link to the compose-page, taking in
429 // consideration the compose_in_new and javascript
430 // settings.
431 //
432 function makeComposeLink($url, $text = null)
433 {
434 global $compose_new_win,$javascript_on;
435
436 if(!$text) {
437 $text = _("Compose");
438 }
439
440
441 // if not using "compose in new window", make
442 // regular link and be done with it
443 //
444 if($compose_new_win != '1') {
445 return makeInternalLink($url, $text, 'right');
446 }
447
448
449 //
450 // build the compose in new window link...
451 //
452
453
454 // if javascript is on, use onClick event to handle it
455 //
456 if($javascript_on) {
457 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
458 return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
459 }
460
461
462 // otherwise, just open new window using regular HTML
463 //
464 return makeInternalLink($url, $text, '_blank');
465
466 }
467
468 /**
469 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
470 * Debugging function - does the same as print_r, but makes sure special
471 * characters are converted to htmlentities first. This will allow
472 * values like <some@email.address> to be displayed.
473 * The output is wrapped in <pre> and </pre> tags.
474 */
475 function sm_print_r() {
476 ob_start(); // Buffer output
477 foreach(func_get_args() as $var) {
478 print_r($var);
479 echo "\n";
480 }
481 $buffer = ob_get_contents(); // Grab the print_r output
482 ob_end_clean(); // Silently discard the output & stop buffering
483 print '<pre>';
484 print htmlentities($buffer);
485 print '</pre>';
486 }
487
488 $PHP_SELF = php_self();
489 ?>