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.
12 * checks given $var and returns it if valid, or $default of not valid
13 * given $var is also checked for type being 'similar' as $default
14 * or against any other type if $type is provided
17 * // $_REQUEST['db'] not set
18 * echo PMA_ifSetOr($_REQUEST['db'], ''); // ''
19 * // $_REQUEST['sql_query'] not set
20 * echo PMA_ifSetOr($_REQUEST['sql_query']); // null
21 * // $cfg['ForceSSL'] not set
22 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
23 * echo PMA_ifSetOr($cfg['ForceSSL']); // null
24 * // $cfg['ForceSSL'] set to 1
25 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
26 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'similar'); // 1
27 * echo PMA_ifSetOr($cfg['ForceSSL'], false); // 1
28 * // $cfg['ForceSSL'] set to true
29 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // true
34 * @param mixed $var param to check
35 * @param mixed $default default value
36 * @param mixed $type var type or array of values to check against $var
37 * @return mixed $var or $default
39 function PMA_ifSetOr(&$var, $default = null, $type = 'similar')
41 if (! PMA_isValid($var, $type, $default)) {
49 * checks given $var against $type or $compare
52 * - false : no type checking
53 * - 'scalar' : whether type of $var is integer, float, string or boolean
54 * - 'numeric' : whether type of $var is any number repesentation
55 * - 'length' : whether type of $var is scalar with a string length > 0
56 * - 'similar' : whether type of $var is similar to type of $compare
57 * - 'equal' : whether type of $var is identical to type of $compare
58 * - 'identical' : whether $var is identical to $compare, not only the type!
59 * - or any other valid PHP variable type
62 * // $_REQUEST['doit'] = true;
63 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false
64 * // $_REQUEST['doit'] = 'true';
65 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true
68 * NOTE: call-by-reference is used to not get NOTICE on undefined vars,
69 * but the var is not altered inside this function, also after checking a var
70 * this var exists nut is not set, example:
73 * isset($var); // false
74 * functionCallByReference($var); // false
75 * isset($var); // true
76 * functionCallByReference($var); // true
79 * to avoid this we set this var to null if not isset
81 * @todo create some testsuites
82 * @todo add some more var types like hex, bin, ...?
89 * @see http://php.net/gettype
90 * @param mixed $var variable to check
91 * @param mixed $type var type or array of valid values to check against $var
92 * @param mixed $compare var to compare with $var
93 * @return boolean whether valid or not
95 function PMA_isValid(&$var, $type = 'length', $compare = null)
98 // var is not even set
102 if ($type === false) {
103 // no vartype requested
107 if (is_array($type)) {
108 return in_array($var, $type);
111 // allow some aliaes of var types
112 $type = strtolower($type);
134 if ($type === 'identical') {
135 return $var === $compare;
138 // whether we should check against given $compare
139 if ($type === 'similar') {
140 switch (gettype($compare)) {
150 $type = gettype($compare);
152 } elseif ($type === 'equal') {
153 $type = gettype($compare);
157 if ($type === 'length' ||
$type === 'scalar') {
158 $is_scalar = is_scalar($var);
159 if ($is_scalar && $type === 'length') {
160 return (bool) strlen($var);
165 if ($type === 'numeric') {
166 return is_numeric($var);
169 if (gettype($var) === $type) {
177 * Removes insecure parts in a path; used before include() or
178 * require() when a part of the path comes from an insecure source
179 * like a cookie or form.
181 * @param string The path to check
183 * @return string The secured path
187 function PMA_securePath($path)
190 $path = preg_replace('@\.\.*@', '.', $path);
196 * displays the given error message on phpMyAdmin error page in foreign language,
197 * ends script execution and closes session
199 * loads language file if not loaded already
201 * @todo use detected argument separator (PMA_Config)
202 * @uses $GLOBALS['session_name']
203 * @uses $GLOBALS['text_dir']
204 * @uses $GLOBALS['available_languages']
205 * @uses $GLOBALS['lang']
206 * @uses $GLOBALS['PMA_Config']->removeCookie()
207 * @uses select_lang.lib.php
211 * @uses http_build_query()
217 * @param string $error_message the error message or named error message
218 * @param string|array $message_args arguments applied to $error_message
221 function PMA_fatalError($error_message, $message_args = null)
223 /* Use format string if applicable */
224 if (is_string($message_args)) {
225 $error_message = sprintf($error_message, $message_args);
226 } elseif (is_array($message_args)) {
227 $error_message = vsprintf($error_message, $message_args);
229 $error_message = strtr($error_message, array('<br />' => '[br]'));
231 if (function_exists('__')) {
232 $error_header = __('Error');
234 $error_header = 'Error';
237 // Displays the error message
238 $lang = $GLOBALS['available_languages'][$GLOBALS['lang']][1];
239 $dir = $GLOBALS['text_dir'];
240 $type = $error_header;
241 $error = $error_message;
243 // on fatal errors it cannot hurt to always delete the current session
244 if (isset($GLOBALS['session_name']) && isset($_COOKIE[$GLOBALS['session_name']])) {
245 $GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
248 require('./libraries/error.inc.php');
254 * Warn or fail on missing extension.
256 * @param string $extension Extension name
257 * @param bool $fatal Whether the error is fatal.
258 / @param string $extra Extra string to append to messsage.
260 function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
262 $message = sprintf(__('The %s extension is missing. Please check your PHP configuration.'),
263 sprintf('[a@http://php.net/%1$s@Documentation][em]%1$s[/em][/a]', $extension));
265 $message .= ' ' . $extra;
268 PMA_fatalError($message);
270 trigger_error($message, E_USER_WARNING
);
275 * returns count of tables in given db
277 * @uses PMA_DBI_try_query()
278 * @uses PMA_backquote()
279 * @uses PMA_DBI_QUERY_STORE()
280 * @uses PMA_DBI_num_rows()
281 * @uses PMA_DBI_free_result()
282 * @param string $db database to count tables for
283 * @return integer count of tables in $db
285 function PMA_getTableCount($db)
287 $tables = PMA_DBI_try_query(
288 'SHOW TABLES FROM ' . PMA_backquote($db) . ';',
289 null, PMA_DBI_QUERY_STORE
);
291 $num_tables = PMA_DBI_num_rows($tables);
293 // do not count hidden blobstreaming tables
294 while ((($num_tables > 0)) && $data = PMA_DBI_fetch_assoc($tables)) {
295 if (PMA_BS_IsHiddenTable($data['Tables_in_' . $db])) {
300 PMA_DBI_free_result($tables);
309 * Converts numbers like 10M into bytes
310 * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
311 * (renamed with PMA prefix to avoid double definition when embedded
317 * @param string $size
318 * @return integer $size
320 function PMA_get_real_size($size = 0)
326 $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
327 $scan['g'] = 1073741824; //1024 * 1024 * 1024;
328 $scan['mb'] = 1048576;
329 $scan['m'] = 1048576;
334 foreach ($scan as $unit => $factor) {
335 if (strlen($size) > strlen($unit)
336 && strtolower(substr($size, strlen($size) - strlen($unit))) == $unit) {
337 return substr($size, 0, strlen($size) - strlen($unit)) * $factor;
342 } // end function PMA_get_real_size()
345 * merges array recursive like array_merge_recursive() but keyed-values are
346 * always overwritten.
348 * array PMA_array_merge_recursive(array $array1[, array $array2[, array ...]])
350 * @see http://php.net/array_merge
351 * @see http://php.net/array_merge_recursive
352 * @uses func_num_args()
353 * @uses func_get_arg()
355 * @uses call_user_func_array()
356 * @param array array to merge
357 * @param array array to merge
359 * @return array merged array
361 function PMA_array_merge_recursive()
363 switch(func_num_args()) {
368 // when does that happen?
369 return func_get_arg(0);
372 $args = func_get_args();
373 if (!is_array($args[0]) ||
!is_array($args[1])) {
376 foreach ($args[1] as $key2 => $value2) {
377 if (isset($args[0][$key2]) && !is_int($key2)) {
378 $args[0][$key2] = PMA_array_merge_recursive($args[0][$key2],
381 // we erase the parent array, otherwise we cannot override a directive that
382 // contains array elements, like this:
383 // (in config.default.php) $cfg['ForeignKeyDropdownOrder'] = array('id-content','content-id');
384 // (in config.inc.php) $cfg['ForeignKeyDropdownOrder'] = array('content-id');
385 if (is_int($key2) && $key2 == 0) {
388 $args[0][$key2] = $value2;
394 $args = func_get_args();
395 $args[1] = PMA_array_merge_recursive($args[0], $args[1]);
397 return call_user_func_array('PMA_array_merge_recursive', $args);
403 * calls $function vor every element in $array recursively
405 * this function is protected against deep recursion attack CVE-2006-1549,
406 * 1000 seems to be more than enough
408 * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
409 * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
411 * @uses PMA_arrayWalkRecursive()
414 * @param array $array array to walk
415 * @param string $function function to call for every array element
417 function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
419 static $recursive_counter = 0;
420 if (++
$recursive_counter > 1000) {
421 die('possible deep recursion attack');
423 foreach ($array as $key => $value) {
424 if (is_array($value)) {
425 PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
427 $array[$key] = $function($value);
430 if ($apply_to_keys_also && is_string($key)) {
431 $new_key = $function($key);
432 if ($new_key != $key) {
433 $array[$new_key] = $array[$key];
438 $recursive_counter--;
442 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
444 * checks given given $page against given $whitelist and returns true if valid
445 * it ignores optionaly query paramters in $page (script.php?ignored)
451 * @param string &$page page to check
452 * @param array $whitelist whitelist to check page against
453 * @return boolean whether $page is valid or not (in $whitelist or not)
455 function PMA_checkPageValidity(&$page, $whitelist)
457 if (! isset($page) ||
!is_string($page)) {
461 if (in_array($page, $whitelist)) {
463 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
466 $_page = urldecode($page);
467 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
475 * trys to find the value for the given environment vriable name
477 * searchs in $_SERVER, $_ENV than trys getenv() and apache_getenv()
483 * @uses function_exists()
484 * @uses apache_getenv()
485 * @param string $var_name variable name
486 * @return string value of $var or empty string
488 function PMA_getenv($var_name) {
489 if (isset($_SERVER[$var_name])) {
490 return $_SERVER[$var_name];
491 } elseif (isset($_ENV[$var_name])) {
492 return $_ENV[$var_name];
493 } elseif (getenv($var_name)) {
494 return getenv($var_name);
495 } elseif (function_exists('apache_getenv')
496 && apache_getenv($var_name, true)) {
497 return apache_getenv($var_name, true);
504 * Send HTTP header, taking IIS limits into account (600 seems ok)
507 * @uses PMA_COMING_FROM_COOKIE_LOGIN
508 * @uses PMA_get_arg_separator()
513 * @uses session_write_close()
514 * @uses headers_sent()
515 * @uses function_exists()
516 * @uses debug_print_backtrace()
517 * @uses trigger_error()
519 * @param string $uri the header to send
520 * @return boolean always true
522 function PMA_sendHeaderLocation($uri)
524 if (PMA_IS_IIS
&& strlen($uri) > 600) {
525 require_once './libraries/js_escape.lib.php';
527 echo '<html><head><title>- - -</title>' . "\n";
528 echo '<meta http-equiv="expires" content="0">' . "\n";
529 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
530 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
531 echo '<meta http-equiv="Refresh" content="0;url=' . htmlspecialchars($uri) . '">' . "\n";
532 echo '<script type="text/javascript">' . "\n";
533 echo '//<![CDATA[' . "\n";
534 echo 'setTimeout("window.location = unescape(\'"' . PMA_escapeJsString($uri) . '"\')", 2000);' . "\n";
536 echo '</script>' . "\n";
537 echo '</head>' . "\n";
538 echo '<body>' . "\n";
539 echo '<script type="text/javascript">' . "\n";
540 echo '//<![CDATA[' . "\n";
541 echo 'document.write(\'<p><a href="' . htmlspecialchars($uri) . '">' . __('Go') . '</a></p>\');' . "\n";
543 echo '</script></body></html>' . "\n";
547 if (strpos($uri, '?') === false) {
548 header('Location: ' . $uri . '?' . SID
);
550 $separator = PMA_get_arg_separator();
551 header('Location: ' . $uri . $separator . SID
);
554 session_write_close();
555 if (headers_sent()) {
556 if (function_exists('debug_print_backtrace')) {
558 debug_print_backtrace();
561 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR
);
563 // bug #1523784: IE6 does not like 'Refresh: 0', it
564 // results in a blank page
565 // but we need it when coming from the cookie login panel)
566 if (PMA_IS_IIS
&& defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
567 header('Refresh: 0; ' . $uri);
569 header('Location: ' . $uri);
576 * Returns value of an element in $array given by $path.
577 * $path is a string describing position of an element in an associative array,
578 * eg. Servers/1/host refers to $array[Servers][1][host]
580 * @param string $path
581 * @param array $array
582 * @param mixed $default
583 * @return mixed array element or $default
585 function PMA_array_read($path, $array, $default = null)
587 $keys = explode('/', $path);
589 foreach ($keys as $key) {
590 if (!isset($value[$key])) {
593 $value =& $value[$key];
599 * Stores value in an array
601 * @param string $path
602 * @param array &$array
603 * @param mixed $value
605 function PMA_array_write($path, &$array, $value)
607 $keys = explode('/', $path);
608 $last_key = array_pop($keys);
610 foreach ($keys as $key) {
611 if (!isset($a[$key])) {
616 $a[$last_key] = $value;
620 * Removes value from an array
622 * @param string $path
623 * @param array &$array
624 * @param mixed $value
626 function PMA_array_remove($path, &$array)
628 $keys = explode('/', $path);
629 $keys_last = array_pop($keys);
635 // go as deep as required or possible
636 foreach ($keys as $key) {
637 if (!isset($path[$depth][$key])) {
642 $path[$depth] =& $path[$depth-1][$key];
644 // if element found, remove it
646 unset($path[$depth][$keys_last]);
650 // remove empty nested arrays
651 for (; $depth >= 0; $depth--) {
652 if (!isset($path[$depth+
1]) ||
count($path[$depth+
1]) == 0) {
653 unset($path[$depth][$keys[$depth]]);