validate.lib.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Various validation functions
  5. *
  6. * Validation function takes two argument: id for which it is called
  7. * and array of fields' values (usually values for entire formset, as defined
  8. * in forms.inc.php).
  9. * The function must always return an array with an error (or error array)
  10. * assigned to a form element (formset name or field path). Even if there are
  11. * no errors, key must be set with an empty value.
  12. *
  13. * Valdiation functions are assigned in $cfg_db['_validators'] (config.values.php).
  14. *
  15. * @package PhpMyAdmin
  16. */
  17. require_once './libraries/Util.class.php';
  18. /**
  19. * Returns validator list
  20. *
  21. * @return array
  22. */
  23. function PMA_config_get_validators()
  24. {
  25. static $validators = null;
  26. if ($validators === null) {
  27. $cf = ConfigFile::getInstance();
  28. $validators = $cf->getDbEntry('_validators', array());
  29. if (!defined('PMA_SETUP')) {
  30. // not in setup script: load additional validators for user
  31. // preferences we need original config values not overwritten
  32. // by user preferences, creating a new PMA_Config instance is a
  33. // better idea than hacking into its code
  34. $org_cfg = $cf->getOrgConfigObj();
  35. $uvs = $cf->getDbEntry('_userValidators', array());
  36. foreach ($uvs as $field => $uv_list) {
  37. $uv_list = (array)$uv_list;
  38. foreach ($uv_list as &$uv) {
  39. if (!is_array($uv)) {
  40. continue;
  41. }
  42. for ($i = 1; $i < count($uv); $i++) {
  43. if (substr($uv[$i], 0, 6) == 'value:') {
  44. $uv[$i] = PMA_arrayRead(
  45. substr($uv[$i], 6), $org_cfg->settings
  46. );
  47. }
  48. }
  49. }
  50. $validators[$field] = isset($validators[$field])
  51. ? array_merge((array)$validators[$field], $uv_list)
  52. : $uv_list;
  53. }
  54. }
  55. }
  56. return $validators;
  57. }
  58. /**
  59. * Runs validation $validator_id on values $values and returns error list.
  60. *
  61. * Return values:
  62. * o array, keys - field path or formset id, values - array of errors
  63. * when $isPostSource is true values is an empty array to allow for error list
  64. * cleanup in HTML documen
  65. * o false - when no validators match name(s) given by $validator_id
  66. *
  67. * @param string|array $validator_id ID of validator(s) to run
  68. * @param array &$values Values to validate
  69. * @param bool $isPostSource tells whether $values are directly from
  70. * POST request
  71. *
  72. * @return bool|array
  73. */
  74. function PMA_config_validate($validator_id, &$values, $isPostSource)
  75. {
  76. // find validators
  77. $validator_id = (array) $validator_id;
  78. $validators = PMA_config_get_validators();
  79. $vids = array();
  80. $cf = ConfigFile::getInstance();
  81. foreach ($validator_id as &$vid) {
  82. $vid = $cf->getCanonicalPath($vid);
  83. if (isset($validators[$vid])) {
  84. $vids[] = $vid;
  85. }
  86. }
  87. if (empty($vids)) {
  88. return false;
  89. }
  90. // create argument list with canonical paths and remember path mapping
  91. $arguments = array();
  92. $key_map = array();
  93. foreach ($values as $k => $v) {
  94. $k2 = $isPostSource ? str_replace('-', '/', $k) : $k;
  95. $k2 = strpos($k2, '/') ? $cf->getCanonicalPath($k2) : $k2;
  96. $key_map[$k2] = $k;
  97. $arguments[$k2] = $v;
  98. }
  99. // validate
  100. $result = array();
  101. foreach ($vids as $vid) {
  102. // call appropriate validation functions
  103. foreach ((array)$validators[$vid] as $validator) {
  104. $vdef = (array) $validator;
  105. $vname = array_shift($vdef);
  106. $args = array_merge(array($vid, &$arguments), $vdef);
  107. $r = call_user_func_array($vname, $args);
  108. // merge results
  109. if (is_array($r)) {
  110. foreach ($r as $key => $error_list) {
  111. // skip empty values if $isPostSource is false
  112. if (!$isPostSource && empty($error_list)) {
  113. continue;
  114. }
  115. if (!isset($result[$key])) {
  116. $result[$key] = array();
  117. }
  118. $result[$key] = array_merge($result[$key], (array)$error_list);
  119. }
  120. }
  121. }
  122. }
  123. // restore original paths
  124. $new_result = array();
  125. foreach ($result as $k => $v) {
  126. $k2 = isset($key_map[$k]) ? $key_map[$k] : $k;
  127. $new_result[$k2] = $v;
  128. }
  129. return empty($new_result) ? true : $new_result;
  130. }
  131. /**
  132. * Empty error handler, used to temporarily restore PHP internal error handler
  133. *
  134. * @return bool
  135. */
  136. function PMA_null_error_handler()
  137. {
  138. return false;
  139. }
  140. /**
  141. * Ensures that $php_errormsg variable will be registered in case of an error
  142. * and enables output buffering (when $start = true).
  143. * Called with $start = false disables output buffering end restores
  144. * html_errors and track_errors.
  145. *
  146. * @param boolean $start Whether to start buffering
  147. *
  148. * @return void
  149. */
  150. function test_php_errormsg($start = true)
  151. {
  152. static $old_html_errors, $old_track_errors, $old_error_reporting;
  153. static $old_display_errors;
  154. if ($start) {
  155. $old_html_errors = ini_get('html_errors');
  156. $old_track_errors = ini_get('track_errors');
  157. $old_display_errors = ini_get('display_errors');
  158. $old_error_reporting = error_reporting(E_ALL);
  159. ini_set('html_errors', false);
  160. ini_set('track_errors', true);
  161. ini_set('display_errors', true);
  162. set_error_handler("PMA_null_error_handler");
  163. ob_start();
  164. } else {
  165. ob_end_clean();
  166. restore_error_handler();
  167. error_reporting($old_error_reporting);
  168. ini_set('html_errors', $old_html_errors);
  169. ini_set('track_errors', $old_track_errors);
  170. ini_set('display_errors', $old_display_errors);
  171. }
  172. }
  173. /**
  174. * Test database connection
  175. *
  176. * @param string $extension 'drizzle', 'mysql' or 'mysqli'
  177. * @param string $connect_type 'tcp' or 'socket'
  178. * @param string $host host name
  179. * @param string $port tcp port to use
  180. * @param string $socket socket to use
  181. * @param string $user username to use
  182. * @param string $pass password to use
  183. * @param string $error_key key to use in return array
  184. *
  185. * @return bool|array
  186. */
  187. function test_db_connection(
  188. $extension,
  189. $connect_type,
  190. $host,
  191. $port,
  192. $socket,
  193. $user,
  194. $pass = null,
  195. $error_key = 'Server'
  196. ) {
  197. // test_php_errormsg();
  198. $socket = empty($socket) || $connect_type == 'tcp' ? null : $socket;
  199. $port = empty($port) || $connect_type == 'socket' ? null : ':' . $port;
  200. $error = null;
  201. if ($extension == 'drizzle') {
  202. while (1) {
  203. $drizzle = @drizzle_create();
  204. if (!$drizzle) {
  205. $error = __('Could not initialize Drizzle connection library');
  206. break;
  207. }
  208. $conn = $socket
  209. ? @drizzle_con_add_uds($socket, $user, $pass, null, 0)
  210. : @drizzle_con_add_tcp(
  211. $drizzle, $host, $port, $user, $pass, null, 0
  212. );
  213. if (!$conn) {
  214. $error = __('Could not connect to Drizzle server');
  215. drizzle_free($drizzle);
  216. break;
  217. }
  218. // connection object is set up but we have to send some query
  219. // to actually connect
  220. $res = @drizzle_query($conn, 'SELECT 1');
  221. if (!$res) {
  222. $error = __('Could not connect to Drizzle server');
  223. } else {
  224. drizzle_result_free($res);
  225. }
  226. drizzle_con_free($conn);
  227. drizzle_free($drizzle);
  228. break;
  229. }
  230. } else if ($extension == 'mysql') {
  231. $conn = @mysql_connect($host . $socket . $port, $user, $pass);
  232. if (!$conn) {
  233. $error = __('Could not connect to MySQL server');
  234. } else {
  235. mysql_close($conn);
  236. }
  237. } else {
  238. $conn = @mysqli_connect($host, $user, $pass, null, $port, $socket);
  239. if (!$conn) {
  240. $error = __('Could not connect to MySQL server');
  241. } else {
  242. mysqli_close($conn);
  243. }
  244. }
  245. // test_php_errormsg(false);
  246. if (isset($php_errormsg)) {
  247. $error .= " - $php_errormsg";
  248. }
  249. return is_null($error) ? true : array($error_key => $error);
  250. }
  251. /**
  252. * Validate server config
  253. *
  254. * @param string $path path to config, not used
  255. * @param array $values config values
  256. *
  257. * @return array
  258. */
  259. function validate_server($path, $values)
  260. {
  261. $result = array(
  262. 'Server' => '',
  263. 'Servers/1/user' => '',
  264. 'Servers/1/SignonSession' => '',
  265. 'Servers/1/SignonURL' => ''
  266. );
  267. $error = false;
  268. if (empty($values['Servers/1/auth_type'])) {
  269. $values['Servers/1/auth_type'] = '';
  270. $result['Servers/1/auth_type'] = __('Invalid authentication type!');
  271. $error = true;
  272. }
  273. if ($values['Servers/1/auth_type'] == 'config'
  274. && empty($values['Servers/1/user'])
  275. ) {
  276. $result['Servers/1/user']
  277. = __('Empty username while using config authentication method');
  278. $error = true;
  279. }
  280. if ($values['Servers/1/auth_type'] == 'signon'
  281. && empty($values['Servers/1/SignonSession'])
  282. ) {
  283. $result['Servers/1/SignonSession'] = __(
  284. 'Empty signon session name '
  285. . 'while using signon authentication method'
  286. );
  287. $error = true;
  288. }
  289. if ($values['Servers/1/auth_type'] == 'signon'
  290. && empty($values['Servers/1/SignonURL'])
  291. ) {
  292. $result['Servers/1/SignonURL']
  293. = __('Empty signon URL while using signon authentication method');
  294. $error = true;
  295. }
  296. if (!$error && $values['Servers/1/auth_type'] == 'config') {
  297. $password = !empty($values['Servers/1/nopassword']) && $values['Servers/1/nopassword'] ? null
  298. : (empty($values['Servers/1/password']) ? '' : $values['Servers/1/password']);
  299. $test = test_db_connection(
  300. empty($values['Servers/1/extension']) ? '' : $values['Servers/1/extension'],
  301. empty($values['Servers/1/connect_type']) ? '' : $values['Servers/1/connect_type'],
  302. empty($values['Servers/1/host']) ? '' : PMA_sanitizeMySQLHost($values['Servers/1/host']),
  303. empty($values['Servers/1/port']) ? '' : $values['Servers/1/port'],
  304. empty($values['Servers/1/socket']) ? '' : $values['Servers/1/socket'],
  305. empty($values['Servers/1/user']) ? '' : $values['Servers/1/user'],
  306. $password,
  307. 'Server'
  308. );
  309. if ($test !== true) {
  310. $result = array_merge($result, $test);
  311. }
  312. }
  313. return $result;
  314. }
  315. /**
  316. * Validate pmadb config
  317. *
  318. * @param string $path path to config, not used
  319. * @param array $values config values
  320. *
  321. * @return array
  322. */
  323. function validate_pmadb($path, $values)
  324. {
  325. $result = array(
  326. 'Server_pmadb' => '',
  327. 'Servers/1/controluser' => '',
  328. 'Servers/1/controlpass' => ''
  329. );
  330. $error = false;
  331. if (empty($values['Servers/1/pmadb'])) {
  332. return $result;
  333. }
  334. $result = array();
  335. if (empty($values['Servers/1/controluser'])) {
  336. $result['Servers/1/controluser']
  337. = __('Empty phpMyAdmin control user while using pmadb');
  338. $error = true;
  339. }
  340. if (empty($values['Servers/1/controlpass'])) {
  341. $result['Servers/1/controlpass']
  342. = __('Empty phpMyAdmin control user password while using pmadb');
  343. $error = true;
  344. }
  345. if (!$error) {
  346. $test = test_db_connection(
  347. $values['Servers/1/extension'], $values['Servers/1/connect_type'],
  348. $values['Servers/1/host'], PMA_sanitizeMySQLHost($values['Servers/1/port']),
  349. $values['Servers/1/socket'], $values['Servers/1/controluser'],
  350. $values['Servers/1/controlpass'], 'Server_pmadb'
  351. );
  352. if ($test !== true) {
  353. $result = array_merge($result, $test);
  354. }
  355. }
  356. return $result;
  357. }
  358. /**
  359. * Validates regular expression
  360. *
  361. * @param string $path path to config
  362. * @param array $values config values
  363. *
  364. * @return array
  365. */
  366. function validate_regex($path, $values)
  367. {
  368. $result = array($path => '');
  369. if (empty($values[$path])) {
  370. return $result;
  371. }
  372. test_php_errormsg();
  373. $matches = array();
  374. // in libraries/List_Database.class.php _checkHideDatabase(),
  375. // a '/' is used as the delimiter for hide_db
  376. preg_match('/' . $values[$path] . '/', '', $matches);
  377. test_php_errormsg(false);
  378. if (isset($php_errormsg)) {
  379. $error = preg_replace('/^preg_match\(\): /', '', $php_errormsg);
  380. return array($path => $error);
  381. }
  382. return $result;
  383. }
  384. /**
  385. * Validates TrustedProxies field
  386. *
  387. * @param string $path path to config
  388. * @param array $values config values
  389. *
  390. * @return array
  391. */
  392. function validate_trusted_proxies($path, $values)
  393. {
  394. $result = array($path => array());
  395. if (empty($values[$path])) {
  396. return $result;
  397. }
  398. if (is_array($values[$path]) || is_object($values[$path])) {
  399. // value already processed by FormDisplay::save
  400. $lines = array();
  401. foreach ($values[$path] as $ip => $v) {
  402. $v = PMA_Util::requestString($v);
  403. $lines[] = preg_match('/^-\d+$/', $ip)
  404. ? $v
  405. : $ip . ': ' . $v;
  406. }
  407. } else {
  408. // AJAX validation
  409. $lines = explode("\n", $values[$path]);
  410. }
  411. foreach ($lines as $line) {
  412. $line = trim($line);
  413. $matches = array();
  414. // we catch anything that may (or may not) be an IP
  415. if (!preg_match("/^(.+):(?:[ ]?)\\w+$/", $line, $matches)) {
  416. $result[$path][] = __('Incorrect value') . ': ' . htmlspecialchars($line);
  417. continue;
  418. }
  419. // now let's check whether we really have an IP address
  420. if (filter_var($matches[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false
  421. && filter_var($matches[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false
  422. ) {
  423. $ip = htmlspecialchars(trim($matches[1]));
  424. $result[$path][] = sprintf(__('Incorrect IP address: %s'), $ip);
  425. continue;
  426. }
  427. }
  428. return $result;
  429. }
  430. /**
  431. * Tests integer value
  432. *
  433. * @param string $path path to config
  434. * @param array $values config values
  435. * @param bool $allow_neg allow negative values
  436. * @param bool $allow_zero allow zero
  437. * @param int $max_value max allowed value
  438. * @param string $error_string error message key:
  439. * $GLOBALS["strConfig$error_lang_key"]
  440. *
  441. * @return string empty string if test is successful
  442. */
  443. function test_number(
  444. $path,
  445. $values,
  446. $allow_neg,
  447. $allow_zero,
  448. $max_value,
  449. $error_string
  450. ) {
  451. if (empty($values[$path])) {
  452. return '';
  453. }
  454. if (intval($values[$path]) != $values[$path]
  455. || (!$allow_neg && $values[$path] < 0)
  456. || (!$allow_zero && $values[$path] == 0)
  457. || $values[$path] > $max_value
  458. ) {
  459. return $error_string;
  460. }
  461. return '';
  462. }
  463. /**
  464. * Validates port number
  465. *
  466. * @param string $path path to config
  467. * @param array $values config values
  468. *
  469. * @return array
  470. */
  471. function validate_port_number($path, $values)
  472. {
  473. return array(
  474. $path => test_number(
  475. $path,
  476. $values,
  477. false,
  478. false,
  479. 65535,
  480. __('Not a valid port number')
  481. )
  482. );
  483. }
  484. /**
  485. * Validates positive number
  486. *
  487. * @param string $path path to config
  488. * @param array $values config values
  489. *
  490. * @return array
  491. */
  492. function validate_positive_number($path, $values)
  493. {
  494. return array(
  495. $path => test_number(
  496. $path,
  497. $values,
  498. false,
  499. false,
  500. PHP_INT_MAX,
  501. __('Not a positive number')
  502. )
  503. );
  504. }
  505. /**
  506. * Validates non-negative number
  507. *
  508. * @param string $path path to config
  509. * @param array $values config values
  510. *
  511. * @return array
  512. */
  513. function validate_non_negative_number($path, $values)
  514. {
  515. return array(
  516. $path => test_number(
  517. $path,
  518. $values,
  519. false,
  520. true,
  521. PHP_INT_MAX,
  522. __('Not a non-negative number')
  523. )
  524. );
  525. }
  526. /**
  527. * Validates value according to given regular expression
  528. * Pattern and modifiers must be a valid for PCRE <b>and</b> JavaScript RegExp
  529. *
  530. * @param string $path path to config
  531. * @param array $values config values
  532. * @param string $regex regullar expression to match
  533. *
  534. * @return array
  535. */
  536. function validate_by_regex($path, $values, $regex)
  537. {
  538. if (empty($values[$path])) {
  539. return '';
  540. }
  541. $result = preg_match($regex, PMA_Util::requestString($values[$path]));
  542. return array($path => ($result ? '' : __('Incorrect value')));
  543. }
  544. /**
  545. * Validates upper bound for numeric inputs
  546. *
  547. * @param string $path path to config
  548. * @param array $values config values
  549. * @param int $max_value maximal allowed value
  550. *
  551. * @return array
  552. */
  553. function validate_upper_bound($path, $values, $max_value)
  554. {
  555. $result = $values[$path] <= $max_value;
  556. return array($path => ($result ? ''
  557. : sprintf(__('Value must be equal or lower than %s'), $max_value)));
  558. }
  559. ?>