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
33 * @param mixed $var param to check
34 * @param mixed $default default value
35 * @param mixed $type var type or array of values to check against $var
36 * @return mixed $var or $default
38 function PMA_ifSetOr(&$var, $default = null, $type = 'similar')
40 if (! PMA_isValid($var, $type, $default)) {
48 * checks given $var against $type or $compare
51 * - false : no type checking
52 * - 'scalar' : whether type of $var is integer, float, string or boolean
53 * - 'numeric' : whether type of $var is any number repesentation
54 * - 'length' : whether type of $var is scalar with a string length > 0
55 * - 'similar' : whether type of $var is similar to type of $compare
56 * - 'equal' : whether type of $var is identical to type of $compare
57 * - 'identical' : whether $var is identical to $compare, not only the type!
58 * - or any other valid PHP variable type
61 * // $_REQUEST['doit'] = true;
62 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false
63 * // $_REQUEST['doit'] = 'true';
64 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true
67 * NOTE: call-by-reference is used to not get NOTICE on undefined vars,
68 * but the var is not altered inside this function, also after checking a var
69 * this var exists nut is not set, example:
72 * isset($var); // false
73 * functionCallByReference($var); // false
74 * isset($var); // true
75 * functionCallByReference($var); // true
78 * to avoid this we set this var to null if not isset
80 * @todo create some testsuites
81 * @todo add some more var types like hex, bin, ...?
82 * @see http://php.net/gettype
83 * @param mixed $var variable to check
84 * @param mixed $type var type or array of valid values to check against $var
85 * @param mixed $compare var to compare with $var
86 * @return boolean whether valid or not
88 function PMA_isValid(&$var, $type = 'length', $compare = null)
91 // var is not even set
95 if ($type === false) {
96 // no vartype requested
100 if (is_array($type)) {
101 return in_array($var, $type);
104 // allow some aliaes of var types
105 $type = strtolower($type);
127 if ($type === 'identical') {
128 return $var === $compare;
131 // whether we should check against given $compare
132 if ($type === 'similar') {
133 switch (gettype($compare)) {
143 $type = gettype($compare);
145 } elseif ($type === 'equal') {
146 $type = gettype($compare);
150 if ($type === 'length' ||
$type === 'scalar') {
151 $is_scalar = is_scalar($var);
152 if ($is_scalar && $type === 'length') {
153 return (bool) strlen($var);
158 if ($type === 'numeric') {
159 return is_numeric($var);
162 if (gettype($var) === $type) {
170 * Removes insecure parts in a path; used before include() or
171 * require() when a part of the path comes from an insecure source
172 * like a cookie or form.
174 * @param string The path to check
176 * @return string The secured path
180 function PMA_securePath($path)
183 $path = preg_replace('@\.\.*@', '.', $path);
189 * displays the given error message on phpMyAdmin error page in foreign language,
190 * ends script execution and closes session
192 * loads language file if not loaded already
194 * @todo use detected argument separator (PMA_Config)
195 * @param string $error_message the error message or named error message
196 * @param string|array $message_args arguments applied to $error_message
199 function PMA_fatalError($error_message, $message_args = null)
201 /* Use format string if applicable */
202 if (is_string($message_args)) {
203 $error_message = sprintf($error_message, $message_args);
204 } elseif (is_array($message_args)) {
205 $error_message = vsprintf($error_message, $message_args);
207 $error_message = strtr($error_message, array('<br />' => '[br]'));
209 if (function_exists('__')) {
210 $error_header = __('Error');
212 $error_header = 'Error';
215 // Displays the error message
216 $lang = $GLOBALS['available_languages'][$GLOBALS['lang']][1];
217 $dir = $GLOBALS['text_dir'];
218 $type = $error_header;
219 $error = $error_message;
221 // on fatal errors it cannot hurt to always delete the current session
222 if (isset($GLOBALS['session_name']) && isset($_COOKIE[$GLOBALS['session_name']])) {
223 $GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
226 require('./libraries/error.inc.php');
228 if (!defined('TESTSUITE')) {
234 * Returns a link to the PHP documentation
236 * @param string anchor in documentation
238 * @return string the URL
242 function PMA_getPHPDocLink($target)
244 /* l10n: Language to use for PHP documentation, please use only languages which do exist in official documentation. */
245 $lang = _pgettext('PHP documentation language', 'en');
247 return 'http://php.net/manual/' . $lang . '/' . $target;
251 * Warn or fail on missing extension.
253 * @param string $extension Extension name
254 * @param bool $fatal Whether the error is fatal.
255 / @param string $extra Extra string to append to messsage.
257 function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
259 /* Gettext does not have to be loaded yet here */
260 if (function_exists('__')) {
261 $message = __('The %s extension is missing. Please check your PHP configuration.');
263 $message = 'The %s extension is missing. Please check your PHP configuration.';
265 $message = sprintf($message,
266 '[a@' . PMA_getPHPDocLink('book.' . $extension . '.php') . '@Documentation][em]' . $extension . '[/em][/a]');
268 $message .= ' ' . $extra;
271 PMA_fatalError($message);
273 trigger_error($message, E_USER_WARNING
);
278 * returns count of tables in given db
280 * @param string $db database to count tables for
281 * @return integer count of tables in $db
283 function PMA_getTableCount($db)
285 $tables = PMA_DBI_try_query(
286 'SHOW TABLES FROM ' . PMA_backquote($db) . ';',
287 null, PMA_DBI_QUERY_STORE
);
289 $num_tables = PMA_DBI_num_rows($tables);
291 // do not count hidden blobstreaming tables
292 while ((($num_tables > 0)) && $data = PMA_DBI_fetch_assoc($tables)) {
293 if (PMA_BS_IsHiddenTable($data['Tables_in_' . $db])) {
298 PMA_DBI_free_result($tables);
307 * Converts numbers like 10M into bytes
308 * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
309 * (renamed with PMA prefix to avoid double definition when embedded
312 * @param string $size
313 * @return integer $size
315 function PMA_get_real_size($size = 0)
321 $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
322 $scan['g'] = 1073741824; //1024 * 1024 * 1024;
323 $scan['mb'] = 1048576;
324 $scan['m'] = 1048576;
329 foreach ($scan as $unit => $factor) {
330 if (strlen($size) > strlen($unit)
331 && strtolower(substr($size, strlen($size) - strlen($unit))) == $unit) {
332 return substr($size, 0, strlen($size) - strlen($unit)) * $factor;
337 } // end function PMA_get_real_size()
340 * merges array recursive like array_merge_recursive() but keyed-values are
341 * always overwritten.
343 * array PMA_array_merge_recursive(array $array1[, array $array2[, array ...]])
345 * @see http://php.net/array_merge
346 * @see http://php.net/array_merge_recursive
347 * @param array array to merge
348 * @param array array to merge
350 * @return array merged array
352 function PMA_array_merge_recursive()
354 switch(func_num_args()) {
359 // when does that happen?
360 return func_get_arg(0);
363 $args = func_get_args();
364 if (! is_array($args[0]) ||
! is_array($args[1])) {
367 foreach ($args[1] as $key2 => $value2) {
368 if (isset($args[0][$key2]) && !is_int($key2)) {
369 $args[0][$key2] = PMA_array_merge_recursive($args[0][$key2],
372 // we erase the parent array, otherwise we cannot override a directive that
373 // contains array elements, like this:
374 // (in config.default.php) $cfg['ForeignKeyDropdownOrder'] = array('id-content','content-id');
375 // (in config.inc.php) $cfg['ForeignKeyDropdownOrder'] = array('content-id');
376 if (is_int($key2) && $key2 == 0) {
379 $args[0][$key2] = $value2;
385 $args = func_get_args();
386 $args[1] = PMA_array_merge_recursive($args[0], $args[1]);
388 return call_user_func_array('PMA_array_merge_recursive', $args);
394 * calls $function vor every element in $array recursively
396 * this function is protected against deep recursion attack CVE-2006-1549,
397 * 1000 seems to be more than enough
399 * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
400 * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
402 * @param array $array array to walk
403 * @param string $function function to call for every array element
405 function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
407 static $recursive_counter = 0;
408 if (++
$recursive_counter > 1000) {
409 die('possible deep recursion attack');
411 foreach ($array as $key => $value) {
412 if (is_array($value)) {
413 PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
415 $array[$key] = $function($value);
418 if ($apply_to_keys_also && is_string($key)) {
419 $new_key = $function($key);
420 if ($new_key != $key) {
421 $array[$new_key] = $array[$key];
426 $recursive_counter--;
430 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
432 * checks given given $page against given $whitelist and returns true if valid
433 * it ignores optionaly query paramters in $page (script.php?ignored)
435 * @param string &$page page to check
436 * @param array $whitelist whitelist to check page against
437 * @return boolean whether $page is valid or not (in $whitelist or not)
439 function PMA_checkPageValidity(&$page, $whitelist)
441 if (! isset($page) ||
!is_string($page)) {
445 if (in_array($page, $whitelist)) {
447 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
450 $_page = urldecode($page);
451 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
459 * trys to find the value for the given environment vriable name
461 * searchs in $_SERVER, $_ENV than trys getenv() and apache_getenv()
464 * @param string $var_name variable name
465 * @return string value of $var or empty string
467 function PMA_getenv($var_name)
469 if (isset($_SERVER[$var_name])) {
470 return $_SERVER[$var_name];
471 } elseif (isset($_ENV[$var_name])) {
472 return $_ENV[$var_name];
473 } elseif (getenv($var_name)) {
474 return getenv($var_name);
475 } elseif (function_exists('apache_getenv')
476 && apache_getenv($var_name, true)) {
477 return apache_getenv($var_name, true);
484 * Send HTTP header, taking IIS limits into account (600 seems ok)
486 * @param string $uri the header to send
487 * @return boolean always true
489 function PMA_sendHeaderLocation($uri)
491 if (PMA_IS_IIS
&& strlen($uri) > 600) {
492 require_once './libraries/js_escape.lib.php';
494 echo '<html><head><title>- - -</title>' . "\n";
495 echo '<meta http-equiv="expires" content="0">' . "\n";
496 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
497 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
498 echo '<meta http-equiv="Refresh" content="0;url=' . htmlspecialchars($uri) . '">' . "\n";
499 echo '<script type="text/javascript">' . "\n";
500 echo '//<![CDATA[' . "\n";
501 echo 'setTimeout("window.location = unescape(\'"' . PMA_escapeJsString($uri) . '"\')", 2000);' . "\n";
503 echo '</script>' . "\n";
504 echo '</head>' . "\n";
505 echo '<body>' . "\n";
506 echo '<script type="text/javascript">' . "\n";
507 echo '//<![CDATA[' . "\n";
508 echo 'document.write(\'<p><a href="' . htmlspecialchars($uri) . '">' . __('Go') . '</a></p>\');' . "\n";
510 echo '</script></body></html>' . "\n";
514 if (strpos($uri, '?') === false) {
515 header('Location: ' . $uri . '?' . SID
);
517 $separator = PMA_get_arg_separator();
518 header('Location: ' . $uri . $separator . SID
);
521 session_write_close();
522 if (headers_sent()) {
523 if (function_exists('debug_print_backtrace')) {
525 debug_print_backtrace();
528 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR
);
530 // bug #1523784: IE6 does not like 'Refresh: 0', it
531 // results in a blank page
532 // but we need it when coming from the cookie login panel)
533 if (PMA_IS_IIS
&& defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
534 header('Refresh: 0; ' . $uri);
536 header('Location: ' . $uri);
543 * Outputs headers to prevent caching in browser (and on the way).
547 function PMA_no_cache_header()
549 header('Expires: ' . date(DATE_RFC1123
)); // rfc2616 - Section 14.21
550 header('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
551 if (PMA_USR_BROWSER_AGENT
== 'IE') {
552 /* FIXME: Why is this speecial case for IE needed? */
553 header('Pragma: public');
555 header('Pragma: no-cache'); // HTTP/1.0
556 // test case: exporting a database into a .gz file with Safari
557 // would produce files not having the current time
558 // (added this header for Safari but should not harm other browsers)
559 header('Last-Modified: ' . date(DATE_RFC1123
));
565 * Sends header indicating file download.
567 * @param string $filename Filename to include in headers.
568 * @param string $mimetype MIME type to include in headers.
569 * @param int $length Length of content (optional)
570 * @param bool $no_cache Whether to include no-caching headers.
574 function PMA_download_header($filename, $mimetype, $length = 0, $no_cache = true)
577 PMA_no_cache_header();
579 /* Replace all possibly dangerous chars in filename */
580 $filename = str_replace(array(';', '"', "\n", "\r"), '-', $filename);
581 header('Content-Description: File Transfer');
582 header('Content-Disposition: attachment; filename="' . $filename . '"');
583 header('Content-Type: ' . $mimetype);
584 header('Content-Transfer-Encoding: binary');
586 header('Content-Length: ' . $length);
592 * Returns value of an element in $array given by $path.
593 * $path is a string describing position of an element in an associative array,
594 * eg. Servers/1/host refers to $array[Servers][1][host]
596 * @param string $path
597 * @param array $array
598 * @param mixed $default
599 * @return mixed array element or $default
601 function PMA_array_read($path, $array, $default = null)
603 $keys = explode('/', $path);
605 foreach ($keys as $key) {
606 if (! isset($value[$key])) {
609 $value =& $value[$key];
615 * Stores value in an array
617 * @param string $path
618 * @param array &$array
619 * @param mixed $value
621 function PMA_array_write($path, &$array, $value)
623 $keys = explode('/', $path);
624 $last_key = array_pop($keys);
626 foreach ($keys as $key) {
627 if (! isset($a[$key])) {
632 $a[$last_key] = $value;
636 * Removes value from an array
638 * @param string $path
639 * @param array &$array
640 * @param mixed $value
642 function PMA_array_remove($path, &$array)
644 $keys = explode('/', $path);
645 $keys_last = array_pop($keys);
651 // go as deep as required or possible
652 foreach ($keys as $key) {
653 if (! isset($path[$depth][$key])) {
658 $path[$depth] =& $path[$depth-1][$key];
660 // if element found, remove it
662 unset($path[$depth][$keys_last]);
666 // remove empty nested arrays
667 for (; $depth >= 0; $depth--) {
668 if (! isset($path[$depth+
1]) ||
count($path[$depth+
1]) == 0) {
669 unset($path[$depth][$keys[$depth]]);
677 * Returns link to (possibly) external site using defined redirector.
679 * @param string $url URL where to go.
681 * @return string URL for a link.
683 function PMA_linkURL($url)
685 if (!preg_match('#^https?://#', $url) ||
defined('PMA_SETUP')) {
689 $params['url'] = $url;
690 return './url.php' . PMA_generate_common_url($params);
695 * Returns HTML code to include javascript file.
697 * @param string $url Location of javascript, relative to js/ folder.
699 * @return string HTML code for javascript inclusion.
701 function PMA_includeJS($url)
703 if (strpos($url, '?') === false) {
704 return '<script src="./js/' . $url . '?ts=' . filemtime('./js/' . $url) . '" type="text/javascript"></script>' . "\n";
706 return '<script src="./js/' . $url . '" type="text/javascript"></script>' . "\n";
711 * Adds JS code snippets to be displayed by header.inc.php. Adds a newline to each snippet.
713 * @param string $str Js code to be added (e.g. "token=1234;")
716 function PMA_AddJSCode($str) {
717 $GLOBALS['js_script'][] = $str;