Translation update done using Pootle.
[phpmyadmin-themes.git] / libraries / core.lib.php
blob97d443af1a1f342d545e6d34c50da460e8af9f0b
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 * @uses PMA_isValid()
33 * @see PMA_isValid()
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)) {
42 return $default;
45 return $var;
48 /**
49 * checks given $var against $type or $compare
51 * $type can be:
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
61 * <code>
62 * // $_REQUEST['doit'] = true;
63 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false
64 * // $_REQUEST['doit'] = 'true';
65 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true
66 * </code>
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:
71 * <code>
72 * // $var is not set
73 * isset($var); // false
74 * functionCallByReference($var); // false
75 * isset($var); // true
76 * functionCallByReference($var); // true
77 * </code>
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, ...?
83 * @uses is_scalar()
84 * @uses is_numeric()
85 * @uses is_array()
86 * @uses in_array()
87 * @uses gettype()
88 * @uses strtolower()
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)
97 if (! isset($var)) {
98 // var is not even set
99 return false;
102 if ($type === false) {
103 // no vartype requested
104 return true;
107 if (is_array($type)) {
108 return in_array($var, $type);
111 // allow some aliaes of var types
112 $type = strtolower($type);
113 switch ($type) {
114 case 'identic' :
115 $type = 'identical';
116 break;
117 case 'len' :
118 $type = 'length';
119 break;
120 case 'bool' :
121 $type = 'boolean';
122 break;
123 case 'float' :
124 $type = 'double';
125 break;
126 case 'int' :
127 $type = 'integer';
128 break;
129 case 'null' :
130 $type = 'NULL';
131 break;
134 if ($type === 'identical') {
135 return $var === $compare;
138 // whether we should check against given $compare
139 if ($type === 'similar') {
140 switch (gettype($compare)) {
141 case 'string':
142 case 'boolean':
143 $type = 'scalar';
144 break;
145 case 'integer':
146 case 'double':
147 $type = 'numeric';
148 break;
149 default:
150 $type = gettype($compare);
152 } elseif ($type === 'equal') {
153 $type = gettype($compare);
156 // do the check
157 if ($type === 'length' || $type === 'scalar') {
158 $is_scalar = is_scalar($var);
159 if ($is_scalar && $type === 'length') {
160 return (bool) strlen($var);
162 return $is_scalar;
165 if ($type === 'numeric') {
166 return is_numeric($var);
169 if (gettype($var) === $type) {
170 return true;
173 return false;
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
185 * @access public
187 function PMA_securePath($path)
189 // change .. to .
190 $path = preg_replace('@\.\.*@', '.', $path);
192 return $path;
193 } // end function
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
208 * @uses $_COOKIE
209 * @uses substr()
210 * @uses header()
211 * @uses http_build_query()
212 * @uses is_string()
213 * @uses sprintf()
214 * @uses vsprintf()
215 * @uses strtr()
216 * @uses defined()
217 * @param string $error_message the error message or named error message
218 * @param string|array $message_args arguments applied to $error_message
219 * @return exit
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');
233 } else {
234 $error_header = 'Error';
237 // Displays the error message
238 // (do not use &amp; for parameters sent by header)
239 $query_params = array(
240 'lang' => $GLOBALS['available_languages'][$GLOBALS['lang']][1],
241 'dir' => $GLOBALS['text_dir'],
242 'type' => $error_header,
243 'error' => $error_message,
245 header('Location: ' . (defined('PMA_SETUP') ? '../' : '') . 'error.php?'
246 . http_build_query($query_params, null, '&'));
248 // on fatal errors it cannot hurt to always delete the current session
249 if (isset($GLOBALS['session_name']) && isset($_COOKIE[$GLOBALS['session_name']])) {
250 $GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
253 exit;
257 * Warn or fail on missing extension.
259 * @param string $extension Extension name
260 * @param bool $fatal Whether the error is fatal.
261 / @param string $extra Extra string to append to messsage.
263 function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
265 $message = sprintf(__('The %s extension is missing. Please check your PHP configuration.'),
266 sprintf('[a@http://php.net/%1$s@Documentation][em]%1$s[/em][/a]', $extension));
267 if ($extra != '') {
268 $message .= ' ' . $extra;
270 if ($fatal) {
271 PMA_fatalError($message);
272 } else {
273 trigger_error($message, E_USER_WARNING);
278 * returns count of tables in given db
280 * @uses PMA_DBI_try_query()
281 * @uses PMA_backquote()
282 * @uses PMA_DBI_QUERY_STORE()
283 * @uses PMA_DBI_num_rows()
284 * @uses PMA_DBI_free_result()
285 * @param string $db database to count tables for
286 * @return integer count of tables in $db
288 function PMA_getTableCount($db)
290 $tables = PMA_DBI_try_query(
291 'SHOW TABLES FROM ' . PMA_backquote($db) . ';',
292 null, PMA_DBI_QUERY_STORE);
293 if ($tables) {
294 $num_tables = PMA_DBI_num_rows($tables);
296 // do not count hidden blobstreaming tables
297 while ((($num_tables > 0)) && $data = PMA_DBI_fetch_assoc($tables)) {
298 if (PMA_BS_IsHiddenTable($data['Tables_in_' . $db])) {
299 $num_tables--;
303 PMA_DBI_free_result($tables);
304 } else {
305 $num_tables = 0;
308 return $num_tables;
312 * Converts numbers like 10M into bytes
313 * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
314 * (renamed with PMA prefix to avoid double definition when embedded
315 * in Moodle)
317 * @uses each()
318 * @uses strlen()
319 * @uses substr()
320 * @param string $size
321 * @return integer $size
323 function PMA_get_real_size($size = 0)
325 if (! $size) {
326 return 0;
329 $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
330 $scan['g'] = 1073741824; //1024 * 1024 * 1024;
331 $scan['mb'] = 1048576;
332 $scan['m'] = 1048576;
333 $scan['kb'] = 1024;
334 $scan['k'] = 1024;
335 $scan['b'] = 1;
337 foreach ($scan as $unit => $factor) {
338 if (strlen($size) > strlen($unit)
339 && strtolower(substr($size, strlen($size) - strlen($unit))) == $unit) {
340 return substr($size, 0, strlen($size) - strlen($unit)) * $factor;
344 return $size;
345 } // end function PMA_get_real_size()
348 * merges array recursive like array_merge_recursive() but keyed-values are
349 * always overwritten.
351 * array PMA_array_merge_recursive(array $array1[, array $array2[, array ...]])
353 * @see http://php.net/array_merge
354 * @see http://php.net/array_merge_recursive
355 * @uses func_num_args()
356 * @uses func_get_arg()
357 * @uses is_array()
358 * @uses call_user_func_array()
359 * @param array array to merge
360 * @param array array to merge
361 * @param array ...
362 * @return array merged array
364 function PMA_array_merge_recursive()
366 switch(func_num_args()) {
367 case 0 :
368 return false;
369 break;
370 case 1 :
371 // when does that happen?
372 return func_get_arg(0);
373 break;
374 case 2 :
375 $args = func_get_args();
376 if (!is_array($args[0]) || !is_array($args[1])) {
377 return $args[1];
379 foreach ($args[1] as $key2 => $value2) {
380 if (isset($args[0][$key2]) && !is_int($key2)) {
381 $args[0][$key2] = PMA_array_merge_recursive($args[0][$key2],
382 $value2);
383 } else {
384 // we erase the parent array, otherwise we cannot override a directive that
385 // contains array elements, like this:
386 // (in config.default.php) $cfg['ForeignKeyDropdownOrder'] = array('id-content','content-id');
387 // (in config.inc.php) $cfg['ForeignKeyDropdownOrder'] = array('content-id');
388 if (is_int($key2) && $key2 == 0) {
389 unset($args[0]);
391 $args[0][$key2] = $value2;
394 return $args[0];
395 break;
396 default :
397 $args = func_get_args();
398 $args[1] = PMA_array_merge_recursive($args[0], $args[1]);
399 array_shift($args);
400 return call_user_func_array('PMA_array_merge_recursive', $args);
401 break;
406 * calls $function vor every element in $array recursively
408 * this function is protected against deep recursion attack CVE-2006-1549,
409 * 1000 seems to be more than enough
411 * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
412 * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
414 * @uses PMA_arrayWalkRecursive()
415 * @uses is_array()
416 * @uses is_string()
417 * @param array $array array to walk
418 * @param string $function function to call for every array element
420 function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
422 static $recursive_counter = 0;
423 if (++$recursive_counter > 1000) {
424 die('possible deep recursion attack');
426 foreach ($array as $key => $value) {
427 if (is_array($value)) {
428 PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
429 } else {
430 $array[$key] = $function($value);
433 if ($apply_to_keys_also && is_string($key)) {
434 $new_key = $function($key);
435 if ($new_key != $key) {
436 $array[$new_key] = $array[$key];
437 unset($array[$key]);
441 $recursive_counter--;
445 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
447 * checks given given $page against given $whitelist and returns true if valid
448 * it ignores optionaly query paramters in $page (script.php?ignored)
450 * @uses in_array()
451 * @uses urldecode()
452 * @uses substr()
453 * @uses strpos()
454 * @param string &$page page to check
455 * @param array $whitelist whitelist to check page against
456 * @return boolean whether $page is valid or not (in $whitelist or not)
458 function PMA_checkPageValidity(&$page, $whitelist)
460 if (! isset($page) || !is_string($page)) {
461 return false;
464 if (in_array($page, $whitelist)) {
465 return true;
466 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
467 return true;
468 } else {
469 $_page = urldecode($page);
470 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
471 return true;
474 return false;
478 * trys to find the value for the given environment vriable name
480 * searchs in $_SERVER, $_ENV than trys getenv() and apache_getenv()
481 * in this order
483 * @uses $_SERVER
484 * @uses $_ENV
485 * @uses getenv()
486 * @uses function_exists()
487 * @uses apache_getenv()
488 * @param string $var_name variable name
489 * @return string value of $var or empty string
491 function PMA_getenv($var_name) {
492 if (isset($_SERVER[$var_name])) {
493 return $_SERVER[$var_name];
494 } elseif (isset($_ENV[$var_name])) {
495 return $_ENV[$var_name];
496 } elseif (getenv($var_name)) {
497 return getenv($var_name);
498 } elseif (function_exists('apache_getenv')
499 && apache_getenv($var_name, true)) {
500 return apache_getenv($var_name, true);
503 return '';
507 * Send HTTP header, taking IIS limits into account (600 seems ok)
509 * @uses PMA_IS_IIS
510 * @uses PMA_COMING_FROM_COOKIE_LOGIN
511 * @uses PMA_get_arg_separator()
512 * @uses SID
513 * @uses strlen()
514 * @uses strpos()
515 * @uses header()
516 * @uses session_write_close()
517 * @uses headers_sent()
518 * @uses function_exists()
519 * @uses debug_print_backtrace()
520 * @uses trigger_error()
521 * @uses defined()
522 * @param string $uri the header to send
523 * @return boolean always true
525 function PMA_sendHeaderLocation($uri)
527 if (PMA_IS_IIS && strlen($uri) > 600) {
528 require_once './libraries/js_escape.lib.php';
530 echo '<html><head><title>- - -</title>' . "\n";
531 echo '<meta http-equiv="expires" content="0">' . "\n";
532 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
533 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
534 echo '<meta http-equiv="Refresh" content="0;url=' . htmlspecialchars($uri) . '">' . "\n";
535 echo '<script type="text/javascript">' . "\n";
536 echo '//<![CDATA[' . "\n";
537 echo 'setTimeout("window.location = unescape(\'"' . PMA_escapeJsString($uri) . '"\')", 2000);' . "\n";
538 echo '//]]>' . "\n";
539 echo '</script>' . "\n";
540 echo '</head>' . "\n";
541 echo '<body>' . "\n";
542 echo '<script type="text/javascript">' . "\n";
543 echo '//<![CDATA[' . "\n";
544 echo 'document.write(\'<p><a href="' . htmlspecialchars($uri) . '">' . __('Go') . '</a></p>\');' . "\n";
545 echo '//]]>' . "\n";
546 echo '</script></body></html>' . "\n";
548 } else {
549 if (SID) {
550 if (strpos($uri, '?') === false) {
551 header('Location: ' . $uri . '?' . SID);
552 } else {
553 $separator = PMA_get_arg_separator();
554 header('Location: ' . $uri . $separator . SID);
556 } else {
557 session_write_close();
558 if (headers_sent()) {
559 if (function_exists('debug_print_backtrace')) {
560 echo '<pre>';
561 debug_print_backtrace();
562 echo '</pre>';
564 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
566 // bug #1523784: IE6 does not like 'Refresh: 0', it
567 // results in a blank page
568 // but we need it when coming from the cookie login panel)
569 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
570 header('Refresh: 0; ' . $uri);
571 } else {
572 header('Location: ' . $uri);
579 * Returns value of an element in $array given by $path.
580 * $path is a string describing position of an element in an associative array,
581 * eg. Servers/1/host refers to $array[Servers][1][host]
583 * @param string $path
584 * @param array $array
585 * @param mixed $default
586 * @return mixed array element or $default
588 function PMA_array_read($path, $array, $default = null)
590 $keys = explode('/', $path);
591 $value =& $array;
592 foreach ($keys as $key) {
593 if (!isset($value[$key])) {
594 return $default;
596 $value =& $value[$key];
598 return $value;
602 * Stores value in an array
604 * @param string $path
605 * @param array &$array
606 * @param mixed $value
608 function PMA_array_write($path, &$array, $value)
610 $keys = explode('/', $path);
611 $last_key = array_pop($keys);
612 $a =& $array;
613 foreach ($keys as $key) {
614 if (!isset($a[$key])) {
615 $a[$key] = array();
617 $a =& $a[$key];
619 $a[$last_key] = $value;
623 * Removes value from an array
625 * @param string $path
626 * @param array &$array
627 * @param mixed $value
629 function PMA_array_remove($path, &$array)
631 $keys = explode('/', $path);
632 $keys_last = array_pop($keys);
633 $path = array();
634 $depth = 0;
636 $path[0] =& $array;
637 $found = true;
638 // go as deep as required or possible
639 foreach ($keys as $key) {
640 if (!isset($path[$depth][$key])) {
641 $found = false;
642 break;
644 $depth++;
645 $path[$depth] =& $path[$depth-1][$key];
647 // if element found, remove it
648 if ($found) {
649 unset($path[$depth][$keys_last]);
650 $depth--;
653 // remove empty nested arrays
654 for (; $depth >= 0; $depth--) {
655 if (!isset($path[$depth+1]) || count($path[$depth+1]) == 0) {
656 unset($path[$depth][$keys[$depth]]);
657 } else {
658 break;