Validation.php 32 KB

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