Drizzle dbi - PMA_DBI_get_host_info - work around a segfault
[phpmyadmin.git] / libraries / core.lib.php
blobbb542ba49d50e329fb011479327feddca3990407
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 */
11 /**
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
16 * <code>
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
30 * </code>
32 * @see PMA_isValid()
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)) {
41 return $default;
44 return $var;
47 /**
48 * checks given $var against $type or $compare
50 * $type can be:
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
60 * <code>
61 * // $_REQUEST['doit'] = true;
62 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false
63 * // $_REQUEST['doit'] = 'true';
64 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true
65 * </code>
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:
70 * <code>
71 * // $var is not set
72 * isset($var); // false
73 * functionCallByReference($var); // false
74 * isset($var); // true
75 * functionCallByReference($var); // true
76 * </code>
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)
90 if (! isset($var)) {
91 // var is not even set
92 return false;
95 if ($type === false) {
96 // no vartype requested
97 return true;
100 if (is_array($type)) {
101 return in_array($var, $type);
104 // allow some aliaes of var types
105 $type = strtolower($type);
106 switch ($type) {
107 case 'identic' :
108 $type = 'identical';
109 break;
110 case 'len' :
111 $type = 'length';
112 break;
113 case 'bool' :
114 $type = 'boolean';
115 break;
116 case 'float' :
117 $type = 'double';
118 break;
119 case 'int' :
120 $type = 'integer';
121 break;
122 case 'null' :
123 $type = 'NULL';
124 break;
127 if ($type === 'identical') {
128 return $var === $compare;
131 // whether we should check against given $compare
132 if ($type === 'similar') {
133 switch (gettype($compare)) {
134 case 'string':
135 case 'boolean':
136 $type = 'scalar';
137 break;
138 case 'integer':
139 case 'double':
140 $type = 'numeric';
141 break;
142 default:
143 $type = gettype($compare);
145 } elseif ($type === 'equal') {
146 $type = gettype($compare);
149 // do the check
150 if ($type === 'length' || $type === 'scalar') {
151 $is_scalar = is_scalar($var);
152 if ($is_scalar && $type === 'length') {
153 return (bool) strlen($var);
155 return $is_scalar;
158 if ($type === 'numeric') {
159 return is_numeric($var);
162 if (gettype($var) === $type) {
163 return true;
166 return false;
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
178 * @access public
180 function PMA_securePath($path)
182 // change .. to .
183 $path = preg_replace('@\.\.*@', '.', $path);
185 return $path;
186 } // end function
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
197 * @return exit
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');
211 } else {
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')) {
229 exit;
234 * Returns a link to the PHP documentation
236 * @param string anchor in documentation
238 * @return string the URL
240 * @access public
242 function PMA_getPHPDocLink($target) {
243 /* l10n: Language to use for PHP documentation, please use only languages which do exist in official documentation. */
244 $lang = _pgettext('PHP documentation language', 'en');
246 return 'http://php.net/manual/' . $lang . '/' . $target;
250 * Warn or fail on missing extension.
252 * @param string $extension Extension name
253 * @param bool $fatal Whether the error is fatal.
254 / @param string $extra Extra string to append to messsage.
256 function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
258 /* Gettext does not have to be loaded yet here */
259 if (function_exists('__')) {
260 $message = __('The %s extension is missing. Please check your PHP configuration.');
261 } else {
262 $message = 'The %s extension is missing. Please check your PHP configuration.';
264 $message = sprintf($message,
265 '[a@' . PMA_getPHPDocLink('book.' . $extension . '.php') . '@Documentation][em]' . $extension . '[/em][/a]');
266 if ($extra != '') {
267 $message .= ' ' . $extra;
269 if ($fatal) {
270 PMA_fatalError($message);
271 } else {
272 trigger_error($message, E_USER_WARNING);
277 * returns count of tables in given db
279 * @param string $db database to count tables for
280 * @return integer count of tables in $db
282 function PMA_getTableCount($db)
284 $tables = PMA_DBI_try_query(
285 'SHOW TABLES FROM ' . PMA_backquote($db) . ';',
286 null, PMA_DBI_QUERY_STORE);
287 if ($tables) {
288 $num_tables = PMA_DBI_num_rows($tables);
290 // do not count hidden blobstreaming tables
291 while ((($num_tables > 0)) && $data = PMA_DBI_fetch_assoc($tables)) {
292 if (PMA_BS_IsHiddenTable($data['Tables_in_' . $db])) {
293 $num_tables--;
297 PMA_DBI_free_result($tables);
298 } else {
299 $num_tables = 0;
302 return $num_tables;
306 * Converts numbers like 10M into bytes
307 * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
308 * (renamed with PMA prefix to avoid double definition when embedded
309 * in Moodle)
311 * @param string $size
312 * @return integer $size
314 function PMA_get_real_size($size = 0)
316 if (! $size) {
317 return 0;
320 $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
321 $scan['g'] = 1073741824; //1024 * 1024 * 1024;
322 $scan['mb'] = 1048576;
323 $scan['m'] = 1048576;
324 $scan['kb'] = 1024;
325 $scan['k'] = 1024;
326 $scan['b'] = 1;
328 foreach ($scan as $unit => $factor) {
329 if (strlen($size) > strlen($unit)
330 && strtolower(substr($size, strlen($size) - strlen($unit))) == $unit) {
331 return substr($size, 0, strlen($size) - strlen($unit)) * $factor;
335 return $size;
336 } // end function PMA_get_real_size()
339 * merges array recursive like array_merge_recursive() but keyed-values are
340 * always overwritten.
342 * array PMA_array_merge_recursive(array $array1[, array $array2[, array ...]])
344 * @see http://php.net/array_merge
345 * @see http://php.net/array_merge_recursive
346 * @param array array to merge
347 * @param array array to merge
348 * @param array ...
349 * @return array merged array
351 function PMA_array_merge_recursive()
353 switch(func_num_args()) {
354 case 0 :
355 return false;
356 break;
357 case 1 :
358 // when does that happen?
359 return func_get_arg(0);
360 break;
361 case 2 :
362 $args = func_get_args();
363 if (! is_array($args[0]) || ! is_array($args[1])) {
364 return $args[1];
366 foreach ($args[1] as $key2 => $value2) {
367 if (isset($args[0][$key2]) && !is_int($key2)) {
368 $args[0][$key2] = PMA_array_merge_recursive($args[0][$key2],
369 $value2);
370 } else {
371 // we erase the parent array, otherwise we cannot override a directive that
372 // contains array elements, like this:
373 // (in config.default.php) $cfg['ForeignKeyDropdownOrder'] = array('id-content','content-id');
374 // (in config.inc.php) $cfg['ForeignKeyDropdownOrder'] = array('content-id');
375 if (is_int($key2) && $key2 == 0) {
376 unset($args[0]);
378 $args[0][$key2] = $value2;
381 return $args[0];
382 break;
383 default :
384 $args = func_get_args();
385 $args[1] = PMA_array_merge_recursive($args[0], $args[1]);
386 array_shift($args);
387 return call_user_func_array('PMA_array_merge_recursive', $args);
388 break;
393 * calls $function vor every element in $array recursively
395 * this function is protected against deep recursion attack CVE-2006-1549,
396 * 1000 seems to be more than enough
398 * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
399 * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
401 * @param array $array array to walk
402 * @param string $function function to call for every array element
404 function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
406 static $recursive_counter = 0;
407 if (++$recursive_counter > 1000) {
408 die('possible deep recursion attack');
410 foreach ($array as $key => $value) {
411 if (is_array($value)) {
412 PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
413 } else {
414 $array[$key] = $function($value);
417 if ($apply_to_keys_also && is_string($key)) {
418 $new_key = $function($key);
419 if ($new_key != $key) {
420 $array[$new_key] = $array[$key];
421 unset($array[$key]);
425 $recursive_counter--;
429 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
431 * checks given given $page against given $whitelist and returns true if valid
432 * it ignores optionaly query paramters in $page (script.php?ignored)
434 * @param string &$page page to check
435 * @param array $whitelist whitelist to check page against
436 * @return boolean whether $page is valid or not (in $whitelist or not)
438 function PMA_checkPageValidity(&$page, $whitelist)
440 if (! isset($page) || !is_string($page)) {
441 return false;
444 if (in_array($page, $whitelist)) {
445 return true;
446 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
447 return true;
448 } else {
449 $_page = urldecode($page);
450 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
451 return true;
454 return false;
458 * trys to find the value for the given environment vriable name
460 * searchs in $_SERVER, $_ENV than trys getenv() and apache_getenv()
461 * in this order
463 * @param string $var_name variable name
464 * @return string value of $var or empty string
466 function PMA_getenv($var_name) {
467 if (isset($_SERVER[$var_name])) {
468 return $_SERVER[$var_name];
469 } elseif (isset($_ENV[$var_name])) {
470 return $_ENV[$var_name];
471 } elseif (getenv($var_name)) {
472 return getenv($var_name);
473 } elseif (function_exists('apache_getenv')
474 && apache_getenv($var_name, true)) {
475 return apache_getenv($var_name, true);
478 return '';
482 * Send HTTP header, taking IIS limits into account (600 seems ok)
484 * @param string $uri the header to send
485 * @return boolean always true
487 function PMA_sendHeaderLocation($uri)
489 if (PMA_IS_IIS && strlen($uri) > 600) {
490 require_once './libraries/js_escape.lib.php';
492 echo '<html><head><title>- - -</title>' . "\n";
493 echo '<meta http-equiv="expires" content="0">' . "\n";
494 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
495 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
496 echo '<meta http-equiv="Refresh" content="0;url=' . htmlspecialchars($uri) . '">' . "\n";
497 echo '<script type="text/javascript">' . "\n";
498 echo '//<![CDATA[' . "\n";
499 echo 'setTimeout("window.location = unescape(\'"' . PMA_escapeJsString($uri) . '"\')", 2000);' . "\n";
500 echo '//]]>' . "\n";
501 echo '</script>' . "\n";
502 echo '</head>' . "\n";
503 echo '<body>' . "\n";
504 echo '<script type="text/javascript">' . "\n";
505 echo '//<![CDATA[' . "\n";
506 echo 'document.write(\'<p><a href="' . htmlspecialchars($uri) . '">' . __('Go') . '</a></p>\');' . "\n";
507 echo '//]]>' . "\n";
508 echo '</script></body></html>' . "\n";
510 } else {
511 if (SID) {
512 if (strpos($uri, '?') === false) {
513 header('Location: ' . $uri . '?' . SID);
514 } else {
515 $separator = PMA_get_arg_separator();
516 header('Location: ' . $uri . $separator . SID);
518 } else {
519 session_write_close();
520 if (headers_sent()) {
521 if (function_exists('debug_print_backtrace')) {
522 echo '<pre>';
523 debug_print_backtrace();
524 echo '</pre>';
526 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
528 // bug #1523784: IE6 does not like 'Refresh: 0', it
529 // results in a blank page
530 // but we need it when coming from the cookie login panel)
531 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
532 header('Refresh: 0; ' . $uri);
533 } else {
534 header('Location: ' . $uri);
541 * Returns value of an element in $array given by $path.
542 * $path is a string describing position of an element in an associative array,
543 * eg. Servers/1/host refers to $array[Servers][1][host]
545 * @param string $path
546 * @param array $array
547 * @param mixed $default
548 * @return mixed array element or $default
550 function PMA_array_read($path, $array, $default = null)
552 $keys = explode('/', $path);
553 $value =& $array;
554 foreach ($keys as $key) {
555 if (! isset($value[$key])) {
556 return $default;
558 $value =& $value[$key];
560 return $value;
564 * Stores value in an array
566 * @param string $path
567 * @param array &$array
568 * @param mixed $value
570 function PMA_array_write($path, &$array, $value)
572 $keys = explode('/', $path);
573 $last_key = array_pop($keys);
574 $a =& $array;
575 foreach ($keys as $key) {
576 if (! isset($a[$key])) {
577 $a[$key] = array();
579 $a =& $a[$key];
581 $a[$last_key] = $value;
585 * Removes value from an array
587 * @param string $path
588 * @param array &$array
589 * @param mixed $value
591 function PMA_array_remove($path, &$array)
593 $keys = explode('/', $path);
594 $keys_last = array_pop($keys);
595 $path = array();
596 $depth = 0;
598 $path[0] =& $array;
599 $found = true;
600 // go as deep as required or possible
601 foreach ($keys as $key) {
602 if (! isset($path[$depth][$key])) {
603 $found = false;
604 break;
606 $depth++;
607 $path[$depth] =& $path[$depth-1][$key];
609 // if element found, remove it
610 if ($found) {
611 unset($path[$depth][$keys_last]);
612 $depth--;
615 // remove empty nested arrays
616 for (; $depth >= 0; $depth--) {
617 if (! isset($path[$depth+1]) || count($path[$depth+1]) == 0) {
618 unset($path[$depth][$keys[$depth]]);
619 } else {
620 break;
626 * Returns link to (possibly) external site using defined redirector.
628 * @param string $url URL where to go.
630 * @return string URL for a link.
632 function PMA_linkURL($url) {
633 if (!preg_match('#^https?://#', $url) || defined('PMA_SETUP')) {
634 return $url;
635 } else {
636 $params = array();
637 $params['url'] = $url;
638 return './url.php' . PMA_generate_common_url($params);
643 * Returns HTML code to include javascript file.
645 * @param string $url Location of javascript, relative to js/ folder.
647 * @return string HTML code for javascript inclusion.
649 function PMA_includeJS($url) {
650 if (strpos($url, '?') === false) {
651 return '<script src="./js/' . $url . '?ts=' . filemtime('./js/' . $url) . '" type="text/javascript"></script>' . "\n";
652 } else {
653 return '<script src="./js/' . $url . '" type="text/javascript"></script>' . "\n";