Validation.php 51 KB

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