Validator.php 19 KB

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