Base for a static organization website

Validation.php 33KB

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