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