- add sqBodyWrap utility functions to rewrap entire body rather than one line at...
[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 * 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 */
89 function &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 /**
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.
275 *
276 * @param string line the line of text to wrap, by ref
277 * @param int wrap the maximum line lenth
278 * @return void
279 */
280 function sqWordWrap(&$line, $wrap) {
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
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 }
298
299 $i = 0;
300 $line = $beginning_spaces;
301
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 ++;
309
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 }
319
320 /* Skip spaces if they are the first thing on a continued line */
321 while (!isset($words[$i]) && $i < count($words)) {
322 $i ++;
323 }
324
325 /* Go to the next line if we have more to process */
326 if ($i < count($words)) {
327 $line .= "\n";
328 }
329 }
330 }
331
332 /**
333 * Does the opposite of sqWordWrap()
334 * @param string body the text to un-wordwrap
335 * @return void
336 */
337 function sqUnWordWrap(&$body) {
338 global $squirrelmail_language;
339
340 if ($squirrelmail_language == 'ja_JP') {
341 return;
342 }
343
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];
353 } else {
354 $CurrentRest = '';
355 }
356
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 /**
373 * If $haystack is a full mailbox name and $needle is the mailbox
374 * separator character, returns the last part of the mailbox name.
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
379 */
380 function readShortMailboxName($haystack, $needle) {
381
382 if ($needle == '') {
383 $elem = $haystack;
384 } else {
385 $parts = explode($needle, $haystack);
386 $elem = array_pop($parts);
387 while ($elem == '' && count($parts)) {
388 $elem = array_pop($parts);
389 }
390 }
391 return( $elem );
392 }
393
394 /**
395 * php_self
396 *
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 */
402 function php_self () {
403 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
404 return $req_uri;
405 }
406
407 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
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
415 return $php_self;
416 }
417
418 return '';
419 }
420
421
422 /**
423 * get_location
424 *
425 * Determines the location to forward to, relative to your server.
426 * This is used in HTTP Location: redirects.
427 * If this doesnt work correctly for you (although it should), you can
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/
432 *
433 * @return string the base url for this SquirrelMail installation
434 */
435 function get_location () {
436
437 global $imap_server_type;
438
439 /* Get the path, handle virtual directories */
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, '/'));
446 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
447 return $full_url . $path;
448 }
449
450 /* Check if this is a HTTPS or regular HTTP request. */
451 $proto = 'http://';
452
453 /*
454 * If you have 'SSLOptions +StdEnvVars' in your apache config
455 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
456 * OR if you are on port 443
457 */
458 $getEnvVar = getenv('HTTPS');
459 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
460 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
461 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
462 $proto = 'https://';
463 }
464
465 /* Get the hostname from the Host header or server config. */
466 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
467 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
468 $host = '';
469 }
470 }
471
472 $port = '';
473 if (! strstr($host, ':')) {
474 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
475 if (($server_port != 80 && $proto == 'http://') ||
476 ($server_port != 443 && $proto == 'https://')) {
477 $port = sprintf(':%d', $server_port);
478 }
479 }
480 }
481
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 */
485
486 if ($imap_server_type == 'macosx' && $port == ':16080') {
487 $port = '';
488 }
489
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;
495 }
496
497
498 /**
499 * Encrypts password
500 *
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
508 */
509 function 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 }
515
516 return base64_encode($encrypted);
517 }
518
519 /**
520 * Decrypts a password from the cookie
521 *
522 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
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 */
529 function 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 }
536
537 return $decrypted;
538 }
539
540
541 /**
542 * Randomizes the mt_rand() function.
543 *
544 * Toss this in strings or integers and it will seed the generator
545 * appropriately. With strings, it is better to get them long.
546 * Use md5() to lengthen smaller strings.
547 *
548 * @param mixed val a value to seed the random number generator
549 * @return void
550 */
551 function sq_mt_seed($Val) {
552 /* if mt_getrandmax() does not return a 2^n - 1 number,
553 this might not work well. This uses $Max as a bitmask. */
554 $Max = mt_getrandmax();
555
556 if (! is_int($Val)) {
557 $Val = crc32($Val);
558 }
559
560 if ($Val < 0) {
561 $Val *= -1;
562 }
563
564 if ($Val = 0) {
565 return;
566 }
567
568 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
569 }
570
571
572 /**
573 * Init random number generator
574 *
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.
578 *
579 * @return void
580 */
581 function sq_mt_randomize() {
582 static $randomized;
583
584 if ($randomized) {
585 return;
586 }
587
588 /* Global. */
589 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
590 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
591 sq_mt_seed((int)((double) microtime() * 1000000));
592 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
593
594 /* getrusage */
595 if (function_exists('getrusage')) {
596 /* Avoid warnings with Win32 */
597 $dat = @getrusage();
598 if (isset($dat) && is_array($dat)) {
599 $Str = '';
600 foreach ($dat as $k => $v)
601 {
602 $Str .= $k . $v;
603 }
604 sq_mt_seed(md5($Str));
605 }
606 }
607
608 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
609 sq_mt_seed(md5($unique_id));
610 }
611
612 $randomized = 1;
613 }
614
615 /**
616 * Creates encryption key
617 *
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 */
624 function OneTimePadCreate ($length=100) {
625 sq_mt_randomize();
626
627 $pad = '';
628 for ($i = 0; $i < $length; $i++) {
629 $pad .= chr(mt_rand(0,255));
630 }
631
632 return base64_encode($pad);
633 }
634
635 /**
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
640 */
641 function show_readable_size($bytes) {
642 $bytes /= 1024;
643 $type = 'k';
644
645 if ($bytes / 1024 > 1) {
646 $bytes /= 1024;
647 $type = 'M';
648 }
649
650 if ($bytes < 10) {
651 $bytes *= 10;
652 settype($bytes, 'integer');
653 $bytes /= 10;
654 } else {
655 settype($bytes, 'integer');
656 }
657
658 return $bytes . '<small>&nbsp;' . $type . '</small>';
659 }
660
661 /**
662 * Generates a random string from the caracter set you pass in
663 *
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
672 */
673 function 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 }
683
684 if (($size < 1) || (strlen($chars) < 1)) {
685 return '';
686 }
687
688 sq_mt_randomize(); /* Initialize the random number generator */
689
690 $String = '';
691 $j = strlen( $chars ) - 1;
692 while (strlen($String) < $size) {
693 $String .= $chars{mt_rand(0, $j)};
694 }
695
696 return $String;
697 }
698
699 /**
700 * Escapes special characters for use in IMAP commands.
701 *
702 * @param string the string to escape
703 * @return string the escaped string
704 */
705 function quoteimap($str) {
706 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
707 }
708
709 /**
710 * Trims array
711 *
712 * Trims every element in the array, ie. remove the first char of each element
713 * @param array array the array to trim
714 */
715 function 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);
721 }
722 } else {
723 $$k = substr($v, 1);
724 }
725
726 /* Re-assign back to array. */
727 $array[$k] = $$k;
728 }
729 }
730
731 /**
732 * Create compose link
733 *
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 */
740 function makeComposeLink($url, $text = null, $target='')
741 {
742 global $compose_new_win,$javascript_on;
743
744 if(!$text) {
745 $text = _("Compose");
746 }
747
748
749 // if not using "compose in new window", make
750 // regular link and be done with it
751 if($compose_new_win != '1') {
752 return makeInternalLink($url, $text, $target);
753 }
754
755
756 // build the compose in new window link...
757
758
759 // if javascript is on, use onClick event to handle it
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
765
766 // otherwise, just open new window using regular HTML
767 return makeInternalLink($url, $text, '_blank');
768
769 }
770
771 /**
772 * Print variable
773 *
774 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
775 *
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.
779 * The output is wrapped in <<pre>> and <</pre>> tags.
780 *
781 * @return void
782 */
783 function sm_print_r() {
784 ob_start(); // Buffer output
785 foreach(func_get_args() as $var) {
786 print_r($var);
787 echo "\n";
788 }
789 $buffer = ob_get_contents(); // Grab the print_r output
790 ob_end_clean(); // Silently discard the output & stop buffering
791 print '<pre>';
792 print htmlentities($buffer);
793 print '</pre>';
794 }
795
796 /**
797 * version of fwrite which checks for failure
798 */
799 function sq_fwrite($fp, $string) {
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;
808 }
809
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):
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>
820 * @param integer $quote_style quote encoding style. Possible values (without quotes):
821 * <ul>
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>
825 * </ul>
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 */
829 function 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,
839 array("<" => '&lt;',
840 ">" => '&gt;')
841 );
842 // double quotes
843 if ($quote_style == ENT_COMPAT)
844 $sq_html_ent_table = array_merge($sq_html_ent_table,
845 array("\"" => '&quot;')
846 );
847
848 // double and single quotes
849 if ($quote_style == ENT_QUOTES)
850 $sq_html_ent_table = array_merge($sq_html_ent_table,
851 array("\"" => '&quot;',
852 "'" => '&#39;')
853 );
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):
881 * <ul>
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>
885 * </ul>
886 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
887 * @return string sanitized string
888 */
889 function 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
896 $PHP_SELF = php_self();
897 ?>