PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Utility/Validation.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 883 lines | 467 code | 59 blank | 357 comment | 99 complexity | c9571c08e63238a8dd55c7ec416952e3 MD5 | raw file
  1. <?php
  2. /**
  3. * Validation Class. Used for validation of model data
  4. *
  5. * PHP Version 5.x
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.Utility
  16. * @since CakePHP(tm) v 1.2.0.3830
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('Multibyte', 'I18n');
  20. // Load multibyte if the extension is missing.
  21. if (!function_exists('mb_strlen')) {
  22. class_exists('Multibyte');
  23. }
  24. /**
  25. * Offers different validation methods.
  26. *
  27. * @package Cake.Utility
  28. * @since CakePHP v 1.2.0.3830
  29. */
  30. class Validation {
  31. /**
  32. * Some complex patterns needed in multiple places
  33. *
  34. * @var array
  35. */
  36. protected static $_pattern = array(
  37. 'hostname' => '(?:[a-z0-9][-a-z0-9]*\.)*(?:[a-z0-9][-a-z0-9]{0,62})\.(?:(?:[a-z]{2}\.)?[a-z]{2,4}|museum|travel)'
  38. );
  39. /**
  40. * Holds an array of errors messages set in this class.
  41. * These are used for debugging purposes
  42. *
  43. * @var array
  44. */
  45. public static $errors = array();
  46. /**
  47. * Checks that a string contains something other than whitespace
  48. *
  49. * Returns true if string contains something other than whitespace
  50. *
  51. * $check can be passed as an array:
  52. * array('check' => 'valueToCheck');
  53. *
  54. * @param mixed $check Value to check
  55. * @return boolean Success
  56. */
  57. public static function notEmpty($check) {
  58. if (is_array($check)) {
  59. extract(self::_defaults($check));
  60. }
  61. if (empty($check) && $check != '0') {
  62. return false;
  63. }
  64. return self::_check($check, '/[^\s]+/m');
  65. }
  66. /**
  67. * Checks that a string contains only integer or letters
  68. *
  69. * Returns true if string contains only integer or letters
  70. *
  71. * $check can be passed as an array:
  72. * array('check' => 'valueToCheck');
  73. *
  74. * @param mixed $check Value to check
  75. * @return boolean Success
  76. */
  77. public static function alphaNumeric($check) {
  78. if (is_array($check)) {
  79. extract(self::_defaults($check));
  80. }
  81. if (empty($check) && $check != '0') {
  82. return false;
  83. }
  84. return self::_check($check, '/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/mu');
  85. }
  86. /**
  87. * Checks that a string length is within s specified range.
  88. * Spaces are included in the character count.
  89. * Returns true is string matches value min, max, or between min and max,
  90. *
  91. * @param string $check Value to check for length
  92. * @param integer $min Minimum value in range (inclusive)
  93. * @param integer $max Maximum value in range (inclusive)
  94. * @return boolean Success
  95. */
  96. public static function between($check, $min, $max) {
  97. $length = mb_strlen($check);
  98. return ($length >= $min && $length <= $max);
  99. }
  100. /**
  101. * Returns true if field is left blank -OR- only whitespace characters are present in it's value
  102. * Whitespace characters include Space, Tab, Carriage Return, Newline
  103. *
  104. * $check can be passed as an array:
  105. * array('check' => 'valueToCheck');
  106. *
  107. * @param mixed $check Value to check
  108. * @return boolean Success
  109. */
  110. public static function blank($check) {
  111. if (is_array($check)) {
  112. extract(self::_defaults($check));
  113. }
  114. return !self::_check($check, '/[^\\s]/');
  115. }
  116. /**
  117. * Validation of credit card numbers.
  118. * Returns true if $check is in the proper credit card format.
  119. *
  120. * @param mixed $check credit card number to validate
  121. * @param mixed $type 'all' may be passed as a sting, defaults to fast which checks format of most major credit cards
  122. * if an array is used only the values of the array are checked.
  123. * Example: array('amex', 'bankcard', 'maestro')
  124. * @param boolean $deep set to true this will check the Luhn algorithm of the credit card.
  125. * @param string $regex A custom regex can also be passed, this will be used instead of the defined regex values
  126. * @return boolean Success
  127. * @see Validation::luhn()
  128. */
  129. public static function cc($check, $type = 'fast', $deep = false, $regex = null) {
  130. if (is_array($check)) {
  131. extract(self::_defaults($check));
  132. }
  133. $check = str_replace(array('-', ' '), '', $check);
  134. if (mb_strlen($check) < 13) {
  135. return false;
  136. }
  137. if (!is_null($regex)) {
  138. if (self::_check($check, $regex)) {
  139. return self::luhn($check, $deep);
  140. }
  141. }
  142. $cards = array(
  143. 'all' => array(
  144. 'amex' => '/^3[4|7]\\d{13}$/',
  145. 'bankcard' => '/^56(10\\d\\d|022[1-5])\\d{10}$/',
  146. 'diners' => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/',
  147. 'disc' => '/^(?:6011|650\\d)\\d{12}$/',
  148. 'electron' => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/',
  149. 'enroute' => '/^2(?:014|149)\\d{11}$/',
  150. 'jcb' => '/^(3\\d{4}|2100|1800)\\d{11}$/',
  151. 'maestro' => '/^(?:5020|6\\d{3})\\d{12}$/',
  152. 'mc' => '/^5[1-5]\\d{14}$/',
  153. 'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/',
  154. 'switch' => '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\\d{10}(\\d{2,3})?)|(?:564182\\d{10}(\\d{2,3})?)|(6(3(33[0-4][0-9])|759[0-9]{2})\\d{10}(\\d{2,3})?)$/',
  155. 'visa' => '/^4\\d{12}(\\d{3})?$/',
  156. 'voyager' => '/^8699[0-9]{11}$/'
  157. ),
  158. 'fast' => '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/'
  159. );
  160. if (is_array($type)) {
  161. foreach ($type as $value) {
  162. $regex = $cards['all'][strtolower($value)];
  163. if (self::_check($check, $regex)) {
  164. return self::luhn($check, $deep);
  165. }
  166. }
  167. } elseif ($type == 'all') {
  168. foreach ($cards['all'] as $value) {
  169. $regex = $value;
  170. if (self::_check($check, $regex)) {
  171. return self::luhn($check, $deep);
  172. }
  173. }
  174. } else {
  175. $regex = $cards['fast'];
  176. if (self::_check($check, $regex)) {
  177. return self::luhn($check, $deep);
  178. }
  179. }
  180. return false;
  181. }
  182. /**
  183. * Used to compare 2 numeric values.
  184. *
  185. * @param mixed $check1 if string is passed for a string must also be passed for $check2
  186. * used as an array it must be passed as array('check1' => value, 'operator' => 'value', 'check2' -> value)
  187. * @param string $operator Can be either a word or operand
  188. * is greater >, is less <, greater or equal >=
  189. * less or equal <=, is less <, equal to ==, not equal !=
  190. * @param integer $check2 only needed if $check1 is a string
  191. * @return boolean Success
  192. */
  193. public static function comparison($check1, $operator = null, $check2 = null) {
  194. if (is_array($check1)) {
  195. extract($check1, EXTR_OVERWRITE);
  196. }
  197. $operator = str_replace(array(' ', "\t", "\n", "\r", "\0", "\x0B"), '', strtolower($operator));
  198. switch ($operator) {
  199. case 'isgreater':
  200. case '>':
  201. if ($check1 > $check2) {
  202. return true;
  203. }
  204. break;
  205. case 'isless':
  206. case '<':
  207. if ($check1 < $check2) {
  208. return true;
  209. }
  210. break;
  211. case 'greaterorequal':
  212. case '>=':
  213. if ($check1 >= $check2) {
  214. return true;
  215. }
  216. break;
  217. case 'lessorequal':
  218. case '<=':
  219. if ($check1 <= $check2) {
  220. return true;
  221. }
  222. break;
  223. case 'equalto':
  224. case '==':
  225. if ($check1 == $check2) {
  226. return true;
  227. }
  228. break;
  229. case 'notequal':
  230. case '!=':
  231. if ($check1 != $check2) {
  232. return true;
  233. }
  234. break;
  235. default:
  236. self::$errors[] = __d('cake_dev', 'You must define the $operator parameter for Validation::comparison()');
  237. break;
  238. }
  239. return false;
  240. }
  241. /**
  242. * Used when a custom regular expression is needed.
  243. *
  244. * @param mixed $check When used as a string, $regex must also be a valid regular expression.
  245. * As and array: array('check' => value, 'regex' => 'valid regular expression')
  246. * @param string $regex If $check is passed as a string, $regex must also be set to valid regular expression
  247. * @return boolean Success
  248. */
  249. public static function custom($check, $regex = null) {
  250. if (is_array($check)) {
  251. extract(self::_defaults($check));
  252. }
  253. if ($regex === null) {
  254. self::$errors[] = __d('cake_dev', 'You must define a regular expression for Validation::custom()');
  255. return false;
  256. }
  257. return self::_check($check, $regex);
  258. }
  259. /**
  260. * Date validation, determines if the string passed is a valid date.
  261. * keys that expect full month, day and year will validate leap years
  262. *
  263. * @param string $check a valid date string
  264. * @param mixed $format Use a string or an array of the keys below. Arrays should be passed as array('dmy', 'mdy', etc)
  265. * Keys: dmy 27-12-2006 or 27-12-06 separators can be a space, period, dash, forward slash
  266. * mdy 12-27-2006 or 12-27-06 separators can be a space, period, dash, forward slash
  267. * ymd 2006-12-27 or 06-12-27 separators can be a space, period, dash, forward slash
  268. * dMy 27 December 2006 or 27 Dec 2006
  269. * Mdy December 27, 2006 or Dec 27, 2006 comma is optional
  270. * My December 2006 or Dec 2006
  271. * my 12/2006 separators can be a space, period, dash, forward slash
  272. * @param string $regex If a custom regular expression is used this is the only validation that will occur.
  273. * @return boolean Success
  274. */
  275. public static function date($check, $format = 'ymd', $regex = null) {
  276. if (!is_null($regex)) {
  277. return self::_check($check, $regex);
  278. }
  279. $regex['dmy'] = '%^(?:(?:31(\\/|-|\\.|\\x20)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.|\\x20)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.|\\x20)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.|\\x20)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%';
  280. $regex['mdy'] = '%^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.|\\x20)31)\\1|(?:(?:0?[13-9]|1[0-2])(\\/|-|\\.|\\x20)(?:29|30)\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:0?2(\\/|-|\\.|\\x20)29\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\\/|-|\\.|\\x20)(?:0?[1-9]|1\\d|2[0-8])\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%';
  281. $regex['ymd'] = '%^(?:(?:(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(\\/|-|\\.|\\x20)(?:0?2\\1(?:29)))|(?:(?:(?:1[6-9]|[2-9]\\d)?\\d{2})(\\/|-|\\.|\\x20)(?:(?:(?:0?[13578]|1[02])\\2(?:31))|(?:(?:0?[1,3-9]|1[0-2])\\2(29|30))|(?:(?:0?[1-9])|(?:1[0-2]))\\2(?:0?[1-9]|1\\d|2[0-8]))))$%';
  282. $regex['dMy'] = '/^((31(?!\\ (Feb(ruary)?|Apr(il)?|June?|(Sep(?=\\b|t)t?|Nov)(ember)?)))|((30|29)(?!\\ Feb(ruary)?))|(29(?=\\ Feb(ruary)?\\ (((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\\d|2[0-8])\\ (Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)\\ ((1[6-9]|[2-9]\\d)\\d{2})$/';
  283. $regex['Mdy'] = '/^(?:(((Jan(uary)?|Ma(r(ch)?|y)|Jul(y)?|Aug(ust)?|Oct(ober)?|Dec(ember)?)\\ 31)|((Jan(uary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep)(tember)?|(Nov|Dec)(ember)?)\\ (0?[1-9]|([12]\\d)|30))|(Feb(ruary)?\\ (0?[1-9]|1\\d|2[0-8]|(29(?=,?\\ ((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))))\\,?\\ ((1[6-9]|[2-9]\\d)\\d{2}))$/';
  284. $regex['My'] = '%^(Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)[ /]((1[6-9]|[2-9]\\d)\\d{2})$%';
  285. $regex['my'] = '%^(((0[123456789]|10|11|12)([- /.])(([1][9][0-9][0-9])|([2][0-9][0-9][0-9]))))$%';
  286. $format = (is_array($format)) ? array_values($format) : array($format);
  287. foreach ($format as $key) {
  288. if (self::_check($check, $regex[$key]) === true) {
  289. return true;
  290. }
  291. }
  292. return false;
  293. }
  294. /**
  295. * Validates a datetime value
  296. * All values matching the "date" core validation rule, and the "time" one will be valid
  297. *
  298. * @param array $check Value to check
  299. * @param mixed $dateFormat Format of the date part
  300. * Use a string or an array of the keys below. Arrays should be passed as array('dmy', 'mdy', etc)
  301. * ## Keys:
  302. *
  303. * - dmy 27-12-2006 or 27-12-06 separators can be a space, period, dash, forward slash
  304. * - mdy 12-27-2006 or 12-27-06 separators can be a space, period, dash, forward slash
  305. * - ymd 2006-12-27 or 06-12-27 separators can be a space, period, dash, forward slash
  306. * - dMy 27 December 2006 or 27 Dec 2006
  307. * - Mdy December 27, 2006 or Dec 27, 2006 comma is optional
  308. * - My December 2006 or Dec 2006
  309. * - my 12/2006 separators can be a space, period, dash, forward slash
  310. * @param string $regex Regex for the date part. If a custom regular expression is used this is the only validation that will occur.
  311. * @return boolean True if the value is valid, false otherwise
  312. * @see Validation::date
  313. * @see Validation::time
  314. */
  315. public static function datetime($check, $dateFormat = 'ymd', $regex = null) {
  316. $valid = false;
  317. $parts = explode(' ', $check);
  318. if (!empty($parts) && count($parts) > 1) {
  319. $time = array_pop($parts);
  320. $date = implode(' ', $parts);
  321. $valid = self::date($date, $dateFormat, $regex) && self::time($time);
  322. }
  323. return $valid;
  324. }
  325. /**
  326. * Time validation, determines if the string passed is a valid time.
  327. * Validates time as 24hr (HH:MM) or am/pm ([H]H:MM[a|p]m)
  328. * Does not allow/validate seconds.
  329. *
  330. * @param string $check a valid time string
  331. * @return boolean Success
  332. */
  333. public static function time($check) {
  334. return self::_check($check, '%^((0?[1-9]|1[012])(:[0-5]\d){0,2} ?([AP]M|[ap]m))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$%');
  335. }
  336. /**
  337. * Boolean validation, determines if value passed is a boolean integer or true/false.
  338. *
  339. * @param string $check a valid boolean
  340. * @return boolean Success
  341. */
  342. public static function boolean($check) {
  343. $booleanList = array(0, 1, '0', '1', true, false);
  344. return in_array($check, $booleanList, true);
  345. }
  346. /**
  347. * Checks that a value is a valid decimal. If $places is null, the $check is allowed to be a scientific float
  348. * If no decimal point is found a false will be returned. Both the sign and exponent are optional.
  349. *
  350. * @param integer $check The value the test for decimal
  351. * @param integer $places if set $check value must have exactly $places after the decimal point
  352. * @param string $regex If a custom regular expression is used this is the only validation that will occur.
  353. * @return boolean Success
  354. */
  355. public static function decimal($check, $places = null, $regex = null) {
  356. if (is_null($regex)) {
  357. if (is_null($places)) {
  358. $regex = '/^[-+]?[0-9]*\\.{1}[0-9]+(?:[eE][-+]?[0-9]+)?$/';
  359. } else {
  360. $regex = '/^[-+]?[0-9]*\\.{1}[0-9]{' . $places . '}$/';
  361. }
  362. }
  363. return self::_check($check, $regex);
  364. }
  365. /**
  366. * Validates for an email address.
  367. *
  368. * Only uses getmxrr() checking for deep validation if PHP 5.3.0+ is used, or
  369. * any PHP version on a non-windows distribution
  370. *
  371. * @param string $check Value to check
  372. * @param boolean $deep Perform a deeper validation (if true), by also checking availability of host
  373. * @param string $regex Regex to use (if none it will use built in regex)
  374. * @return boolean Success
  375. */
  376. public static function email($check, $deep = false, $regex = null) {
  377. if (is_array($check)) {
  378. extract(self::_defaults($check));
  379. }
  380. if (is_null($regex)) {
  381. $regex = '/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@' . self::$_pattern['hostname'] . '$/i';
  382. }
  383. $return = self::_check($check, $regex);
  384. if ($deep === false || $deep === null) {
  385. return $return;
  386. }
  387. if ($return === true && preg_match('/@(' . self::$_pattern['hostname'] . ')$/i', $check, $regs)) {
  388. if (function_exists('getmxrr') && getmxrr($regs[1], $mxhosts)) {
  389. return true;
  390. }
  391. if (function_exists('checkdnsrr') && checkdnsrr($regs[1], 'MX')) {
  392. return true;
  393. }
  394. return is_array(gethostbynamel($regs[1]));
  395. }
  396. return false;
  397. }
  398. /**
  399. * Check that value is exactly $comparedTo.
  400. *
  401. * @param mixed $check Value to check
  402. * @param mixed $comparedTo Value to compare
  403. * @return boolean Success
  404. */
  405. public static function equalTo($check, $comparedTo) {
  406. return ($check === $comparedTo);
  407. }
  408. /**
  409. * Check that value has a valid file extension.
  410. *
  411. * @param mixed $check Value to check
  412. * @param array $extensions file extensions to allow
  413. * @return boolean Success
  414. */
  415. public static function extension($check, $extensions = array('gif', 'jpeg', 'png', 'jpg')) {
  416. if (is_array($check)) {
  417. return self::extension(array_shift($check), $extensions);
  418. }
  419. $pathSegments = explode('.', $check);
  420. $extension = strtolower(array_pop($pathSegments));
  421. foreach ($extensions as $value) {
  422. if ($extension == strtolower($value)) {
  423. return true;
  424. }
  425. }
  426. return false;
  427. }
  428. /**
  429. * Validation of an IP address.
  430. *
  431. * @param string $check The string to test.
  432. * @param string $type The IP Protocol version to validate against
  433. * @return boolean Success
  434. */
  435. public static function ip($check, $type = 'both') {
  436. $type = strtolower($type);
  437. $flags = array();
  438. if ($type === 'ipv4' || $type === 'both') {
  439. $flags[] = FILTER_FLAG_IPV4;
  440. }
  441. if ($type === 'ipv6' || $type === 'both') {
  442. $flags[] = FILTER_FLAG_IPV6;
  443. }
  444. return (boolean)filter_var($check, FILTER_VALIDATE_IP, array('flags' => $flags));
  445. }
  446. /**
  447. * Checks whether the length of a string is greater or equal to a minimal length.
  448. *
  449. * @param string $check The string to test
  450. * @param integer $min The minimal string length
  451. * @return boolean Success
  452. */
  453. public static function minLength($check, $min) {
  454. return mb_strlen($check) >= $min;
  455. }
  456. /**
  457. * Checks whether the length of a string is smaller or equal to a maximal length..
  458. *
  459. * @param string $check The string to test
  460. * @param integer $max The maximal string length
  461. * @return boolean Success
  462. */
  463. public static function maxLength($check, $max) {
  464. return mb_strlen($check) <= $max;
  465. }
  466. /**
  467. * Checks that a value is a monetary amount.
  468. *
  469. * @param string $check Value to check
  470. * @param string $symbolPosition Where symbol is located (left/right)
  471. * @return boolean Success
  472. */
  473. public static function money($check, $symbolPosition = 'left') {
  474. $money = '(?!0,?\d)(?:\d{1,3}(?:([, .])\d{3})?(?:\1\d{3})*|(?:\d+))((?!\1)[,.]\d{2})?';
  475. if ($symbolPosition == 'right') {
  476. $regex = '/^' . $money . '(?<!\x{00a2})\p{Sc}?$/u';
  477. } else {
  478. $regex = '/^(?!\x{00a2})\p{Sc}?' . $money . '$/u';
  479. }
  480. return self::_check($check, $regex);
  481. }
  482. /**
  483. * Validate a multiple select.
  484. *
  485. * Valid Options
  486. *
  487. * - in => provide a list of choices that selections must be made from
  488. * - max => maximum number of non-zero choices that can be made
  489. * - min => minimum number of non-zero choices that can be made
  490. *
  491. * @param mixed $check Value to check
  492. * @param mixed $options Options for the check.
  493. * @return boolean Success
  494. */
  495. public static function multiple($check, $options = array()) {
  496. $defaults = array('in' => null, 'max' => null, 'min' => null);
  497. $options = array_merge($defaults, $options);
  498. $check = array_filter((array)$check);
  499. if (empty($check)) {
  500. return false;
  501. }
  502. if ($options['max'] && count($check) > $options['max']) {
  503. return false;
  504. }
  505. if ($options['min'] && count($check) < $options['min']) {
  506. return false;
  507. }
  508. if ($options['in'] && is_array($options['in'])) {
  509. foreach ($check as $val) {
  510. if (!in_array($val, $options['in'])) {
  511. return false;
  512. }
  513. }
  514. }
  515. return true;
  516. }
  517. /**
  518. * Checks if a value is numeric.
  519. *
  520. * @param string $check Value to check
  521. * @return boolean Success
  522. */
  523. public static function numeric($check) {
  524. return is_numeric($check);
  525. }
  526. /**
  527. * Check that a value is a valid phone number.
  528. *
  529. * @param mixed $check Value to check (string or array)
  530. * @param string $regex Regular expression to use
  531. * @param string $country Country code (defaults to 'all')
  532. * @return boolean Success
  533. */
  534. public static function phone($check, $regex = null, $country = 'all') {
  535. if (is_array($check)) {
  536. extract(self::_defaults($check));
  537. }
  538. if (is_null($regex)) {
  539. switch ($country) {
  540. case 'us':
  541. case 'all':
  542. case 'can':
  543. // includes all NANPA members. see http://en.wikipedia.org/wiki/North_American_Numbering_Plan#List_of_NANPA_countries_and_territories
  544. $regex = '/^(?:\+?1)?[-. ]?\\(?[2-9][0-8][0-9]\\)?[-. ]?[2-9][0-9]{2}[-. ]?[0-9]{4}$/';
  545. break;
  546. }
  547. }
  548. if (empty($regex)) {
  549. return self::_pass('phone', $check, $country);
  550. }
  551. return self::_check($check, $regex);
  552. }
  553. /**
  554. * Checks that a given value is a valid postal code.
  555. *
  556. * @param mixed $check Value to check
  557. * @param string $regex Regular expression to use
  558. * @param string $country Country to use for formatting
  559. * @return boolean Success
  560. */
  561. public static function postal($check, $regex = null, $country = 'us') {
  562. if (is_array($check)) {
  563. extract(self::_defaults($check));
  564. }
  565. if (is_null($regex)) {
  566. switch ($country) {
  567. case 'uk':
  568. $regex = '/\\A\\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\\b\\z/i';
  569. break;
  570. case 'ca':
  571. $regex = '/\\A\\b[ABCEGHJKLMNPRSTVXY][0-9][A-Z] [0-9][A-Z][0-9]\\b\\z/i';
  572. break;
  573. case 'it':
  574. case 'de':
  575. $regex = '/^[0-9]{5}$/i';
  576. break;
  577. case 'be':
  578. $regex = '/^[1-9]{1}[0-9]{3}$/i';
  579. break;
  580. case 'us':
  581. $regex = '/\\A\\b[0-9]{5}(?:-[0-9]{4})?\\b\\z/i';
  582. break;
  583. }
  584. }
  585. if (empty($regex)) {
  586. return self::_pass('postal', $check, $country);
  587. }
  588. return self::_check($check, $regex);
  589. }
  590. /**
  591. * Validate that a number is in specified range.
  592. * if $lower and $upper are not set, will return true if
  593. * $check is a legal finite on this platform
  594. *
  595. * @param string $check Value to check
  596. * @param integer $lower Lower limit
  597. * @param integer $upper Upper limit
  598. * @return boolean Success
  599. */
  600. public static function range($check, $lower = null, $upper = null) {
  601. if (!is_numeric($check)) {
  602. return false;
  603. }
  604. if (isset($lower) && isset($upper)) {
  605. return ($check > $lower && $check < $upper);
  606. }
  607. return is_finite($check);
  608. }
  609. /**
  610. * Checks that a value is a valid Social Security Number.
  611. *
  612. * @param mixed $check Value to check
  613. * @param string $regex Regular expression to use
  614. * @param string $country Country
  615. * @return boolean Success
  616. */
  617. public static function ssn($check, $regex = null, $country = null) {
  618. if (is_array($check)) {
  619. extract(self::_defaults($check));
  620. }
  621. if (is_null($regex)) {
  622. switch ($country) {
  623. case 'dk':
  624. $regex = '/\\A\\b[0-9]{6}-[0-9]{4}\\b\\z/i';
  625. break;
  626. case 'nl':
  627. $regex = '/\\A\\b[0-9]{9}\\b\\z/i';
  628. break;
  629. case 'us':
  630. $regex = '/\\A\\b[0-9]{3}-[0-9]{2}-[0-9]{4}\\b\\z/i';
  631. break;
  632. }
  633. }
  634. if (empty($regex)) {
  635. return self::_pass('ssn', $check, $country);
  636. }
  637. return self::_check($check, $regex);
  638. }
  639. /**
  640. * Checks that a value is a valid URL according to http://www.w3.org/Addressing/URL/url-spec.txt
  641. *
  642. * The regex checks for the following component parts:
  643. *
  644. * - a valid, optional, scheme
  645. * - a valid ip address OR
  646. * a valid domain name as defined by section 2.3.1 of http://www.ietf.org/rfc/rfc1035.txt
  647. * with an optional port number
  648. * - an optional valid path
  649. * - an optional query string (get parameters)
  650. * - an optional fragment (anchor tag)
  651. *
  652. * @param string $check Value to check
  653. * @param boolean $strict Require URL to be prefixed by a valid scheme (one of http(s)/ftp(s)/file/news/gopher)
  654. * @return boolean Success
  655. */
  656. public static function url($check, $strict = false) {
  657. self::_populateIp();
  658. $validChars = '([' . preg_quote('!"$&\'()*+,-.@_:;=~[]') . '\/0-9a-z\p{L}\p{N}]|(%[0-9a-f]{2}))';
  659. $regex = '/^(?:(?:https?|ftps?|file|news|gopher):\/\/)' . (!empty($strict) ? '' : '?') .
  660. '(?:' . self::$_pattern['IPv4'] . '|\[' . self::$_pattern['IPv6'] . '\]|' . self::$_pattern['hostname'] . ')(?::[1-9][0-9]{0,4})?' .
  661. '(?:\/?|\/' . $validChars . '*)?' .
  662. '(?:\?' . $validChars . '*)?' .
  663. '(?:#' . $validChars . '*)?$/iu';
  664. return self::_check($check, $regex);
  665. }
  666. /**
  667. * Checks if a value is in a given list.
  668. *
  669. * @param string $check Value to check
  670. * @param array $list List to check against
  671. * @return boolean Success
  672. */
  673. public static function inList($check, $list) {
  674. return in_array($check, $list);
  675. }
  676. /**
  677. * Runs an user-defined validation.
  678. *
  679. * @param mixed $check value that will be validated in user-defined methods.
  680. * @param object $object class that holds validation method
  681. * @param string $method class method name for validation to run
  682. * @param array $args arguments to send to method
  683. * @return mixed user-defined class class method returns
  684. */
  685. public static function userDefined($check, $object, $method, $args = null) {
  686. return call_user_func_array(array($object, $method), array($check, $args));
  687. }
  688. /**
  689. * Checks that a value is a valid uuid - http://tools.ietf.org/html/rfc4122
  690. *
  691. * @param string $check Value to check
  692. * @return boolean Success
  693. */
  694. public static function uuid($check) {
  695. $regex = '/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i';
  696. return self::_check($check, $regex);
  697. }
  698. /**
  699. * Attempts to pass unhandled Validation locales to a class starting with $classPrefix
  700. * and ending with Validation. For example $classPrefix = 'nl', the class would be
  701. * `NlValidation`.
  702. *
  703. * @param string $method The method to call on the other class.
  704. * @param mixed $check The value to check or an array of parameters for the method to be called.
  705. * @param string $classPrefix The prefix for the class to do the validation.
  706. * @return mixed Return of Passed method, false on failure
  707. */
  708. protected static function _pass($method, $check, $classPrefix) {
  709. $className = ucwords($classPrefix) . 'Validation';
  710. if (!class_exists($className)) {
  711. trigger_error(__d('cake_dev', 'Could not find %s class, unable to complete validation.', $className), E_USER_WARNING);
  712. return false;
  713. }
  714. if (!method_exists($className, $method)) {
  715. trigger_error(__d('cake_dev', 'Method %s does not exist on %s unable to complete validation.', $method, $className), E_USER_WARNING);
  716. return false;
  717. }
  718. $check = (array)$check;
  719. return call_user_func_array(array($className, $method), $check);
  720. }
  721. /**
  722. * Runs a regular expression match.
  723. *
  724. * @param mixed $check Value to check against the $regex expression
  725. * @param string $regex Regular expression
  726. * @return boolean Success of match
  727. */
  728. protected static function _check($check, $regex) {
  729. if (preg_match($regex, $check)) {
  730. self::$errors[] = false;
  731. return true;
  732. } else {
  733. self::$errors[] = true;
  734. return false;
  735. }
  736. }
  737. /**
  738. * Get the values to use when value sent to validation method is
  739. * an array.
  740. *
  741. * @param array $params Parameters sent to validation method
  742. * @return void
  743. */
  744. protected static function _defaults($params) {
  745. self::_reset();
  746. $defaults = array(
  747. 'check' => null,
  748. 'regex' => null,
  749. 'country' => null,
  750. 'deep' => false,
  751. 'type' => null
  752. );
  753. $params = array_merge($defaults, $params);
  754. if ($params['country'] !== null) {
  755. $params['country'] = mb_strtolower($params['country']);
  756. }
  757. return $params;
  758. }
  759. /**
  760. * Luhn algorithm
  761. *
  762. * @param string|array $check
  763. * @param boolean $deep
  764. * @return boolean Success
  765. * @see http://en.wikipedia.org/wiki/Luhn_algorithm
  766. */
  767. public static function luhn($check, $deep = false) {
  768. if (is_array($check)) {
  769. extract(self::_defaults($check));
  770. }
  771. if ($deep !== true) {
  772. return true;
  773. }
  774. if ($check == 0) {
  775. return false;
  776. }
  777. $sum = 0;
  778. $length = strlen($check);
  779. for ($position = 1 - ($length % 2); $position < $length; $position += 2) {
  780. $sum += $check[$position];
  781. }
  782. for ($position = ($length % 2); $position < $length; $position += 2) {
  783. $number = $check[$position] * 2;
  784. $sum += ($number < 10) ? $number : $number - 9;
  785. }
  786. return ($sum % 10 == 0);
  787. }
  788. /**
  789. * Lazily populate the IP address patterns used for validations
  790. *
  791. * @return void
  792. */
  793. protected static function _populateIp() {
  794. if (!isset(self::$_pattern['IPv6'])) {
  795. $pattern = '((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}';
  796. $pattern .= '(:|((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})';
  797. $pattern .= '|(:[0-9A-Fa-f]{1,4})))|(([0-9A-Fa-f]{1,4}:){5}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})';
  798. $pattern .= '(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)';
  799. $pattern .= '{4}(:[0-9A-Fa-f]{1,4}){0,1}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2}))';
  800. $pattern .= '{3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}';
  801. $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|';
  802. $pattern .= '((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}';
  803. $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2}))';
  804. $pattern .= '{3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4})';
  805. $pattern .= '{0,4}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)';
  806. $pattern .= '|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]';
  807. $pattern .= '\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4})';
  808. $pattern .= '{1,2})))|(((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))(%.+)?';
  809. self::$_pattern['IPv6'] = $pattern;
  810. }
  811. if (!isset(self::$_pattern['IPv4'])) {
  812. $pattern = '(?:(?:25[0-5]|2[0-4][0-9]|(?:(?:1[0-9])?|[1-9]?)[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|(?:(?:1[0-9])?|[1-9]?)[0-9])';
  813. self::$_pattern['IPv4'] = $pattern;
  814. }
  815. }
  816. /**
  817. * Reset internal variables for another validation run.
  818. *
  819. * @return void
  820. */
  821. protected static function _reset() {
  822. self::$errors = array();
  823. }
  824. }