fix for replying to html mail.
[squirrelmail.git] / functions / strings.php
CommitLineData
59177427 1<?php
7350889b 2
f1ca21bd 3/**
35586184 4 * strings.php
5 *
82d304a0 6 * Copyright (c) 1999-2004 The SquirrelMail Project Team
35586184 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 *
31841a9e 12 * @version $Id$
d6c32258 13 * @package squirrelmail
35586184 14 */
9374671f 15
35586184 16/**
17 * SquirrelMail version number -- DO NOT CHANGE
18 */
19global $version;
509fc585 20$version = '1.5.1 [CVS]';
d068c0ec 21
f1ca21bd 22/**
97bdc607 23 * SquirrelMail internal version number -- DO NOT CHANGE
24 * $sm_internal_version = array (release, major, minor)
25 */
0567e4d5 26global $SQM_INTERNAL_VERSION;
a959e855 27$SQM_INTERNAL_VERSION = array(1,5,1);
87d8c725 28
87d8c725 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 */
34require_once(SM_PATH . 'functions/global.php');
97bdc607 35
66239b65 36/**
c9d61baf 37 * Appends citation markers to the string.
38 * Also appends a trailing space.
39 *
40 * @author Justus Pendleton
41 *
42 * @param string str The string to append to
43 * @param int citeLevel the number of markers to append
44 * @return null
45 */
46function sqMakeCite (&$str, $citeLevel) {
47 for ($i = 0; $i < $citeLevel; $i++) {
48 $str .= '>';
49 }
50 if ($citeLevel != 0) {
51 $str .= ' ';
52 }
53}
54
55/**
56 * Create a newline in the string, adding citation
57 * markers to the newline as necessary.
58 *
59 * @author Justus Pendleton
60 *
61 * @param string str the string to make a newline in
62 * @param int citeLevel the citation level the newline is at
63 * @param int column starting column of the newline
64 * @return null
65 */
66function sqMakeNewLine (&$str, $citeLevel, &$column) {
67 $str .= "\n";
68 $column = 0;
69 if ($citeLevel > 0) {
70 sqMakeCite ($str, $citeLevel);
71 $column = $citeLevel + 1;
72 } else {
73 $column = 0;
74 }
75}
76
77/**
5e7ae713 78 * Checks for spaces in strings - only used if PHP doesn't have native ctype support
79 *
80 * @author Tomas Kuliavas
326727cf 81 *
82 * You might be able to rewrite the function by adding short evaluation form.
5e7ae713 83 *
84 * possible problems:
85 * - iso-2022-xx charsets - hex 20 might be part of other symbol. I might
86 * be wrong. 0x20 is not used in iso-2022-jp. I haven't checked iso-2022-kr
87 * and iso-2022-cn mappings.
88 *
89 * - no-break space (&nbsp;) - it is 8bit symbol, that depends on charset.
90 * there are at least three different charset groups that have nbsp in
91 * different places.
92 *
93 * I don't see any charset/nbsp options in php ctype either.
94 *
95 * @param string $string tested string
326727cf 96 * @return bool true when only whitespace symbols are present in test string
5e7ae713 97 */
98function sm_ctype_space($string) {
326727cf 99 if ( preg_match('/^[\x09-\x0D]|^\x20/', $string) || $string=='') {
100 return true;
101 } else {
102 return false;
103 }
5e7ae713 104}
105
106/**
c9d61baf 107 * Wraps text at $wrap characters. While sqWordWrap takes
108 * a single line of text and wraps it, this function works
109 * on the entire corpus at once, this allows it to be a little
110 * bit smarter and when and how to wrap.
111 *
112 * @author Justus Pendleton
113 *
114 * @param string body the entire body of text
115 * @param int wrap the maximum line length
116 * @return string the wrapped text
117 */
118function &sqBodyWrap (&$body, $wrap) {
6eaf5320 119 //sm_print_r($body);
5e7ae713 120 //check for ctype support, and fake it if it doesn't exist
121 if (!function_exists('ctype_space')) {
122 function ctype_space ($string) {
123 return sm_ctype_space($string);
124 }
125 }
126
c9d61baf 127 // the newly wrapped text
128 $outString = '';
129 // current column since the last newline in the outstring
130 $outStringCol = 0;
131 $length = strlen($body);
132 // where we are in the original string
133 $pos = 0;
134 // the number of >>> citation markers we are currently at
135 $citeLevel = 0;
136
137 // the main loop, whenever we start a newline of input text
138 // we start from here
139 while ($pos < $length) {
140 // we're at the beginning of a line, get the new cite level
141 $newCiteLevel = 0;
142
143 while (($pos < $length) && ($body{$pos} == '>')) {
144 $newCiteLevel++;
145 $pos++;
146
147 // skip over any spaces interleaved among the cite markers
148 while (($pos < $length) && ($body{$pos} == ' ')) {
6eaf5320 149
c9d61baf 150 $pos++;
6eaf5320 151
c9d61baf 152 }
153 if ($pos >= $length) {
154 break;
155 }
156 }
157
158 // special case: if this is a blank line then maintain it
159 // (i.e. try to preserve original paragraph breaks)
160 // unless they occur at the very beginning of the text
6eaf5320 161 if (($body{$pos} == "\n" ) && (strlen($outString) != 0)) {
c9d61baf 162 $outStringLast = $outString{strlen($outString) - 1};
163 if ($outStringLast != "\n") {
164 $outString .= "\n";
165 }
166 sqMakeCite ($outString, $newCiteLevel);
167 $outString .= "\n";
168 $pos++;
169 $outStringCol = 0;
170 continue;
171 }
172
173 // if the cite level has changed, then start a new line
174 // with the new cite level.
175 if (($citeLevel != $newCiteLevel) && ($pos > ($newCiteLevel + 1)) && ($outStringCol != 0)) {
176 sqMakeNewLine ($outString, 0, $outStringCol);
177 }
178
179 $citeLevel = $newCiteLevel;
180
181 // prepend the quote level if necessary
182 if ($outStringCol == 0) {
183 sqMakeCite ($outString, $citeLevel);
184 // if we added a citation then move the column
185 // out by citelevel + 1 (the cite markers + the space)
186 $outStringCol = $citeLevel + ($citeLevel ? 1 : 0);
187 } else if ($outStringCol > $citeLevel) {
188 // not a cite and we're not at the beginning of a line
189 // in the output. add a space to separate the new text
190 // from previous text.
191 $outString .= ' ';
192 $outStringCol++;
193 }
194
195 // find the next newline -- we don't want to go further than that
196 $nextNewline = strpos ($body, "\n", $pos);
197 if ($nextNewline === FALSE) {
198 $nextNewline = $length;
199 }
200
201 // Don't wrap unquoted lines at all. For now the textarea
202 // will work fine for this. Maybe revisit this later though
203 // (for completeness more than anything else, I think)
204 if ($citeLevel == 0) {
205 $outString .= substr ($body, $pos, ($nextNewline - $pos));
206 $outStringCol = $nextNewline - $pos;
207 if ($nextNewline != $length) {
208 sqMakeNewLine ($outString, 0, $outStringCol);
209 }
210 $pos = $nextNewline + 1;
211 continue;
212 }
213
214 // inner loop, (obviously) handles wrapping up to
215 // the next newline
216 while ($pos < $nextNewline) {
217 // skip over initial spaces
218 while (($pos < $nextNewline) && (ctype_space ($body{$pos}))) {
219 $pos++;
220 }
221
222 // if this is a short line then just append it and continue outer loop
6eaf5320 223 if (($outStringCol + $nextNewline - $pos) <= ($wrap - $citeLevel - 1) ) {
c9d61baf 224 // if this is the final line in the input string then include
225 // any trailing newlines
6eaf5320 226 // echo substr($body,$pos,$wrap). "<br />";
c9d61baf 227 if (($nextNewline + 1 == $length) && ($body{$nextNewline} == "\n")) {
228 $nextNewline++;
229 }
230
6eaf5320 231 if (($nextNewline < $length && $body{$nextNewline} == "\n") &&
232 isset($lastRealChar)) {
233
234 // trim trailing spaces
235 $lastRealChar = $nextNewline;
236 while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space ($body{$lastRealChar}))) {
237 $lastRealChar--;
238 }
239
240 //check the first word:
241 $mypos = $nextNewline+1;
242 while (($mypos < $length) && ($body{$mypos} == '>')) {
243 $mypos++;
244
245 // skip over any spaces interleaved among the cite markers
246 while (($mypos < $length) && ($body{$mypos} == ' ')) {
247
248 $mypos++;
249
250 }
251 }
252 $firstword = substr($body,$mypos,strpos($body,' ',$mypos) - $mypos);
253 if ($firstword && ($firstword{0} == '-' ||
254 $firstword{0} == '+' ||
255 $firstword{0} == '*' ||
256 strpos($firstword,':'))) {
257 $outString .= substr($body,$pos,($lastRealChar - $pos+1));
258 $outStringCol += ($lastRealChar - $pos);
259 sqMakeNewLine($outString,$citeLevel,$outStringCol);
260 $nextNewline++;
261 $pos = $nextNewline;
262 $outStringCol--;
263 continue; //break 2;
264 }
265 }
266
267
c9d61baf 268 // trim trailing spaces
269 $lastRealChar = $nextNewline;
6eaf5320 270 while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space ($body{$lastRealChar}))) {
c9d61baf 271 $lastRealChar--;
272 }
c9d61baf 273 $outString .= substr ($body, $pos, ($lastRealChar - $pos + 1));
274 $outStringCol += ($lastRealChar - $pos);
275 $pos = $nextNewline + 1;
276 continue;
277 }
c9d61baf 278 $eol = $pos + $wrap - $citeLevel - $outStringCol;
279 // eol is the tentative end of line.
280 // look backwards for there for a whitespace to break at.
281 // if it's already less than our current position then
282 // our current line is already too long, break immediately
283 // and restart outer loop
284 if ($eol <= $pos) {
6eaf5320 285 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
c9d61baf 286 continue;
287 }
288
289 // start looking backwards for whitespace to break at.
290 $breakPoint = $eol;
291 while (($breakPoint > $pos) && (! ctype_space ($body{$breakPoint}))) {
292 $breakPoint--;
293 }
294
295 // if we didn't find a breakpoint by looking backward then we
296 // need to figure out what to do about that
297 if ($breakPoint == $pos) {
298 // if we are not at the beginning then end this line
299 // and start a new loop
300 if ($outStringCol > ($citeLevel + 1)) {
301 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
302 continue;
303 } else {
304 // just hard break here. most likely we are breaking
305 // a really long URL. could also try searching
306 // forward for a break point, which is what Mozilla
307 // does. don't bother for now.
308 $breakPoint = $eol;
309 }
310 }
311
312 // special case: maybe we should have wrapped last
313 // time. if the first breakpoint here makes the
314 // current line too long and there is already text on
315 // the current line, break and loop again if at
316 // beginning of current line, don't force break
317 $SLOP = 6;
318 if ((($outStringCol + ($breakPoint - $pos)) > ($wrap + $SLOP)) && ($outStringCol > ($citeLevel + 1))) {
319 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
320 continue;
321 }
322
323 // skip newlines or whitespace at the beginning of the string
324 $substring = substr ($body, $pos, ($breakPoint - $pos));
325 $substring = rtrim ($substring); // do rtrim and ctype_space have the same ideas about whitespace?
326 $outString .= $substring;
327 $outStringCol += strlen ($substring);
328 // advance past the whitespace which caused the wrap
329 $pos = $breakPoint;
330 while (($pos < $length) && (ctype_space ($body{$pos}))) {
331 $pos++;
332 }
333 if ($pos < $length) {
334 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
335 }
336 }
337 }
338
339 return $outString;
340}
341
342/**
5cc0b70e 343 * Wraps text at $wrap characters
344 *
345 * Has a problem with special HTML characters, so call this before
346 * you do character translation.
347 *
348 * Specifically, &#039 comes up as 5 characters instead of 1.
349 * This should not add newlines to the end of lines.
8b096f0a 350 *
351 * @param string line the line of text to wrap, by ref
352 * @param int wrap the maximum line lenth
353 * @return void
5cc0b70e 354 */
355function sqWordWrap(&$line, $wrap) {
e842b215 356 global $languages, $squirrelmail_language;
357
358 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
359 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
360 if (mb_detect_encoding($line) != 'ASCII') {
361 $line = $languages[$squirrelmail_language]['XTRA_CODE']('wordwrap', $line, $wrap);
362 return;
363 }
364 }
365
5cc0b70e 366 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
367 $beginning_spaces = $regs[1];
368 if (isset($regs[2])) {
369 $words = explode(' ', $regs[2]);
370 } else {
371 $words = '';
372 }
f1ca21bd 373
5cc0b70e 374 $i = 0;
375 $line = $beginning_spaces;
f1ca21bd 376
5cc0b70e 377 while ($i < count($words)) {
378 /* Force one word to be on a line (minimum) */
379 $line .= $words[$i];
380 $line_len = strlen($beginning_spaces) + strlen($words[$i]) + 2;
381 if (isset($words[$i + 1]))
382 $line_len += strlen($words[$i + 1]);
383 $i ++;
f1ca21bd 384
5cc0b70e 385 /* Add more words (as long as they fit) */
386 while ($line_len < $wrap && $i < count($words)) {
387 $line .= ' ' . $words[$i];
388 $i++;
389 if (isset($words[$i]))
390 $line_len += strlen($words[$i]) + 1;
391 else
392 $line_len += 1;
393 }
f1ca21bd 394
5cc0b70e 395 /* Skip spaces if they are the first thing on a continued line */
396 while (!isset($words[$i]) && $i < count($words)) {
397 $i ++;
398 }
f1ca21bd 399
5cc0b70e 400 /* Go to the next line if we have more to process */
401 if ($i < count($words)) {
e0858036 402 $line .= "\n";
5cc0b70e 403 }
404 }
405}
406
407/**
341abbd6 408 * Does the opposite of sqWordWrap()
8b096f0a 409 * @param string body the text to un-wordwrap
410 * @return void
341abbd6 411 */
412function sqUnWordWrap(&$body) {
e842b215 413 global $squirrelmail_language;
f1ca21bd 414
e842b215 415 if ($squirrelmail_language == 'ja_JP') {
416 return;
417 }
418
341abbd6 419 $lines = explode("\n", $body);
420 $body = '';
421 $PreviousSpaces = '';
422 $cnt = count($lines);
423 for ($i = 0; $i < $cnt; $i ++) {
424 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
425 $CurrentSpaces = $regs[1];
426 if (isset($regs[2])) {
427 $CurrentRest = $regs[2];
1e4a4feb 428 } else {
f1ca21bd 429 $CurrentRest = '';
430 }
431
341abbd6 432 if ($i == 0) {
433 $PreviousSpaces = $CurrentSpaces;
434 $body = $lines[$i];
435 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
436 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
437 && strlen($CurrentRest)) { /* and there's a line to continue with */
438 $body .= ' ' . $CurrentRest;
439 } else {
440 $body .= "\n" . $lines[$i];
441 $PreviousSpaces = $CurrentSpaces;
442 }
443 }
444 $body .= "\n";
445}
446
447/**
66239b65 448 * If $haystack is a full mailbox name and $needle is the mailbox
449 * separator character, returns the last part of the mailbox name.
8b096f0a 450 *
451 * @param string haystack full mailbox name to search
452 * @param string needle the mailbox separator character
453 * @return string the last part of the mailbox name
66239b65 454 */
455function readShortMailboxName($haystack, $needle) {
97b1248c 456
66239b65 457 if ($needle == '') {
97b1248c 458 $elem = $haystack;
459 } else {
f1ca21bd 460 $parts = explode($needle, $haystack);
461 $elem = array_pop($parts);
462 while ($elem == '' && count($parts)) {
463 $elem = array_pop($parts);
464 }
66239b65 465 }
97b1248c 466 return( $elem );
66239b65 467}
3302d0d4 468
8b096f0a 469/**
4445e6b3 470 * php_self
471 *
8b096f0a 472 * Creates an URL for the page calling this function, using either the PHP global
473 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
474 *
475 * @return string the complete url for this page
476 */
43fdb2a4 477function php_self () {
961ca3d8 478 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
479 return $req_uri;
43fdb2a4 480 }
f1ca21bd 481
961ca3d8 482 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
f72f61d8 483
484 // need to add query string to end of PHP_SELF to match REQUEST_URI
485 //
486 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
487 $php_self .= '?' . $query_string;
488 }
489
961ca3d8 490 return $php_self;
f1ca21bd 491 }
492
961ca3d8 493 return '';
43fdb2a4 494}
495
496
66239b65 497/**
4445e6b3 498 * get_location
499 *
8b096f0a 500 * Determines the location to forward to, relative to your server.
501 * This is used in HTTP Location: redirects.
66239b65 502 * If this doesnt work correctly for you (although it should), you can
8b096f0a 503 * remove all this code except the last two lines, and have it return
504 * the right URL for your site, something like:
505 *
506 * http://www.example.com/squirrelmail/
66239b65 507 *
8b096f0a 508 * @return string the base url for this SquirrelMail installation
66239b65 509 */
510function get_location () {
f1ca21bd 511
961ca3d8 512 global $imap_server_type;
238703be 513
4deb32f1 514 /* Get the path, handle virtual directories */
f1ca21bd 515 if(strpos(php_self(), '?')) {
516 $path = substr(php_self(), 0, strpos(php_self(), '?'));
517 } else {
518 $path = php_self();
519 }
520 $path = substr($path, 0, strrpos($path, '/'));
238703be 521 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
522 return $full_url . $path;
523 }
524
66239b65 525 /* Check if this is a HTTPS or regular HTTP request. */
526 $proto = 'http://';
f1ca21bd 527
66239b65 528 /*
529 * If you have 'SSLOptions +StdEnvVars' in your apache config
44827b4d 530 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
66239b65 531 * OR if you are on port 443
532 */
533 $getEnvVar = getenv('HTTPS');
534 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
961ca3d8 535 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
536 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
8a549df2 537 $proto = 'https://';
66239b65 538 }
f1ca21bd 539
4deb32f1 540 /* Get the hostname from the Host header or server config. */
961ca3d8 541 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
542 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
543 $host = '';
544 }
66239b65 545 }
f1ca21bd 546
66239b65 547 $port = '';
548 if (! strstr($host, ':')) {
961ca3d8 549 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
f1ca21bd 550 if (($server_port != 80 && $proto == 'http://') ||
961ca3d8 551 ($server_port != 443 && $proto == 'https://')) {
552 $port = sprintf(':%d', $server_port);
66239b65 553 }
554 }
555 }
f1ca21bd 556
8de7f698 557 /* this is a workaround for the weird macosx caching that
558 causes Apache to return 16080 as the port number, which causes
559 SM to bail */
f1ca21bd 560
8de7f698 561 if ($imap_server_type == 'macosx' && $port == ':16080') {
562 $port = '';
563 }
f1ca21bd 564
238703be 565 /* Fallback is to omit the server name and use a relative */
566 /* URI, although this is not RFC 2616 compliant. */
567 $full_url = ($host ? $proto . $host . $port : '');
568 sqsession_register($full_url, 'sq_base_url');
569 return $full_url . $path;
66239b65 570}
dcaf2a49 571
9374671f 572
66239b65 573/**
4445e6b3 574 * Encrypts password
575 *
8b096f0a 576 * These functions are used to encrypt the password before it is
577 * stored in a cookie. The encryption key is generated by
578 * OneTimePadCreate();
579 *
580 * @param string string the (password)string to encrypt
581 * @param string epad the encryption key
582 * @return string the base64-encoded encrypted password
66239b65 583 */
584function OneTimePadEncrypt ($string, $epad) {
585 $pad = base64_decode($epad);
586 $encrypted = '';
587 for ($i = 0; $i < strlen ($string); $i++) {
588 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
589 }
f1ca21bd 590
66239b65 591 return base64_encode($encrypted);
592}
593
8b096f0a 594/**
4445e6b3 595 * Decrypts a password from the cookie
596 *
597 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
8b096f0a 598 * This uses the encryption key that is stored in the session.
599 *
600 * @param string string the string to decrypt
601 * @param string epad the encryption key from the session
602 * @return string the decrypted password
603 */
66239b65 604function OneTimePadDecrypt ($string, $epad) {
605 $pad = base64_decode($epad);
606 $encrypted = base64_decode ($string);
607 $decrypted = '';
608 for ($i = 0; $i < strlen ($encrypted); $i++) {
609 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
610 }
f1ca21bd 611
66239b65 612 return $decrypted;
613}
9374671f 614
9374671f 615
66239b65 616/**
4445e6b3 617 * Randomizes the mt_rand() function.
618 *
c9d61baf 619 * Toss this in strings or integers and it will seed the generator
620 * appropriately. With strings, it is better to get them long.
4445e6b3 621 * Use md5() to lengthen smaller strings.
8b096f0a 622 *
623 * @param mixed val a value to seed the random number generator
624 * @return void
66239b65 625 */
626function sq_mt_seed($Val) {
4deb32f1 627 /* if mt_getrandmax() does not return a 2^n - 1 number,
628 this might not work well. This uses $Max as a bitmask. */
66239b65 629 $Max = mt_getrandmax();
f1ca21bd 630
66239b65 631 if (! is_int($Val)) {
66239b65 632 $Val = crc32($Val);
66239b65 633 }
f1ca21bd 634
66239b65 635 if ($Val < 0) {
636 $Val *= -1;
637 }
f1ca21bd 638
66239b65 639 if ($Val = 0) {
640 return;
641 }
f1ca21bd 642
66239b65 643 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
644}
9374671f 645
9374671f 646
66239b65 647/**
4445e6b3 648 * Init random number generator
649 *
66239b65 650 * This function initializes the random number generator fairly well.
651 * It also only initializes it once, so you don't accidentally get
652 * the same 'random' numbers twice in one session.
8b096f0a 653 *
654 * @return void
66239b65 655 */
656function sq_mt_randomize() {
66239b65 657 static $randomized;
f1ca21bd 658
66239b65 659 if ($randomized) {
660 return;
661 }
f1ca21bd 662
66239b65 663 /* Global. */
961ca3d8 664 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
665 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
66239b65 666 sq_mt_seed((int)((double) microtime() * 1000000));
961ca3d8 667 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
f1ca21bd 668
66239b65 669 /* getrusage */
670 if (function_exists('getrusage')) {
4deb32f1 671 /* Avoid warnings with Win32 */
66239b65 672 $dat = @getrusage();
673 if (isset($dat) && is_array($dat)) {
821a8e9c 674 $Str = '';
675 foreach ($dat as $k => $v)
66239b65 676 {
677 $Str .= $k . $v;
678 }
821a8e9c 679 sq_mt_seed(md5($Str));
66239b65 680 }
681 }
f1ca21bd 682
961ca3d8 683 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
684 sq_mt_seed(md5($unique_id));
0b97a708 685 }
f1ca21bd 686
66239b65 687 $randomized = 1;
688}
689
8b096f0a 690/**
4445e6b3 691 * Creates encryption key
692 *
8b096f0a 693 * Creates an encryption key for encrypting the password stored in the cookie.
694 * The encryption key itself is stored in the session.
695 *
696 * @param int length optional, length of the string to generate
697 * @return string the encryption key
698 */
66239b65 699function OneTimePadCreate ($length=100) {
700 sq_mt_randomize();
f1ca21bd 701
66239b65 702 $pad = '';
703 for ($i = 0; $i < $length; $i++) {
704 $pad .= chr(mt_rand(0,255));
705 }
f1ca21bd 706
66239b65 707 return base64_encode($pad);
708}
9374671f 709
66239b65 710/**
8b096f0a 711 * Returns a string showing the size of the message/attachment.
712 *
713 * @param int bytes the filesize in bytes
714 * @return string the filesize in human readable format
66239b65 715 */
716function show_readable_size($bytes) {
717 $bytes /= 1024;
718 $type = 'k';
f1ca21bd 719
66239b65 720 if ($bytes / 1024 > 1) {
721 $bytes /= 1024;
e5f1e71c 722 $type = 'M';
66239b65 723 }
f1ca21bd 724
66239b65 725 if ($bytes < 10) {
726 $bytes *= 10;
727 settype($bytes, 'integer');
728 $bytes /= 10;
729 } else {
730 settype($bytes, 'integer');
731 }
f1ca21bd 732
66239b65 733 return $bytes . '<small>&nbsp;' . $type . '</small>';
734}
9374671f 735
66239b65 736/**
737 * Generates a random string from the caracter set you pass in
738 *
8b096f0a 739 * @param int size the size of the string to generate
740 * @param string chars a string containing the characters to use
741 * @param int flags a flag to add a specific set to the characters to use:
742 * Flags:
743 * 1 = add lowercase a-z to $chars
744 * 2 = add uppercase A-Z to $chars
745 * 4 = add numbers 0-9 to $chars
746 * @return string the random string
66239b65 747 */
66239b65 748function GenerateRandomString($size, $chars, $flags = 0) {
749 if ($flags & 0x1) {
750 $chars .= 'abcdefghijklmnopqrstuvwxyz';
751 }
752 if ($flags & 0x2) {
753 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
754 }
755 if ($flags & 0x4) {
756 $chars .= '0123456789';
757 }
f1ca21bd 758
66239b65 759 if (($size < 1) || (strlen($chars) < 1)) {
760 return '';
761 }
ff4f08ff 762
4deb32f1 763 sq_mt_randomize(); /* Initialize the random number generator */
ff4f08ff 764
4deb32f1 765 $String = '';
ff4f08ff 766 $j = strlen( $chars ) - 1;
66239b65 767 while (strlen($String) < $size) {
ff4f08ff 768 $String .= $chars{mt_rand(0, $j)};
66239b65 769 }
ff4f08ff 770
66239b65 771 return $String;
772}
9374671f 773
8b096f0a 774/**
775 * Escapes special characters for use in IMAP commands.
4445e6b3 776 *
8b096f0a 777 * @param string the string to escape
778 * @return string the escaped string
779 */
fbb76d0e 780function quoteimap($str) {
ab1df059 781 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
66239b65 782}
1899535f 783
66239b65 784/**
4445e6b3 785 * Trims array
786 *
8b096f0a 787 * Trims every element in the array, ie. remove the first char of each element
788 * @param array array the array to trim
66239b65 789 */
790function TrimArray(&$array) {
791 foreach ($array as $k => $v) {
792 global $$k;
793 if (is_array($$k)) {
794 foreach ($$k as $k2 => $v2) {
795 $$k[$k2] = substr($v2, 1);
23d6bd09 796 }
66239b65 797 } else {
798 $$k = substr($v, 1);
23d6bd09 799 }
f1ca21bd 800
4deb32f1 801 /* Re-assign back to array. */
66239b65 802 $array[$k] = $$k;
803 }
f1ca21bd 804}
23d6bd09 805
8b096f0a 806/**
4445e6b3 807 * Create compose link
808 *
8b096f0a 809 * Returns a link to the compose-page, taking in consideration
810 * the compose_in_new and javascript settings.
811 * @param string url the URL to the compose page
812 * @param string text the link text, default "Compose"
813 * @return string a link to the compose page
814 */
21a957a9 815function makeComposeLink($url, $text = null, $target='')
d62c4938 816{
817 global $compose_new_win,$javascript_on;
818
819 if(!$text) {
820 $text = _("Compose");
821 }
822
f72f61d8 823
c9d61baf 824 // if not using "compose in new window", make
f72f61d8 825 // regular link and be done with it
d62c4938 826 if($compose_new_win != '1') {
21a957a9 827 return makeInternalLink($url, $text, $target);
d62c4938 828 }
829
f72f61d8 830
c9d61baf 831 // build the compose in new window link...
f72f61d8 832
833
834 // if javascript is on, use onClick event to handle it
d62c4938 835 if($javascript_on) {
836 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
837 return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
838 }
839
f72f61d8 840
841 // otherwise, just open new window using regular HTML
d62c4938 842 return makeInternalLink($url, $text, '_blank');
f72f61d8 843
d62c4938 844}
845
f1ca21bd 846/**
4445e6b3 847 * Print variable
848 *
8b096f0a 849 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
4445e6b3 850 *
8b096f0a 851 * Debugging function - does the same as print_r, but makes sure special
852 * characters are converted to htmlentities first. This will allow
853 * values like <some@email.address> to be displayed.
4445e6b3 854 * The output is wrapped in <<pre>> and <</pre>> tags.
8b096f0a 855 *
856 * @return void
857 */
7fe09a30 858function sm_print_r() {
50cc40fe 859 ob_start(); // Buffer output
7fe09a30 860 foreach(func_get_args() as $var) {
861 print_r($var);
862 echo "\n";
863 }
50cc40fe 864 $buffer = ob_get_contents(); // Grab the print_r output
865 ob_end_clean(); // Silently discard the output & stop buffering
f1ca21bd 866 print '<pre>';
50cc40fe 867 print htmlentities($buffer);
f1ca21bd 868 print '</pre>';
50cc40fe 869}
870
3ecad5e6 871/**
872 * version of fwrite which checks for failure
873 */
874function sq_fwrite($fp, $string) {
c9d61baf 875 // write to file
876 $count = @fwrite($fp,$string);
877 // the number of bytes written should be the length of the string
878 if($count != strlen($string)) {
879 return FALSE;
880 }
881
882 return $count;
3ecad5e6 883}
884
36e1180b 885/**
886 * sq_get_html_translation_table
887 *
888 * Returns the translation table used by sq_htmlentities()
889 *
890 * @param integer $table html translation table. Possible values (without quotes):
deb22cec 891 * <ul>
892 * <li>HTML_ENTITIES - full html entities table defined by charset</li>
893 * <li>HTML_SPECIALCHARS - html special characters table</li>
894 * </ul>
36e1180b 895 * @param integer $quote_style quote encoding style. Possible values (without quotes):
c9d61baf 896 * <ul>
deb22cec 897 * <li>ENT_COMPAT - (default) encode double quotes</li>
898 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
899 * <li>ENT_QUOTES - encode double and single quotes</li>
c9d61baf 900 * </ul>
36e1180b 901 * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
902 * @return array html translation array
903 */
904function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
905 global $default_charset;
906
907 if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
908
909 // Start array with ampersand
910 $sq_html_ent_table = array( "&" => '&amp;' );
911
912 // < and >
913 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 914 array("<" => '&lt;',
915 ">" => '&gt;')
916 );
36e1180b 917 // double quotes
918 if ($quote_style == ENT_COMPAT)
919 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 920 array("\"" => '&quot;')
921 );
36e1180b 922
923 // double and single quotes
924 if ($quote_style == ENT_QUOTES)
925 $sq_html_ent_table = array_merge($sq_html_ent_table,
c9d61baf 926 array("\"" => '&quot;',
927 "'" => '&#39;')
928 );
36e1180b 929
930 if ($charset=='auto') $charset=$default_charset;
931
932 // add entities that depend on charset
933 switch($charset){
934 case 'iso-8859-1':
935 include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
936 break;
937 case 'utf-8':
938 include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
939 break;
940 case 'us-ascii':
941 default:
942 break;
943 }
944 // return table
945 return $sq_html_ent_table;
946}
947
948/**
949 * sq_htmlentities
950 *
951 * Convert all applicable characters to HTML entities.
952 * Minimal php requirement - v.4.0.5
953 *
954 * @param string $string string that has to be sanitized
955 * @param integer $quote_style quote encoding style. Possible values (without quotes):
c9d61baf 956 * <ul>
deb22cec 957 * <li>ENT_COMPAT - (default) encode double quotes</li>
958 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
959 * <li>ENT_QUOTES - encode double and single quotes</li>
c9d61baf 960 * </ul>
36e1180b 961 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
962 * @return string sanitized string
963 */
964function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
965 // get translation table
966 $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
967 // convert characters
968 return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
969}
970
43fdb2a4 971$PHP_SELF = php_self();
4445e6b3 972?>