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