c09716d691ff2557081744bc3b6ea95b873e22a3
[squirrelmail.git] / functions / global.php
1 <?php
2
3 /**
4 * global.php
5 *
6 * This includes code to update < 4.1.0 globals to the newer format
7 * It also has some session register functions that work across various
8 * php versions.
9 *
10 * @copyright &copy; 1999-2007 The SquirrelMail Project Team
11 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
12 * @version $Id$
13 * @package squirrelmail
14 */
15
16 /**
17 */
18 define('SQ_INORDER',0);
19 define('SQ_GET',1);
20 define('SQ_POST',2);
21 define('SQ_SESSION',3);
22 define('SQ_COOKIE',4);
23 define('SQ_SERVER',5);
24 define('SQ_FORM',6);
25
26
27 /**
28 * returns true if current php version is at mimimum a.b.c
29 *
30 * Called: check_php_version(4,1)
31 * @param int a major version number
32 * @param int b minor version number
33 * @param int c release number
34 * @return bool
35 */
36 function check_php_version ($a = '0', $b = '0', $c = '0')
37 {
38 return version_compare ( PHP_VERSION, "$a.$b.$c", 'ge' );
39 }
40
41 /**
42 * returns true if the current internal SM version is at minimum a.b.c
43 * These are plain integer comparisons, as our internal version is
44 * constructed by us, as an array of 3 ints.
45 *
46 * Called: check_sm_version(1,3,3)
47 * @param int a major version number
48 * @param int b minor version number
49 * @param int c release number
50 * @return bool
51 */
52 function check_sm_version($a = 0, $b = 0, $c = 0)
53 {
54 global $SQM_INTERNAL_VERSION;
55 if ( !isset($SQM_INTERNAL_VERSION) ||
56 $SQM_INTERNAL_VERSION[0] < $a ||
57 ( $SQM_INTERNAL_VERSION[0] == $a &&
58 $SQM_INTERNAL_VERSION[1] < $b) ||
59 ( $SQM_INTERNAL_VERSION[0] == $a &&
60 $SQM_INTERNAL_VERSION[1] == $b &&
61 $SQM_INTERNAL_VERSION[2] < $c ) ) {
62 return FALSE;
63 }
64 return TRUE;
65 }
66
67
68 /**
69 * Recursively strip slashes from the values of an array.
70 * @param array array the array to strip, passed by reference
71 * @return void
72 */
73 function sqstripslashes(&$array) {
74 if(count($array) > 0) {
75 foreach ($array as $index=>$value) {
76 if (is_array($array[$index])) {
77 sqstripslashes($array[$index]);
78 }
79 else {
80 $array[$index] = stripslashes($value);
81 }
82 }
83 }
84 }
85
86 /**
87 * Squelch error output to screen (only) for the given function.
88 * If the SquirrelMail debug mode SM_DEBUG_MODE_ADVANCED is not
89 * enabled, error output will not go to the log, either.
90 *
91 * This provides an alternative to the @ error-suppression
92 * operator where errors will not be shown in the interface
93 * but will show up in the server log file (assuming the
94 * administrator has configured PHP logging).
95 *
96 * @since 1.4.12 and 1.5.2
97 *
98 * @param string $function The function to be executed
99 * @param array $args The arguments to be passed to the function
100 * (OPTIONAL; default no arguments)
101 * NOTE: The caller must take extra action if
102 * the function being called is supposed
103 * to use any of the parameters by
104 * reference. In the following example,
105 * $x is passed by reference and $y is
106 * passed by value to the "my_func"
107 * function.
108 * sq_call_function_suppress_errors('my_func', array(&$x, $y));
109 *
110 * @return mixed The return value, if any, of the function being
111 * executed will be returned.
112 *
113 */
114 function sq_call_function_suppress_errors($function, $args=NULL) {
115 global $sm_debug_mode;
116
117 $display_errors = ini_get('display_errors');
118 ini_set('display_errors', '0');
119
120 // if advanced debug mode isn't enabled, don't log the error, either
121 //
122 if (!($sm_debug_mode & SM_DEBUG_MODE_ADVANCED))
123 $error_reporting = error_reporting(0);
124
125 $ret = call_user_func_array($function, $args);
126
127 if (!($sm_debug_mode & SM_DEBUG_MODE_ADVANCED))
128 error_reporting($error_reporting);
129
130 ini_set('display_errors', $display_errors);
131 return $ret;
132 }
133
134 /**
135 * Add a variable to the session.
136 * @param mixed $var the variable to register
137 * @param string $name the name to refer to this variable
138 * @return void
139 */
140 function sqsession_register ($var, $name) {
141
142 sqsession_is_active();
143
144 $_SESSION[$name] = $var;
145 }
146
147 /**
148 * Delete a variable from the session.
149 * @param string $name the name of the var to delete
150 * @return void
151 */
152 function sqsession_unregister ($name) {
153
154 sqsession_is_active();
155
156 unset($_SESSION[$name]);
157
158 session_unregister("$name");
159 }
160
161 /**
162 * Checks to see if a variable has already been registered
163 * in the session.
164 * @param string $name the name of the var to check
165 * @return bool whether the var has been registered
166 */
167 function sqsession_is_registered ($name) {
168 $test_name = &$name;
169 $result = false;
170
171 if (isset($_SESSION[$test_name])) {
172 $result = true;
173 }
174
175 return $result;
176 }
177
178
179 /**
180 * Retrieves a form variable, from a set of possible similarly named
181 * form variables, based on finding a different, single field. This
182 * is intended to allow more than one same-named inputs in a single
183 * <form>, where the submit button that is clicked tells us which
184 * input we should retrieve. An example is if we have:
185 * <select name="startMessage_1">
186 * <select name="startMessage_2">
187 * <input type="submit" name="form_submit_1" />
188 * <input type="submit" name="form_submit_2" />
189 * and we want to know which one of the select inputs should be
190 * returned as $startMessage (without the suffix!), this function
191 * decides by looking for either "form_submit_1" or "form_submit_2"
192 * (both should not appear). In this example, $name should be
193 * "startMessage" and $indicator_field should be "form_submit".
194 *
195 * NOTE that form widgets must be named with the suffix "_1", "_2", "_3"
196 * and so on, or this function will not work.
197 *
198 * If more than one of the indicator fields is found, the first one
199 * (numerically) will win.
200 *
201 * If an indicator field is found without a matching input ($name)
202 * field, FALSE is returned.
203 *
204 * If no indicator fields are found, a field of $name *without* any
205 * suffix is searched for (but only if $fallback_no_suffix is TRUE),
206 * and if not found, FALSE is ultimately returned.
207 *
208 * It should also be possible to use the same string for both
209 * $name and $indicator_field to look for the first possible
210 * widget with a suffix that can be found (and possibly fallback
211 * to a widget without a suffix).
212 *
213 * @param string name the name of the var to search
214 * @param mixed value the variable to return
215 * @param string indicator_field the name of the field upon which to base
216 * our decision upon (see above)
217 * @param int search constant defining where to look
218 * @param bool fallback_no_suffix whether or not to look for $name with
219 * no suffix when nothing else is found
220 * @param mixed default the value to assign to $value when nothing is found
221 * @param int typecast force variable to be cast to given type (please
222 * use SQ_TYPE_XXX constants or set to FALSE (default)
223 * to leave variable type unmolested)
224 *
225 * @return bool whether variable is found.
226 */
227 function sqGetGlobalVarMultiple($name, &$value, $indicator_field,
228 $search = SQ_INORDER,
229 $fallback_no_suffix=TRUE, $default=NULL,
230 $typecast=FALSE) {
231
232 // Set arbitrary max limit -- should be much lower except on the
233 // search results page, if there are many (50 or more?) mailboxes
234 // shown, this may not be high enough. Is there some way we should
235 // automate this value?
236 //
237 $max_form_search = 100;
238
239 for ($i = 1; $i <= $max_form_search; $i++) {
240 if (sqGetGlobalVar($indicator_field . '_' . $i, $temp, $search)) {
241 return sqGetGlobalVar($name . '_' . $i, $value, $search, $default, $typecast);
242 }
243 }
244
245
246 // no indicator field found; just try without suffix if allowed
247 //
248 if ($fallback_no_suffix) {
249 return sqGetGlobalVar($name, $value, $search, $default, $typecast);
250 }
251
252
253 // no dice, set default and return FALSE
254 //
255 if (!is_null($default)) {
256 $value = $default;
257 }
258 return FALSE;
259
260 }
261
262
263 /**
264 * Search for the var $name in $_SESSION, $_POST, $_GET, $_COOKIE, or $_SERVER
265 * and set it in provided var.
266 *
267 * If $search is not provided, or if it is SQ_INORDER, it will search $_SESSION,
268 * then $_POST, then $_GET. If $search is SQ_FORM it will search $_POST and
269 * $_GET. Otherwise, use one of the defined constants to look for a var in one
270 * place specifically.
271 *
272 * Note: $search is an int value equal to one of the constants defined above.
273 *
274 * Example:
275 * sqgetGlobalVar('username',$username,SQ_SESSION);
276 * // No quotes around last param, it's a constant - not a string!
277 *
278 * @param string name the name of the var to search
279 * @param mixed value the variable to return
280 * @param int search constant defining where to look
281 * @param mixed default the value to assign to $value when nothing is found
282 * @param int typecast force variable to be cast to given type (please
283 * use SQ_TYPE_XXX constants or set to FALSE (default)
284 * to leave variable type unmolested)
285 *
286 * @return bool whether variable is found.
287 */
288 function sqgetGlobalVar($name, &$value, $search = SQ_INORDER, $default = NULL, $typecast = false) {
289
290 $result = false;
291
292 switch ($search) {
293 /* we want the default case to be first here,
294 so that if a valid value isn't specified,
295 all three arrays will be searched. */
296 default:
297 case SQ_INORDER: // check session, post, get
298 case SQ_SESSION:
299 if( isset($_SESSION[$name]) ) {
300 $value = $_SESSION[$name];
301 $result = TRUE;
302 break;
303 } elseif ( $search == SQ_SESSION ) {
304 break;
305 }
306 case SQ_FORM: // check post, get
307 case SQ_POST:
308 if( isset($_POST[$name]) ) {
309 $value = $_POST[$name];
310 $result = TRUE;
311 break;
312 } elseif ( $search == SQ_POST ) {
313 break;
314 }
315 case SQ_GET:
316 if ( isset($_GET[$name]) ) {
317 $value = $_GET[$name];
318 $result = TRUE;
319 break;
320 }
321 /* NO IF HERE. FOR SQ_INORDER CASE, EXIT after GET */
322 break;
323 case SQ_COOKIE:
324 if ( isset($_COOKIE[$name]) ) {
325 $value = $_COOKIE[$name];
326 $result = TRUE;
327 break;
328 }
329 break;
330 case SQ_SERVER:
331 if ( isset($_SERVER[$name]) ) {
332 $value = $_SERVER[$name];
333 $result = TRUE;
334 break;
335 }
336 break;
337 }
338 if ($result && $typecast) {
339 switch ($typecast) {
340 case SQ_TYPE_INT: $value = (int) $value; break;
341 case SQ_TYPE_STRING: $value = (string) $value; break;
342 case SQ_TYPE_BOOL: $value = (bool) $value; break;
343 default: break;
344 }
345 } else if (!$result && !is_null($default)) {
346 $value = $default;
347 }
348 return $result;
349 }
350
351 /**
352 * Deletes an existing session, more advanced than the standard PHP
353 * session_destroy(), it explicitly deletes the cookies and global vars.
354 *
355 * WARNING: Older PHP versions have some issues with session management.
356 * See http://bugs.php.net/11643 (warning, spammed bug tracker) and
357 * http://bugs.php.net/13834. SID constant is not destroyed in PHP 4.1.2,
358 * 4.2.3 and maybe other versions. If you restart session after session
359 * is destroyed, affected PHP versions produce PHP notice. Bug should
360 * be fixed only in 4.3.0
361 */
362 function sqsession_destroy() {
363
364 /*
365 * php.net says we can kill the cookie by setting just the name:
366 * http://www.php.net/manual/en/function.setcookie.php
367 * maybe this will help fix the session merging again.
368 *
369 * Changed the theory on this to kill the cookies first starting
370 * a new session will provide a new session for all instances of
371 * the browser, we don't want that, as that is what is causing the
372 * merging of sessions.
373 */
374
375 global $base_uri, $_COOKIE, $_SESSION;
376
377 if (isset($_COOKIE[session_name()]) && session_name()) sqsetcookie(session_name(), '', 0, $base_uri);
378 if (isset($_COOKIE['username']) && $_COOKIE['username']) sqsetcookie('username','',0,$base_uri);
379 if (isset($_COOKIE['key']) && $_COOKIE['key']) sqsetcookie('key','',0,$base_uri);
380
381 $sessid = session_id();
382 if (!empty( $sessid )) {
383 $_SESSION = array();
384 @session_destroy();
385 }
386 }
387
388 /**
389 * Function to verify a session has been started. If it hasn't
390 * start a session up. php.net doesn't tell you that $_SESSION
391 * (even though autoglobal), is not created unless a session is
392 * started, unlike $_POST, $_GET and such
393 * Update: (see #1685031) the session ID is left over after the
394 * session is closed in some PHP setups; this function just becomes
395 * a passthru to sqsession_start(), but leaving old code in for
396 * edification.
397 */
398 function sqsession_is_active() {
399 //$sessid = session_id();
400 //if ( empty( $sessid ) ) {
401 sqsession_start();
402 //}
403 }
404
405 /**
406 * Function to start the session and store the cookie with the session_id as
407 * HttpOnly cookie which means that the cookie isn't accessible by javascript
408 * (IE6 only)
409 * Note that as sqsession_is_active() no longer discriminates as to when
410 * it calls this function, session_start() has to have E_NOTICE suppression
411 * (thus the @ sign).
412 */
413 function sqsession_start() {
414 global $base_uri;
415
416 sq_call_function_suppress_errors('session_start');
417 // was: @session_start();
418 $session_id = session_id();
419
420 // session_starts sets the sessionid cookie buth without the httponly var
421 // setting the cookie again sets the httponly cookie attribute
422 sqsetcookie(session_name(),$session_id,false,$base_uri);
423 }
424
425
426 /**
427 * Set a cookie
428 * @param string $sName The name of the cookie.
429 * @param string $sValue The value of the cookie.
430 * @param int $iExpire The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch.
431 * @param string $sPath The path on the server in which the cookie will be available on.
432 * @param string $sDomain The domain that the cookie is available.
433 * @param boolean $bSecure Indicates that the cookie should only be transmitted over a secure HTTPS connection.
434 * @param boolean $bHttpOnly Disallow JS to access the cookie (IE6 only)
435 * @return void
436 */
437 function sqsetcookie($sName,$sValue='deleted',$iExpire=0,$sPath="",$sDomain="",$bSecure=false,$bHttpOnly=true) {
438 // if we have a secure connection then limit the cookies to https only.
439 if ($sName && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']) {
440 $bSecure = true;
441 }
442
443 // admin config can override the restriction of secure-only cookies
444 global $only_secure_cookies;
445 if (!$only_secure_cookies)
446 $bSecure = false;
447
448 if (false && check_php_version(5,2)) {
449 // php 5 supports the httponly attribute in setcookie, but because setcookie seems a bit
450 // broken we use the header function for php 5.2 as well. We might change that later.
451 //setcookie($sName,$sValue,(int) $iExpire,$sPath,$sDomain,$bSecure,$bHttpOnly);
452 } else {
453 if (!empty($sDomain)) {
454 // Fix the domain to accept domains with and without 'www.'.
455 if (strtolower(substr($sDomain, 0, 4)) == 'www.') $sDomain = substr($sDomain, 4);
456 $sDomain = '.' . $sDomain;
457
458 // Remove port information.
459 $Port = strpos($sDomain, ':');
460 if ($Port !== false) $sDomain = substr($sDomain, 0, $Port);
461 }
462 if (!$sValue) $sValue = 'deleted';
463 header('Set-Cookie: ' . rawurlencode($sName) . '=' . rawurlencode($sValue)
464 . (empty($iExpire) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', $iExpire) . ' GMT')
465 . (empty($sPath) ? '' : '; path=' . $sPath)
466 . (empty($sDomain) ? '' : '; domain=' . $sDomain)
467 . (!$bSecure ? '' : '; secure')
468 . (!$bHttpOnly ? '' : '; HttpOnly'), false);
469 }
470 }
471
472 /**
473 * session_regenerate_id replacement for PHP < 4.3.2
474 *
475 * This code is borrowed from Gallery, session.php version 1.53.2.1
476 */
477 if (!function_exists('session_regenerate_id')) {
478 function make_seed() {
479 list($usec, $sec) = explode(' ', microtime());
480 return (float)$sec + ((float)$usec * 100000);
481 }
482
483 function php_combined_lcg() {
484 mt_srand(make_seed());
485 $tv = gettimeofday();
486 $lcg['s1'] = $tv['sec'] ^ (~$tv['usec']);
487 $lcg['s2'] = mt_rand();
488 $q = (int) ($lcg['s1'] / 53668);
489 $lcg['s1'] = (int) (40014 * ($lcg['s1'] - 53668 * $q) - 12211 * $q);
490 if ($lcg['s1'] < 0) {
491 $lcg['s1'] += 2147483563;
492 }
493 $q = (int) ($lcg['s2'] / 52774);
494 $lcg['s2'] = (int) (40692 * ($lcg['s2'] - 52774 * $q) - 3791 * $q);
495 if ($lcg['s2'] < 0) {
496 $lcg['s2'] += 2147483399;
497 }
498 $z = (int) ($lcg['s1'] - $lcg['s2']);
499 if ($z < 1) {
500 $z += 2147483562;
501 }
502 return $z * 4.656613e-10;
503 }
504
505 function session_regenerate_id() {
506 global $base_uri;
507 $tv = gettimeofday();
508 sqgetGlobalVar('REMOTE_ADDR',$remote_addr,SQ_SERVER);
509 $buf = sprintf("%.15s%ld%ld%0.8f", $remote_addr, $tv['sec'], $tv['usec'], php_combined_lcg() * 10);
510 session_id(md5($buf));
511 if (ini_get('session.use_cookies')) {
512 // at a later stage we use sqsetcookie. At this point just do
513 // what session_regenerate_id would do
514 setcookie(session_name(), session_id(), NULL, $base_uri);
515 }
516 return TRUE;
517 }
518 }
519
520
521 /**
522 * php_self
523 *
524 * Creates an URL for the page calling this function, using either the PHP global
525 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added. Before 1.5.1
526 * function was stored in function/strings.php.
527 *
528 * @return string the complete url for this page
529 * @since 1.2.3
530 */
531 function php_self () {
532 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
533 return $req_uri;
534 }
535
536 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
537
538 // need to add query string to end of PHP_SELF to match REQUEST_URI
539 //
540 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
541 $php_self .= '?' . $query_string;
542 }
543
544 return $php_self;
545 }
546
547 return '';
548 }
549
550
551 /**
552 * Find files and/or directories in a given directory optionally
553 * limited to only those with the given file extension. If the
554 * directory is not found or cannot be opened, no error is generated;
555 * only an empty file list is returned.
556 FIXME: do we WANT to throw an error or a notice or... or return FALSE?
557 *
558 * @param string $directory_path The path (relative or absolute)
559 * to the desired directory.
560 * @param mixed $extension The file extension filter - either
561 * an array of desired extension(s),
562 * or a comma-separated list of same
563 * (optional; default is to return
564 * all files (dirs).
565 * @param boolean $return_filenames_only When TRUE, only file/dir names
566 * are returned, otherwise the
567 * $directory_path string is
568 * prepended to each file/dir in
569 * the returned list (optional;
570 * default is filename/dirname only)
571 * @param boolean $include_directories When TRUE, directories are
572 * included (optional; default
573 * DO include directories).
574 * @param boolean $directories_only When TRUE, ONLY directories
575 * are included (optional; default
576 * is to include files too).
577 * @param boolean $separate_files_and_directories When TRUE, files and
578 * directories are returned
579 * in separate lists, so
580 * the return value is
581 * formatted as a two-element
582 * array with the two keys
583 * "FILES" and "DIRECTORIES",
584 * where corresponding values
585 * are lists of either all
586 * files or all directories
587 * (optional; default do not
588 * split up return array).
589 * @param boolean $only_sm When TRUE, a security check will
590 * limit directory access to only
591 * paths within the SquirrelMail
592 * installation currently being used
593 * (optional; default TRUE)
594 *
595 * @return array The requested file/directory list(s).
596 *
597 * @since 1.5.2
598 *
599 */
600 function list_files($directory_path, $extensions='', $return_filenames_only=TRUE,
601 $include_directories=TRUE, $directories_only=FALSE,
602 $separate_files_and_directories=FALSE, $only_sm=TRUE) {
603
604 $files = array();
605 $directories = array();
606
607
608 // make sure requested path is under SM_PATH if needed
609 //
610 if ($only_sm) {
611 if (strpos(realpath($directory_path), realpath(SM_PATH)) !== 0) {
612 //plain_error_message(_("Illegal filesystem access was requested"));
613 echo _("Illegal filesystem access was requested");
614 exit;
615 }
616 }
617
618
619 // validate given directory
620 //
621 if (empty($directory_path)
622 || !is_dir($directory_path)
623 || !($DIR = opendir($directory_path))) {
624 return $files;
625 }
626
627
628 // ensure extensions is an array and is properly formatted
629 //
630 if (!empty($extensions)) {
631 if (!is_array($extensions))
632 $extensions = explode(',', $extensions);
633 $temp_extensions = array();
634 foreach ($extensions as $ext)
635 $temp_extensions[] = '.' . trim(trim($ext), '.');
636 $extensions = $temp_extensions;
637 } else $extensions = array();
638
639
640 $directory_path = rtrim($directory_path, '/');
641
642
643 // parse through the files
644 //
645 while (($file = readdir($DIR)) !== false) {
646
647 if ($file == '.' || $file == '..') continue;
648
649 if (!empty($extensions))
650 foreach ($extensions as $ext)
651 if (strrpos($file, $ext) !== (strlen($file) - strlen($ext)))
652 continue 2;
653
654 // only use is_dir() if we really need to (be as efficient as possible)
655 //
656 $is_dir = FALSE;
657 if (!$include_directories || $directories_only
658 || $separate_files_and_directories) {
659 if (is_dir($directory_path . '/' . $file)) {
660 if (!$include_directories) continue;
661 $is_dir = TRUE;
662 $directories[] = ($return_filenames_only
663 ? $file
664 : $directory_path . '/' . $file);
665 }
666 if ($directories_only) continue;
667 }
668
669 if (!$separate_files_and_directories
670 || ($separate_files_and_directories && !$is_dir)) {
671 $files[] = ($return_filenames_only
672 ? $file
673 : $directory_path . '/' . $file);
674 }
675
676 }
677 closedir($DIR);
678
679
680 if ($directories_only) return $directories;
681 if ($separate_files_and_directories) return array('FILES' => $files,
682 'DIRECTORIES' => $directories);
683 return $files;
684
685 }
686
687
688 /**
689 * Print variable
690 *
691 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
692 *
693 * Debugging function - does the same as print_r, but makes sure special
694 * characters are converted to htmlentities first. This will allow
695 * values like <some@email.address> to be displayed.
696 * The output is wrapped in <<pre>> and <</pre>> tags.
697 * Since 1.4.2 accepts unlimited number of arguments.
698 * @since 1.4.1
699 * @return void
700 */
701 function sm_print_r() {
702 ob_start(); // Buffer output
703 foreach(func_get_args() as $var) {
704 print_r($var);
705 echo "\n";
706 // php has get_class_methods function that can print class methods
707 if (is_object($var)) {
708 // get class methods if $var is object
709 $aMethods=get_class_methods(get_class($var));
710 // make sure that $aMethods is array and array is not empty
711 if (is_array($aMethods) && $aMethods!=array()) {
712 echo "Object methods:\n";
713 foreach($aMethods as $method) {
714 echo '* ' . $method . "\n";
715 }
716 }
717 echo "\n";
718 }
719 }
720 $buffer = ob_get_contents(); // Grab the print_r output
721 ob_end_clean(); // Silently discard the output & stop buffering
722 print '<div align="left"><pre>';
723 print htmlentities($buffer);
724 print '</pre></div>';
725 }
726
727
728 /**
729 * Sanitize a value using htmlspecialchars() or similar, but also
730 * recursively run htmlspecialchars() (or similar) on array keys
731 * and values.
732 *
733 * If $value is not a string or an array with strings in it,
734 * the value is returned as is.
735 *
736 * @param mixed $value The value to be sanitized.
737 * @param mixed $quote_style Either boolean or an integer. If it
738 * is an integer, it must be the PHP
739 * constant indicating if/how to escape
740 * quotes: ENT_QUOTES, ENT_COMPAT, or
741 * ENT_NOQUOTES. If it is a boolean value,
742 * it must be TRUE and thus indicates
743 * that the only sanitizing to be done
744 * herein is to replace single and double
745 * quotes with &#039; and &quot;, no other
746 * changes are made to $value. If it is
747 * boolean and FALSE, behavior reverts
748 * to same as if the value was ENT_QUOTES
749 * (OPTIONAL; default is ENT_QUOTES).
750 *
751 * @return mixed The sanitized value.
752 *
753 * @since 1.5.2
754 *
755 **/
756 function sq_htmlspecialchars($value, $quote_style=ENT_QUOTES) {
757
758 if ($quote_style === FALSE) $quote_style = ENT_QUOTES;
759
760 // array? go recursive...
761 //
762 if (is_array($value)) {
763 $return_array = array();
764 foreach ($value as $key => $val) {
765 $return_array[sq_htmlspecialchars($key, $quote_style)]
766 = sq_htmlspecialchars($val, $quote_style);
767 }
768 return $return_array;
769
770 // sanitize strings only
771 //
772 } else if (is_string($value)) {
773 if ($quote_style === TRUE)
774 return str_replace(array('\'', '"'), array('&#039;', '&quot;'), $value);
775 else
776 return htmlspecialchars($value, $quote_style);
777 }
778
779 // anything else gets returned with no changes
780 //
781 return $value;
782
783 }