typo
[phpmyadmin/arisferyanto.git] / libraries / core.lib.php
bloba449710843367971fbd5aa65a3807ed007fcf74b
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 * @version $Id$
9 * @package phpMyAdmin
12 /**
13 * checks given $var and returns it if valid, or $default of not valid
14 * given $var is also checked for type being 'similar' as $default
15 * or against any other type if $type is provided
17 * <code>
18 * // $_REQUEST['db'] not set
19 * echo PMA_ifSetOr($_REQUEST['db'], ''); // ''
20 * // $_REQUEST['sql_query'] not set
21 * echo PMA_ifSetOr($_REQUEST['sql_query']); // null
22 * // $cfg['ForceSSL'] not set
23 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
24 * echo PMA_ifSetOr($cfg['ForceSSL']); // null
25 * // $cfg['ForceSSL'] set to 1
26 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
27 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'similar'); // 1
28 * echo PMA_ifSetOr($cfg['ForceSSL'], false); // 1
29 * // $cfg['ForceSSL'] set to true
30 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // true
31 * </code>
33 * @uses PMA_isValid()
34 * @see PMA_isValid()
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
38 * @return mixed $var or $default
40 function PMA_ifSetOr(&$var, $default = null, $type = 'similar')
42 if (! PMA_isValid($var, $type, $default)) {
43 return $default;
46 return $var;
49 /**
50 * checks given $var against $type or $compare
52 * $type can be:
53 * - false : no type checking
54 * - 'scalar' : whether type of $var is integer, float, string or boolean
55 * - 'numeric' : whether type of $var is any number repesentation
56 * - 'length' : whether type of $var is scalar with a string length > 0
57 * - 'similar' : whether type of $var is similar to type of $compare
58 * - 'equal' : whether type of $var is identical to type of $compare
59 * - 'identical' : whether $var is identical to $compare, not only the type!
60 * - or any other valid PHP variable type
62 * <code>
63 * // $_REQUEST['doit'] = true;
64 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false
65 * // $_REQUEST['doit'] = 'true';
66 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true
67 * </code>
69 * NOTE: call-by-reference is used to not get NOTICE on undefined vars,
70 * but the var is not altered inside this function, also after checking a var
71 * this var exists nut is not set, example:
72 * <code>
73 * // $var is not set
74 * isset($var); // false
75 * functionCallByReference($var); // false
76 * isset($var); // true
77 * functionCallByReference($var); // true
78 * </code>
80 * to avoid this we set this var to null if not isset
82 * @todo create some testsuites
83 * @todo add some more var types like hex, bin, ...?
84 * @uses is_scalar()
85 * @uses is_numeric()
86 * @uses is_array()
87 * @uses in_array()
88 * @uses gettype()
89 * @uses strtolower()
90 * @see http://php.net/gettype
91 * @param mixed $var variable to check
92 * @param mixed $type var type or array of valid values to check against $var
93 * @param mixed $compare var to compare with $var
94 * @return boolean whether valid or not
96 function PMA_isValid(&$var, $type = 'length', $compare = null)
98 if (! isset($var)) {
99 // var is not even set
100 return false;
103 if ($type === false) {
104 // no vartype requested
105 return true;
108 if (is_array($type)) {
109 return in_array($var, $type);
112 // allow some aliaes of var types
113 $type = strtolower($type);
114 switch ($type) {
115 case 'identic' :
116 $type = 'identical';
117 break;
118 case 'len' :
119 $type = 'length';
120 break;
121 case 'bool' :
122 $type = 'boolean';
123 break;
124 case 'float' :
125 $type = 'double';
126 break;
127 case 'int' :
128 $type = 'integer';
129 break;
130 case 'null' :
131 $type = 'NULL';
132 break;
135 if ($type === 'identical') {
136 return $var === $compare;
139 // whether we should check against given $compare
140 if ($type === 'similar') {
141 switch (gettype($compare)) {
142 case 'string':
143 case 'boolean':
144 $type = 'scalar';
145 break;
146 case 'integer':
147 case 'double':
148 $type = 'numeric';
149 break;
150 default:
151 $type = gettype($compare);
153 } elseif ($type === 'equal') {
154 $type = gettype($compare);
157 // do the check
158 if ($type === 'length' || $type === 'scalar') {
159 $is_scalar = is_scalar($var);
160 if ($is_scalar && $type === 'length') {
161 return (bool) strlen($var);
163 return $is_scalar;
166 if ($type === 'numeric') {
167 return is_numeric($var);
170 if (gettype($var) === $type) {
171 return true;
174 return false;
178 * Removes insecure parts in a path; used before include() or
179 * require() when a part of the path comes from an insecure source
180 * like a cookie or form.
182 * @param string The path to check
184 * @return string The secured path
186 * @access public
187 * @author Marc Delisle (lem9@users.sourceforge.net)
189 function PMA_securePath($path)
191 // change .. to .
192 $path = preg_replace('@\.\.*@', '.', $path);
194 return $path;
195 } // end function
198 * displays the given error message on phpMyAdmin error page in foreign language,
199 * ends script execution and closes session
201 * loads language file if not loaded already
203 * @todo use detected argument separator (PMA_Config)
204 * @uses $GLOBALS['session_name']
205 * @uses $GLOBALS['text_dir']
206 * @uses $GLOBALS['strError']
207 * @uses $GLOBALS['available_languages']
208 * @uses $GLOBALS['lang']
209 * @uses PMA_removeCookie()
210 * @uses select_lang.lib.php
211 * @uses $_COOKIE
212 * @uses substr()
213 * @uses header()
214 * @uses http_build_query()
215 * @uses is_string()
216 * @uses sprintf()
217 * @uses vsprintf()
218 * @uses strtr()
219 * @uses defined()
220 * @param string $error_message the error message or named error message
221 * @param string|array $message_args arguments applied to $error_message
222 * @return exit
224 function PMA_fatalError($error_message, $message_args = null)
226 // it could happen PMA_fatalError() is called before language file is loaded
227 if (! isset($GLOBALS['available_languages'])) {
228 $GLOBALS['cfg'] = array(
229 'DefaultLang' => 'en-utf-8',
230 'AllowAnywhereRecoding' => false);
232 // Loads the language file
233 require_once './libraries/select_lang.lib.php';
235 if (isset($strError)) {
236 $GLOBALS['strError'] = $strError;
237 } else {
238 $GLOBALS['strError'] = 'Error';
241 // $text_dir is set in lang/language-utf-8.inc.php
242 if (isset($text_dir)) {
243 $GLOBALS['text_dir'] = $text_dir;
247 // $error_message could be a language string identifier: strString
248 if (substr($error_message, 0, 3) === 'str') {
249 if (isset($$error_message)) {
250 $error_message = $$error_message;
251 } elseif (isset($GLOBALS[$error_message])) {
252 $error_message = $GLOBALS[$error_message];
256 if (is_string($message_args)) {
257 $error_message = sprintf($error_message, $message_args);
258 } elseif (is_array($message_args)) {
259 $error_message = vsprintf($error_message, $message_args);
261 $error_message = strtr($error_message, array('<br />' => '[br]'));
263 // Displays the error message
264 // (do not use &amp; for parameters sent by header)
265 $query_params = array(
266 'lang' => $GLOBALS['available_languages'][$GLOBALS['lang']][2],
267 'dir' => $GLOBALS['text_dir'],
268 'type' => $GLOBALS['strError'],
269 'error' => $error_message,
271 header('Location: ' . (defined('PMA_SETUP') ? '../' : '') . 'error.php?'
272 . http_build_query($query_params, null, '&'));
274 // on fatal errors it cannot hurt to always delete the current session
275 if (isset($GLOBALS['session_name']) && isset($_COOKIE[$GLOBALS['session_name']])) {
276 PMA_removeCookie($GLOBALS['session_name']);
279 exit;
283 * returns count of tables in given db
285 * @uses PMA_DBI_try_query()
286 * @uses PMA_backquote()
287 * @uses PMA_DBI_QUERY_STORE()
288 * @uses PMA_DBI_num_rows()
289 * @uses PMA_DBI_free_result()
290 * @param string $db database to count tables for
291 * @return integer count of tables in $db
293 function PMA_getTableCount($db)
295 $tables = PMA_DBI_try_query(
296 'SHOW TABLES FROM ' . PMA_backquote($db) . ';',
297 null, PMA_DBI_QUERY_STORE);
298 if ($tables) {
299 $num_tables = PMA_DBI_num_rows($tables);
301 // for blobstreaming - get blobstreaming tables
302 // for use in determining if a table here is a blobstreaming table - rajk
304 // load PMA configuration
305 $PMA_Config = $_SESSION['PMA_Config'];
307 // if PMA configuration exists
308 if (!empty($PMA_Config))
310 // load BS tables
311 $session_bs_tables = $_SESSION['PMA_Config']->get('BLOBSTREAMING_TABLES');
313 // if BS tables exist
314 if (isset ($session_bs_tables))
315 while ($data = PMA_DBI_fetch_assoc($tables))
316 foreach ($session_bs_tables as $table_key=>$table_val)
317 // if the table is a blobstreaming table, reduce the table count
318 if ($data['Tables_in_' . $db] == $table_key)
320 if ($num_tables > 0)
321 $num_tables--;
323 break;
325 } // end if PMA configuration exists
327 PMA_DBI_free_result($tables);
328 } else {
329 $num_tables = 0;
332 return $num_tables;
336 * Converts numbers like 10M into bytes
337 * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
338 * (renamed with PMA prefix to avoid double definition when embedded
339 * in Moodle)
341 * @uses each()
342 * @uses strlen()
343 * @uses substr()
344 * @param string $size
345 * @return integer $size
347 function PMA_get_real_size($size = 0)
349 if (! $size) {
350 return 0;
353 $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
354 $scan['g'] = 1073741824; //1024 * 1024 * 1024;
355 $scan['mb'] = 1048576;
356 $scan['m'] = 1048576;
357 $scan['kb'] = 1024;
358 $scan['k'] = 1024;
359 $scan['b'] = 1;
361 foreach ($scan as $unit => $factor) {
362 if (strlen($size) > strlen($unit)
363 && strtolower(substr($size, strlen($size) - strlen($unit))) == $unit) {
364 return substr($size, 0, strlen($size) - strlen($unit)) * $factor;
368 return $size;
369 } // end function PMA_get_real_size()
372 * merges array recursive like array_merge_recursive() but keyed-values are
373 * always overwritten.
375 * array PMA_array_merge_recursive(array $array1[, array $array2[, array ...]])
377 * @see http://php.net/array_merge
378 * @see http://php.net/array_merge_recursive
379 * @uses func_num_args()
380 * @uses func_get_arg()
381 * @uses is_array()
382 * @uses call_user_func_array()
383 * @param array array to merge
384 * @param array array to merge
385 * @param array ...
386 * @return array merged array
388 function PMA_array_merge_recursive()
390 switch(func_num_args()) {
391 case 0 :
392 return false;
393 break;
394 case 1 :
395 // when does that happen?
396 return func_get_arg(0);
397 break;
398 case 2 :
399 $args = func_get_args();
400 if (!is_array($args[0]) || !is_array($args[1])) {
401 return $args[1];
403 foreach ($args[1] as $key2 => $value2) {
404 if (isset($args[0][$key2]) && !is_int($key2)) {
405 $args[0][$key2] = PMA_array_merge_recursive($args[0][$key2],
406 $value2);
407 } else {
408 // we erase the parent array, otherwise we cannot override a directive that
409 // contains array elements, like this:
410 // (in config.default.php) $cfg['ForeignKeyDropdownOrder'] = array('id-content','content-id');
411 // (in config.inc.php) $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_array_merge_recursive($args[0], $args[1]);
423 array_shift($args);
424 return call_user_func_array('PMA_array_merge_recursive', $args);
425 break;
430 * calls $function vor 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 * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
436 * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
438 * @uses PMA_arrayWalkRecursive()
439 * @uses is_array()
440 * @uses is_string()
441 * @param array $array array to walk
442 * @param string $function function to call for every array element
444 function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
446 static $recursive_counter = 0;
447 if (++$recursive_counter > 1000) {
448 die('possible deep recursion attack');
450 foreach ($array as $key => $value) {
451 if (is_array($value)) {
452 PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
453 } else {
454 $array[$key] = $function($value);
457 if ($apply_to_keys_also && is_string($key)) {
458 $new_key = $function($key);
459 if ($new_key != $key) {
460 $array[$new_key] = $array[$key];
461 unset($array[$key]);
465 $recursive_counter--;
469 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
471 * checks given given $page against given $whitelist and returns true if valid
472 * it ignores optionaly query paramters in $page (script.php?ignored)
474 * @uses in_array()
475 * @uses urldecode()
476 * @uses substr()
477 * @uses strpos()
478 * @param string &$page page to check
479 * @param array $whitelist whitelist to check page against
480 * @return boolean whether $page is valid or not (in $whitelist or not)
482 function PMA_checkPageValidity(&$page, $whitelist)
484 if (! isset($page) || !is_string($page)) {
485 return false;
488 if (in_array($page, $whitelist)) {
489 return true;
490 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
491 return true;
492 } else {
493 $_page = urldecode($page);
494 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
495 return true;
498 return false;
502 * trys to find the value for the given environment vriable name
504 * searchs in $_SERVER, $_ENV than trys getenv() and apache_getenv()
505 * in this order
507 * @uses $_SERVER
508 * @uses $_ENV
509 * @uses getenv()
510 * @uses function_exists()
511 * @uses apache_getenv()
512 * @param string $var_name variable name
513 * @return string value of $var or empty string
515 function PMA_getenv($var_name) {
516 if (isset($_SERVER[$var_name])) {
517 return $_SERVER[$var_name];
518 } elseif (isset($_ENV[$var_name])) {
519 return $_ENV[$var_name];
520 } elseif (getenv($var_name)) {
521 return getenv($var_name);
522 } elseif (function_exists('apache_getenv')
523 && apache_getenv($var_name, true)) {
524 return apache_getenv($var_name, true);
527 return '';
531 * removes cookie
533 * @uses PMA_Config::isHttps()
534 * @uses PMA_Config::getCookiePath()
535 * @uses setcookie()
536 * @uses time()
537 * @param string $cookie name of cookie to remove
538 * @return boolean result of setcookie()
540 function PMA_removeCookie($cookie)
542 return setcookie($cookie, '', time() - 3600,
543 PMA_Config::getCookiePath(), '', PMA_Config::isHttps());
547 * sets cookie if value is different from current cokkie value,
548 * or removes if value is equal to default
550 * @uses PMA_Config::isHttps()
551 * @uses PMA_Config::getCookiePath()
552 * @uses $_COOKIE
553 * @uses PMA_removeCookie()
554 * @uses setcookie()
555 * @uses time()
556 * @param string $cookie name of cookie to remove
557 * @param mixed $value new cookie value
558 * @param string $default default value
559 * @param int $validity validity of cookie in seconds (default is one month)
560 * @param bool $httponlt whether cookie is only for HTTP (and not for scripts)
561 * @return boolean result of setcookie()
563 function PMA_setCookie($cookie, $value, $default = null, $validity = null, $httponly = true)
565 if ($validity == null) {
566 $validity = 2592000;
568 if (strlen($value) && null !== $default && $value === $default
569 && isset($_COOKIE[$cookie])) {
570 // remove cookie, default value is used
571 return PMA_removeCookie($cookie);
574 if (! strlen($value) && isset($_COOKIE[$cookie])) {
575 // remove cookie, value is empty
576 return PMA_removeCookie($cookie);
579 if (! isset($_COOKIE[$cookie]) || $_COOKIE[$cookie] !== $value) {
580 // set cookie with new value
581 /* Calculate cookie validity */
582 if ($validity == 0) {
583 $v = 0;
584 } else {
585 $v = time() + $validity;
587 return setcookie($cookie, $value, $v,
588 PMA_Config::getCookiePath(), '', PMA_Config::isHttps(), $httponly);
591 // cookie has already $value as value
592 return true;