added japanese language
[openemr.git] / phpmyadmin / libraries / core.lib.php
bloba415f3f6159643f05ad9d089af2a6722d7bd65be
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 */
10 if (! defined('PHPMYADMIN')) {
11 exit;
14 /**
15 * checks given $var and returns it if valid, or $default of not valid
16 * given $var is also checked for type being 'similar' as $default
17 * or against any other type if $type is provided
19 * <code>
20 * // $_REQUEST['db'] not set
21 * echo PMA_ifSetOr($_REQUEST['db'], ''); // ''
22 * // $_REQUEST['sql_query'] not set
23 * echo PMA_ifSetOr($_REQUEST['sql_query']); // null
24 * // $cfg['ForceSSL'] not set
25 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
26 * echo PMA_ifSetOr($cfg['ForceSSL']); // null
27 * // $cfg['ForceSSL'] set to 1
28 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
29 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'similar'); // 1
30 * echo PMA_ifSetOr($cfg['ForceSSL'], false); // 1
31 * // $cfg['ForceSSL'] set to true
32 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // true
33 * </code>
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
39 * @return mixed $var or $default
41 * @see PMA_isValid()
43 function PMA_ifSetOr(&$var, $default = null, $type = 'similar')
45 if (! PMA_isValid($var, $type, $default)) {
46 return $default;
49 return $var;
52 /**
53 * checks given $var against $type or $compare
55 * $type can be:
56 * - false : no type checking
57 * - 'scalar' : whether type of $var is integer, float, string or boolean
58 * - 'numeric' : whether type of $var is any number representation
59 * - 'length' : whether type of $var is scalar with a string length > 0
60 * - 'similar' : whether type of $var is similar to type of $compare
61 * - 'equal' : whether type of $var is identical to type of $compare
62 * - 'identical' : whether $var is identical to $compare, not only the type!
63 * - or any other valid PHP variable type
65 * <code>
66 * // $_REQUEST['doit'] = true;
67 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false
68 * // $_REQUEST['doit'] = 'true';
69 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true
70 * </code>
72 * NOTE: call-by-reference is used to not get NOTICE on undefined vars,
73 * but the var is not altered inside this function, also after checking a var
74 * this var exists nut is not set, example:
75 * <code>
76 * // $var is not set
77 * isset($var); // false
78 * functionCallByReference($var); // false
79 * isset($var); // true
80 * functionCallByReference($var); // true
81 * </code>
83 * to avoid this we set this var to null if not isset
85 * @param mixed &$var variable to check
86 * @param mixed $type var type or array of valid values to check against $var
87 * @param mixed $compare var to compare with $var
89 * @return boolean whether valid or not
91 * @todo add some more var types like hex, bin, ...?
92 * @see http://php.net/gettype
94 function PMA_isValid(&$var, $type = 'length', $compare = null)
96 if (! isset($var)) {
97 // var is not even set
98 return false;
101 if ($type === false) {
102 // no vartype requested
103 return true;
106 if (is_array($type)) {
107 return in_array($var, $type);
110 // allow some aliaes of var types
111 $type = strtolower($type);
112 switch ($type) {
113 case 'identic' :
114 $type = 'identical';
115 break;
116 case 'len' :
117 $type = 'length';
118 break;
119 case 'bool' :
120 $type = 'boolean';
121 break;
122 case 'float' :
123 $type = 'double';
124 break;
125 case 'int' :
126 $type = 'integer';
127 break;
128 case 'null' :
129 $type = 'NULL';
130 break;
133 if ($type === 'identical') {
134 return $var === $compare;
137 // whether we should check against given $compare
138 if ($type === 'similar') {
139 switch (gettype($compare)) {
140 case 'string':
141 case 'boolean':
142 $type = 'scalar';
143 break;
144 case 'integer':
145 case 'double':
146 $type = 'numeric';
147 break;
148 default:
149 $type = gettype($compare);
151 } elseif ($type === 'equal') {
152 $type = gettype($compare);
155 // do the check
156 if ($type === 'length' || $type === 'scalar') {
157 $is_scalar = is_scalar($var);
158 if ($is_scalar && $type === 'length') {
159 return (bool) strlen($var);
161 return $is_scalar;
164 if ($type === 'numeric') {
165 return is_numeric($var);
168 if (gettype($var) === $type) {
169 return true;
172 return false;
176 * Removes insecure parts in a path; used before include() or
177 * require() when a part of the path comes from an insecure source
178 * like a cookie or form.
180 * @param string $path The path to check
182 * @return string The secured path
184 * @access public
186 function PMA_securePath($path)
188 // change .. to .
189 $path = preg_replace('@\.\.*@', '.', $path);
191 return $path;
192 } // end function
195 * displays the given error message on phpMyAdmin error page in foreign language,
196 * ends script execution and closes session
198 * loads language file if not loaded already
200 * @param string $error_message the error message or named error message
201 * @param string|array $message_args arguments applied to $error_message
202 * @param boolean $delete_session whether to delete session cookie
204 * @return void
206 function PMA_fatalError(
207 $error_message, $message_args = null, $delete_session = true
209 /* Use format string if applicable */
210 if (is_string($message_args)) {
211 $error_message = sprintf($error_message, $message_args);
212 } elseif (is_array($message_args)) {
213 $error_message = vsprintf($error_message, $message_args);
216 if ($GLOBALS['is_ajax_request']) {
217 $response = PMA_Response::getInstance();
218 $response->isSuccess(false);
219 $response->addJSON('message', PMA_Message::error($error_message));
220 } else {
221 $error_message = strtr($error_message, array('<br />' => '[br]'));
223 /* Load gettext for fatal errors */
224 if (!function_exists('__')) {
225 include_once './libraries/php-gettext/gettext.inc';
228 // these variables are used in the included file libraries/error.inc.php
229 $error_header = __('Error');
230 $lang = $GLOBALS['available_languages'][$GLOBALS['lang']][1];
231 $dir = $GLOBALS['text_dir'];
233 // on fatal errors it cannot hurt to always delete the current session
234 if ($delete_session
235 && isset($GLOBALS['session_name'])
236 && isset($_COOKIE[$GLOBALS['session_name']])
238 $GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
241 // Displays the error message
242 include './libraries/error.inc.php';
244 if (! defined('TESTSUITE')) {
245 exit;
250 * Returns a link to the PHP documentation
252 * @param string $target anchor in documentation
254 * @return string the URL
256 * @access public
258 function PMA_getPHPDocLink($target)
260 /* List of PHP documentation translations */
261 $php_doc_languages = array(
262 'pt_BR', 'zh', 'fr', 'de', 'it', 'ja', 'pl', 'ro', 'ru', 'fa', 'es', 'tr'
265 $lang = 'en';
266 if (in_array($GLOBALS['lang'], $php_doc_languages)) {
267 $lang = $GLOBALS['lang'];
270 return PMA_linkURL('http://php.net/manual/' . $lang . '/' . $target);
274 * Warn or fail on missing extension.
276 * @param string $extension Extension name
277 * @param bool $fatal Whether the error is fatal.
278 * @param string $extra Extra string to append to messsage.
280 * @return void
282 function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
284 /* Gettext does not have to be loaded yet here */
285 if (function_exists('__')) {
286 $message = __(
287 'The %s extension is missing. Please check your PHP configuration.'
289 } else {
290 $message
291 = 'The %s extension is missing. Please check your PHP configuration.';
293 $doclink = PMA_getPHPDocLink('book.' . $extension . '.php');
294 $message = sprintf(
295 $message,
296 '[a@' . $doclink . '@Documentation][em]' . $extension . '[/em][/a]'
298 if ($extra != '') {
299 $message .= ' ' . $extra;
301 if ($fatal) {
302 PMA_fatalError($message);
303 return;
306 $GLOBALS['error_handler']->addError(
307 $message,
308 E_USER_WARNING,
311 false
316 * returns count of tables in given db
318 * @param string $db database to count tables for
320 * @return integer count of tables in $db
322 function PMA_getTableCount($db)
324 $tables = $GLOBALS['dbi']->tryQuery(
325 'SHOW TABLES FROM ' . PMA_Util::backquote($db) . ';',
326 null, PMA_DatabaseInterface::QUERY_STORE
328 if ($tables) {
329 $num_tables = $GLOBALS['dbi']->numRows($tables);
330 $GLOBALS['dbi']->freeResult($tables);
331 } else {
332 $num_tables = 0;
335 return $num_tables;
339 * Converts numbers like 10M into bytes
340 * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
341 * (renamed with PMA prefix to avoid double definition when embedded
342 * in Moodle)
344 * @param string|int $size size (Default = 0)
346 * @return integer $size
348 function PMA_getRealSize($size = 0)
350 if (! $size) {
351 return 0;
354 $scan = array();
355 $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
356 $scan['g'] = 1073741824; //1024 * 1024 * 1024;
357 $scan['mb'] = 1048576;
358 $scan['m'] = 1048576;
359 $scan['kb'] = 1024;
360 $scan['k'] = 1024;
361 $scan['b'] = 1;
363 foreach ($scan as $unit => $factor) {
364 if (strlen($size) > strlen($unit)
365 && strtolower(substr($size, strlen($size) - strlen($unit))) == $unit
367 return substr($size, 0, strlen($size) - strlen($unit)) * $factor;
371 return $size;
372 } // end function PMA_getRealSize()
375 * merges array recursive like array_merge_recursive() but keyed-values are
376 * always overwritten.
378 * array PMA_arrayMergeRecursive(array $array1[, array $array2[, array ...]])
380 * @return array merged array
382 * @see http://php.net/array_merge
383 * @see http://php.net/array_merge_recursive
385 function PMA_arrayMergeRecursive()
387 switch(func_num_args()) {
388 case 0 :
389 return false;
390 break;
391 case 1 :
392 // when does that happen?
393 return func_get_arg(0);
394 break;
395 case 2 :
396 $args = func_get_args();
397 if (! is_array($args[0]) || ! is_array($args[1])) {
398 return $args[1];
400 foreach ($args[1] as $key2 => $value2) {
401 if (isset($args[0][$key2]) && !is_int($key2)) {
402 $args[0][$key2] = PMA_arrayMergeRecursive(
403 $args[0][$key2], $value2
405 } else {
406 // we erase the parent array, otherwise we cannot override
407 // a directive that contains array elements, like this:
408 // (in config.default.php)
409 // $cfg['ForeignKeyDropdownOrder']= array('id-content','content-id');
410 // (in config.inc.php)
411 // $cfg['ForeignKeyDropdownOrder']= array('content-id');
412 if (is_int($key2) && $key2 == 0) {
413 unset($args[0]);
415 $args[0][$key2] = $value2;
418 return $args[0];
419 break;
420 default :
421 $args = func_get_args();
422 $args[1] = PMA_arrayMergeRecursive($args[0], $args[1]);
423 array_shift($args);
424 return call_user_func_array('PMA_arrayMergeRecursive', $args);
425 break;
430 * calls $function for every element in $array recursively
432 * this function is protected against deep recursion attack CVE-2006-1549,
433 * 1000 seems to be more than enough
435 * @param array &$array array to walk
436 * @param string $function function to call for every array element
437 * @param bool $apply_to_keys_also whether to call the function for the keys also
439 * @return void
441 * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
442 * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
444 function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
446 static $recursive_counter = 0;
447 $walked_keys = array();
449 if (++$recursive_counter > 1000) {
450 PMA_fatalError(__('possible deep recursion attack'));
452 foreach ($array as $key => $value) {
453 if (isset($walked_keys[$key])) {
454 continue;
456 $walked_keys[$key] = true;
458 if (is_array($value)) {
459 PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
460 } else {
461 $array[$key] = $function($value);
464 if ($apply_to_keys_also && is_string($key)) {
465 $new_key = $function($key);
466 if ($new_key != $key) {
467 $array[$new_key] = $array[$key];
468 unset($array[$key]);
469 $walked_keys[$new_key] = true;
473 $recursive_counter--;
477 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
479 * checks given $page against given $whitelist and returns true if valid
480 * it optionally ignores query parameters in $page (script.php?ignored)
482 * @param string &$page page to check
483 * @param array $whitelist whitelist to check page against
485 * @return boolean whether $page is valid or not (in $whitelist or not)
487 function PMA_checkPageValidity(&$page, $whitelist)
489 if (! isset($page) || !is_string($page)) {
490 return false;
493 if (in_array($page, $whitelist)) {
494 return true;
497 if (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
498 return true;
501 $_page = urldecode($page);
502 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
503 return true;
506 return false;
510 * tries to find the value for the given environment variable name
512 * searches in $_SERVER, $_ENV then tries getenv() and apache_getenv()
513 * in this order
515 * @param string $var_name variable name
517 * @return string value of $var or empty string
519 function PMA_getenv($var_name)
521 if (isset($_SERVER[$var_name])) {
522 return $_SERVER[$var_name];
525 if (isset($_ENV[$var_name])) {
526 return $_ENV[$var_name];
529 if (getenv($var_name)) {
530 return getenv($var_name);
533 if (function_exists('apache_getenv')
534 && apache_getenv($var_name, true)
536 return apache_getenv($var_name, true);
539 return '';
543 * Send HTTP header, taking IIS limits into account (600 seems ok)
545 * @param string $uri the header to send
546 * @param bool $use_refresh whether to use Refresh: header when running on IIS
548 * @return boolean always true
550 function PMA_sendHeaderLocation($uri, $use_refresh = false)
552 if (PMA_IS_IIS && strlen($uri) > 600) {
553 include_once './libraries/js_escape.lib.php';
554 PMA_Response::getInstance()->disable();
556 echo '<html><head><title>- - -</title>' . "\n";
557 echo '<meta http-equiv="expires" content="0">' . "\n";
558 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
559 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
560 echo '<meta http-equiv="Refresh" content="0;url='
561 . htmlspecialchars($uri) . '">' . "\n";
562 echo '<script type="text/javascript">' . "\n";
563 echo '//<![CDATA[' . "\n";
564 echo 'setTimeout("window.location = unescape(\'"'
565 . PMA_escapeJsString($uri) . '"\')", 2000);' . "\n";
566 echo '//]]>' . "\n";
567 echo '</script>' . "\n";
568 echo '</head>' . "\n";
569 echo '<body>' . "\n";
570 echo '<script type="text/javascript">' . "\n";
571 echo '//<![CDATA[' . "\n";
572 echo 'document.write(\'<p><a href="' . htmlspecialchars($uri) . '">'
573 . __('Go') . '</a></p>\');' . "\n";
574 echo '//]]>' . "\n";
575 echo '</script></body></html>' . "\n";
577 return;
580 if (SID) {
581 if (strpos($uri, '?') === false) {
582 header('Location: ' . $uri . '?' . SID);
583 } else {
584 $separator = PMA_URL_getArgSeparator();
585 header('Location: ' . $uri . $separator . SID);
587 return;
590 session_write_close();
591 if (headers_sent()) {
592 if (function_exists('debug_print_backtrace')) {
593 echo '<pre>';
594 debug_print_backtrace();
595 echo '</pre>';
597 trigger_error(
598 'PMA_sendHeaderLocation called when headers are already sent!',
599 E_USER_ERROR
602 // bug #1523784: IE6 does not like 'Refresh: 0', it
603 // results in a blank page
604 // but we need it when coming from the cookie login panel)
605 if (PMA_IS_IIS && $use_refresh) {
606 header('Refresh: 0; ' . $uri);
607 } else {
608 header('Location: ' . $uri);
613 * Outputs headers to prevent caching in browser (and on the way).
615 * @return void
617 function PMA_noCacheHeader()
619 if (defined('TESTSUITE')) {
620 return;
622 // rfc2616 - Section 14.21
623 header('Expires: ' . date(DATE_RFC1123));
624 // HTTP/1.1
625 header(
626 'Cache-Control: no-store, no-cache, must-revalidate,'
627 . ' pre-check=0, post-check=0, max-age=0'
629 if (PMA_USR_BROWSER_AGENT == 'IE') {
630 /* On SSL IE sometimes fails with:
632 * Internet Explorer was not able to open this Internet site. The
633 * requested site is either unavailable or cannot be found. Please
634 * try again later.
636 * Adding Pragma: public fixes this.
638 header('Pragma: public');
639 return;
642 header('Pragma: no-cache'); // HTTP/1.0
643 // test case: exporting a database into a .gz file with Safari
644 // would produce files not having the current time
645 // (added this header for Safari but should not harm other browsers)
646 header('Last-Modified: ' . date(DATE_RFC1123));
651 * Sends header indicating file download.
653 * @param string $filename Filename to include in headers if empty,
654 * none Content-Disposition header will be sent.
655 * @param string $mimetype MIME type to include in headers.
656 * @param int $length Length of content (optional)
657 * @param bool $no_cache Whether to include no-caching headers.
659 * @return void
661 function PMA_downloadHeader($filename, $mimetype, $length = 0, $no_cache = true)
663 if ($no_cache) {
664 PMA_noCacheHeader();
666 /* Replace all possibly dangerous chars in filename */
667 $filename = str_replace(array(';', '"', "\n", "\r"), '-', $filename);
668 if (!empty($filename)) {
669 header('Content-Description: File Transfer');
670 header('Content-Disposition: attachment; filename="' . $filename . '"');
672 header('Content-Type: ' . $mimetype);
673 // inform the server that compression has been done,
674 // to avoid a double compression (for example with Apache + mod_deflate)
675 if (strpos($mimetype, 'gzip') !== false) {
676 header('Content-Encoding: gzip');
678 header('Content-Transfer-Encoding: binary');
679 if ($length > 0) {
680 header('Content-Length: ' . $length);
685 * Checks whether element given by $path exists in $array.
686 * $path is a string describing position of an element in an associative array,
687 * eg. Servers/1/host refers to $array[Servers][1][host]
689 * @param string $path path in the arry
690 * @param array $array the array
692 * @return mixed array element or $default
694 function PMA_arrayKeyExists($path, $array)
696 $keys = explode('/', $path);
697 $value =& $array;
698 foreach ($keys as $key) {
699 if (! isset($value[$key])) {
700 return false;
702 $value =& $value[$key];
704 return true;
708 * Returns value of an element in $array given by $path.
709 * $path is a string describing position of an element in an associative array,
710 * eg. Servers/1/host refers to $array[Servers][1][host]
712 * @param string $path path in the arry
713 * @param array $array the array
714 * @param mixed $default default value
716 * @return mixed array element or $default
718 function PMA_arrayRead($path, $array, $default = null)
720 $keys = explode('/', $path);
721 $value =& $array;
722 foreach ($keys as $key) {
723 if (! isset($value[$key])) {
724 return $default;
726 $value =& $value[$key];
728 return $value;
732 * Stores value in an array
734 * @param string $path path in the array
735 * @param array &$array the array
736 * @param mixed $value value to store
738 * @return void
740 function PMA_arrayWrite($path, &$array, $value)
742 $keys = explode('/', $path);
743 $last_key = array_pop($keys);
744 $a =& $array;
745 foreach ($keys as $key) {
746 if (! isset($a[$key])) {
747 $a[$key] = array();
749 $a =& $a[$key];
751 $a[$last_key] = $value;
755 * Removes value from an array
757 * @param string $path path in the array
758 * @param array &$array the array
760 * @return void
762 function PMA_arrayRemove($path, &$array)
764 $keys = explode('/', $path);
765 $keys_last = array_pop($keys);
766 $path = array();
767 $depth = 0;
769 $path[0] =& $array;
770 $found = true;
771 // go as deep as required or possible
772 foreach ($keys as $key) {
773 if (! isset($path[$depth][$key])) {
774 $found = false;
775 break;
777 $depth++;
778 $path[$depth] =& $path[$depth-1][$key];
780 // if element found, remove it
781 if ($found) {
782 unset($path[$depth][$keys_last]);
783 $depth--;
786 // remove empty nested arrays
787 for (; $depth >= 0; $depth--) {
788 if (! isset($path[$depth+1]) || count($path[$depth+1]) == 0) {
789 unset($path[$depth][$keys[$depth]]);
790 } else {
791 break;
797 * Returns link to (possibly) external site using defined redirector.
799 * @param string $url URL where to go.
801 * @return string URL for a link.
803 function PMA_linkURL($url)
805 if (!preg_match('#^https?://#', $url) || defined('PMA_SETUP')) {
806 return $url;
809 if (!function_exists('PMA_URL_getCommon')) {
810 include_once './libraries/url_generating.lib.php';
812 $params = array();
813 $params['url'] = $url;
815 $url = PMA_URL_getCommon($params);
816 //strip off token and such sensitive information. Just keep url.
817 $arr = parse_url($url);
818 parse_str($arr["query"], $vars);
819 $query = http_build_query(array("url" => $vars["url"]));
820 $url = './url.php?' . $query;
822 return $url;
826 * Checks whether domain of URL is whitelisted domain or not.
827 * Use only for URLs of external sites.
829 * @param string $url URL of external site.
831 * @return boolean.True:if domain of $url is allowed domain, False:otherwise.
833 function PMA_isAllowedDomain($url)
835 $arr = parse_url($url);
836 $domain = $arr["host"];
837 $domainWhiteList = array(
838 /* Include current domain */
839 $_SERVER['SERVER_NAME'],
840 /* phpMyAdmin domains */
841 'wiki.phpmyadmin.net', 'www.phpMyAdmin.net', 'phpmyadmin.net',
842 'docs.phpmyadmin.net',
843 /* mysql.com domains */
844 'dev.mysql.com','bugs.mysql.com',
845 /* php.net domains */
846 'php.net',
847 /* Github domains*/
848 'github.com','www.github.com',
849 /* Following are doubtful ones. */
850 'www.primebase.com','pbxt.blogspot.com'
852 if (in_array($domain, $domainWhiteList)) {
853 return true;
856 return false;
861 * Adds JS code snippets to be displayed by the PMA_Response class.
862 * Adds a newline to each snippet.
864 * @param string $str Js code to be added (e.g. "token=1234;")
866 * @return void
868 function PMA_addJSCode($str)
870 $response = PMA_Response::getInstance();
871 $header = $response->getHeader();
872 $scripts = $header->getScripts();
873 $scripts->addCode($str);
877 * Adds JS code snippet for variable assignment
878 * to be displayed by the PMA_Response class.
880 * @param string $key Name of value to set
881 * @param mixed $value Value to set, can be either string or array of strings
882 * @param bool $escape Whether to escape value or keep it as it is
883 * (for inclusion of js code)
885 * @return void
887 function PMA_addJSVar($key, $value, $escape = true)
889 PMA_addJSCode(PMA_getJsValue($key, $value, $escape));