Added the zend framework 2 library, the path is specified in line no.26 in zend_modul...
[openemr.git] / phpmyadmin / libraries / core.lib.php
blobf5d92bd361292e77a57c1ceade99bc759f34bfd4
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Core functions used all over the scripts.
5 * This script is distinct from libraries/common.inc.php because this
6 * script is called from /test.
8 * @package PhpMyAdmin
9 */
10 if (! defined('PHPMYADMIN')) {
11 exit;
14 /**
15 * checks given $var and returns it if valid, or $default of not valid
16 * given $var is also checked for type being 'similar' as $default
17 * or against any other type if $type is provided
19 * <code>
20 * // $_REQUEST['db'] not set
21 * echo PMA_ifSetOr($_REQUEST['db'], ''); // ''
22 * // $_REQUEST['sql_query'] not set
23 * echo PMA_ifSetOr($_REQUEST['sql_query']); // null
24 * // $cfg['ForceSSL'] not set
25 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
26 * echo PMA_ifSetOr($cfg['ForceSSL']); // null
27 * // $cfg['ForceSSL'] set to 1
28 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
29 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'similar'); // 1
30 * echo PMA_ifSetOr($cfg['ForceSSL'], false); // 1
31 * // $cfg['ForceSSL'] set to true
32 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // true
33 * </code>
35 * @param mixed &$var param to check
36 * @param mixed $default default value
37 * @param mixed $type var type or array of values to check against $var
39 * @return mixed $var or $default
41 * @see PMA_isValid()
43 function PMA_ifSetOr(&$var, $default = null, $type = 'similar')
45 if (! PMA_isValid($var, $type, $default)) {
46 return $default;
49 return $var;
52 /**
53 * checks given $var against $type or $compare
55 * $type can be:
56 * - false : no type checking
57 * - 'scalar' : whether type of $var is integer, float, string or boolean
58 * - 'numeric' : whether type of $var is any number repesentation
59 * - 'length' : whether type of $var is scalar with a string length > 0
60 * - 'similar' : whether type of $var is similar to type of $compare
61 * - 'equal' : whether type of $var is identical to type of $compare
62 * - 'identical' : whether $var is identical to $compare, not only the type!
63 * - or any other valid PHP variable type
65 * <code>
66 * // $_REQUEST['doit'] = true;
67 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false
68 * // $_REQUEST['doit'] = 'true';
69 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true
70 * </code>
72 * NOTE: call-by-reference is used to not get NOTICE on undefined vars,
73 * but the var is not altered inside this function, also after checking a var
74 * this var exists nut is not set, example:
75 * <code>
76 * // $var is not set
77 * isset($var); // false
78 * functionCallByReference($var); // false
79 * isset($var); // true
80 * functionCallByReference($var); // true
81 * </code>
83 * to avoid this we set this var to null if not isset
85 * @param mixed &$var variable to check
86 * @param mixed $type var type or array of valid values to check against $var
87 * @param mixed $compare var to compare with $var
89 * @return boolean whether valid or not
91 * @todo add some more var types like hex, bin, ...?
92 * @see http://php.net/gettype
94 function PMA_isValid(&$var, $type = 'length', $compare = null)
96 if (! isset($var)) {
97 // var is not even set
98 return false;
101 if ($type === false) {
102 // no vartype requested
103 return true;
106 if (is_array($type)) {
107 return in_array($var, $type);
110 // allow some aliaes of var types
111 $type = strtolower($type);
112 switch ($type) {
113 case 'identic' :
114 $type = 'identical';
115 break;
116 case 'len' :
117 $type = 'length';
118 break;
119 case 'bool' :
120 $type = 'boolean';
121 break;
122 case 'float' :
123 $type = 'double';
124 break;
125 case 'int' :
126 $type = 'integer';
127 break;
128 case 'null' :
129 $type = 'NULL';
130 break;
133 if ($type === 'identical') {
134 return $var === $compare;
137 // whether we should check against given $compare
138 if ($type === 'similar') {
139 switch (gettype($compare)) {
140 case 'string':
141 case 'boolean':
142 $type = 'scalar';
143 break;
144 case 'integer':
145 case 'double':
146 $type = 'numeric';
147 break;
148 default:
149 $type = gettype($compare);
151 } elseif ($type === 'equal') {
152 $type = gettype($compare);
155 // do the check
156 if ($type === 'length' || $type === 'scalar') {
157 $is_scalar = is_scalar($var);
158 if ($is_scalar && $type === 'length') {
159 return (bool) strlen($var);
161 return $is_scalar;
164 if ($type === 'numeric') {
165 return is_numeric($var);
168 if (gettype($var) === $type) {
169 return true;
172 return false;
176 * Removes insecure parts in a path; used before include() or
177 * require() when a part of the path comes from an insecure source
178 * like a cookie or form.
180 * @param string $path The path to check
182 * @return string The secured path
184 * @access public
186 function PMA_securePath($path)
188 // change .. to .
189 $path = preg_replace('@\.\.*@', '.', $path);
191 return $path;
192 } // end function
195 * displays the given error message on phpMyAdmin error page in foreign language,
196 * ends script execution and closes session
198 * loads language file if not loaded already
200 * @param string $error_message the error message or named error message
201 * @param string|array $message_args arguments applied to $error_message
202 * @param boolean $delete_session whether to delete session cookie
204 * @return exit
206 function PMA_fatalError(
207 $error_message, $message_args = null, $delete_session = true
209 /* Use format string if applicable */
210 if (is_string($message_args)) {
211 $error_message = sprintf($error_message, $message_args);
212 } elseif (is_array($message_args)) {
213 $error_message = vsprintf($error_message, $message_args);
216 if ($GLOBALS['is_ajax_request']) {
217 $response = PMA_Response::getInstance();
218 $response->isSuccess(false);
219 $response->addJSON('message', PMA_Message::error($error_message));
220 } else {
221 $error_message = strtr($error_message, array('<br />' => '[br]'));
223 /* Define fake gettext for fatal errors */
224 if (!function_exists('__')) {
225 function __($text)
227 return $text;
231 // these variables are used in the included file libraries/error.inc.php
232 $error_header = __('Error');
233 $lang = $GLOBALS['available_languages'][$GLOBALS['lang']][1];
234 $dir = $GLOBALS['text_dir'];
236 // on fatal errors it cannot hurt to always delete the current session
237 if ($delete_session
238 && isset($GLOBALS['session_name'])
239 && isset($_COOKIE[$GLOBALS['session_name']])
241 $GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
244 // Displays the error message
245 include './libraries/error.inc.php';
247 if (! defined('TESTSUITE')) {
248 exit;
253 * Returns a link to the PHP documentation
255 * @param string $target anchor in documentation
257 * @return string the URL
259 * @access public
261 function PMA_getPHPDocLink($target)
263 /* List of PHP documentation translations */
264 $php_doc_languages = array(
265 'pt_BR', 'zh', 'fr', 'de', 'it', 'ja', 'pl', 'ro', 'ru', 'fa', 'es', 'tr'
268 $lang = 'en';
269 if (in_array($GLOBALS['lang'], $php_doc_languages)) {
270 $lang = $GLOBALS['lang'];
273 return PMA_linkURL('http://php.net/manual/' . $lang . '/' . $target);
277 * Warn or fail on missing extension.
279 * @param string $extension Extension name
280 * @param bool $fatal Whether the error is fatal.
281 * @param string $extra Extra string to append to messsage.
283 * @return void
285 function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
287 /* Gettext does not have to be loaded yet here */
288 if (function_exists('__')) {
289 $message = __(
290 'The %s extension is missing. Please check your PHP configuration.'
292 } else {
293 $message
294 = 'The %s extension is missing. Please check your PHP configuration.';
296 $doclink = PMA_getPHPDocLink('book.' . $extension . '.php');
297 $message = sprintf(
298 $message,
299 '[a@' . $doclink . '@Documentation][em]' . $extension . '[/em][/a]'
301 if ($extra != '') {
302 $message .= ' ' . $extra;
304 if ($fatal) {
305 PMA_fatalError($message);
306 } else {
307 $GLOBALS['error_handler']->addError(
308 $message,
309 E_USER_WARNING,
312 false
318 * returns count of tables in given db
320 * @param string $db database to count tables for
322 * @return integer count of tables in $db
324 function PMA_getTableCount($db)
326 $tables = PMA_DBI_try_query(
327 'SHOW TABLES FROM ' . PMA_Util::backquote($db) . ';',
328 null, PMA_DBI_QUERY_STORE
330 if ($tables) {
331 $num_tables = PMA_DBI_num_rows($tables);
332 PMA_DBI_free_result($tables);
333 } else {
334 $num_tables = 0;
337 return $num_tables;
341 * Converts numbers like 10M into bytes
342 * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
343 * (renamed with PMA prefix to avoid double definition when embedded
344 * in Moodle)
346 * @param string $size size
348 * @return integer $size
350 function PMA_getRealSize($size = 0)
352 if (! $size) {
353 return 0;
356 $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
357 $scan['g'] = 1073741824; //1024 * 1024 * 1024;
358 $scan['mb'] = 1048576;
359 $scan['m'] = 1048576;
360 $scan['kb'] = 1024;
361 $scan['k'] = 1024;
362 $scan['b'] = 1;
364 foreach ($scan as $unit => $factor) {
365 if (strlen($size) > strlen($unit)
366 && strtolower(substr($size, strlen($size) - strlen($unit))) == $unit
368 return substr($size, 0, strlen($size) - strlen($unit)) * $factor;
372 return $size;
373 } // end function PMA_getRealSize()
376 * merges array recursive like array_merge_recursive() but keyed-values are
377 * always overwritten.
379 * array PMA_arrayMergeRecursive(array $array1[, array $array2[, array ...]])
381 * @return array merged array
383 * @see http://php.net/array_merge
384 * @see http://php.net/array_merge_recursive
386 function PMA_arrayMergeRecursive()
388 switch(func_num_args()) {
389 case 0 :
390 return false;
391 break;
392 case 1 :
393 // when does that happen?
394 return func_get_arg(0);
395 break;
396 case 2 :
397 $args = func_get_args();
398 if (! is_array($args[0]) || ! is_array($args[1])) {
399 return $args[1];
401 foreach ($args[1] as $key2 => $value2) {
402 if (isset($args[0][$key2]) && !is_int($key2)) {
403 $args[0][$key2] = PMA_arrayMergeRecursive(
404 $args[0][$key2], $value2
406 } else {
407 // we erase the parent array, otherwise we cannot override
408 // a directive that contains array elements, like this:
409 // (in config.default.php)
410 // $cfg['ForeignKeyDropdownOrder']= array('id-content','content-id');
411 // (in config.inc.php)
412 // $cfg['ForeignKeyDropdownOrder']= array('content-id');
413 if (is_int($key2) && $key2 == 0) {
414 unset($args[0]);
416 $args[0][$key2] = $value2;
419 return $args[0];
420 break;
421 default :
422 $args = func_get_args();
423 $args[1] = PMA_arrayMergeRecursive($args[0], $args[1]);
424 array_shift($args);
425 return call_user_func_array('PMA_arrayMergeRecursive', $args);
426 break;
431 * calls $function for every element in $array recursively
433 * this function is protected against deep recursion attack CVE-2006-1549,
434 * 1000 seems to be more than enough
436 * @param array &$array array to walk
437 * @param string $function function to call for every array element
438 * @param bool $apply_to_keys_also whether to call the function for the keys also
440 * @return void
442 * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
443 * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
445 function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
447 static $recursive_counter = 0;
448 if (++$recursive_counter > 1000) {
449 PMA_fatalError(__('possible deep recursion attack'));
451 foreach ($array as $key => $value) {
452 if (is_array($value)) {
453 PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
454 } else {
455 $array[$key] = $function($value);
458 if ($apply_to_keys_also && is_string($key)) {
459 $new_key = $function($key);
460 if ($new_key != $key) {
461 $array[$new_key] = $array[$key];
462 unset($array[$key]);
466 $recursive_counter--;
470 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
472 * checks given given $page against given $whitelist and returns true if valid
473 * it ignores optionaly query paramters in $page (script.php?ignored)
475 * @param string &$page page to check
476 * @param array $whitelist whitelist to check page against
478 * @return boolean whether $page is valid or not (in $whitelist or not)
480 function PMA_checkPageValidity(&$page, $whitelist)
482 if (! isset($page) || !is_string($page)) {
483 return false;
486 if (in_array($page, $whitelist)) {
487 return true;
488 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
489 return true;
490 } else {
491 $_page = urldecode($page);
492 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
493 return true;
496 return false;
500 * tries to find the value for the given environment variable name
502 * searches in $_SERVER, $_ENV then tries getenv() and apache_getenv()
503 * in this order
505 * @param string $var_name variable name
507 * @return string value of $var or empty string
509 function PMA_getenv($var_name)
511 if (isset($_SERVER[$var_name])) {
512 return $_SERVER[$var_name];
513 } elseif (isset($_ENV[$var_name])) {
514 return $_ENV[$var_name];
515 } elseif (getenv($var_name)) {
516 return getenv($var_name);
517 } elseif (function_exists('apache_getenv')
518 && apache_getenv($var_name, true)) {
519 return apache_getenv($var_name, true);
522 return '';
526 * Send HTTP header, taking IIS limits into account (600 seems ok)
528 * @param string $uri the header to send
529 * @param bool $use_refresh whether to use Refresh: header when running on IIS
531 * @return boolean always true
533 function PMA_sendHeaderLocation($uri, $use_refresh = false)
535 if (PMA_IS_IIS && strlen($uri) > 600) {
536 include_once './libraries/js_escape.lib.php';
537 PMA_Response::getInstance()->disable();
539 echo '<html><head><title>- - -</title>' . "\n";
540 echo '<meta http-equiv="expires" content="0">' . "\n";
541 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
542 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
543 echo '<meta http-equiv="Refresh" content="0;url='
544 . htmlspecialchars($uri) . '">' . "\n";
545 echo '<script type="text/javascript">' . "\n";
546 echo '//<![CDATA[' . "\n";
547 echo 'setTimeout("window.location = unescape(\'"'
548 . PMA_escapeJsString($uri) . '"\')", 2000);' . "\n";
549 echo '//]]>' . "\n";
550 echo '</script>' . "\n";
551 echo '</head>' . "\n";
552 echo '<body>' . "\n";
553 echo '<script type="text/javascript">' . "\n";
554 echo '//<![CDATA[' . "\n";
555 echo 'document.write(\'<p><a href="' . htmlspecialchars($uri) . '">'
556 . __('Go') . '</a></p>\');' . "\n";
557 echo '//]]>' . "\n";
558 echo '</script></body></html>' . "\n";
560 } else {
561 if (SID) {
562 if (strpos($uri, '?') === false) {
563 header('Location: ' . $uri . '?' . SID);
564 } else {
565 $separator = PMA_get_arg_separator();
566 header('Location: ' . $uri . $separator . SID);
568 } else {
569 session_write_close();
570 if (headers_sent()) {
571 if (function_exists('debug_print_backtrace')) {
572 echo '<pre>';
573 debug_print_backtrace();
574 echo '</pre>';
576 trigger_error(
577 'PMA_sendHeaderLocation called when headers are already sent!',
578 E_USER_ERROR
581 // bug #1523784: IE6 does not like 'Refresh: 0', it
582 // results in a blank page
583 // but we need it when coming from the cookie login panel)
584 if (PMA_IS_IIS && $use_refresh) {
585 header('Refresh: 0; ' . $uri);
586 } else {
587 header('Location: ' . $uri);
594 * Outputs headers to prevent caching in browser (and on the way).
596 * @return void
598 function PMA_noCacheHeader()
600 if (defined('TESTSUITE')) {
601 return;
603 // rfc2616 - Section 14.21
604 header('Expires: ' . date(DATE_RFC1123));
605 // HTTP/1.1
606 header(
607 'Cache-Control: no-store, no-cache, must-revalidate,'
608 . ' pre-check=0, post-check=0, max-age=0'
610 if (PMA_USR_BROWSER_AGENT == 'IE') {
611 /* On SSL IE sometimes fails with:
613 * Internet Explorer was not able to open this Internet site. The
614 * requested site is either unavailable or cannot be found. Please
615 * try again later.
617 * Adding Pragma: public fixes this.
619 header('Pragma: public');
620 } else {
621 header('Pragma: no-cache'); // HTTP/1.0
622 // test case: exporting a database into a .gz file with Safari
623 // would produce files not having the current time
624 // (added this header for Safari but should not harm other browsers)
625 header('Last-Modified: ' . date(DATE_RFC1123));
631 * Sends header indicating file download.
633 * @param string $filename Filename to include in headers if empty,
634 * none Content-Disposition header will be sent.
635 * @param string $mimetype MIME type to include in headers.
636 * @param int $length Length of content (optional)
637 * @param bool $no_cache Whether to include no-caching headers.
639 * @return void
641 function PMA_downloadHeader($filename, $mimetype, $length = 0, $no_cache = true)
643 if ($no_cache) {
644 PMA_noCacheHeader();
646 /* Replace all possibly dangerous chars in filename */
647 $filename = str_replace(array(';', '"', "\n", "\r"), '-', $filename);
648 if (!empty($filename)) {
649 header('Content-Description: File Transfer');
650 header('Content-Disposition: attachment; filename="' . $filename . '"');
652 header('Content-Type: ' . $mimetype);
653 header('Content-Transfer-Encoding: binary');
654 if ($length > 0) {
655 header('Content-Length: ' . $length);
661 * Returns value of an element in $array given by $path.
662 * $path is a string describing position of an element in an associative array,
663 * eg. Servers/1/host refers to $array[Servers][1][host]
665 * @param string $path path in the arry
666 * @param array $array the array
667 * @param mixed $default default value
669 * @return mixed array element or $default
671 function PMA_arrayRead($path, $array, $default = null)
673 $keys = explode('/', $path);
674 $value =& $array;
675 foreach ($keys as $key) {
676 if (! isset($value[$key])) {
677 return $default;
679 $value =& $value[$key];
681 return $value;
685 * Stores value in an array
687 * @param string $path path in the array
688 * @param array &$array the array
689 * @param mixed $value value to store
691 * @return void
693 function PMA_arrayWrite($path, &$array, $value)
695 $keys = explode('/', $path);
696 $last_key = array_pop($keys);
697 $a =& $array;
698 foreach ($keys as $key) {
699 if (! isset($a[$key])) {
700 $a[$key] = array();
702 $a =& $a[$key];
704 $a[$last_key] = $value;
708 * Removes value from an array
710 * @param string $path path in the array
711 * @param array &$array the array
713 * @return void
715 function PMA_arrayRemove($path, &$array)
717 $keys = explode('/', $path);
718 $keys_last = array_pop($keys);
719 $path = array();
720 $depth = 0;
722 $path[0] =& $array;
723 $found = true;
724 // go as deep as required or possible
725 foreach ($keys as $key) {
726 if (! isset($path[$depth][$key])) {
727 $found = false;
728 break;
730 $depth++;
731 $path[$depth] =& $path[$depth-1][$key];
733 // if element found, remove it
734 if ($found) {
735 unset($path[$depth][$keys_last]);
736 $depth--;
739 // remove empty nested arrays
740 for (; $depth >= 0; $depth--) {
741 if (! isset($path[$depth+1]) || count($path[$depth+1]) == 0) {
742 unset($path[$depth][$keys[$depth]]);
743 } else {
744 break;
750 * Returns link to (possibly) external site using defined redirector.
752 * @param string $url URL where to go.
754 * @return string URL for a link.
756 function PMA_linkURL($url)
758 if (!preg_match('#^https?://#', $url) || defined('PMA_SETUP')) {
759 return $url;
760 } else {
761 if (!function_exists('PMA_generate_common_url')) {
762 include_once './libraries/url_generating.lib.php';
764 $params = array();
765 $params['url'] = $url;
766 return './url.php' . PMA_generate_common_url($params);
771 * Adds JS code snippets to be displayed by the PMA_Response class.
772 * Adds a newline to each snippet.
774 * @param string $str Js code to be added (e.g. "token=1234;")
776 * @return void
778 function PMA_addJSCode($str)
780 $response = PMA_Response::getInstance();
781 $header = $response->getHeader();
782 $scripts = $header->getScripts();
783 $scripts->addCode($str);
787 * Adds JS code snippet for variable assignment
788 * to be displayed by the PMA_Response class.
790 * @param string $key Name of value to set
791 * @param mixed $value Value to set, can be either string or array of strings
792 * @param bool $escape Whether to escape value or keep it as it is
793 * (for inclusion of js code)
795 * @return void
797 function PMA_addJSVar($key, $value, $escape = true)
799 PMA_addJSCode(PMA_getJsValue($key, $value, $escape));