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