Fix: php_self() not working right for Windoze servers that don't have REQUEST_URI
[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
159 // need to add query string to end of PHP_SELF to match REQUEST_URI
160 //
161 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
162 $php_self .= '?' . $query_string;
163 }
164
165 return $php_self;
166 }
167
168 return '';
169 }
170
171
172 /**
173 * This determines the location to forward to relative to your server.
174 * If this doesnt work correctly for you (although it should), you can
175 * remove all this code except the last two lines, and change the header()
176 * function to look something like this, customized to the location of
177 * SquirrelMail on your server:
178 *
179 * http://www.myhost.com/squirrelmail/src/login.php
180 */
181 function get_location () {
182
183 global $imap_server_type;
184
185 /* Get the path, handle virtual directories */
186 if(strpos(php_self(), '?')) {
187 $path = substr(php_self(), 0, strpos(php_self(), '?'));
188 } else {
189 $path = php_self();
190 }
191 $path = substr($path, 0, strrpos($path, '/'));
192 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
193 return $full_url . $path;
194 }
195
196 /* Check if this is a HTTPS or regular HTTP request. */
197 $proto = 'http://';
198
199 /*
200 * If you have 'SSLOptions +StdEnvVars' in your apache config
201 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
202 * OR if you are on port 443
203 */
204 $getEnvVar = getenv('HTTPS');
205 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
206 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
207 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
208 $proto = 'https://';
209 }
210
211 /* Get the hostname from the Host header or server config. */
212 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
213 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
214 $host = '';
215 }
216 }
217
218 $port = '';
219 if (! strstr($host, ':')) {
220 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
221 if (($server_port != 80 && $proto == 'http://') ||
222 ($server_port != 443 && $proto == 'https://')) {
223 $port = sprintf(':%d', $server_port);
224 }
225 }
226 }
227
228 /* this is a workaround for the weird macosx caching that
229 causes Apache to return 16080 as the port number, which causes
230 SM to bail */
231
232 if ($imap_server_type == 'macosx' && $port == ':16080') {
233 $port = '';
234 }
235
236 /* Fallback is to omit the server name and use a relative */
237 /* URI, although this is not RFC 2616 compliant. */
238 $full_url = ($host ? $proto . $host . $port : '');
239 sqsession_register($full_url, 'sq_base_url');
240 return $full_url . $path;
241 }
242
243
244 /**
245 * These functions are used to encrypt the passowrd before it is
246 * stored in a cookie.
247 */
248 function OneTimePadEncrypt ($string, $epad) {
249 $pad = base64_decode($epad);
250 $encrypted = '';
251 for ($i = 0; $i < strlen ($string); $i++) {
252 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
253 }
254
255 return base64_encode($encrypted);
256 }
257
258 function OneTimePadDecrypt ($string, $epad) {
259 $pad = base64_decode($epad);
260 $encrypted = base64_decode ($string);
261 $decrypted = '';
262 for ($i = 0; $i < strlen ($encrypted); $i++) {
263 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
264 }
265
266 return $decrypted;
267 }
268
269
270 /**
271 * Randomize the mt_rand() function. Toss this in strings or integers
272 * and it will seed the generator appropriately. With strings, it is
273 * better to get them long. Use md5() to lengthen smaller strings.
274 */
275 function sq_mt_seed($Val) {
276 /* if mt_getrandmax() does not return a 2^n - 1 number,
277 this might not work well. This uses $Max as a bitmask. */
278 $Max = mt_getrandmax();
279
280 if (! is_int($Val)) {
281 $Val = crc32($Val);
282 }
283
284 if ($Val < 0) {
285 $Val *= -1;
286 }
287
288 if ($Val = 0) {
289 return;
290 }
291
292 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
293 }
294
295
296 /**
297 * This function initializes the random number generator fairly well.
298 * It also only initializes it once, so you don't accidentally get
299 * the same 'random' numbers twice in one session.
300 */
301 function sq_mt_randomize() {
302 static $randomized;
303
304 if ($randomized) {
305 return;
306 }
307
308 /* Global. */
309 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
310 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
311 sq_mt_seed((int)((double) microtime() * 1000000));
312 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
313
314 /* getrusage */
315 if (function_exists('getrusage')) {
316 /* Avoid warnings with Win32 */
317 $dat = @getrusage();
318 if (isset($dat) && is_array($dat)) {
319 $Str = '';
320 foreach ($dat as $k => $v)
321 {
322 $Str .= $k . $v;
323 }
324 sq_mt_seed(md5($Str));
325 }
326 }
327
328 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
329 sq_mt_seed(md5($unique_id));
330 }
331
332 $randomized = 1;
333 }
334
335 function OneTimePadCreate ($length=100) {
336 sq_mt_randomize();
337
338 $pad = '';
339 for ($i = 0; $i < $length; $i++) {
340 $pad .= chr(mt_rand(0,255));
341 }
342
343 return base64_encode($pad);
344 }
345
346 /**
347 * Returns a string showing the size of the message/attachment.
348 */
349 function show_readable_size($bytes) {
350 $bytes /= 1024;
351 $type = 'k';
352
353 if ($bytes / 1024 > 1) {
354 $bytes /= 1024;
355 $type = 'M';
356 }
357
358 if ($bytes < 10) {
359 $bytes *= 10;
360 settype($bytes, 'integer');
361 $bytes /= 10;
362 } else {
363 settype($bytes, 'integer');
364 }
365
366 return $bytes . '<small>&nbsp;' . $type . '</small>';
367 }
368
369 /**
370 * Generates a random string from the caracter set you pass in
371 *
372 * Flags:
373 * 1 = add lowercase a-z to $chars
374 * 2 = add uppercase A-Z to $chars
375 * 4 = add numbers 0-9 to $chars
376 */
377
378 function GenerateRandomString($size, $chars, $flags = 0) {
379 if ($flags & 0x1) {
380 $chars .= 'abcdefghijklmnopqrstuvwxyz';
381 }
382 if ($flags & 0x2) {
383 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
384 }
385 if ($flags & 0x4) {
386 $chars .= '0123456789';
387 }
388
389 if (($size < 1) || (strlen($chars) < 1)) {
390 return '';
391 }
392
393 sq_mt_randomize(); /* Initialize the random number generator */
394
395 $String = '';
396 $j = strlen( $chars ) - 1;
397 while (strlen($String) < $size) {
398 $String .= $chars{mt_rand(0, $j)};
399 }
400
401 return $String;
402 }
403
404 function quoteimap($str) {
405 return ereg_replace('(["\\])', '\\\\1', $str);
406 }
407
408 /**
409 * Trims every element in the array
410 */
411 function TrimArray(&$array) {
412 foreach ($array as $k => $v) {
413 global $$k;
414 if (is_array($$k)) {
415 foreach ($$k as $k2 => $v2) {
416 $$k[$k2] = substr($v2, 1);
417 }
418 } else {
419 $$k = substr($v, 1);
420 }
421
422 /* Re-assign back to array. */
423 $array[$k] = $$k;
424 }
425 }
426
427 // Returns a link to the compose-page, taking in
428 // consideration the compose_in_new and javascript
429 // settings.
430 //
431 function makeComposeLink($url, $text = null)
432 {
433 global $compose_new_win,$javascript_on;
434
435 if(!$text) {
436 $text = _("Compose");
437 }
438
439
440 // if not using "compose in new window", make
441 // regular link and be done with it
442 //
443 if($compose_new_win != '1') {
444 return makeInternalLink($url, $text, 'right');
445 }
446
447
448 //
449 // build the compose in new window link...
450 //
451
452
453 // if javascript is on, use onClick event to handle it
454 //
455 if($javascript_on) {
456 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
457 return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
458 }
459
460
461 // otherwise, just open new window using regular HTML
462 //
463 return makeInternalLink($url, $text, '_blank');
464
465 }
466
467 /**
468 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
469 * Debugging function - does the same as print_r, but makes sure special
470 * characters are converted to htmlentities first. This will allow
471 * values like <some@email.address> to be displayed.
472 * The output is wrapped in <pre> and </pre> tags.
473 */
474 function sm_print_r() {
475 ob_start(); // Buffer output
476 foreach(func_get_args() as $var) {
477 print_r($var);
478 echo "\n";
479 }
480 $buffer = ob_get_contents(); // Grab the print_r output
481 ob_end_clean(); // Silently discard the output & stop buffering
482 print '<pre>';
483 print htmlentities($buffer);
484 print '</pre>';
485 }
486
487 $PHP_SELF = php_self();
488 ?>