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