2 /* vim: set expandtab sw=4 ts=4 sts=4: */
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.
10 if (! defined('PHPMYADMIN')) {
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
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
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
43 function PMA_ifSetOr(&$var, $default = null, $type = 'similar')
45 if (! PMA_isValid($var, $type, $default)) {
53 * checks given $var against $type or $compare
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
66 * // $_REQUEST['doit'] = true;
67 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false
68 * // $_REQUEST['doit'] = 'true';
69 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true
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:
77 * isset($var); // false
78 * functionCallByReference($var); // false
79 * isset($var); // true
80 * functionCallByReference($var); // true
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)
97 // var is not even set
101 if ($type === false) {
102 // no vartype requested
106 if (is_array($type)) {
107 return in_array($var, $type);
110 // allow some aliaes of var types
111 $type = strtolower($type);
133 if ($type === 'identical') {
134 return $var === $compare;
137 // whether we should check against given $compare
138 if ($type === 'similar') {
139 switch (gettype($compare)) {
149 $type = gettype($compare);
151 } elseif ($type === 'equal') {
152 $type = gettype($compare);
156 if ($type === 'length' ||
$type === 'scalar') {
157 $is_scalar = is_scalar($var);
158 if ($is_scalar && $type === 'length') {
159 return (bool) strlen($var);
164 if ($type === 'numeric') {
165 return is_numeric($var);
168 if (gettype($var) === $type) {
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
186 function PMA_securePath($path)
189 $path = preg_replace('@\.\.*@', '.', $path);
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
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));
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
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')) {
250 * Returns a link to the PHP documentation
252 * @param string $target anchor in documentation
254 * @return string the URL
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'
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.
282 function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
284 /* Gettext does not have to be loaded yet here */
285 if (function_exists('__')) {
287 'The %s extension is missing. Please check your PHP configuration.'
291 = 'The %s extension is missing. Please check your PHP configuration.';
293 $doclink = PMA_getPHPDocLink('book.' . $extension . '.php');
296 '[a@' . $doclink . '@Documentation][em]' . $extension . '[/em][/a]'
299 $message .= ' ' . $extra;
302 PMA_fatalError($message);
304 $GLOBALS['error_handler']->addError(
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
328 $num_tables = $GLOBALS['dbi']->numRows($tables);
329 $GLOBALS['dbi']->freeResult($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
343 * @param string $size size
345 * @return integer $size
347 function PMA_getRealSize($size = 0)
353 $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
354 $scan['g'] = 1073741824; //1024 * 1024 * 1024;
355 $scan['mb'] = 1048576;
356 $scan['m'] = 1048576;
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;
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()) {
390 // when does that happen?
391 return func_get_arg(0);
394 $args = func_get_args();
395 if (! is_array($args[0]) ||
! is_array($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
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) {
413 $args[0][$key2] = $value2;
419 $args = func_get_args();
420 $args[1] = PMA_arrayMergeRecursive($args[0], $args[1]);
422 return call_user_func_array('PMA_arrayMergeRecursive', $args);
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
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);
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];
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)) {
483 if (in_array($page, $whitelist)) {
485 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
488 $_page = urldecode($page);
489 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
497 * tries to find the value for the given environment variable name
499 * searches in $_SERVER, $_ENV then tries getenv() and apache_getenv()
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);
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";
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";
556 echo '</script></body></html>' . "\n";
560 if (strpos($uri, '?') === false) {
561 header('Location: ' . $uri . '?' . SID
);
563 $separator = PMA_URL_getArgSeparator();
564 header('Location: ' . $uri . $separator . SID
);
567 session_write_close();
568 if (headers_sent()) {
569 if (function_exists('debug_print_backtrace')) {
571 debug_print_backtrace();
575 'PMA_sendHeaderLocation called when headers are already sent!',
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);
585 header('Location: ' . $uri);
592 * Outputs headers to prevent caching in browser (and on the way).
596 function PMA_noCacheHeader()
598 if (defined('TESTSUITE')) {
601 // rfc2616 - Section 14.21
602 header('Expires: ' . date(DATE_RFC1123
));
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
615 * Adding Pragma: public fixes this.
617 header('Pragma: public');
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.
639 function PMA_downloadHeader($filename, $mimetype, $length = 0, $no_cache = true)
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');
653 header('Content-Length: ' . $length);
659 * Returns value of an element in $array given by $path.
660 * $path is a string describing position of an element in an associative array,
661 * eg. Servers/1/host refers to $array[Servers][1][host]
663 * @param string $path path in the arry
664 * @param array $array the array
665 * @param mixed $default default value
667 * @return mixed array element or $default
669 function PMA_arrayRead($path, $array, $default = null)
671 $keys = explode('/', $path);
673 foreach ($keys as $key) {
674 if (! isset($value[$key])) {
677 $value =& $value[$key];
683 * Stores value in an array
685 * @param string $path path in the array
686 * @param array &$array the array
687 * @param mixed $value value to store
691 function PMA_arrayWrite($path, &$array, $value)
693 $keys = explode('/', $path);
694 $last_key = array_pop($keys);
696 foreach ($keys as $key) {
697 if (! isset($a[$key])) {
702 $a[$last_key] = $value;
706 * Removes value from an array
708 * @param string $path path in the array
709 * @param array &$array the array
713 function PMA_arrayRemove($path, &$array)
715 $keys = explode('/', $path);
716 $keys_last = array_pop($keys);
722 // go as deep as required or possible
723 foreach ($keys as $key) {
724 if (! isset($path[$depth][$key])) {
729 $path[$depth] =& $path[$depth-1][$key];
731 // if element found, remove it
733 unset($path[$depth][$keys_last]);
737 // remove empty nested arrays
738 for (; $depth >= 0; $depth--) {
739 if (! isset($path[$depth+
1]) ||
count($path[$depth+
1]) == 0) {
740 unset($path[$depth][$keys[$depth]]);
748 * Returns link to (possibly) external site using defined redirector.
750 * @param string $url URL where to go.
752 * @return string URL for a link.
754 function PMA_linkURL($url)
756 if (!preg_match('#^https?://#', $url) ||
defined('PMA_SETUP')) {
759 if (!function_exists('PMA_URL_getCommon')) {
760 include_once './libraries/url_generating.lib.php';
763 $params['url'] = $url;
764 return './url.php' . PMA_URL_getCommon($params);
769 * Adds JS code snippets to be displayed by the PMA_Response class.
770 * Adds a newline to each snippet.
772 * @param string $str Js code to be added (e.g. "token=1234;")
776 function PMA_addJSCode($str)
778 $response = PMA_Response
::getInstance();
779 $header = $response->getHeader();
780 $scripts = $header->getScripts();
781 $scripts->addCode($str);
785 * Adds JS code snippet for variable assignment
786 * to be displayed by the PMA_Response class.
788 * @param string $key Name of value to set
789 * @param mixed $value Value to set, can be either string or array of strings
790 * @param bool $escape Whether to escape value or keep it as it is
791 * (for inclusion of js code)
795 function PMA_addJSVar($key, $value, $escape = true)
797 PMA_addJSCode(PMA_getJsValue($key, $value, $escape));