Validation.php 32 KB

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