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