Validation.php 33 KB

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