Validation.php 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 1.2.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Validation;
  16. use Cake\I18n\Time;
  17. use Cake\Utility\Text;
  18. use DateTimeInterface;
  19. use InvalidArgumentException;
  20. use LogicException;
  21. use NumberFormatter;
  22. use Psr\Http\Message\UploadedFileInterface;
  23. use RuntimeException;
  24. /**
  25. * Validation Class. Used for validation of model data
  26. *
  27. * Offers different validation methods.
  28. */
  29. class Validation
  30. {
  31. /**
  32. * Default locale
  33. *
  34. * @var string
  35. */
  36. const DEFAULT_LOCALE = 'en_US';
  37. /**
  38. * Some complex patterns needed in multiple places
  39. *
  40. * @var array
  41. */
  42. protected static $_pattern = [
  43. '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,})',
  44. 'latitude' => '[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?)',
  45. 'longitude' => '[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)',
  46. ];
  47. /**
  48. * Holds an array of errors messages set in this class.
  49. * These are used for debugging purposes
  50. *
  51. * @var array
  52. */
  53. public static $errors = [];
  54. /**
  55. * Backwards compatibility wrapper for Validation::notBlank().
  56. *
  57. * @param string|array $check Value to check.
  58. * @return bool Success.
  59. * @deprecated 3.0.2 Use Validation::notBlank() instead.
  60. * @see \Cake\Validation\Validation::notBlank()
  61. */
  62. public static function notEmpty($check)
  63. {
  64. trigger_error('Validation::notEmpty() is deprecated. Use Validation::notBlank() instead.', E_USER_DEPRECATED);
  65. return static::notBlank($check);
  66. }
  67. /**
  68. * Checks that a string contains something other than whitespace
  69. *
  70. * Returns true if string contains something other than whitespace
  71. *
  72. * $check can be passed as an array:
  73. * ['check' => 'valueToCheck'];
  74. *
  75. * @param string|array $check Value to check
  76. * @return bool Success
  77. */
  78. public static function notBlank($check)
  79. {
  80. if (empty($check) && $check !== '0' && $check !== 0) {
  81. return false;
  82. }
  83. return static::_check($check, '/[^\s]+/m');
  84. }
  85. /**
  86. * Checks that a string contains only integer or letters
  87. *
  88. * Returns true if string contains only integer or letters
  89. *
  90. * $check can be passed as an array:
  91. * ['check' => 'valueToCheck'];
  92. *
  93. * @param string|array $check Value to check
  94. * @return bool Success
  95. */
  96. public static function alphaNumeric($check)
  97. {
  98. if (empty($check) && $check !== '0') {
  99. return false;
  100. }
  101. return self::_check($check, '/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/Du');
  102. }
  103. /**
  104. * Checks that a string length is within specified range.
  105. * Spaces are included in the character count.
  106. * Returns true if string matches value min, max, or between min and max,
  107. *
  108. * @param string $check Value to check for length
  109. * @param int $min Minimum value in range (inclusive)
  110. * @param int $max Maximum value in range (inclusive)
  111. * @return bool Success
  112. */
  113. public static function lengthBetween($check, $min, $max)
  114. {
  115. if (!is_string($check)) {
  116. return false;
  117. }
  118. $length = mb_strlen($check);
  119. return ($length >= $min && $length <= $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. * @param string|array $check Value to check
  126. * @return bool Success
  127. * @deprecated 3.0.2
  128. */
  129. public static function blank($check)
  130. {
  131. trigger_error('Validation::blank() is deprecated.', E_USER_DEPRECATED);
  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 string, defaults to fast which checks format of most major credit cards
  140. * if an array is used only the values of the array are checked.
  141. * Example: ['amex', 'bankcard', 'maestro']
  142. * @param bool $deep set to true this will check the Luhn algorithm of the credit card.
  143. * @param string|null $regex A custom regex can also be passed, this will be used instead of the defined regex values
  144. * @return bool Success
  145. * @see \Cake\Validation\Validation::luhn()
  146. */
  147. public static function cc($check, $type = 'fast', $deep = false, $regex = null)
  148. {
  149. if (!is_scalar($check)) {
  150. return false;
  151. }
  152. $check = str_replace(['-', ' '], '', $check);
  153. if (mb_strlen($check) < 13) {
  154. return false;
  155. }
  156. if ($regex !== null) {
  157. if (static::_check($check, $regex)) {
  158. return !$deep || static::luhn($check);
  159. }
  160. }
  161. $cards = [
  162. 'all' => [
  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})|(2(?:22[1-9]|2[3-9][0-9]|[3-6][0-9]{2}|7[0-1][0-9]|720)\\d{12})$/',
  172. 'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/',
  173. '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})?)$/',
  174. 'visa' => '/^4\\d{12}(\\d{3})?$/',
  175. 'voyager' => '/^8699[0-9]{11}$/'
  176. ],
  177. '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})$/'
  178. ];
  179. if (is_array($type)) {
  180. foreach ($type as $value) {
  181. $regex = $cards['all'][strtolower($value)];
  182. if (static::_check($check, $regex)) {
  183. return static::luhn($check);
  184. }
  185. }
  186. } elseif ($type === 'all') {
  187. foreach ($cards['all'] as $value) {
  188. $regex = $value;
  189. if (static::_check($check, $regex)) {
  190. return static::luhn($check);
  191. }
  192. }
  193. } else {
  194. $regex = $cards['fast'];
  195. if (static::_check($check, $regex)) {
  196. return static::luhn($check);
  197. }
  198. }
  199. return false;
  200. }
  201. /**
  202. * Used to check the count of a given value of type array or Countable.
  203. *
  204. * @param array|\Countable $check The value to check the count on.
  205. * @param string $operator Can be either a word or operand
  206. * is greater >, is less <, greater or equal >=
  207. * less or equal <=, is less <, equal to ==, not equal !=
  208. * @param int $expectedCount The expected count value.
  209. * @return bool Success
  210. */
  211. public static function numElements($check, $operator, $expectedCount)
  212. {
  213. if (!is_array($check) && !$check instanceof \Countable) {
  214. return false;
  215. }
  216. return self::comparison(count($check), $operator, $expectedCount);
  217. }
  218. /**
  219. * Used to compare 2 numeric values.
  220. *
  221. * @param string $check1 if string is passed for, a string must also be passed for $check2
  222. * used as an array it must be passed as ['check1' => value, 'operator' => 'value', 'check2' => value]
  223. * @param string $operator Can be either a word or operand
  224. * is greater >, is less <, greater or equal >=
  225. * less or equal <=, is less <, equal to ==, not equal !=
  226. * @param int $check2 only needed if $check1 is a string
  227. * @return bool Success
  228. */
  229. public static function comparison($check1, $operator, $check2)
  230. {
  231. if ((float)$check1 != $check1) {
  232. return false;
  233. }
  234. $operator = str_replace([' ', "\t", "\n", "\r", "\0", "\x0B"], '', strtolower($operator));
  235. switch ($operator) {
  236. case 'isgreater':
  237. case '>':
  238. if ($check1 > $check2) {
  239. return true;
  240. }
  241. break;
  242. case 'isless':
  243. case '<':
  244. if ($check1 < $check2) {
  245. return true;
  246. }
  247. break;
  248. case 'greaterorequal':
  249. case '>=':
  250. if ($check1 >= $check2) {
  251. return true;
  252. }
  253. break;
  254. case 'lessorequal':
  255. case '<=':
  256. if ($check1 <= $check2) {
  257. return true;
  258. }
  259. break;
  260. case 'equalto':
  261. case '==':
  262. if ($check1 == $check2) {
  263. return true;
  264. }
  265. break;
  266. case 'notequal':
  267. case '!=':
  268. if ($check1 != $check2) {
  269. return true;
  270. }
  271. break;
  272. default:
  273. static::$errors[] = 'You must define the $operator parameter for Validation::comparison()';
  274. }
  275. return false;
  276. }
  277. /**
  278. * Compare one field to another.
  279. *
  280. * If both fields have exactly the same value this method will return true.
  281. *
  282. * @param mixed $check The value to find in $field.
  283. * @param string $field The field to check $check against. This field must be present in $context.
  284. * @param array $context The validation context.
  285. * @return bool
  286. */
  287. public static function compareWith($check, $field, $context)
  288. {
  289. if (!isset($context['data'][$field])) {
  290. return false;
  291. }
  292. return $context['data'][$field] === $check;
  293. }
  294. /**
  295. * Checks if a string contains one or more non-alphanumeric characters.
  296. *
  297. * Returns true if string contains at least the specified number of non-alphanumeric characters
  298. *
  299. * @param string $check Value to check
  300. * @param int $count Number of non-alphanumerics to check for
  301. * @return bool Success
  302. */
  303. public static function containsNonAlphaNumeric($check, $count = 1)
  304. {
  305. if (!is_scalar($check)) {
  306. return false;
  307. }
  308. $matches = preg_match_all('/[^a-zA-Z0-9]/', $check);
  309. return $matches >= $count;
  310. }
  311. /**
  312. * Used when a custom regular expression is needed.
  313. *
  314. * @param string|array $check When used as a string, $regex must also be a valid regular expression.
  315. * As and array: ['check' => value, 'regex' => 'valid regular expression']
  316. * @param string|null $regex If $check is passed as a string, $regex must also be set to valid regular expression
  317. * @return bool Success
  318. */
  319. public static function custom($check, $regex = null)
  320. {
  321. if ($regex === null) {
  322. static::$errors[] = 'You must define a regular expression for Validation::custom()';
  323. return false;
  324. }
  325. return static::_check($check, $regex);
  326. }
  327. /**
  328. * Date validation, determines if the string passed is a valid date.
  329. * keys that expect full month, day and year will validate leap years.
  330. *
  331. * Years are valid from 1800 to 2999.
  332. *
  333. * ### Formats:
  334. *
  335. * - `dmy` 27-12-2006 or 27-12-06 separators can be a space, period, dash, forward slash
  336. * - `mdy` 12-27-2006 or 12-27-06 separators can be a space, period, dash, forward slash
  337. * - `ymd` 2006-12-27 or 06-12-27 separators can be a space, period, dash, forward slash
  338. * - `dMy` 27 December 2006 or 27 Dec 2006
  339. * - `Mdy` December 27, 2006 or Dec 27, 2006 comma is optional
  340. * - `My` December 2006 or Dec 2006
  341. * - `my` 12/2006 or 12/06 separators can be a space, period, dash, forward slash
  342. * - `ym` 2006/12 or 06/12 separators can be a space, period, dash, forward slash
  343. * - `y` 2006 just the year without any separators
  344. *
  345. * @param string|\DateTimeInterface $check a valid date string/object
  346. * @param string|array $format Use a string or an array of the keys above.
  347. * Arrays should be passed as ['dmy', 'mdy', etc]
  348. * @param string|null $regex If a custom regular expression is used this is the only validation that will occur.
  349. * @return bool Success
  350. */
  351. public static function date($check, $format = 'ymd', $regex = null)
  352. {
  353. if ($check instanceof DateTimeInterface) {
  354. return true;
  355. }
  356. if (is_array($check)) {
  357. $check = static::_getDateString($check);
  358. $format = 'ymd';
  359. }
  360. if ($regex !== null) {
  361. return static::_check($check, $regex);
  362. }
  363. $month = '(0[123456789]|10|11|12)';
  364. $separator = '([- /.])';
  365. $fourDigitYear = '(([1][8-9][0-9][0-9])|([2][0-9][0-9][0-9]))';
  366. $twoDigitYear = '([0-9]{2})';
  367. $year = '(?:' . $fourDigitYear . '|' . $twoDigitYear . ')';
  368. $regex['dmy'] = '%^(?:(?:31(\\/|-|\\.|\\x20)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)' .
  369. $separator . '(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29' .
  370. $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])' .
  371. $separator . '(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%';
  372. $regex['mdy'] = '%^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.|\\x20)31)\\1|(?:(?:0?[13-9]|1[0-2])' .
  373. $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]))' .
  374. $separator . '(?:0?[1-9]|1\\d|2[0-8])\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%';
  375. $regex['ymd'] = '%^(?:(?:(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))' .
  376. $separator . '(?:0?2\\1(?:29)))|(?:(?:(?:1[6-9]|[2-9]\\d)?\\d{2})' .
  377. $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]))))$%';
  378. $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})$/';
  379. $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}))$/';
  380. $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)?)' .
  381. $separator . '((1[6-9]|[2-9]\\d)\\d{2})$%';
  382. $regex['my'] = '%^(' . $month . $separator . $year . ')$%';
  383. $regex['ym'] = '%^(' . $year . $separator . $month . ')$%';
  384. $regex['y'] = '%^(' . $fourDigitYear . ')$%';
  385. $format = (is_array($format)) ? array_values($format) : [$format];
  386. foreach ($format as $key) {
  387. if (static::_check($check, $regex[$key]) === true) {
  388. return true;
  389. }
  390. }
  391. return false;
  392. }
  393. /**
  394. * Validates a datetime value
  395. *
  396. * All values matching the "date" core validation rule, and the "time" one will be valid
  397. *
  398. * @param string|\DateTimeInterface $check Value to check
  399. * @param string|array $dateFormat Format of the date part. See Validation::date() for more information.
  400. * @param string|null $regex Regex for the date part. If a custom regular expression is used this is the only validation that will occur.
  401. * @return bool True if the value is valid, false otherwise
  402. * @see \Cake\Validation\Validation::date()
  403. * @see \Cake\Validation\Validation::time()
  404. */
  405. public static function datetime($check, $dateFormat = 'ymd', $regex = null)
  406. {
  407. if ($check instanceof DateTimeInterface) {
  408. return true;
  409. }
  410. $valid = false;
  411. if (is_array($check)) {
  412. $check = static::_getDateString($check);
  413. $dateFormat = 'ymd';
  414. }
  415. $parts = explode(' ', $check);
  416. if (!empty($parts) && count($parts) > 1) {
  417. $date = rtrim(array_shift($parts), ',');
  418. $time = implode(' ', $parts);
  419. $valid = static::date($date, $dateFormat, $regex) && static::time($time);
  420. }
  421. return $valid;
  422. }
  423. /**
  424. * Time validation, determines if the string passed is a valid time.
  425. * Validates time as 24hr (HH:MM) or am/pm ([H]H:MM[a|p]m)
  426. * Does not allow/validate seconds.
  427. *
  428. * @param string|\DateTimeInterface $check a valid time string/object
  429. * @return bool Success
  430. */
  431. public static function time($check)
  432. {
  433. if ($check instanceof DateTimeInterface) {
  434. return true;
  435. }
  436. if (is_array($check)) {
  437. $check = static::_getDateString($check);
  438. }
  439. 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}$%');
  440. }
  441. /**
  442. * Date and/or time string validation.
  443. * Uses `I18n::Time` to parse the date. This means parsing is locale dependent.
  444. *
  445. * @param string|\DateTime $check a date string or object (will always pass)
  446. * @param string $type Parser type, one out of 'date', 'time', and 'datetime'
  447. * @param string|int|null $format any format accepted by IntlDateFormatter
  448. * @return bool Success
  449. * @throws \InvalidArgumentException when unsupported $type given
  450. * @see \Cake\I18N\Time::parseDate(), \Cake\I18N\Time::parseTime(), \Cake\I18N\Time::parseDateTime()
  451. */
  452. public static function localizedTime($check, $type = 'datetime', $format = null)
  453. {
  454. if ($check instanceof DateTimeInterface) {
  455. return true;
  456. }
  457. static $methods = [
  458. 'date' => 'parseDate',
  459. 'time' => 'parseTime',
  460. 'datetime' => 'parseDateTime',
  461. ];
  462. if (empty($methods[$type])) {
  463. throw new InvalidArgumentException('Unsupported parser type given.');
  464. }
  465. $method = $methods[$type];
  466. return (Time::$method($check, $format) !== null);
  467. }
  468. /**
  469. * Validates if passed value is boolean-like.
  470. *
  471. * The list of what is considered to be boolean values, may be set via $booleanValues.
  472. *
  473. * @param bool|int|string $check Value to check.
  474. * @param string $booleanValues List of valid boolean values, defaults to `[true, false, 0, 1, '0', '1']`.
  475. * @return bool Success.
  476. */
  477. public static function boolean($check, array $booleanValues = [])
  478. {
  479. if (!$booleanValues) {
  480. $booleanValues = [true, false, 0, 1, '0', '1'];
  481. }
  482. return in_array($check, $booleanValues, true);
  483. }
  484. /**
  485. * Validates if given value is truthy.
  486. *
  487. * The list of what is considered to be truthy values, may be set via $truthyValues.
  488. *
  489. * @param bool|int|string $check Value to check.
  490. * @param array $truthyValues List of valid truthy values, defaults to `[true, 1, '1']`.
  491. * @return bool Success.
  492. */
  493. public static function truthy($check, array $truthyValues = [])
  494. {
  495. if (!$truthyValues) {
  496. $truthyValues = [true, 1, '1'];
  497. }
  498. return in_array($check, $truthyValues, true);
  499. }
  500. /**
  501. * Validates if given value is falsey.
  502. *
  503. * The list of what is considered to be falsey values, may be set via $falseyValues.
  504. *
  505. * @param bool|int|string $check Value to check.
  506. * @param array $falseyValues List of valid falsey values, defaults to `[false, 0, '0']`.
  507. * @return bool Success.
  508. */
  509. public static function falsey($check, array $falseyValues = [])
  510. {
  511. if (!$falseyValues) {
  512. $falseyValues = [false, 0, '0'];
  513. }
  514. return in_array($check, $falseyValues, true);
  515. }
  516. /**
  517. * Checks that a value is a valid decimal. Both the sign and exponent are optional.
  518. *
  519. * Valid Places:
  520. *
  521. * - null => Any number of decimal places, including none. The '.' is not required.
  522. * - true => Any number of decimal places greater than 0, or a float|double. The '.' is required.
  523. * - 1..N => Exactly that many number of decimal places. The '.' is required.
  524. *
  525. * @param float $check The value the test for decimal.
  526. * @param int|null $places Decimal places.
  527. * @param string|null $regex If a custom regular expression is used, this is the only validation that will occur.
  528. * @return bool Success
  529. */
  530. public static function decimal($check, $places = null, $regex = null)
  531. {
  532. if ($regex === null) {
  533. $lnum = '[0-9]+';
  534. $dnum = "[0-9]*[\.]{$lnum}";
  535. $sign = '[+-]?';
  536. $exp = "(?:[eE]{$sign}{$lnum})?";
  537. if ($places === null) {
  538. $regex = "/^{$sign}(?:{$lnum}|{$dnum}){$exp}$/";
  539. } elseif ($places === true) {
  540. if (is_float($check) && floor($check) === $check) {
  541. $check = sprintf("%.1f", $check);
  542. }
  543. $regex = "/^{$sign}{$dnum}{$exp}$/";
  544. } elseif (is_numeric($places)) {
  545. $places = '[0-9]{' . $places . '}';
  546. $dnum = "(?:[0-9]*[\.]{$places}|{$lnum}[\.]{$places})";
  547. $regex = "/^{$sign}{$dnum}{$exp}$/";
  548. }
  549. }
  550. // account for localized floats.
  551. $locale = ini_get('intl.default_locale') ?: static::DEFAULT_LOCALE;
  552. $formatter = new NumberFormatter($locale, NumberFormatter::DECIMAL);
  553. $decimalPoint = $formatter->getSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
  554. $groupingSep = $formatter->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL);
  555. $check = str_replace($groupingSep, '', $check);
  556. $check = str_replace($decimalPoint, '.', $check);
  557. return static::_check($check, $regex);
  558. }
  559. /**
  560. * Validates for an email address.
  561. *
  562. * Only uses getmxrr() checking for deep validation, or
  563. * any PHP version on a non-windows distribution
  564. *
  565. * @param string $check Value to check
  566. * @param bool $deep Perform a deeper validation (if true), by also checking availability of host
  567. * @param string|null $regex Regex to use (if none it will use built in regex)
  568. * @return bool Success
  569. */
  570. public static function email($check, $deep = false, $regex = null)
  571. {
  572. if (!is_string($check)) {
  573. return false;
  574. }
  575. if ($regex === null) {
  576. $regex = '/^[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+)*@' . self::$_pattern['hostname'] . '$/ui';
  577. }
  578. $return = static::_check($check, $regex);
  579. if ($deep === false || $deep === null) {
  580. return $return;
  581. }
  582. if ($return === true && preg_match('/@(' . static::$_pattern['hostname'] . ')$/i', $check, $regs)) {
  583. if (function_exists('getmxrr') && getmxrr($regs[1], $mxhosts)) {
  584. return true;
  585. }
  586. if (function_exists('checkdnsrr') && checkdnsrr($regs[1], 'MX')) {
  587. return true;
  588. }
  589. return is_array(gethostbynamel($regs[1]));
  590. }
  591. return false;
  592. }
  593. /**
  594. * Checks that value is exactly $comparedTo.
  595. *
  596. * @param mixed $check Value to check
  597. * @param mixed $comparedTo Value to compare
  598. * @return bool Success
  599. */
  600. public static function equalTo($check, $comparedTo)
  601. {
  602. return ($check === $comparedTo);
  603. }
  604. /**
  605. * Checks that value has a valid file extension.
  606. *
  607. * @param string|array $check Value to check
  608. * @param array $extensions file extensions to allow. By default extensions are 'gif', 'jpeg', 'png', 'jpg'
  609. * @return bool Success
  610. */
  611. public static function extension($check, $extensions = ['gif', 'jpeg', 'png', 'jpg'])
  612. {
  613. if (is_array($check)) {
  614. return static::extension(array_shift($check), $extensions);
  615. }
  616. $extension = strtolower(pathinfo($check, PATHINFO_EXTENSION));
  617. foreach ($extensions as $value) {
  618. if ($extension === strtolower($value)) {
  619. return true;
  620. }
  621. }
  622. return false;
  623. }
  624. /**
  625. * Validation of an IP address.
  626. *
  627. * @param string $check The string to test.
  628. * @param string $type The IP Protocol version to validate against
  629. * @return bool Success
  630. */
  631. public static function ip($check, $type = 'both')
  632. {
  633. $type = strtolower($type);
  634. $flags = 0;
  635. if ($type === 'ipv4') {
  636. $flags = FILTER_FLAG_IPV4;
  637. }
  638. if ($type === 'ipv6') {
  639. $flags = FILTER_FLAG_IPV6;
  640. }
  641. return (bool)filter_var($check, FILTER_VALIDATE_IP, ['flags' => $flags]);
  642. }
  643. /**
  644. * Checks whether the length of a string is greater or equal to a minimal length.
  645. *
  646. * @param string $check The string to test
  647. * @param int $min The minimal string length
  648. * @return bool Success
  649. */
  650. public static function minLength($check, $min)
  651. {
  652. return mb_strlen($check) >= $min;
  653. }
  654. /**
  655. * Checks whether the length of a string is smaller or equal to a maximal length..
  656. *
  657. * @param string $check The string to test
  658. * @param int $max The maximal string length
  659. * @return bool Success
  660. */
  661. public static function maxLength($check, $max)
  662. {
  663. return mb_strlen($check) <= $max;
  664. }
  665. /**
  666. * Checks that a value is a monetary amount.
  667. *
  668. * @param string $check Value to check
  669. * @param string $symbolPosition Where symbol is located (left/right)
  670. * @return bool Success
  671. */
  672. public static function money($check, $symbolPosition = 'left')
  673. {
  674. $money = '(?!0,?\d)(?:\d{1,3}(?:([, .])\d{3})?(?:\1\d{3})*|(?:\d+))((?!\1)[,.]\d{1,2})?';
  675. if ($symbolPosition === 'right') {
  676. $regex = '/^' . $money . '(?<!\x{00a2})\p{Sc}?$/u';
  677. } else {
  678. $regex = '/^(?!\x{00a2})\p{Sc}?' . $money . '$/u';
  679. }
  680. return static::_check($check, $regex);
  681. }
  682. /**
  683. * Validates a multiple select. Comparison is case sensitive by default.
  684. *
  685. * Valid Options
  686. *
  687. * - in => provide a list of choices that selections must be made from
  688. * - max => maximum number of non-zero choices that can be made
  689. * - min => minimum number of non-zero choices that can be made
  690. *
  691. * @param array $check Value to check
  692. * @param array $options Options for the check.
  693. * @param bool $caseInsensitive Set to true for case insensitive comparison.
  694. * @return bool Success
  695. */
  696. public static function multiple($check, array $options = [], $caseInsensitive = false)
  697. {
  698. $defaults = ['in' => null, 'max' => null, 'min' => null];
  699. $options += $defaults;
  700. $check = array_filter((array)$check, function ($value) {
  701. return ($value || is_numeric($value));
  702. });
  703. if (empty($check)) {
  704. return false;
  705. }
  706. if ($options['max'] && count($check) > $options['max']) {
  707. return false;
  708. }
  709. if ($options['min'] && count($check) < $options['min']) {
  710. return false;
  711. }
  712. if ($options['in'] && is_array($options['in'])) {
  713. if ($caseInsensitive) {
  714. $options['in'] = array_map('mb_strtolower', $options['in']);
  715. }
  716. foreach ($check as $val) {
  717. $strict = !is_numeric($val);
  718. if ($caseInsensitive) {
  719. $val = mb_strtolower($val);
  720. }
  721. if (!in_array((string)$val, $options['in'], $strict)) {
  722. return false;
  723. }
  724. }
  725. }
  726. return true;
  727. }
  728. /**
  729. * Checks if a value is numeric.
  730. *
  731. * @param string $check Value to check
  732. * @return bool Success
  733. */
  734. public static function numeric($check)
  735. {
  736. return is_numeric($check);
  737. }
  738. /**
  739. * Checks if a value is a natural number.
  740. *
  741. * @param string $check Value to check
  742. * @param bool $allowZero Set true to allow zero, defaults to false
  743. * @return bool Success
  744. * @see http://en.wikipedia.org/wiki/Natural_number
  745. */
  746. public static function naturalNumber($check, $allowZero = false)
  747. {
  748. $regex = $allowZero ? '/^(?:0|[1-9][0-9]*)$/' : '/^[1-9][0-9]*$/';
  749. return static::_check($check, $regex);
  750. }
  751. /**
  752. * Validates that a number is in specified range.
  753. *
  754. * If $lower and $upper are set, the range is inclusive.
  755. * If they are not set, will return true if $check is a
  756. * legal finite on this platform.
  757. *
  758. * @param string $check Value to check
  759. * @param int|float|null $lower Lower limit
  760. * @param int|float|null $upper Upper limit
  761. * @return bool Success
  762. */
  763. public static function range($check, $lower = null, $upper = null)
  764. {
  765. if (!is_numeric($check)) {
  766. return false;
  767. }
  768. if ((float)$check != $check) {
  769. return false;
  770. }
  771. if (isset($lower, $upper)) {
  772. return ($check >= $lower && $check <= $upper);
  773. }
  774. return is_finite($check);
  775. }
  776. /**
  777. * Checks that a value is a valid URL according to http://www.w3.org/Addressing/URL/url-spec.txt
  778. *
  779. * The regex checks for the following component parts:
  780. *
  781. * - a valid, optional, scheme
  782. * - a valid ip address OR
  783. * a valid domain name as defined by section 2.3.1 of http://www.ietf.org/rfc/rfc1035.txt
  784. * with an optional port number
  785. * - an optional valid path
  786. * - an optional query string (get parameters)
  787. * - an optional fragment (anchor tag)
  788. *
  789. * @param string $check Value to check
  790. * @param bool $strict Require URL to be prefixed by a valid scheme (one of http(s)/ftp(s)/file/news/gopher)
  791. * @return bool Success
  792. */
  793. public static function url($check, $strict = false)
  794. {
  795. static::_populateIp();
  796. $validChars = '([' . preg_quote('!"$&\'()*+,-.@_:;=~[]') . '\/0-9\p{L}\p{N}]|(%[0-9a-f]{2}))';
  797. $regex = '/^(?:(?:https?|ftps?|sftp|file|news|gopher):\/\/)' . (!empty($strict) ? '' : '?') .
  798. '(?:' . static::$_pattern['IPv4'] . '|\[' . static::$_pattern['IPv6'] . '\]|' . static::$_pattern['hostname'] . ')(?::[1-9][0-9]{0,4})?' .
  799. '(?:\/?|\/' . $validChars . '*)?' .
  800. '(?:\?' . $validChars . '*)?' .
  801. '(?:#' . $validChars . '*)?$/iu';
  802. return static::_check($check, $regex);
  803. }
  804. /**
  805. * Checks if a value is in a given list. Comparison is case sensitive by default.
  806. *
  807. * @param string $check Value to check.
  808. * @param array $list List to check against.
  809. * @param bool $caseInsensitive Set to true for case insensitive comparison.
  810. * @return bool Success.
  811. */
  812. public static function inList($check, array $list, $caseInsensitive = false)
  813. {
  814. if ($caseInsensitive) {
  815. $list = array_map('mb_strtolower', $list);
  816. $check = mb_strtolower($check);
  817. } else {
  818. $list = array_map('strval', $list);
  819. }
  820. return in_array((string)$check, $list, true);
  821. }
  822. /**
  823. * Runs an user-defined validation.
  824. *
  825. * @param string|array $check value that will be validated in user-defined methods.
  826. * @param object $object class that holds validation method
  827. * @param string $method class method name for validation to run
  828. * @param array|null $args arguments to send to method
  829. * @return mixed user-defined class class method returns
  830. * @deprecated 3.0.2 You can just set a callable for `rule` key when adding validators.
  831. */
  832. public static function userDefined($check, $object, $method, $args = null)
  833. {
  834. trigger_error(
  835. 'Validation::userDefined() is deprecated. Just set a callable for `rule` key when adding validators instead.',
  836. E_USER_DEPRECATED
  837. );
  838. return $object->$method($check, $args);
  839. }
  840. /**
  841. * Checks that a value is a valid UUID - http://tools.ietf.org/html/rfc4122
  842. *
  843. * @param string $check Value to check
  844. * @return bool Success
  845. */
  846. public static function uuid($check)
  847. {
  848. $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}$/';
  849. return self::_check($check, $regex);
  850. }
  851. /**
  852. * Runs a regular expression match.
  853. *
  854. * @param string $check Value to check against the $regex expression
  855. * @param string $regex Regular expression
  856. * @return bool Success of match
  857. */
  858. protected static function _check($check, $regex)
  859. {
  860. return is_string($regex) && is_scalar($check) && preg_match($regex, $check);
  861. }
  862. /**
  863. * Luhn algorithm
  864. *
  865. * @param string|array $check Value to check.
  866. * @return bool Success
  867. * @see http://en.wikipedia.org/wiki/Luhn_algorithm
  868. */
  869. public static function luhn($check)
  870. {
  871. if (!is_scalar($check) || (int)$check === 0) {
  872. return false;
  873. }
  874. $sum = 0;
  875. $length = strlen($check);
  876. for ($position = 1 - ($length % 2); $position < $length; $position += 2) {
  877. $sum += $check[$position];
  878. }
  879. for ($position = ($length % 2); $position < $length; $position += 2) {
  880. $number = $check[$position] * 2;
  881. $sum += ($number < 10) ? $number : $number - 9;
  882. }
  883. return ($sum % 10 === 0);
  884. }
  885. /**
  886. * Checks the mime type of a file.
  887. *
  888. * Will check the mimetype of files/UploadedFileInterface instances
  889. * by checking the using finfo on the file, not relying on the content-type
  890. * sent by the client.
  891. *
  892. * @param string|array|\Psr\Http\Message\UploadedFileInterface $check Value to check.
  893. * @param array|string $mimeTypes Array of mime types or regex pattern to check.
  894. * @return bool Success
  895. * @throws \RuntimeException when mime type can not be determined.
  896. * @throws \LogicException when ext/fileinfo is missing
  897. */
  898. public static function mimeType($check, $mimeTypes = [])
  899. {
  900. $file = static::getFilename($check);
  901. if ($file === false) {
  902. return false;
  903. }
  904. if (!function_exists('finfo_open')) {
  905. throw new LogicException('ext/fileinfo is required for validating file mime types');
  906. }
  907. if (!is_file($file)) {
  908. throw new RuntimeException('Cannot validate mimetype for a missing file');
  909. }
  910. $finfo = finfo_open(FILEINFO_MIME);
  911. $finfo = finfo_file($finfo, $file);
  912. if (!$finfo) {
  913. throw new RuntimeException('Can not determine the mimetype.');
  914. }
  915. list($mime) = explode(';', $finfo);
  916. if (is_string($mimeTypes)) {
  917. return self::_check($mime, $mimeTypes);
  918. }
  919. foreach ($mimeTypes as $key => $val) {
  920. $mimeTypes[$key] = strtolower($val);
  921. }
  922. return in_array($mime, $mimeTypes);
  923. }
  924. /**
  925. * Helper for reading the file out of the various file implementations
  926. * we accept.
  927. *
  928. * @param string|array|\Psr\Http\Message\UploadedFileInterface $check The data to read a filename out of.
  929. * @return string|bool Either the filename or false on failure.
  930. */
  931. protected static function getFilename($check)
  932. {
  933. if ($check instanceof UploadedFileInterface) {
  934. try {
  935. // Uploaded files throw exceptions on upload errors.
  936. return $check->getStream()->getMetadata('uri');
  937. } catch (RuntimeException $e) {
  938. return false;
  939. }
  940. }
  941. if (is_array($check) && isset($check['tmp_name'])) {
  942. return $check['tmp_name'];
  943. }
  944. return $check;
  945. }
  946. /**
  947. * Checks the filesize
  948. *
  949. * Will check the filesize of files/UploadedFileInterface instances
  950. * by checking the filesize() on disk and not relying on the length
  951. * reported by the client.
  952. *
  953. * @param string|array|\Psr\Http\Message\UploadedFileInterface $check Value to check.
  954. * @param string|null $operator See `Validation::comparison()`.
  955. * @param int|string|null $size Size in bytes or human readable string like '5MB'.
  956. * @return bool Success
  957. */
  958. public static function fileSize($check, $operator = null, $size = null)
  959. {
  960. $file = static::getFilename($check);
  961. if ($file === false) {
  962. return false;
  963. }
  964. if (is_string($size)) {
  965. $size = Text::parseFileSize($size);
  966. }
  967. $filesize = filesize($file);
  968. return static::comparison($filesize, $operator, $size);
  969. }
  970. /**
  971. * Checking for upload errors
  972. *
  973. * @param string|array|\Psr\Http\Message\UploadedFileInterface $check Value to check.
  974. * @param bool $allowNoFile Set to true to allow UPLOAD_ERR_NO_FILE as a pass.
  975. * @return bool
  976. * @see http://www.php.net/manual/en/features.file-upload.errors.php
  977. */
  978. public static function uploadError($check, $allowNoFile = false)
  979. {
  980. if ($check instanceof UploadedFileInterface) {
  981. $code = $check->getError();
  982. } elseif (is_array($check) && isset($check['error'])) {
  983. $code = $check['error'];
  984. } else {
  985. $code = $check;
  986. }
  987. if ($allowNoFile) {
  988. return in_array((int)$code, [UPLOAD_ERR_OK, UPLOAD_ERR_NO_FILE], true);
  989. }
  990. return (int)$code === UPLOAD_ERR_OK;
  991. }
  992. /**
  993. * Validate an uploaded file.
  994. *
  995. * Helps join `uploadError`, `fileSize` and `mimeType` into
  996. * one higher level validation method.
  997. *
  998. * ### Options
  999. *
  1000. * - `types` - An array of valid mime types. If empty all types
  1001. * will be accepted. The `type` will not be looked at, instead
  1002. * the file type will be checked with ext/finfo.
  1003. * - `minSize` - The minimum file size in bytes. Defaults to not checking.
  1004. * - `maxSize` - The maximum file size in bytes. Defaults to not checking.
  1005. * - `optional` - Whether or not this file is optional. Defaults to false.
  1006. * If true a missing file will pass the validator regardless of other constraints.
  1007. *
  1008. * @param array $file The uploaded file data from PHP.
  1009. * @param array $options An array of options for the validation.
  1010. * @return bool
  1011. */
  1012. public static function uploadedFile($file, array $options = [])
  1013. {
  1014. $options += [
  1015. 'minSize' => null,
  1016. 'maxSize' => null,
  1017. 'types' => null,
  1018. 'optional' => false,
  1019. ];
  1020. if (!is_array($file) && !($file instanceof UploadedFileInterface)) {
  1021. return false;
  1022. }
  1023. $error = $isUploaded = false;
  1024. if ($file instanceof UploadedFileInterface) {
  1025. $error = $file->getError();
  1026. $isUploaded = true;
  1027. }
  1028. if (is_array($file)) {
  1029. $keys = ['error', 'name', 'size', 'tmp_name', 'type'];
  1030. ksort($file);
  1031. if (array_keys($file) != $keys) {
  1032. return false;
  1033. }
  1034. $error = (int)$file['error'];
  1035. $isUploaded = is_uploaded_file($file['tmp_name']);
  1036. }
  1037. if (!static::uploadError($file, $options['optional'])) {
  1038. return false;
  1039. }
  1040. if ($options['optional'] && $error === UPLOAD_ERR_NO_FILE) {
  1041. return true;
  1042. }
  1043. if (isset($options['minSize']) && !static::fileSize($file, '>=', $options['minSize'])) {
  1044. return false;
  1045. }
  1046. if (isset($options['maxSize']) && !static::fileSize($file, '<=', $options['maxSize'])) {
  1047. return false;
  1048. }
  1049. if (isset($options['types']) && !static::mimeType($file, $options['types'])) {
  1050. return false;
  1051. }
  1052. return $isUploaded;
  1053. }
  1054. /**
  1055. * Validates the size of an uploaded image.
  1056. *
  1057. * @param array $file The uploaded file data from PHP.
  1058. * @param array $options Options to validate width and height.
  1059. * @return bool
  1060. */
  1061. public static function imageSize($file, $options)
  1062. {
  1063. if (!isset($options['height']) && !isset($options['width'])) {
  1064. throw new InvalidArgumentException('Invalid image size validation parameters! Missing `width` and / or `height`.');
  1065. }
  1066. if ($file instanceof UploadedFileInterface) {
  1067. $file = $file->getStream()->getContents();
  1068. } elseif (is_array($file) && isset($file['tmp_name'])) {
  1069. $file = $file['tmp_name'];
  1070. }
  1071. list($width, $height) = getimagesize($file);
  1072. if (isset($options['height'])) {
  1073. $validHeight = self::comparison($height, $options['height'][0], $options['height'][1]);
  1074. }
  1075. if (isset($options['width'])) {
  1076. $validWidth = self::comparison($width, $options['width'][0], $options['width'][1]);
  1077. }
  1078. if (isset($validHeight) && isset($validWidth)) {
  1079. return ($validHeight && $validWidth);
  1080. }
  1081. if (isset($validHeight)) {
  1082. return $validHeight;
  1083. }
  1084. if (isset($validWidth)) {
  1085. return $validWidth;
  1086. }
  1087. throw new InvalidArgumentException('The 2nd argument is missing the `width` and / or `height` options.');
  1088. }
  1089. /**
  1090. * Validates the image width.
  1091. *
  1092. * @param array $file The uploaded file data from PHP.
  1093. * @param string $operator Comparision operator.
  1094. * @param int $width Min or max width.
  1095. * @return bool
  1096. */
  1097. public static function imageWidth($file, $operator, $width)
  1098. {
  1099. return self::imageSize($file, [
  1100. 'width' => [
  1101. $operator,
  1102. $width
  1103. ]
  1104. ]);
  1105. }
  1106. /**
  1107. * Validates the image width.
  1108. *
  1109. * @param array $file The uploaded file data from PHP.
  1110. * @param string $operator Comparision operator.
  1111. * @param int $height Min or max width.
  1112. * @return bool
  1113. */
  1114. public static function imageHeight($file, $operator, $height)
  1115. {
  1116. return self::imageSize($file, [
  1117. 'height' => [
  1118. $operator,
  1119. $height
  1120. ]
  1121. ]);
  1122. }
  1123. /**
  1124. * Validates a geographic coordinate.
  1125. *
  1126. * Supported formats:
  1127. *
  1128. * - `<latitude>, <longitude>` Example: `-25.274398, 133.775136`
  1129. *
  1130. * ### Options
  1131. *
  1132. * - `type` - A string of the coordinate format, right now only `latLong`.
  1133. * - `format` - By default `both`, can be `long` and `lat` as well to validate
  1134. * only a part of the coordinate.
  1135. *
  1136. * @param string $value Geographic location as string
  1137. * @param array $options Options for the validation logic.
  1138. * @return bool
  1139. */
  1140. public static function geoCoordinate($value, array $options = [])
  1141. {
  1142. $options += [
  1143. 'format' => 'both',
  1144. 'type' => 'latLong'
  1145. ];
  1146. if ($options['type'] !== 'latLong') {
  1147. throw new RuntimeException(sprintf(
  1148. 'Unsupported coordinate type "%s". Use "latLong" instead.',
  1149. $options['type']
  1150. ));
  1151. }
  1152. $pattern = '/^' . self::$_pattern['latitude'] . ',\s*' . self::$_pattern['longitude'] . '$/';
  1153. if ($options['format'] === 'long') {
  1154. $pattern = '/^' . self::$_pattern['longitude'] . '$/';
  1155. }
  1156. if ($options['format'] === 'lat') {
  1157. $pattern = '/^' . self::$_pattern['latitude'] . '$/';
  1158. }
  1159. return (bool)preg_match($pattern, $value);
  1160. }
  1161. /**
  1162. * Convenience method for latitude validation.
  1163. *
  1164. * @param string $value Latitude as string
  1165. * @param array $options Options for the validation logic.
  1166. * @return bool
  1167. * @link https://en.wikipedia.org/wiki/Latitude
  1168. * @see \Cake\Validation\Validation::geoCoordinate()
  1169. */
  1170. public static function latitude($value, array $options = [])
  1171. {
  1172. $options['format'] = 'lat';
  1173. return self::geoCoordinate($value, $options);
  1174. }
  1175. /**
  1176. * Convenience method for longitude validation.
  1177. *
  1178. * @param string $value Latitude as string
  1179. * @param array $options Options for the validation logic.
  1180. * @return bool
  1181. * @link https://en.wikipedia.org/wiki/Longitude
  1182. * @see \Cake\Validation\Validation::geoCoordinate()
  1183. */
  1184. public static function longitude($value, array $options = [])
  1185. {
  1186. $options['format'] = 'long';
  1187. return self::geoCoordinate($value, $options);
  1188. }
  1189. /**
  1190. * Check that the input value is within the ascii byte range.
  1191. *
  1192. * This method will reject all non-string values.
  1193. *
  1194. * @param string $value The value to check
  1195. * @return bool
  1196. */
  1197. public static function ascii($value)
  1198. {
  1199. if (!is_string($value)) {
  1200. return false;
  1201. }
  1202. return strlen($value) <= mb_strlen($value, 'utf-8');
  1203. }
  1204. /**
  1205. * Check that the input value is a utf8 string.
  1206. *
  1207. * This method will reject all non-string values.
  1208. *
  1209. * # Options
  1210. *
  1211. * - `extended` - Disallow bytes higher within the basic multilingual plane.
  1212. * MySQL's older utf8 encoding type does not allow characters above
  1213. * the basic multilingual plane. Defaults to false.
  1214. *
  1215. * @param string $value The value to check
  1216. * @param array $options An array of options. See above for the supported options.
  1217. * @return bool
  1218. */
  1219. public static function utf8($value, array $options = [])
  1220. {
  1221. if (!is_string($value)) {
  1222. return false;
  1223. }
  1224. $options += ['extended' => false];
  1225. if ($options['extended']) {
  1226. return true;
  1227. }
  1228. return preg_match('/[\x{10000}-\x{10FFFF}]/u', $value) === 0;
  1229. }
  1230. /**
  1231. * Check that the input value is an integer
  1232. *
  1233. * This method will accept strings that contain only integer data
  1234. * as well.
  1235. *
  1236. * @param string $value The value to check
  1237. * @return bool
  1238. */
  1239. public static function isInteger($value)
  1240. {
  1241. if (!is_scalar($value) || is_float($value)) {
  1242. return false;
  1243. }
  1244. if (is_int($value)) {
  1245. return true;
  1246. }
  1247. return (bool)preg_match('/^-?[0-9]+$/', $value);
  1248. }
  1249. /**
  1250. * Check that the input value is an array.
  1251. *
  1252. * @param array $value The value to check
  1253. * @return bool
  1254. */
  1255. public static function isArray($value)
  1256. {
  1257. return is_array($value);
  1258. }
  1259. /**
  1260. * Converts an array representing a date or datetime into a ISO string.
  1261. * The arrays are typically sent for validation from a form generated by
  1262. * the CakePHP FormHelper.
  1263. *
  1264. * @param array $value The array representing a date or datetime.
  1265. * @return string
  1266. */
  1267. protected static function _getDateString($value)
  1268. {
  1269. $formatted = '';
  1270. if (isset($value['year'], $value['month'], $value['day']) &&
  1271. (is_numeric($value['year']) && is_numeric($value['month']) && is_numeric($value['day']))
  1272. ) {
  1273. $formatted .= sprintf('%d-%02d-%02d ', $value['year'], $value['month'], $value['day']);
  1274. }
  1275. if (isset($value['hour'])) {
  1276. if (isset($value['meridian']) && (int)$value['hour'] === 12) {
  1277. $value['hour'] = 0;
  1278. }
  1279. if (isset($value['meridian'])) {
  1280. $value['hour'] = strtolower($value['meridian']) === 'am' ? $value['hour'] : $value['hour'] + 12;
  1281. }
  1282. $value += ['minute' => 0, 'second' => 0];
  1283. if (is_numeric($value['hour']) && is_numeric($value['minute']) && is_numeric($value['second'])) {
  1284. $formatted .= sprintf('%02d:%02d:%02d', $value['hour'], $value['minute'], $value['second']);
  1285. }
  1286. }
  1287. return trim($formatted);
  1288. }
  1289. /**
  1290. * Lazily populate the IP address patterns used for validations
  1291. *
  1292. * @return void
  1293. */
  1294. protected static function _populateIp()
  1295. {
  1296. if (!isset(static::$_pattern['IPv6'])) {
  1297. $pattern = '((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}';
  1298. $pattern .= '(:|((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})';
  1299. $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})';
  1300. $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}:)';
  1301. $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}))';
  1302. $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}';
  1303. $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|';
  1304. $pattern .= '((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}';
  1305. $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2}))';
  1306. $pattern .= '{3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4})';
  1307. $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})?)';
  1308. $pattern .= '|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]';
  1309. $pattern .= '\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4})';
  1310. $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})))(%.+)?';
  1311. static::$_pattern['IPv6'] = $pattern;
  1312. }
  1313. if (!isset(static::$_pattern['IPv4'])) {
  1314. $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])';
  1315. static::$_pattern['IPv4'] = $pattern;
  1316. }
  1317. }
  1318. /**
  1319. * Reset internal variables for another validation run.
  1320. *
  1321. * @return void
  1322. */
  1323. protected static function _reset()
  1324. {
  1325. static::$errors = [];
  1326. }
  1327. }