Refactored ConfigFile class so that it is no longer a singleton
[phpmyadmin.git] / libraries / core.lib.php
blobc58ad31a4f487aec0691dbc343102d4e06ac26a6
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 representation
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 /* Load gettext for fatal errors */
224 if (!function_exists('__')) {
225 include_once './libraries/php-gettext/gettext.inc';
228 // these variables are used in the included file libraries/error.inc.php
229 $error_header = __('Error');
230 $lang = $GLOBALS['available_languages'][$GLOBALS['lang']][1];
231 $dir = $GLOBALS['text_dir'];
233 // on fatal errors it cannot hurt to always delete the current session
234 if ($delete_session
235 && isset($GLOBALS['session_name'])
236 && isset($_COOKIE[$GLOBALS['session_name']])
238 $GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
241 // Displays the error message
242 include './libraries/error.inc.php';
244 if (! defined('TESTSUITE')) {
245 exit;
250 * Returns a link to the PHP documentation
252 * @param string $target anchor in documentation
254 * @return string the URL
256 * @access public
258 function PMA_getPHPDocLink($target)
260 /* List of PHP documentation translations */
261 $php_doc_languages = array(
262 'pt_BR', 'zh', 'fr', 'de', 'it', 'ja', 'pl', 'ro', 'ru', 'fa', 'es', 'tr'
265 $lang = 'en';
266 if (in_array($GLOBALS['lang'], $php_doc_languages)) {
267 $lang = $GLOBALS['lang'];
270 return PMA_linkURL('http://php.net/manual/' . $lang . '/' . $target);
274 * Warn or fail on missing extension.
276 * @param string $extension Extension name
277 * @param bool $fatal Whether the error is fatal.
278 * @param string $extra Extra string to append to messsage.
280 * @return void
282 function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
284 /* Gettext does not have to be loaded yet here */
285 if (function_exists('__')) {
286 $message = __(
287 'The %s extension is missing. Please check your PHP configuration.'
289 } else {
290 $message
291 = 'The %s extension is missing. Please check your PHP configuration.';
293 $doclink = PMA_getPHPDocLink('book.' . $extension . '.php');
294 $message = sprintf(
295 $message,
296 '[a@' . $doclink . '@Documentation][em]' . $extension . '[/em][/a]'
298 if ($extra != '') {
299 $message .= ' ' . $extra;
301 if ($fatal) {
302 PMA_fatalError($message);
303 } else {
304 $GLOBALS['error_handler']->addError(
305 $message,
306 E_USER_WARNING,
309 false
315 * returns count of tables in given db
317 * @param string $db database to count tables for
319 * @return integer count of tables in $db
321 function PMA_getTableCount($db)
323 $tables = $GLOBALS['dbi']->tryQuery(
324 'SHOW TABLES FROM ' . PMA_Util::backquote($db) . ';',
325 null, PMA_DatabaseInterface::QUERY_STORE
327 if ($tables) {
328 $num_tables = $GLOBALS['dbi']->numRows($tables);
329 $GLOBALS['dbi']->freeResult($tables);
330 } else {
331 $num_tables = 0;
334 return $num_tables;
338 * Converts numbers like 10M into bytes
339 * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
340 * (renamed with PMA prefix to avoid double definition when embedded
341 * in Moodle)
343 * @param string $size size
345 * @return integer $size
347 function PMA_getRealSize($size = 0)
349 if (! $size) {
350 return 0;
353 $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
354 $scan['g'] = 1073741824; //1024 * 1024 * 1024;
355 $scan['mb'] = 1048576;
356 $scan['m'] = 1048576;
357 $scan['kb'] = 1024;
358 $scan['k'] = 1024;
359 $scan['b'] = 1;
361 foreach ($scan as $unit => $factor) {
362 if (strlen($size) > strlen($unit)
363 && strtolower(substr($size, strlen($size) - strlen($unit))) == $unit
365 return substr($size, 0, strlen($size) - strlen($unit)) * $factor;
369 return $size;
370 } // end function PMA_getRealSize()
373 * merges array recursive like array_merge_recursive() but keyed-values are
374 * always overwritten.
376 * array PMA_arrayMergeRecursive(array $array1[, array $array2[, array ...]])
378 * @return array merged array
380 * @see http://php.net/array_merge
381 * @see http://php.net/array_merge_recursive
383 function PMA_arrayMergeRecursive()
385 switch(func_num_args()) {
386 case 0 :
387 return false;
388 break;
389 case 1 :
390 // when does that happen?
391 return func_get_arg(0);
392 break;
393 case 2 :
394 $args = func_get_args();
395 if (! is_array($args[0]) || ! is_array($args[1])) {
396 return $args[1];
398 foreach ($args[1] as $key2 => $value2) {
399 if (isset($args[0][$key2]) && !is_int($key2)) {
400 $args[0][$key2] = PMA_arrayMergeRecursive(
401 $args[0][$key2], $value2
403 } else {
404 // we erase the parent array, otherwise we cannot override
405 // a directive that contains array elements, like this:
406 // (in config.default.php)
407 // $cfg['ForeignKeyDropdownOrder']= array('id-content','content-id');
408 // (in config.inc.php)
409 // $cfg['ForeignKeyDropdownOrder']= array('content-id');
410 if (is_int($key2) && $key2 == 0) {
411 unset($args[0]);
413 $args[0][$key2] = $value2;
416 return $args[0];
417 break;
418 default :
419 $args = func_get_args();
420 $args[1] = PMA_arrayMergeRecursive($args[0], $args[1]);
421 array_shift($args);
422 return call_user_func_array('PMA_arrayMergeRecursive', $args);
423 break;
428 * calls $function for every element in $array recursively
430 * this function is protected against deep recursion attack CVE-2006-1549,
431 * 1000 seems to be more than enough
433 * @param array &$array array to walk
434 * @param string $function function to call for every array element
435 * @param bool $apply_to_keys_also whether to call the function for the keys also
437 * @return void
439 * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
440 * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
442 function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
444 static $recursive_counter = 0;
445 if (++$recursive_counter > 1000) {
446 PMA_fatalError(__('possible deep recursion attack'));
448 foreach ($array as $key => $value) {
449 if (is_array($value)) {
450 PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
451 } else {
452 $array[$key] = $function($value);
455 if ($apply_to_keys_also && is_string($key)) {
456 $new_key = $function($key);
457 if ($new_key != $key) {
458 $array[$new_key] = $array[$key];
459 unset($array[$key]);
463 $recursive_counter--;
467 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
469 * checks given given $page against given $whitelist and returns true if valid
470 * it ignores optionaly query paramters in $page (script.php?ignored)
472 * @param string &$page page to check
473 * @param array $whitelist whitelist to check page against
475 * @return boolean whether $page is valid or not (in $whitelist or not)
477 function PMA_checkPageValidity(&$page, $whitelist)
479 if (! isset($page) || !is_string($page)) {
480 return false;
483 if (in_array($page, $whitelist)) {
484 return true;
485 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
486 return true;
487 } else {
488 $_page = urldecode($page);
489 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
490 return true;
493 return false;
497 * tries to find the value for the given environment variable name
499 * searches in $_SERVER, $_ENV then tries getenv() and apache_getenv()
500 * in this order
502 * @param string $var_name variable name
504 * @return string value of $var or empty string
506 function PMA_getenv($var_name)
508 if (isset($_SERVER[$var_name])) {
509 return $_SERVER[$var_name];
510 } elseif (isset($_ENV[$var_name])) {
511 return $_ENV[$var_name];
512 } elseif (getenv($var_name)) {
513 return getenv($var_name);
514 } elseif (function_exists('apache_getenv')
515 && apache_getenv($var_name, true)
517 return apache_getenv($var_name, true);
520 return '';
524 * Send HTTP header, taking IIS limits into account (600 seems ok)
526 * @param string $uri the header to send
527 * @param bool $use_refresh whether to use Refresh: header when running on IIS
529 * @return boolean always true
531 function PMA_sendHeaderLocation($uri, $use_refresh = false)
533 if (PMA_IS_IIS && strlen($uri) > 600) {
534 include_once './libraries/js_escape.lib.php';
535 PMA_Response::getInstance()->disable();
537 echo '<html><head><title>- - -</title>' . "\n";
538 echo '<meta http-equiv="expires" content="0">' . "\n";
539 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
540 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
541 echo '<meta http-equiv="Refresh" content="0;url='
542 . htmlspecialchars($uri) . '">' . "\n";
543 echo '<script type="text/javascript">' . "\n";
544 echo '//<![CDATA[' . "\n";
545 echo 'setTimeout("window.location = unescape(\'"'
546 . PMA_escapeJsString($uri) . '"\')", 2000);' . "\n";
547 echo '//]]>' . "\n";
548 echo '</script>' . "\n";
549 echo '</head>' . "\n";
550 echo '<body>' . "\n";
551 echo '<script type="text/javascript">' . "\n";
552 echo '//<![CDATA[' . "\n";
553 echo 'document.write(\'<p><a href="' . htmlspecialchars($uri) . '">'
554 . __('Go') . '</a></p>\');' . "\n";
555 echo '//]]>' . "\n";
556 echo '</script></body></html>' . "\n";
558 } else {
559 if (SID) {
560 if (strpos($uri, '?') === false) {
561 header('Location: ' . $uri . '?' . SID);
562 } else {
563 $separator = PMA_URL_getArgSeparator();
564 header('Location: ' . $uri . $separator . SID);
566 } else {
567 session_write_close();
568 if (headers_sent()) {
569 if (function_exists('debug_print_backtrace')) {
570 echo '<pre>';
571 debug_print_backtrace();
572 echo '</pre>';
574 trigger_error(
575 'PMA_sendHeaderLocation called when headers are already sent!',
576 E_USER_ERROR
579 // bug #1523784: IE6 does not like 'Refresh: 0', it
580 // results in a blank page
581 // but we need it when coming from the cookie login panel)
582 if (PMA_IS_IIS && $use_refresh) {
583 header('Refresh: 0; ' . $uri);
584 } else {
585 header('Location: ' . $uri);
592 * Outputs headers to prevent caching in browser (and on the way).
594 * @return void
596 function PMA_noCacheHeader()
598 if (defined('TESTSUITE')) {
599 return;
601 // rfc2616 - Section 14.21
602 header('Expires: ' . date(DATE_RFC1123));
603 // HTTP/1.1
604 header(
605 'Cache-Control: no-store, no-cache, must-revalidate,'
606 . ' pre-check=0, post-check=0, max-age=0'
608 if (PMA_USR_BROWSER_AGENT == 'IE') {
609 /* On SSL IE sometimes fails with:
611 * Internet Explorer was not able to open this Internet site. The
612 * requested site is either unavailable or cannot be found. Please
613 * try again later.
615 * Adding Pragma: public fixes this.
617 header('Pragma: public');
618 } else {
619 header('Pragma: no-cache'); // HTTP/1.0
620 // test case: exporting a database into a .gz file with Safari
621 // would produce files not having the current time
622 // (added this header for Safari but should not harm other browsers)
623 header('Last-Modified: ' . date(DATE_RFC1123));
629 * Sends header indicating file download.
631 * @param string $filename Filename to include in headers if empty,
632 * none Content-Disposition header will be sent.
633 * @param string $mimetype MIME type to include in headers.
634 * @param int $length Length of content (optional)
635 * @param bool $no_cache Whether to include no-caching headers.
637 * @return void
639 function PMA_downloadHeader($filename, $mimetype, $length = 0, $no_cache = true)
641 if ($no_cache) {
642 PMA_noCacheHeader();
644 /* Replace all possibly dangerous chars in filename */
645 $filename = str_replace(array(';', '"', "\n", "\r"), '-', $filename);
646 if (!empty($filename)) {
647 header('Content-Description: File Transfer');
648 header('Content-Disposition: attachment; filename="' . $filename . '"');
650 header('Content-Type: ' . $mimetype);
651 header('Content-Transfer-Encoding: binary');
652 if ($length > 0) {
653 header('Content-Length: ' . $length);
658 * Checks whether element given by $path exists in $array.
659 * $path is a string describing position of an element in an associative array,
660 * eg. Servers/1/host refers to $array[Servers][1][host]
662 * @param string $path path in the arry
663 * @param array $array the array
665 * @return mixed array element or $default
667 function PMA_arrayKeyExists($path, $array)
669 $keys = explode('/', $path);
670 $value =& $array;
671 foreach ($keys as $key) {
672 if (! isset($value[$key])) {
673 return false;
675 $value =& $value[$key];
677 return true;
681 * Returns value of an element in $array given by $path.
682 * $path is a string describing position of an element in an associative array,
683 * eg. Servers/1/host refers to $array[Servers][1][host]
685 * @param string $path path in the arry
686 * @param array $array the array
687 * @param mixed $default default value
689 * @return mixed array element or $default
691 function PMA_arrayRead($path, $array, $default = null)
693 $keys = explode('/', $path);
694 $value =& $array;
695 foreach ($keys as $key) {
696 if (! isset($value[$key])) {
697 return $default;
699 $value =& $value[$key];
701 return $value;
705 * Stores value in an array
707 * @param string $path path in the array
708 * @param array &$array the array
709 * @param mixed $value value to store
711 * @return void
713 function PMA_arrayWrite($path, &$array, $value)
715 $keys = explode('/', $path);
716 $last_key = array_pop($keys);
717 $a =& $array;
718 foreach ($keys as $key) {
719 if (! isset($a[$key])) {
720 $a[$key] = array();
722 $a =& $a[$key];
724 $a[$last_key] = $value;
728 * Removes value from an array
730 * @param string $path path in the array
731 * @param array &$array the array
733 * @return void
735 function PMA_arrayRemove($path, &$array)
737 $keys = explode('/', $path);
738 $keys_last = array_pop($keys);
739 $path = array();
740 $depth = 0;
742 $path[0] =& $array;
743 $found = true;
744 // go as deep as required or possible
745 foreach ($keys as $key) {
746 if (! isset($path[$depth][$key])) {
747 $found = false;
748 break;
750 $depth++;
751 $path[$depth] =& $path[$depth-1][$key];
753 // if element found, remove it
754 if ($found) {
755 unset($path[$depth][$keys_last]);
756 $depth--;
759 // remove empty nested arrays
760 for (; $depth >= 0; $depth--) {
761 if (! isset($path[$depth+1]) || count($path[$depth+1]) == 0) {
762 unset($path[$depth][$keys[$depth]]);
763 } else {
764 break;
770 * Returns link to (possibly) external site using defined redirector.
772 * @param string $url URL where to go.
774 * @return string URL for a link.
776 function PMA_linkURL($url)
778 if (!preg_match('#^https?://#', $url) || defined('PMA_SETUP')) {
779 return $url;
780 } else {
781 if (!function_exists('PMA_URL_getCommon')) {
782 include_once './libraries/url_generating.lib.php';
784 $params = array();
785 $params['url'] = $url;
786 return './url.php' . PMA_URL_getCommon($params);
791 * Adds JS code snippets to be displayed by the PMA_Response class.
792 * Adds a newline to each snippet.
794 * @param string $str Js code to be added (e.g. "token=1234;")
796 * @return void
798 function PMA_addJSCode($str)
800 $response = PMA_Response::getInstance();
801 $header = $response->getHeader();
802 $scripts = $header->getScripts();
803 $scripts->addCode($str);
807 * Adds JS code snippet for variable assignment
808 * to be displayed by the PMA_Response class.
810 * @param string $key Name of value to set
811 * @param mixed $value Value to set, can be either string or array of strings
812 * @param bool $escape Whether to escape value or keep it as it is
813 * (for inclusion of js code)
815 * @return void
817 function PMA_addJSVar($key, $value, $escape = true)
819 PMA_addJSCode(PMA_getJsValue($key, $value, $escape));