Validation.php 33 KB

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