Fix format strings
[phpmyadmin/madhuracj.git] / libraries / core.lib.php
blob9587071b961d91f500c7ecb7951c95c7b80ec8cf
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 include './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)
244 /* Gettext does not have to be loaded yet */
245 if (function_exists('_pgettext')) {
246 /* l10n: Please check that translation actually exists. */
247 $lang = _pgettext('PHP documentation language', 'en');
248 } else {
249 $lang = 'en';
252 return PMA_linkURL('http://php.net/manual/' . $lang . '/' . $target);
256 * Warn or fail on missing extension.
258 * @param string $extension Extension name
259 * @param bool $fatal Whether the error is fatal.
260 / @param string $extra Extra string to append to messsage.
262 function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
264 /* Gettext does not have to be loaded yet here */
265 if (function_exists('__')) {
266 $message = __('The %s extension is missing. Please check your PHP configuration.');
267 } else {
268 $message = 'The %s extension is missing. Please check your PHP configuration.';
270 $message = sprintf($message,
271 '[a@' . PMA_getPHPDocLink('book.' . $extension . '.php') . '@Documentation][em]' . $extension . '[/em][/a]');
272 if ($extra != '') {
273 $message .= ' ' . $extra;
275 if ($fatal) {
276 PMA_fatalError($message);
277 } else {
278 trigger_error($message, E_USER_WARNING);
283 * returns count of tables in given db
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 * @param string $size
318 * @return integer $size
320 function PMA_get_real_size($size = 0)
322 if (! $size) {
323 return 0;
326 $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
327 $scan['g'] = 1073741824; //1024 * 1024 * 1024;
328 $scan['mb'] = 1048576;
329 $scan['m'] = 1048576;
330 $scan['kb'] = 1024;
331 $scan['k'] = 1024;
332 $scan['b'] = 1;
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;
341 return $size;
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 * @param array array to merge
353 * @param array array to merge
354 * @param array ...
355 * @return array merged array
357 function PMA_array_merge_recursive()
359 switch(func_num_args()) {
360 case 0 :
361 return false;
362 break;
363 case 1 :
364 // when does that happen?
365 return func_get_arg(0);
366 break;
367 case 2 :
368 $args = func_get_args();
369 if (! is_array($args[0]) || ! is_array($args[1])) {
370 return $args[1];
372 foreach ($args[1] as $key2 => $value2) {
373 if (isset($args[0][$key2]) && !is_int($key2)) {
374 $args[0][$key2] = PMA_array_merge_recursive($args[0][$key2],
375 $value2);
376 } else {
377 // we erase the parent array, otherwise we cannot override a directive that
378 // contains array elements, like this:
379 // (in config.default.php) $cfg['ForeignKeyDropdownOrder'] = array('id-content','content-id');
380 // (in config.inc.php) $cfg['ForeignKeyDropdownOrder'] = array('content-id');
381 if (is_int($key2) && $key2 == 0) {
382 unset($args[0]);
384 $args[0][$key2] = $value2;
387 return $args[0];
388 break;
389 default :
390 $args = func_get_args();
391 $args[1] = PMA_array_merge_recursive($args[0], $args[1]);
392 array_shift($args);
393 return call_user_func_array('PMA_array_merge_recursive', $args);
394 break;
399 * calls $function vor every element in $array recursively
401 * this function is protected against deep recursion attack CVE-2006-1549,
402 * 1000 seems to be more than enough
404 * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
405 * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
407 * @param array $array array to walk
408 * @param string $function function to call for every array element
410 function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
412 static $recursive_counter = 0;
413 if (++$recursive_counter > 1000) {
414 die(__('possible deep recursion attack'));
416 foreach ($array as $key => $value) {
417 if (is_array($value)) {
418 PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
419 } else {
420 $array[$key] = $function($value);
423 if ($apply_to_keys_also && is_string($key)) {
424 $new_key = $function($key);
425 if ($new_key != $key) {
426 $array[$new_key] = $array[$key];
427 unset($array[$key]);
431 $recursive_counter--;
435 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
437 * checks given given $page against given $whitelist and returns true if valid
438 * it ignores optionaly query paramters in $page (script.php?ignored)
440 * @param string &$page page to check
441 * @param array $whitelist whitelist to check page against
442 * @return boolean whether $page is valid or not (in $whitelist or not)
444 function PMA_checkPageValidity(&$page, $whitelist)
446 if (! isset($page) || !is_string($page)) {
447 return false;
450 if (in_array($page, $whitelist)) {
451 return true;
452 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
453 return true;
454 } else {
455 $_page = urldecode($page);
456 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
457 return true;
460 return false;
464 * trys to find the value for the given environment vriable name
466 * searchs in $_SERVER, $_ENV than trys getenv() and apache_getenv()
467 * in this order
469 * @param string $var_name variable name
470 * @return string value of $var or empty string
472 function PMA_getenv($var_name)
474 if (isset($_SERVER[$var_name])) {
475 return $_SERVER[$var_name];
476 } elseif (isset($_ENV[$var_name])) {
477 return $_ENV[$var_name];
478 } elseif (getenv($var_name)) {
479 return getenv($var_name);
480 } elseif (function_exists('apache_getenv')
481 && apache_getenv($var_name, true)) {
482 return apache_getenv($var_name, true);
485 return '';
489 * Send HTTP header, taking IIS limits into account (600 seems ok)
491 * @param string $uri the header to send
492 * @return boolean always true
494 function PMA_sendHeaderLocation($uri)
496 if (PMA_IS_IIS && strlen($uri) > 600) {
497 include_once './libraries/js_escape.lib.php';
499 echo '<html><head><title>- - -</title>' . "\n";
500 echo '<meta http-equiv="expires" content="0">' . "\n";
501 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
502 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
503 echo '<meta http-equiv="Refresh" content="0;url=' . htmlspecialchars($uri) . '">' . "\n";
504 echo '<script type="text/javascript">' . "\n";
505 echo '//<![CDATA[' . "\n";
506 echo 'setTimeout("window.location = unescape(\'"' . PMA_escapeJsString($uri) . '"\')", 2000);' . "\n";
507 echo '//]]>' . "\n";
508 echo '</script>' . "\n";
509 echo '</head>' . "\n";
510 echo '<body>' . "\n";
511 echo '<script type="text/javascript">' . "\n";
512 echo '//<![CDATA[' . "\n";
513 echo 'document.write(\'<p><a href="' . htmlspecialchars($uri) . '">' . __('Go') . '</a></p>\');' . "\n";
514 echo '//]]>' . "\n";
515 echo '</script></body></html>' . "\n";
517 } else {
518 if (SID) {
519 if (strpos($uri, '?') === false) {
520 header('Location: ' . $uri . '?' . SID);
521 } else {
522 $separator = PMA_get_arg_separator();
523 header('Location: ' . $uri . $separator . SID);
525 } else {
526 session_write_close();
527 if (headers_sent()) {
528 if (function_exists('debug_print_backtrace')) {
529 echo '<pre>';
530 debug_print_backtrace();
531 echo '</pre>';
533 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
535 // bug #1523784: IE6 does not like 'Refresh: 0', it
536 // results in a blank page
537 // but we need it when coming from the cookie login panel)
538 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
539 header('Refresh: 0; ' . $uri);
540 } else {
541 header('Location: ' . $uri);
548 * Outputs headers to prevent caching in browser (and on the way).
550 * @return nothing
552 function PMA_no_cache_header()
554 header('Expires: ' . date(DATE_RFC1123)); // rfc2616 - Section 14.21
555 header('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
556 if (PMA_USR_BROWSER_AGENT == 'IE') {
557 /* FIXME: Why is this speecial case for IE needed? */
558 header('Pragma: public');
559 } else {
560 header('Pragma: no-cache'); // HTTP/1.0
561 // test case: exporting a database into a .gz file with Safari
562 // would produce files not having the current time
563 // (added this header for Safari but should not harm other browsers)
564 header('Last-Modified: ' . date(DATE_RFC1123));
570 * Sends header indicating file download.
572 * @param string $filename Filename to include in headers if empty,
573 * none Content-Disposition header will be sent.
574 * @param string $mimetype MIME type to include in headers.
575 * @param int $length Length of content (optional)
576 * @param bool $no_cache Whether to include no-caching headers.
578 * @return nothing
580 function PMA_download_header($filename, $mimetype, $length = 0, $no_cache = true)
582 if ($no_cache) {
583 PMA_no_cache_header();
585 /* Replace all possibly dangerous chars in filename */
586 $filename = str_replace(array(';', '"', "\n", "\r"), '-', $filename);
587 if (!empty($filename)) {
588 header('Content-Description: File Transfer');
589 header('Content-Disposition: attachment; filename="' . $filename . '"');
591 header('Content-Type: ' . $mimetype);
592 header('Content-Transfer-Encoding: binary');
593 if ($length > 0) {
594 header('Content-Length: ' . $length);
600 * Returns value of an element in $array given by $path.
601 * $path is a string describing position of an element in an associative array,
602 * eg. Servers/1/host refers to $array[Servers][1][host]
604 * @param string $path
605 * @param array $array
606 * @param mixed $default
607 * @return mixed array element or $default
609 function PMA_array_read($path, $array, $default = null)
611 $keys = explode('/', $path);
612 $value =& $array;
613 foreach ($keys as $key) {
614 if (! isset($value[$key])) {
615 return $default;
617 $value =& $value[$key];
619 return $value;
623 * Stores value in an array
625 * @param string $path
626 * @param array &$array
627 * @param mixed $value
629 function PMA_array_write($path, &$array, $value)
631 $keys = explode('/', $path);
632 $last_key = array_pop($keys);
633 $a =& $array;
634 foreach ($keys as $key) {
635 if (! isset($a[$key])) {
636 $a[$key] = array();
638 $a =& $a[$key];
640 $a[$last_key] = $value;
644 * Removes value from an array
646 * @param string $path
647 * @param array &$array
648 * @param mixed $value
650 function PMA_array_remove($path, &$array)
652 $keys = explode('/', $path);
653 $keys_last = array_pop($keys);
654 $path = array();
655 $depth = 0;
657 $path[0] =& $array;
658 $found = true;
659 // go as deep as required or possible
660 foreach ($keys as $key) {
661 if (! isset($path[$depth][$key])) {
662 $found = false;
663 break;
665 $depth++;
666 $path[$depth] =& $path[$depth-1][$key];
668 // if element found, remove it
669 if ($found) {
670 unset($path[$depth][$keys_last]);
671 $depth--;
674 // remove empty nested arrays
675 for (; $depth >= 0; $depth--) {
676 if (! isset($path[$depth+1]) || count($path[$depth+1]) == 0) {
677 unset($path[$depth][$keys[$depth]]);
678 } else {
679 break;
685 * Returns link to (possibly) external site using defined redirector.
687 * @param string $url URL where to go.
689 * @return string URL for a link.
691 function PMA_linkURL($url)
693 if (!preg_match('#^https?://#', $url) || defined('PMA_SETUP')) {
694 return $url;
695 } else {
696 if (!function_exists('PMA_generate_common_url')) {
697 include_once './libraries/url_generating.lib.php';
699 $params = array();
700 $params['url'] = $url;
701 return './url.php' . PMA_generate_common_url($params);
706 * Returns HTML code to include javascript file.
708 * @param string $url Location of javascript, relative to js/ folder.
710 * @return string HTML code for javascript inclusion.
712 function PMA_includeJS($url)
714 if (strpos($url, '?') === false) {
715 return '<script src="./js/' . $url . '?ts=' . filemtime('./js/' . $url) . '" type="text/javascript"></script>' . "\n";
716 } else {
717 return '<script src="./js/' . $url . '" type="text/javascript"></script>' . "\n";
722 * Adds JS code snippets to be displayed by header.inc.php. Adds a
723 * newline to each snippet.
725 * @param string $str Js code to be added (e.g. "token=1234;")
728 function PMA_AddJSCode($str)
730 $GLOBALS['js_script'][] = $str;
734 * Adds JS code snippet for variable assignment to be displayed by header.inc.php.
736 * @param string $key Name of value to set
737 * @param mixed $value Value to set, can be either string or array of strings
738 * @param bool $escape Whether to escape value or keep it as it is (for inclusion of js code)
741 function PMA_AddJSVar($key, $value, $escape = true)
743 PMA_AddJsCode(PMA_getJsValue($key, $value, $escape));