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.
13 * checks given $var and returns it if valid, or $default of not valid
14 * given $var is also checked for type being 'similar' as $default
15 * or against any other type if $type is provided
18 * // $_REQUEST['db'] not set
19 * echo PMA_ifSetOr($_REQUEST['db'], ''); // ''
20 * // $_REQUEST['sql_query'] not set
21 * echo PMA_ifSetOr($_REQUEST['sql_query']); // null
22 * // $cfg['ForceSSL'] not set
23 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
24 * echo PMA_ifSetOr($cfg['ForceSSL']); // null
25 * // $cfg['ForceSSL'] set to 1
26 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
27 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'similar'); // 1
28 * echo PMA_ifSetOr($cfg['ForceSSL'], false); // 1
29 * // $cfg['ForceSSL'] set to true
30 * 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
38 * @return mixed $var or $default
40 function PMA_ifSetOr(&$var, $default = null, $type = 'similar')
42 if (! PMA_isValid($var, $type, $default)) {
50 * checks given $var against $type or $compare
53 * - false : no type checking
54 * - 'scalar' : whether type of $var is integer, float, string or boolean
55 * - 'numeric' : whether type of $var is any number repesentation
56 * - 'length' : whether type of $var is scalar with a string length > 0
57 * - 'similar' : whether type of $var is similar to type of $compare
58 * - 'equal' : whether type of $var is identical to type of $compare
59 * - 'identical' : whether $var is identical to $compare, not only the type!
60 * - or any other valid PHP variable type
63 * // $_REQUEST['doit'] = true;
64 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false
65 * // $_REQUEST['doit'] = 'true';
66 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true
69 * NOTE: call-by-reference is used to not get NOTICE on undefined vars,
70 * but the var is not altered inside this function, also after checking a var
71 * this var exists nut is not set, example:
74 * isset($var); // false
75 * functionCallByReference($var); // false
76 * isset($var); // true
77 * functionCallByReference($var); // true
80 * to avoid this we set this var to null if not isset
82 * @todo create some testsuites
83 * @todo add some more var types like hex, bin, ...?
90 * @see http://php.net/gettype
91 * @param mixed $var variable to check
92 * @param mixed $type var type or array of valid values to check against $var
93 * @param mixed $compare var to compare with $var
94 * @return boolean whether valid or not
96 function PMA_isValid(&$var, $type = 'length', $compare = null)
99 // var is not even set
103 if ($type === false) {
104 // no vartype requested
108 if (is_array($type)) {
109 return in_array($var, $type);
112 // allow some aliaes of var types
113 $type = strtolower($type);
135 if ($type === 'identical') {
136 return $var === $compare;
139 // whether we should check against given $compare
140 if ($type === 'similar') {
141 switch (gettype($compare)) {
151 $type = gettype($compare);
153 } elseif ($type === 'equal') {
154 $type = gettype($compare);
158 if ($type === 'length' ||
$type === 'scalar') {
159 $is_scalar = is_scalar($var);
160 if ($is_scalar && $type === 'length') {
161 return (bool) strlen($var);
166 if ($type === 'numeric') {
167 return is_numeric($var);
170 if (gettype($var) === $type) {
178 * Removes insecure parts in a path; used before include() or
179 * require() when a part of the path comes from an insecure source
180 * like a cookie or form.
182 * @param string The path to check
184 * @return string The secured path
187 * @author Marc Delisle (lem9@users.sourceforge.net)
189 function PMA_securePath($path)
192 $path = preg_replace('@\.\.*@', '.', $path);
198 * displays the given error message on phpMyAdmin error page in foreign language,
199 * ends script execution and closes session
201 * loads language file if not loaded already
203 * @todo use detected argument separator (PMA_Config)
204 * @uses $GLOBALS['session_name']
205 * @uses $GLOBALS['text_dir']
206 * @uses $GLOBALS['strError']
207 * @uses $GLOBALS['available_languages']
208 * @uses $GLOBALS['lang']
209 * @uses PMA_removeCookie()
210 * @uses select_lang.lib.php
214 * @uses http_build_query()
220 * @param string $error_message the error message or named error message
221 * @param string|array $message_args arguments applied to $error_message
224 function PMA_fatalError($error_message, $message_args = null)
226 // it could happen PMA_fatalError() is called before language file is loaded
227 if (! isset($GLOBALS['available_languages'])) {
228 $GLOBALS['cfg'] = array(
229 'DefaultLang' => 'en-utf-8',
230 'AllowAnywhereRecoding' => false);
232 // Loads the language file
233 require_once './libraries/select_lang.lib.php';
235 if (isset($strError)) {
236 $GLOBALS['strError'] = $strError;
238 $GLOBALS['strError'] = 'Error';
241 // $text_dir is set in lang/language-utf-8.inc.php
242 if (isset($text_dir)) {
243 $GLOBALS['text_dir'] = $text_dir;
247 // $error_message could be a language string identifier: strString
248 if (substr($error_message, 0, 3) === 'str') {
249 if (isset($
$error_message)) {
250 $error_message = $
$error_message;
251 } elseif (isset($GLOBALS[$error_message])) {
252 $error_message = $GLOBALS[$error_message];
256 if (is_string($message_args)) {
257 $error_message = sprintf($error_message, $message_args);
258 } elseif (is_array($message_args)) {
259 $error_message = vsprintf($error_message, $message_args);
261 $error_message = strtr($error_message, array('<br />' => '[br]'));
263 // Displays the error message
264 $lang = $GLOBALS['available_languages'][$GLOBALS['lang']][2];
265 $dir = $GLOBALS['text_dir'];
266 $type = $GLOBALS['strError'];
267 $error = $error_message;
269 // on fatal errors it cannot hurt to always delete the current session
270 if (isset($GLOBALS['session_name']) && isset($_COOKIE[$GLOBALS['session_name']])) {
271 PMA_removeCookie($GLOBALS['session_name']);
274 require('./libraries/error.inc.php');
280 * returns count of tables in given db
282 * @uses PMA_DBI_try_query()
283 * @uses PMA_backquote()
284 * @uses PMA_DBI_QUERY_STORE()
285 * @uses PMA_DBI_num_rows()
286 * @uses PMA_DBI_free_result()
287 * @param string $db database to count tables for
288 * @return integer count of tables in $db
290 function PMA_getTableCount($db)
292 $tables = PMA_DBI_try_query(
293 'SHOW TABLES FROM ' . PMA_backquote($db) . ';',
294 null, PMA_DBI_QUERY_STORE
);
296 $num_tables = PMA_DBI_num_rows($tables);
298 // for blobstreaming - get blobstreaming tables
299 // for use in determining if a table here is a blobstreaming table - rajk
301 // load PMA configuration
302 $PMA_Config = $_SESSION['PMA_Config'];
304 // if PMA configuration exists
305 if (!empty($PMA_Config))
308 $session_bs_tables = $_SESSION['PMA_Config']->get('BLOBSTREAMING_TABLES');
310 // if BS tables exist
311 if (isset ($session_bs_tables))
312 while ($data = PMA_DBI_fetch_assoc($tables))
313 foreach ($session_bs_tables as $table_key=>$table_val)
314 // if the table is a blobstreaming table, reduce the table count
315 if ($data['Tables_in_' . $db] == $table_key)
322 } // end if PMA configuration exists
324 PMA_DBI_free_result($tables);
333 * Converts numbers like 10M into bytes
334 * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
335 * (renamed with PMA prefix to avoid double definition when embedded
341 * @param string $size
342 * @return integer $size
344 function PMA_get_real_size($size = 0)
350 $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
351 $scan['g'] = 1073741824; //1024 * 1024 * 1024;
352 $scan['mb'] = 1048576;
353 $scan['m'] = 1048576;
358 foreach ($scan as $unit => $factor) {
359 if (strlen($size) > strlen($unit)
360 && strtolower(substr($size, strlen($size) - strlen($unit))) == $unit) {
361 return substr($size, 0, strlen($size) - strlen($unit)) * $factor;
366 } // end function PMA_get_real_size()
369 * merges array recursive like array_merge_recursive() but keyed-values are
370 * always overwritten.
372 * array PMA_array_merge_recursive(array $array1[, array $array2[, array ...]])
374 * @see http://php.net/array_merge
375 * @see http://php.net/array_merge_recursive
376 * @uses func_num_args()
377 * @uses func_get_arg()
379 * @uses call_user_func_array()
380 * @param array array to merge
381 * @param array array to merge
383 * @return array merged array
385 function PMA_array_merge_recursive()
387 switch(func_num_args()) {
392 // when does that happen?
393 return func_get_arg(0);
396 $args = func_get_args();
397 if (!is_array($args[0]) ||
!is_array($args[1])) {
400 foreach ($args[1] as $key2 => $value2) {
401 if (isset($args[0][$key2]) && !is_int($key2)) {
402 $args[0][$key2] = PMA_array_merge_recursive($args[0][$key2],
405 // we erase the parent array, otherwise we cannot override a directive that
406 // contains array elements, like this:
407 // (in config.default.php) $cfg['ForeignKeyDropdownOrder'] = array('id-content','content-id');
408 // (in config.inc.php) $cfg['ForeignKeyDropdownOrder'] = array('content-id');
409 if (is_int($key2) && $key2 == 0) {
412 $args[0][$key2] = $value2;
418 $args = func_get_args();
419 $args[1] = PMA_array_merge_recursive($args[0], $args[1]);
421 return call_user_func_array('PMA_array_merge_recursive', $args);
427 * calls $function vor every element in $array recursively
429 * this function is protected against deep recursion attack CVE-2006-1549,
430 * 1000 seems to be more than enough
432 * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
433 * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
435 * @uses PMA_arrayWalkRecursive()
438 * @param array $array array to walk
439 * @param string $function function to call for every array element
441 function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
443 static $recursive_counter = 0;
444 if (++
$recursive_counter > 1000) {
445 die('possible deep recursion attack');
447 foreach ($array as $key => $value) {
448 if (is_array($value)) {
449 PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
451 $array[$key] = $function($value);
454 if ($apply_to_keys_also && is_string($key)) {
455 $new_key = $function($key);
456 if ($new_key != $key) {
457 $array[$new_key] = $array[$key];
462 $recursive_counter--;
466 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
468 * checks given given $page against given $whitelist and returns true if valid
469 * 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
477 * @return boolean whether $page is valid or not (in $whitelist or not)
479 function PMA_checkPageValidity(&$page, $whitelist)
481 if (! isset($page) ||
!is_string($page)) {
485 if (in_array($page, $whitelist)) {
487 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
490 $_page = urldecode($page);
491 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
499 * trys to find the value for the given environment vriable name
501 * searchs in $_SERVER, $_ENV than trys getenv() and apache_getenv()
507 * @uses function_exists()
508 * @uses apache_getenv()
509 * @param string $var_name variable name
510 * @return string value of $var or empty string
512 function PMA_getenv($var_name) {
513 if (isset($_SERVER[$var_name])) {
514 return $_SERVER[$var_name];
515 } elseif (isset($_ENV[$var_name])) {
516 return $_ENV[$var_name];
517 } elseif (getenv($var_name)) {
518 return getenv($var_name);
519 } elseif (function_exists('apache_getenv')
520 && apache_getenv($var_name, true)) {
521 return apache_getenv($var_name, true);
530 * @uses PMA_Config::isHttps()
531 * @uses PMA_Config::getCookiePath()
534 * @param string $cookie name of cookie to remove
535 * @return boolean result of setcookie()
537 function PMA_removeCookie($cookie)
539 return setcookie($cookie, '', time() - 3600,
540 PMA_Config
::getCookiePath(), '', PMA_Config
::isHttps());
544 * sets cookie if value is different from current cokkie value,
545 * or removes if value is equal to default
547 * @uses PMA_Config::isHttps()
548 * @uses PMA_Config::getCookiePath()
550 * @uses PMA_removeCookie()
553 * @param string $cookie name of cookie to remove
554 * @param mixed $value new cookie value
555 * @param string $default default value
556 * @param int $validity validity of cookie in seconds (default is one month)
557 * @param bool $httponlt whether cookie is only for HTTP (and not for scripts)
558 * @return boolean result of setcookie()
560 function PMA_setCookie($cookie, $value, $default = null, $validity = null, $httponly = true)
562 if ($validity == null) {
565 if (strlen($value) && null !== $default && $value === $default
566 && isset($_COOKIE[$cookie])) {
567 // remove cookie, default value is used
568 return PMA_removeCookie($cookie);
571 if (! strlen($value) && isset($_COOKIE[$cookie])) {
572 // remove cookie, value is empty
573 return PMA_removeCookie($cookie);
576 if (! isset($_COOKIE[$cookie]) ||
$_COOKIE[$cookie] !== $value) {
577 // set cookie with new value
578 /* Calculate cookie validity */
579 if ($validity == 0) {
582 $v = time() +
$validity;
584 return setcookie($cookie, $value, $v,
585 PMA_Config
::getCookiePath(), '', PMA_Config
::isHttps(), $httponly);
588 // cookie has already $value as value
593 * Send HTTP header, taking IIS limits into account (600 seems ok)
596 * @uses PMA_COMING_FROM_COOKIE_LOGIN
597 * @uses PMA_get_arg_separator()
602 * @uses session_write_close()
603 * @uses headers_sent()
604 * @uses function_exists()
605 * @uses debug_print_backtrace()
606 * @uses trigger_error()
608 * @param string $uri the header to send
609 * @return boolean always true
611 function PMA_sendHeaderLocation($uri)
613 if (PMA_IS_IIS
&& strlen($uri) > 600) {
614 require_once './libraries/js_escape.lib.php';
616 echo '<html><head><title>- - -</title>' . "\n";
617 echo '<meta http-equiv="expires" content="0">' . "\n";
618 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
619 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
620 echo '<meta http-equiv="Refresh" content="0;url=' . htmlspecialchars($uri) . '">' . "\n";
621 echo '<script type="text/javascript">' . "\n";
622 echo '//<![CDATA[' . "\n";
623 echo 'setTimeout("window.location = unescape(\'"' . PMA_escapeJsString($uri) . '"\')", 2000);' . "\n";
625 echo '</script>' . "\n";
626 echo '</head>' . "\n";
627 echo '<body>' . "\n";
628 echo '<script type="text/javascript">' . "\n";
629 echo '//<![CDATA[' . "\n";
630 echo 'document.write(\'<p><a href="' . htmlspecialchars($uri) . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
632 echo '</script></body></html>' . "\n";
636 if (strpos($uri, '?') === false) {
637 header('Location: ' . $uri . '?' . SID
);
639 $separator = PMA_get_arg_separator();
640 header('Location: ' . $uri . $separator . SID
);
643 session_write_close();
644 if (headers_sent()) {
645 if (function_exists('debug_print_backtrace')) {
647 debug_print_backtrace();
650 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR
);
652 // bug #1523784: IE6 does not like 'Refresh: 0', it
653 // results in a blank page
654 // but we need it when coming from the cookie login panel)
655 if (PMA_IS_IIS
&& defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
656 header('Refresh: 0; ' . $uri);
658 header('Location: ' . $uri);