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