Add cc: to the list of checks for empty recipients
[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 * Add a variable to the session.
88 * @param mixed $var the variable to register
89 * @param string $name the name to refer to this variable
90 * @return void
91 */
92 function sqsession_register ($var, $name) {
93
94 sqsession_is_active();
95
96 $_SESSION[$name] = $var;
97 }
98
99 /**
100 * Delete a variable from the session.
101 * @param string $name the name of the var to delete
102 * @return void
103 */
104 function sqsession_unregister ($name) {
105
106 sqsession_is_active();
107
108 unset($_SESSION[$name]);
109
110 session_unregister("$name");
111 }
112
113 /**
114 * Checks to see if a variable has already been registered
115 * in the session.
116 * @param string $name the name of the var to check
117 * @return bool whether the var has been registered
118 */
119 function sqsession_is_registered ($name) {
120 $test_name = &$name;
121 $result = false;
122
123 if (isset($_SESSION[$test_name])) {
124 $result = true;
125 }
126
127 return $result;
128 }
129
130
131 /**
132 * Retrieves a form variable, from a set of possible similarly named
133 * form variables, based on finding a different, single field. This
134 * is intended to allow more than one same-named inputs in a single
135 * <form>, where the submit button that is clicked tells us which
136 * input we should retrieve. An example is if we have:
137 * <select name="startMessage_1">
138 * <select name="startMessage_2">
139 * <input type="submit" name="form_submit_1" />
140 * <input type="submit" name="form_submit_2" />
141 * and we want to know which one of the select inputs should be
142 * returned as $startMessage (without the suffix!), this function
143 * decides by looking for either "form_submit_1" or "form_submit_2"
144 * (both should not appear). In this example, $name should be
145 * "startMessage" and $indicator_field should be "form_submit".
146 *
147 * NOTE that form widgets must be named with the suffix "_1", "_2", "_3"
148 * and so on, or this function will not work.
149 *
150 * If more than one of the indicator fields is found, the first one
151 * (numerically) will win.
152 *
153 * If an indicator field is found without a matching input ($name)
154 * field, FALSE is returned.
155 *
156 * If no indicator fields are found, a field of $name *without* any
157 * suffix is searched for (but only if $fallback_no_suffix is TRUE),
158 * and if not found, FALSE is ultimately returned.
159 *
160 * It should also be possible to use the same string for both
161 * $name and $indicator_field to look for the first possible
162 * widget with a suffix that can be found (and possibly fallback
163 * to a widget without a suffix).
164 *
165 * @param string name the name of the var to search
166 * @param mixed value the variable to return
167 * @param string indicator_field the name of the field upon which to base
168 * our decision upon (see above)
169 * @param int search constant defining where to look
170 * @param bool fallback_no_suffix whether or not to look for $name with
171 * no suffix when nothing else is found
172 * @param mixed default the value to assign to $value when nothing is found
173 * @param int typecast force variable to be cast to given type (please
174 * use SQ_TYPE_XXX constants or set to FALSE (default)
175 * to leave variable type unmolested)
176 *
177 * @return bool whether variable is found.
178 */
179 function sqGetGlobalVarMultiple($name, &$value, $indicator_field,
180 $search = SQ_INORDER,
181 $fallback_no_suffix=TRUE, $default=NULL,
182 $typecast=FALSE) {
183
184 // Set arbitrary max limit -- should be much lower except on the
185 // search results page, if there are many (50 or more?) mailboxes
186 // shown, this may not be high enough. Is there some way we should
187 // automate this value?
188 //
189 $max_form_search = 100;
190
191 for ($i = 1; $i <= $max_form_search; $i++) {
192 if (sqGetGlobalVar($indicator_field . '_' . $i, $temp, $search)) {
193 return sqGetGlobalVar($name . '_' . $i, $value, $search, $default, $typecast);
194 }
195 }
196
197
198 // no indicator field found; just try without suffix if allowed
199 //
200 if ($fallback_no_suffix) {
201 return sqGetGlobalVar($name, $value, $search, $default, $typecast);
202 }
203
204
205 // no dice, set default and return FALSE
206 //
207 if (!is_null($default)) {
208 $value = $default;
209 }
210 return FALSE;
211
212 }
213
214
215 /**
216 * Search for the var $name in $_SESSION, $_POST, $_GET, $_COOKIE, or $_SERVER
217 * and set it in provided var.
218 *
219 * If $search is not provided, or if it is SQ_INORDER, it will search $_SESSION,
220 * then $_POST, then $_GET. If $search is SQ_FORM it will search $_POST and
221 * $_GET. Otherwise, use one of the defined constants to look for a var in one
222 * place specifically.
223 *
224 * Note: $search is an int value equal to one of the constants defined above.
225 *
226 * Example:
227 * sqgetGlobalVar('username',$username,SQ_SESSION);
228 * // No quotes around last param, it's a constant - not a string!
229 *
230 * @param string name the name of the var to search
231 * @param mixed value the variable to return
232 * @param int search constant defining where to look
233 * @param mixed default the value to assign to $value when nothing is found
234 * @param int typecast force variable to be cast to given type (please
235 * use SQ_TYPE_XXX constants or set to FALSE (default)
236 * to leave variable type unmolested)
237 *
238 * @return bool whether variable is found.
239 */
240 function sqgetGlobalVar($name, &$value, $search = SQ_INORDER, $default = NULL, $typecast = false) {
241
242 $result = false;
243
244 switch ($search) {
245 /* we want the default case to be first here,
246 so that if a valid value isn't specified,
247 all three arrays will be searched. */
248 default:
249 case SQ_INORDER: // check session, post, get
250 case SQ_SESSION:
251 if( isset($_SESSION[$name]) ) {
252 $value = $_SESSION[$name];
253 $result = TRUE;
254 break;
255 } elseif ( $search == SQ_SESSION ) {
256 break;
257 }
258 case SQ_FORM: // check post, get
259 case SQ_POST:
260 if( isset($_POST[$name]) ) {
261 $value = $_POST[$name];
262 $result = TRUE;
263 break;
264 } elseif ( $search == SQ_POST ) {
265 break;
266 }
267 case SQ_GET:
268 if ( isset($_GET[$name]) ) {
269 $value = $_GET[$name];
270 $result = TRUE;
271 break;
272 }
273 /* NO IF HERE. FOR SQ_INORDER CASE, EXIT after GET */
274 break;
275 case SQ_COOKIE:
276 if ( isset($_COOKIE[$name]) ) {
277 $value = $_COOKIE[$name];
278 $result = TRUE;
279 break;
280 }
281 break;
282 case SQ_SERVER:
283 if ( isset($_SERVER[$name]) ) {
284 $value = $_SERVER[$name];
285 $result = TRUE;
286 break;
287 }
288 break;
289 }
290 if ($result && $typecast) {
291 switch ($typecast) {
292 case SQ_TYPE_INT: $value = (int) $value; break;
293 case SQ_TYPE_STRING: $value = (string) $value; break;
294 case SQ_TYPE_BOOL: $value = (bool) $value; break;
295 default: break;
296 }
297 } else if (!$result && !is_null($default)) {
298 $value = $default;
299 }
300 return $result;
301 }
302
303 /**
304 * Deletes an existing session, more advanced than the standard PHP
305 * session_destroy(), it explicitly deletes the cookies and global vars.
306 *
307 * WARNING: Older PHP versions have some issues with session management.
308 * See http://bugs.php.net/11643 (warning, spammed bug tracker) and
309 * http://bugs.php.net/13834. SID constant is not destroyed in PHP 4.1.2,
310 * 4.2.3 and maybe other versions. If you restart session after session
311 * is destroyed, affected PHP versions produce PHP notice. Bug should
312 * be fixed only in 4.3.0
313 */
314 function sqsession_destroy() {
315
316 /*
317 * php.net says we can kill the cookie by setting just the name:
318 * http://www.php.net/manual/en/function.setcookie.php
319 * maybe this will help fix the session merging again.
320 *
321 * Changed the theory on this to kill the cookies first starting
322 * a new session will provide a new session for all instances of
323 * the browser, we don't want that, as that is what is causing the
324 * merging of sessions.
325 */
326
327 global $base_uri, $_COOKIE, $_SESSION;
328
329 if (isset($_COOKIE[session_name()]) && session_name()) sqsetcookie(session_name(), '', 0, $base_uri);
330 if (isset($_COOKIE['username']) && $_COOKIE['username']) sqsetcookie('username','',0,$base_uri);
331 if (isset($_COOKIE['key']) && $_COOKIE['key']) sqsetcookie('key','',0,$base_uri);
332
333 $sessid = session_id();
334 if (!empty( $sessid )) {
335 $_SESSION = array();
336 @session_destroy();
337 }
338 }
339
340 /**
341 * Function to verify a session has been started. If it hasn't
342 * start a session up. php.net doesn't tell you that $_SESSION
343 * (even though autoglobal), is not created unless a session is
344 * started, unlike $_POST, $_GET and such
345 * Update: (see #1685031) the session ID is left over after the
346 * session is closed in some PHP setups; this function just becomes
347 * a passthru to sqsession_start(), but leaving old code in for
348 * edification.
349 */
350 function sqsession_is_active() {
351 //$sessid = session_id();
352 //if ( empty( $sessid ) ) {
353 sqsession_start();
354 //}
355 }
356
357 /**
358 * Function to start the session and store the cookie with the session_id as
359 * HttpOnly cookie which means that the cookie isn't accessible by javascript
360 * (IE6 only)
361 * Note that as sqsession_is_active() no longer discriminates as to when
362 * it calls this function, session_start() has to have E_NOTICE suppression
363 * (thus the @ sign).
364 */
365 function sqsession_start() {
366 global $base_uri;
367
368 @session_start();
369 $session_id = session_id();
370
371 // session_starts sets the sessionid cookie buth without the httponly var
372 // setting the cookie again sets the httponly cookie attribute
373 sqsetcookie(session_name(),$session_id,false,$base_uri);
374 }
375
376
377 /**
378 * Set a cookie
379 * @param string $sName The name of the cookie.
380 * @param string $sValue The value of the cookie.
381 * @param int $iExpire The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch.
382 * @param string $sPath The path on the server in which the cookie will be available on.
383 * @param string $sDomain The domain that the cookie is available.
384 * @param boolean $bSecure Indicates that the cookie should only be transmitted over a secure HTTPS connection.
385 * @param boolean $bHttpOnly Disallow JS to access the cookie (IE6 only)
386 * @return void
387 */
388 function sqsetcookie($sName,$sValue='deleted',$iExpire=0,$sPath="",$sDomain="",$bSecure=false,$bHttpOnly=true) {
389 // if we have a secure connection then limit the cookies to https only.
390 if ($sName && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']) {
391 $bSecure = true;
392 }
393
394 // admin config can override the restriction of secure-only cookies
395 global $only_secure_cookies;
396 if (!$only_secure_cookies)
397 $bSecure = false;
398
399 if (false && check_php_version(5,2)) {
400 // php 5 supports the httponly attribute in setcookie, but because setcookie seems a bit
401 // broken we use the header function for php 5.2 as well. We might change that later.
402 //setcookie($sName,$sValue,(int) $iExpire,$sPath,$sDomain,$bSecure,$bHttpOnly);
403 } else {
404 if (!empty($Domain)) {
405 // Fix the domain to accept domains with and without 'www.'.
406 if (strtolower(substr($Domain, 0, 4)) == 'www.') $Domain = substr($Domain, 4);
407 $Domain = '.' . $Domain;
408
409 // Remove port information.
410 $Port = strpos($Domain, ':');
411 if ($Port !== false) $Domain = substr($Domain, 0, $Port);
412 }
413 if (!$sValue) $sValue = 'deleted';
414 header('Set-Cookie: ' . rawurlencode($sName) . '=' . rawurlencode($sValue)
415 . (empty($iExpires) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', $iExpires) . ' GMT')
416 . (empty($sPath) ? '' : '; path=' . $sPath)
417 . (empty($sDomain) ? '' : '; domain=' . $sDomain)
418 . (!$bSecure ? '' : '; secure')
419 . (!$bHttpOnly ? '' : '; HttpOnly'), false);
420 }
421 }
422
423 /**
424 * session_regenerate_id replacement for PHP < 4.3.2
425 *
426 * This code is borrowed from Gallery, session.php version 1.53.2.1
427 */
428 if (!function_exists('session_regenerate_id')) {
429 function make_seed() {
430 list($usec, $sec) = explode(' ', microtime());
431 return (float)$sec + ((float)$usec * 100000);
432 }
433
434 function php_combined_lcg() {
435 mt_srand(make_seed());
436 $tv = gettimeofday();
437 $lcg['s1'] = $tv['sec'] ^ (~$tv['usec']);
438 $lcg['s2'] = mt_rand();
439 $q = (int) ($lcg['s1'] / 53668);
440 $lcg['s1'] = (int) (40014 * ($lcg['s1'] - 53668 * $q) - 12211 * $q);
441 if ($lcg['s1'] < 0) {
442 $lcg['s1'] += 2147483563;
443 }
444 $q = (int) ($lcg['s2'] / 52774);
445 $lcg['s2'] = (int) (40692 * ($lcg['s2'] - 52774 * $q) - 3791 * $q);
446 if ($lcg['s2'] < 0) {
447 $lcg['s2'] += 2147483399;
448 }
449 $z = (int) ($lcg['s1'] - $lcg['s2']);
450 if ($z < 1) {
451 $z += 2147483562;
452 }
453 return $z * 4.656613e-10;
454 }
455
456 function session_regenerate_id() {
457 global $base_uri;
458 $tv = gettimeofday();
459 sqgetGlobalVar('REMOTE_ADDR',$remote_addr,SQ_SERVER);
460 $buf = sprintf("%.15s%ld%ld%0.8f", $remote_addr, $tv['sec'], $tv['usec'], php_combined_lcg() * 10);
461 session_id(md5($buf));
462 if (ini_get('session.use_cookies')) {
463 // at a later stage we use sqsetcookie. At this point just do
464 // what session_regenerate_id would do
465 setcookie(session_name(), session_id(), NULL, $base_uri);
466 }
467 return TRUE;
468 }
469 }
470
471
472 /**
473 * php_self
474 *
475 * Creates an URL for the page calling this function, using either the PHP global
476 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added. Before 1.5.1
477 * function was stored in function/strings.php.
478 *
479 * @return string the complete url for this page
480 * @since 1.2.3
481 */
482 function php_self () {
483 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
484 return $req_uri;
485 }
486
487 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
488
489 // need to add query string to end of PHP_SELF to match REQUEST_URI
490 //
491 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
492 $php_self .= '?' . $query_string;
493 }
494
495 return $php_self;
496 }
497
498 return '';
499 }
500
501
502 /**
503 * Find files and/or directories in a given directory optionally
504 * limited to only those with the given file extension. If the
505 * directory is not found or cannot be opened, no error is generated;
506 * only an empty file list is returned.
507 FIXME: do we WANT to throw an error or a notice or... or return FALSE?
508 *
509 * @param string $directory_path The path (relative or absolute)
510 * to the desired directory.
511 * @param mixed $extension The file extension filter - either
512 * an array of desired extension(s),
513 * or a comma-separated list of same
514 * (optional; default is to return
515 * all files (dirs).
516 * @param boolean $return_filenames_only When TRUE, only file/dir names
517 * are returned, otherwise the
518 * $directory_path string is
519 * prepended to each file/dir in
520 * the returned list (optional;
521 * default is filename/dirname only)
522 * @param boolean $include_directories When TRUE, directories are
523 * included (optional; default
524 * DO include directories).
525 * @param boolean $directories_only When TRUE, ONLY directories
526 * are included (optional; default
527 * is to include files too).
528 * @param boolean $separate_files_and_directories When TRUE, files and
529 * directories are returned
530 * in separate lists, so
531 * the return value is
532 * formatted as a two-element
533 * array with the two keys
534 * "FILES" and "DIRECTORIES",
535 * where corresponding values
536 * are lists of either all
537 * files or all directories
538 * (optional; default do not
539 * split up return array).
540 * @param boolean $only_sm When TRUE, a security check will
541 * limit directory access to only
542 * paths within the SquirrelMail
543 * installation currently being used
544 * (optional; default TRUE)
545 *
546 * @return array The requested file/directory list(s).
547 *
548 * @since 1.5.2
549 *
550 */
551 function list_files($directory_path, $extensions='', $return_filenames_only=TRUE,
552 $include_directories=TRUE, $directories_only=FALSE,
553 $separate_files_and_directories=FALSE, $only_sm=TRUE) {
554
555 $files = array();
556 $directories = array();
557
558
559 // make sure requested path is under SM_PATH if needed
560 //
561 if ($only_sm) {
562 if (strpos(realpath($directory_path), realpath(SM_PATH)) !== 0) {
563 //plain_error_message(_("Illegal filesystem access was requested"));
564 echo _("Illegal filesystem access was requested");
565 exit;
566 }
567 }
568
569
570 // validate given directory
571 //
572 if (empty($directory_path)
573 || !is_dir($directory_path)
574 || !($DIR = opendir($directory_path))) {
575 return $files;
576 }
577
578
579 // ensure extensions is an array and is properly formatted
580 //
581 if (!empty($extensions)) {
582 if (!is_array($extensions))
583 $extensions = explode(',', $extensions);
584 $temp_extensions = array();
585 foreach ($extensions as $ext)
586 $temp_extensions[] = '.' . trim(trim($ext), '.');
587 $extensions = $temp_extensions;
588 } else $extensions = array();
589
590
591 $directory_path = rtrim($directory_path, '/');
592
593
594 // parse through the files
595 //
596 while (($file = readdir($DIR)) !== false) {
597
598 if ($file == '.' || $file == '..') continue;
599
600 if (!empty($extensions))
601 foreach ($extensions as $ext)
602 if (strrpos($file, $ext) !== (strlen($file) - strlen($ext)))
603 continue 2;
604
605 // only use is_dir() if we really need to (be as efficient as possible)
606 //
607 $is_dir = FALSE;
608 if (!$include_directories || $directories_only
609 || $separate_files_and_directories) {
610 if (is_dir($directory_path . '/' . $file)) {
611 if (!$include_directories) continue;
612 $is_dir = TRUE;
613 $directories[] = ($return_filenames_only
614 ? $file
615 : $directory_path . '/' . $file);
616 }
617 if ($directories_only) continue;
618 }
619
620 if (!$separate_files_and_directories
621 || ($separate_files_and_directories && !$is_dir)) {
622 $files[] = ($return_filenames_only
623 ? $file
624 : $directory_path . '/' . $file);
625 }
626
627 }
628 closedir($DIR);
629
630
631 if ($directories_only) return $directories;
632 if ($separate_files_and_directories) return array('FILES' => $files,
633 'DIRECTORIES' => $directories);
634 return $files;
635
636 }
637
638
639 /**
640 * Print variable
641 *
642 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
643 *
644 * Debugging function - does the same as print_r, but makes sure special
645 * characters are converted to htmlentities first. This will allow
646 * values like <some@email.address> to be displayed.
647 * The output is wrapped in <<pre>> and <</pre>> tags.
648 * Since 1.4.2 accepts unlimited number of arguments.
649 * @since 1.4.1
650 * @return void
651 */
652 function sm_print_r() {
653 ob_start(); // Buffer output
654 foreach(func_get_args() as $var) {
655 print_r($var);
656 echo "\n";
657 // php has get_class_methods function that can print class methods
658 if (is_object($var)) {
659 // get class methods if $var is object
660 $aMethods=get_class_methods(get_class($var));
661 // make sure that $aMethods is array and array is not empty
662 if (is_array($aMethods) && $aMethods!=array()) {
663 echo "Object methods:\n";
664 foreach($aMethods as $method) {
665 echo '* ' . $method . "\n";
666 }
667 }
668 echo "\n";
669 }
670 }
671 $buffer = ob_get_contents(); // Grab the print_r output
672 ob_end_clean(); // Silently discard the output & stop buffering
673 print '<div align="left"><pre>';
674 print htmlentities($buffer);
675 print '</pre></div>';
676 }
677
678
679 /**
680 * SquirrelMail wrapper for popen()/proc_open()
681 *
682 * This emulates popen() by using proc_open() if at all
683 * possible (reverts seamlessly to popen() if proc_open()
684 * is not supported in current PHP installation).
685 *
686 * This is intended for use with the related sq_pclose(),
687 * sq_get_pipe_stdout() and sq_get_pipe_stderr() functions,
688 * the latter of which add an easy interface for retrieving
689 * output from a child process that was opened with traditional
690 * popen() syntax (in write mode), while not breaking under
691 * earlier versions of PHP.
692 *
693 * @param string $command The command identifying what to
694 * execute in the child process.
695 * @param string $mode The desired mode for the
696 * unidirectional pipe that is returned;
697 * either 'r' for read or 'w' for write.
698 *
699 * @return resource A handle on the desired read or write pipe
700 * to the child process, or FALSE if the
701 * process cannot be created.
702 *
703 * @since 1.5.2
704 *
705 */
706 function sq_popen($command, $mode) {
707
708 $mode = strtolower($mode{0});
709
710
711 if (!function_exists('proc_open'))
712 return popen($command, $mode);
713
714
715 // set up our process store if not done already
716 //
717 global $processes;
718 if (empty($processes))
719 $processes = array();
720
721
722 // define read, write and error pipes
723 //
724 $descriptors = array(0 => array('pipe', 'r'),
725 1 => array('pipe', 'w'),
726 2 => array('pipe', 'w'));
727
728
729 // start the child process
730 //
731 $proc = proc_open($command, $descriptors, $pipes);
732 if (!is_resource($proc))
733 return FALSE;
734
735
736 // when in read mode, we'll return a handle to the child's write pipe
737 //
738 if ($mode == 'r')
739 $return_value = $pipes[1];
740 else if ($mode == 'w')
741 $return_value = $pipes[0];
742 else
743 die('sq_popen() expects $mode to be "r" or "w"');
744
745
746 // store the handle to the process and its pipes
747 // internally, keyed by whatever handle we'll be
748 // returning
749 //
750 $processes[$return_value] = array($proc, $pipes);
751
752
753 return $return_value;
754
755 }
756
757
758 /**
759 * Get STDERR output from a child process
760 *
761 * This is designed to be used with processes that were
762 * opened with sq_popen(), and will return any output
763 * that may be available from STDERR of the child process
764 * at the current time.
765 *
766 * If a value is given for $timeout_seconds, this function
767 * will wait that long for output in case there is none
768 * right now.
769 *
770 * In PHP environments that do not support proc_open(),
771 * an empty string will always be returned.
772 *
773 * @param resource $handle The handle to the child process,
774 * as returned from sq_popen().
775 * @param int $timeout_seconds The number of seconds to wait
776 * for output if there is none
777 * available immediately (OPTIONAL;
778 * default is not to wait)
779 * @param boolean $quiet When TRUE, errors are silently
780 * ignored (OPTIONAL; default is TRUE).
781 *
782 * @return string Any STDERR output that may have been found.
783 *
784 * @since 1.5.2
785 *
786 */
787 function sq_get_pipe_stderr($handle, $timeout_seconds=0, $quiet=TRUE) {
788
789 // yes, we are testing for proc_OPEN
790 // because we need to know how the
791 // handle was actually OPENED
792 //
793 if (!function_exists('proc_open'))
794 return '';
795
796
797 // get our process out of the process store
798 //
799 global $processes;
800 if (!is_array($processes) || !isset($processes[$handle])) {
801 if (!quiet) {
802 plain_error_message(_("Failed to find corresponding open process handle"));
803 }
804 return '';
805 }
806 $proc = $processes[$handle];
807
808
809 // get all we can from stderr, don't wait longer
810 // than our timeout for input
811 //
812 $contents = '';
813 $read = array($proc[1][2]);
814 $write = NULL;
815 $except = NULL;
816 if (stream_select($read, $write, $except, $timeout_seconds))
817 while (!feof($proc[1][2])) $contents .= fread($proc[1][2], 8192);
818 return $contents;
819
820 }
821
822
823 /**
824 * Get STDOUT output from a child process
825 *
826 * This is designed to be used with processes that were
827 * opened with sq_popen(), and will return any output
828 * that may be available from STDOUT of the child process
829 * at the current time.
830 *
831 * If a value is given for $timeout_seconds, this function
832 * will wait that long for output in case there is none
833 * right now.
834 *
835 * In PHP environments that do not support proc_open(),
836 * an empty string will always be returned.
837 *
838 * @param resource $handle The handle to the child process,
839 * as returned from sq_popen().
840 * @param int $timeout_seconds The number of seconds to wait
841 * for output if there is none
842 * available immediately (OPTIONAL;
843 * default is not to wait)
844 * @param boolean $quiet When TRUE, errors are silently
845 * ignored (OPTIONAL; default is TRUE).
846 *
847 * @return string Any STDOUT output that may have been found.
848 *
849 * @since 1.5.2
850 *
851 */
852 function sq_get_pipe_stdout($handle, $timeout_seconds=0, $quiet=TRUE) {
853
854 // yes, we are testing for proc_OPEN
855 // because we need to know how the
856 // handle was actually OPENED
857 //
858 if (!function_exists('proc_open'))
859 return '';
860
861
862 // get our process out of the process store
863 //
864 global $processes;
865 if (!is_array($processes) || !isset($processes[$handle])) {
866 if (!quiet) {
867 plain_error_message(_("Failed to find corresponding open process handle"));
868 }
869 return '';
870 }
871 $proc = $processes[$handle];
872
873
874 // get all we can from stdout, don't wait longer
875 // than our timeout for input
876 //
877 $contents = '';
878 $read = array($proc[1][1]);
879 $write = NULL;
880 $except = NULL;
881 if (stream_select($read, $write, $except, $timeout_seconds))
882 while (!feof($proc[1][1])) $contents .= fread($proc[1][1], 8192);
883 return $contents;
884
885 }
886
887
888 /**
889 * SquirrelMail wrapper for pclose()/proc_close()
890 *
891 * This is designed to be used with processes that were
892 * opened with sq_popen(), and will correctly close
893 * all pipes/handles that were opened as well as the
894 * child process itself.
895 *
896 * @param resource $handle The handle to the child process,
897 * as returned from sq_popen().
898 * @param boolean $quiet When TRUE, errors are silently
899 * ignored (OPTIONAL; default is TRUE).
900 *
901 * @return int The termination status of the child process.
902 *
903 * @since 1.5.2
904 *
905 */
906 function sq_pclose($handle, $quiet=TRUE) {
907
908 // yes, we are testing for proc_OPEN
909 // because we need to know how the
910 // handle was actually OPENED
911 //
912 if (!function_exists('proc_open'))
913 return pclose($handle);
914
915
916 // get our process out of the process store
917 //
918 global $processes;
919 if (!is_array($processes) || !isset($processes[$handle])) {
920 if (!quiet) {
921 plain_error_message(_("Failed to find corresponding open process handle"));
922 }
923 return 127;
924 }
925 $proc = $processes[$handle];
926 unset($processes[$handle]);
927
928
929 // close all pipes
930 //
931 fclose($proc[1][0]);
932 fclose($proc[1][1]);
933 fclose($proc[1][2]);
934
935
936 // close process
937 //
938 return proc_close($proc[0]);
939
940 }
941
942
943 /**
944 * Sanitize a value using htmlspecialchars() or similar, but also
945 * recursively run htmlspecialchars() (or similar) on array keys
946 * and values.
947 *
948 * If $value is not a string or an array with strings in it,
949 * the value is returned as is.
950 *
951 * @param mixed $value The value to be sanitized.
952 * @param mixed $quote_style Either boolean or an integer. If it
953 * is an integer, it must be the PHP
954 * constant indicating if/how to escape
955 * quotes: ENT_QUOTES, ENT_COMPAT, or
956 * ENT_NOQUOTES. If it is a boolean value,
957 * it must be TRUE and thus indicates
958 * that the only sanitizing to be done
959 * herein is to replace single and double
960 * quotes with &#039; and &quot;, no other
961 * changes are made to $value. If it is
962 * boolean and FALSE, behavior reverts
963 * to same as if the value was ENT_QUOTES
964 * (OPTIONAL; default is ENT_QUOTES).
965 *
966 * @return mixed The sanitized value.
967 *
968 * @since 1.5.2
969 *
970 **/
971 function sq_htmlspecialchars($value, $quote_style=ENT_QUOTES) {
972
973 if ($quote_style === FALSE) $quote_style = ENT_QUOTES;
974
975 // array? go recursive...
976 //
977 if (is_array($value)) {
978 $return_array = array();
979 foreach ($value as $key => $val) {
980 $return_array[sq_htmlspecialchars($key, $quote_style)]
981 = sq_htmlspecialchars($val, $quote_style);
982 }
983 return $return_array;
984
985 // sanitize strings only
986 //
987 } else if (is_string($value)) {
988 if ($quote_style === TRUE)
989 return str_replace(array('\'', '"'), array('&#039;', '&quot;'), $value);
990 else
991 return htmlspecialchars($value, $quote_style);
992 }
993
994 // anything else gets returned with no changes
995 //
996 return $value;
997
998 }