Validator.class.php 19 KB

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