Validation.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  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) && !is_bool($check) && !is_numeric($check)) {
  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_object($check)) {
  357. return false;
  358. }
  359. if (is_array($check)) {
  360. $check = static::_getDateString($check);
  361. $format = 'ymd';
  362. }
  363. if ($regex !== null) {
  364. return static::_check($check, $regex);
  365. }
  366. $month = '(0[123456789]|10|11|12)';
  367. $separator = '([- /.])';
  368. $fourDigitYear = '(([1][8-9][0-9][0-9])|([2][0-9][0-9][0-9]))';
  369. $twoDigitYear = '([0-9]{2})';
  370. $year = '(?:' . $fourDigitYear . '|' . $twoDigitYear . ')';
  371. $regex['dmy'] = '%^(?:(?:31(\\/|-|\\.|\\x20)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)' .
  372. $separator . '(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29' .
  373. $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])' .
  374. $separator . '(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%';
  375. $regex['mdy'] = '%^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.|\\x20)31)\\1|(?:(?:0?[13-9]|1[0-2])' .
  376. $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]))' .
  377. $separator . '(?:0?[1-9]|1\\d|2[0-8])\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%';
  378. $regex['ymd'] = '%^(?:(?:(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))' .
  379. $separator . '(?:0?2\\1(?:29)))|(?:(?:(?:1[6-9]|[2-9]\\d)?\\d{2})' .
  380. $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]))))$%';
  381. $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})$/';
  382. $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}))$/';
  383. $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)?)' .
  384. $separator . '((1[6-9]|[2-9]\\d)\\d{2})$%';
  385. $regex['my'] = '%^(' . $month . $separator . $year . ')$%';
  386. $regex['ym'] = '%^(' . $year . $separator . $month . ')$%';
  387. $regex['y'] = '%^(' . $fourDigitYear . ')$%';
  388. $format = is_array($format) ? array_values($format) : [$format];
  389. foreach ($format as $key) {
  390. if (static::_check($check, $regex[$key]) === true) {
  391. return true;
  392. }
  393. }
  394. return false;
  395. }
  396. /**
  397. * Validates a datetime value
  398. *
  399. * All values matching the "date" core validation rule, and the "time" one will be valid
  400. *
  401. * @param string|\DateTimeInterface $check Value to check
  402. * @param string|array $dateFormat Format of the date part. See Validation::date() for more information.
  403. * @param string|null $regex Regex for the date part. If a custom regular expression is used this is the only validation that will occur.
  404. * @return bool True if the value is valid, false otherwise
  405. * @see \Cake\Validation\Validation::date()
  406. * @see \Cake\Validation\Validation::time()
  407. */
  408. public static function datetime($check, $dateFormat = 'ymd', $regex = null)
  409. {
  410. if ($check instanceof DateTimeInterface) {
  411. return true;
  412. }
  413. if (is_object($check)) {
  414. return false;
  415. }
  416. $valid = false;
  417. if (is_array($check)) {
  418. $check = static::_getDateString($check);
  419. $dateFormat = 'ymd';
  420. }
  421. $parts = explode(' ', $check);
  422. if (!empty($parts) && count($parts) > 1) {
  423. $date = rtrim(array_shift($parts), ',');
  424. $time = implode(' ', $parts);
  425. $valid = static::date($date, $dateFormat, $regex) && static::time($time);
  426. }
  427. return $valid;
  428. }
  429. /**
  430. * Time validation, determines if the string passed is a valid time.
  431. * Validates time as 24hr (HH:MM) or am/pm ([H]H:MM[a|p]m)
  432. * Does not allow/validate seconds.
  433. *
  434. * @param string|\DateTimeInterface $check a valid time string/object
  435. * @return bool Success
  436. */
  437. public static function time($check)
  438. {
  439. if ($check instanceof DateTimeInterface) {
  440. return true;
  441. }
  442. if (is_array($check)) {
  443. $check = static::_getDateString($check);
  444. }
  445. 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}$%');
  446. }
  447. /**
  448. * Date and/or time string validation.
  449. * Uses `I18n::Time` to parse the date. This means parsing is locale dependent.
  450. *
  451. * @param string|\DateTime $check a date string or object (will always pass)
  452. * @param string $type Parser type, one out of 'date', 'time', and 'datetime'
  453. * @param string|int|null $format any format accepted by IntlDateFormatter
  454. * @return bool Success
  455. * @throws \InvalidArgumentException when unsupported $type given
  456. * @see \Cake\I18N\Time::parseDate(), \Cake\I18N\Time::parseTime(), \Cake\I18N\Time::parseDateTime()
  457. */
  458. public static function localizedTime($check, $type = 'datetime', $format = null)
  459. {
  460. if ($check instanceof DateTimeInterface) {
  461. return true;
  462. }
  463. if (is_object($check)) {
  464. return false;
  465. }
  466. static $methods = [
  467. 'date' => 'parseDate',
  468. 'time' => 'parseTime',
  469. 'datetime' => 'parseDateTime',
  470. ];
  471. if (empty($methods[$type])) {
  472. throw new InvalidArgumentException('Unsupported parser type given.');
  473. }
  474. $method = $methods[$type];
  475. return (Time::$method($check, $format) !== null);
  476. }
  477. /**
  478. * Validates if passed value is boolean-like.
  479. *
  480. * The list of what is considered to be boolean values, may be set via $booleanValues.
  481. *
  482. * @param bool|int|string $check Value to check.
  483. * @param string $booleanValues List of valid boolean values, defaults to `[true, false, 0, 1, '0', '1']`.
  484. * @return bool Success.
  485. */
  486. public static function boolean($check, array $booleanValues = [])
  487. {
  488. if (!$booleanValues) {
  489. $booleanValues = [true, false, 0, 1, '0', '1'];
  490. }
  491. return in_array($check, $booleanValues, true);
  492. }
  493. /**
  494. * Validates if given value is truthy.
  495. *
  496. * The list of what is considered to be truthy values, may be set via $truthyValues.
  497. *
  498. * @param bool|int|string $check Value to check.
  499. * @param array $truthyValues List of valid truthy values, defaults to `[true, 1, '1']`.
  500. * @return bool Success.
  501. */
  502. public static function truthy($check, array $truthyValues = [])
  503. {
  504. if (!$truthyValues) {
  505. $truthyValues = [true, 1, '1'];
  506. }
  507. return in_array($check, $truthyValues, true);
  508. }
  509. /**
  510. * Validates if given value is falsey.
  511. *
  512. * The list of what is considered to be falsey values, may be set via $falseyValues.
  513. *
  514. * @param bool|int|string $check Value to check.
  515. * @param array $falseyValues List of valid falsey values, defaults to `[false, 0, '0']`.
  516. * @return bool Success.
  517. */
  518. public static function falsey($check, array $falseyValues = [])
  519. {
  520. if (!$falseyValues) {
  521. $falseyValues = [false, 0, '0'];
  522. }
  523. return in_array($check, $falseyValues, true);
  524. }
  525. /**
  526. * Checks that a value is a valid decimal. Both the sign and exponent are optional.
  527. *
  528. * Valid Places:
  529. *
  530. * - null => Any number of decimal places, including none. The '.' is not required.
  531. * - true => Any number of decimal places greater than 0, or a float|double. The '.' is required.
  532. * - 1..N => Exactly that many number of decimal places. The '.' is required.
  533. *
  534. * @param float $check The value the test for decimal.
  535. * @param int|bool|null $places Decimal places.
  536. * @param string|null $regex If a custom regular expression is used, this is the only validation that will occur.
  537. * @return bool Success
  538. */
  539. public static function decimal($check, $places = null, $regex = null)
  540. {
  541. if ($regex === null) {
  542. $lnum = '[0-9]+';
  543. $dnum = "[0-9]*[\.]{$lnum}";
  544. $sign = '[+-]?';
  545. $exp = "(?:[eE]{$sign}{$lnum})?";
  546. if ($places === null) {
  547. $regex = "/^{$sign}(?:{$lnum}|{$dnum}){$exp}$/";
  548. } elseif ($places === true) {
  549. if (is_float($check) && floor($check) === $check) {
  550. $check = sprintf("%.1f", $check);
  551. }
  552. $regex = "/^{$sign}{$dnum}{$exp}$/";
  553. } elseif (is_numeric($places)) {
  554. $places = '[0-9]{' . $places . '}';
  555. $dnum = "(?:[0-9]*[\.]{$places}|{$lnum}[\.]{$places})";
  556. $regex = "/^{$sign}{$dnum}{$exp}$/";
  557. }
  558. }
  559. // account for localized floats.
  560. $locale = ini_get('intl.default_locale') ?: static::DEFAULT_LOCALE;
  561. $formatter = new NumberFormatter($locale, NumberFormatter::DECIMAL);
  562. $decimalPoint = $formatter->getSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
  563. $groupingSep = $formatter->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL);
  564. $check = str_replace($groupingSep, '', $check);
  565. $check = str_replace($decimalPoint, '.', $check);
  566. return static::_check($check, $regex);
  567. }
  568. /**
  569. * Validates for an email address.
  570. *
  571. * Only uses getmxrr() checking for deep validation, or
  572. * any PHP version on a non-windows distribution
  573. *
  574. * @param string $check Value to check
  575. * @param bool $deep Perform a deeper validation (if true), by also checking availability of host
  576. * @param string|null $regex Regex to use (if none it will use built in regex)
  577. * @return bool Success
  578. */
  579. public static function email($check, $deep = false, $regex = null)
  580. {
  581. if (!is_string($check)) {
  582. return false;
  583. }
  584. if ($regex === null) {
  585. $regex = '/^[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+)*@' . self::$_pattern['hostname'] . '$/ui';
  586. }
  587. $return = static::_check($check, $regex);
  588. if ($deep === false || $deep === null) {
  589. return $return;
  590. }
  591. if ($return === true && preg_match('/@(' . static::$_pattern['hostname'] . ')$/i', $check, $regs)) {
  592. if (function_exists('getmxrr') && getmxrr($regs[1], $mxhosts)) {
  593. return true;
  594. }
  595. if (function_exists('checkdnsrr') && checkdnsrr($regs[1], 'MX')) {
  596. return true;
  597. }
  598. return is_array(gethostbynamel($regs[1]));
  599. }
  600. return false;
  601. }
  602. /**
  603. * Checks that value is exactly $comparedTo.
  604. *
  605. * @param mixed $check Value to check
  606. * @param mixed $comparedTo Value to compare
  607. * @return bool Success
  608. */
  609. public static function equalTo($check, $comparedTo)
  610. {
  611. return ($check === $comparedTo);
  612. }
  613. /**
  614. * Checks that value has a valid file extension.
  615. *
  616. * @param string|array $check Value to check
  617. * @param array $extensions file extensions to allow. By default extensions are 'gif', 'jpeg', 'png', 'jpg'
  618. * @return bool Success
  619. */
  620. public static function extension($check, $extensions = ['gif', 'jpeg', 'png', 'jpg'])
  621. {
  622. if (is_array($check)) {
  623. $check = isset($check['name']) ? $check['name'] : array_shift($check);
  624. return static::extension($check, $extensions);
  625. }
  626. $extension = strtolower(pathinfo($check, PATHINFO_EXTENSION));
  627. foreach ($extensions as $value) {
  628. if ($extension === strtolower($value)) {
  629. return true;
  630. }
  631. }
  632. return false;
  633. }
  634. /**
  635. * Validation of an IP address.
  636. *
  637. * @param string $check The string to test.
  638. * @param string $type The IP Protocol version to validate against
  639. * @return bool Success
  640. */
  641. public static function ip($check, $type = 'both')
  642. {
  643. $type = strtolower($type);
  644. $flags = 0;
  645. if ($type === 'ipv4') {
  646. $flags = FILTER_FLAG_IPV4;
  647. }
  648. if ($type === 'ipv6') {
  649. $flags = FILTER_FLAG_IPV6;
  650. }
  651. return (bool)filter_var($check, FILTER_VALIDATE_IP, ['flags' => $flags]);
  652. }
  653. /**
  654. * Checks whether the length of a string (in characters) is greater or equal to a minimal length.
  655. *
  656. * @param string $check The string to test
  657. * @param int $min The minimal string length
  658. * @return bool Success
  659. */
  660. public static function minLength($check, $min)
  661. {
  662. return mb_strlen($check) >= $min;
  663. }
  664. /**
  665. * Checks whether the length of a string (in characters) is smaller or equal to a maximal length.
  666. *
  667. * @param string $check The string to test
  668. * @param int $max The maximal string length
  669. * @return bool Success
  670. */
  671. public static function maxLength($check, $max)
  672. {
  673. return mb_strlen($check) <= $max;
  674. }
  675. /**
  676. * Checks whether the length of a string (in bytes) is greater or equal to a minimal length.
  677. *
  678. * @param string $check The string to test
  679. * @param int $min The minimal string length (in bytes)
  680. * @return bool Success
  681. */
  682. public static function minLengthBytes($check, $min)
  683. {
  684. return strlen($check) >= $min;
  685. }
  686. /**
  687. * Checks whether the length of a string (in bytes) is smaller or equal to a maximal length.
  688. *
  689. * @param string $check The string to test
  690. * @param int $max The maximal string length
  691. * @return bool Success
  692. */
  693. public static function maxLengthBytes($check, $max)
  694. {
  695. return strlen($check) <= $max;
  696. }
  697. /**
  698. * Checks that a value is a monetary amount.
  699. *
  700. * @param string $check Value to check
  701. * @param string $symbolPosition Where symbol is located (left/right)
  702. * @return bool Success
  703. */
  704. public static function money($check, $symbolPosition = 'left')
  705. {
  706. $money = '(?!0,?\d)(?:\d{1,3}(?:([, .])\d{3})?(?:\1\d{3})*|(?:\d+))((?!\1)[,.]\d{1,2})?';
  707. if ($symbolPosition === 'right') {
  708. $regex = '/^' . $money . '(?<!\x{00a2})\p{Sc}?$/u';
  709. } else {
  710. $regex = '/^(?!\x{00a2})\p{Sc}?' . $money . '$/u';
  711. }
  712. return static::_check($check, $regex);
  713. }
  714. /**
  715. * Validates a multiple select. Comparison is case sensitive by default.
  716. *
  717. * Valid Options
  718. *
  719. * - in => provide a list of choices that selections must be made from
  720. * - max => maximum number of non-zero choices that can be made
  721. * - min => minimum number of non-zero choices that can be made
  722. *
  723. * @param array $check Value to check
  724. * @param array $options Options for the check.
  725. * @param bool $caseInsensitive Set to true for case insensitive comparison.
  726. * @return bool Success
  727. */
  728. public static function multiple($check, array $options = [], $caseInsensitive = false)
  729. {
  730. $defaults = ['in' => null, 'max' => null, 'min' => null];
  731. $options += $defaults;
  732. $check = array_filter((array)$check, function ($value) {
  733. return ($value || is_numeric($value));
  734. });
  735. if (empty($check)) {
  736. return false;
  737. }
  738. if ($options['max'] && count($check) > $options['max']) {
  739. return false;
  740. }
  741. if ($options['min'] && count($check) < $options['min']) {
  742. return false;
  743. }
  744. if ($options['in'] && is_array($options['in'])) {
  745. if ($caseInsensitive) {
  746. $options['in'] = array_map('mb_strtolower', $options['in']);
  747. }
  748. foreach ($check as $val) {
  749. $strict = !is_numeric($val);
  750. if ($caseInsensitive) {
  751. $val = mb_strtolower($val);
  752. }
  753. if (!in_array((string)$val, $options['in'], $strict)) {
  754. return false;
  755. }
  756. }
  757. }
  758. return true;
  759. }
  760. /**
  761. * Checks if a value is numeric.
  762. *
  763. * @param string $check Value to check
  764. * @return bool Success
  765. */
  766. public static function numeric($check)
  767. {
  768. return is_numeric($check);
  769. }
  770. /**
  771. * Checks if a value is a natural number.
  772. *
  773. * @param string $check Value to check
  774. * @param bool $allowZero Set true to allow zero, defaults to false
  775. * @return bool Success
  776. * @see http://en.wikipedia.org/wiki/Natural_number
  777. */
  778. public static function naturalNumber($check, $allowZero = false)
  779. {
  780. $regex = $allowZero ? '/^(?:0|[1-9][0-9]*)$/' : '/^[1-9][0-9]*$/';
  781. return static::_check($check, $regex);
  782. }
  783. /**
  784. * Validates that a number is in specified range.
  785. *
  786. * If $lower and $upper are set, the range is inclusive.
  787. * If they are not set, will return true if $check is a
  788. * legal finite on this platform.
  789. *
  790. * @param string $check Value to check
  791. * @param int|float|null $lower Lower limit
  792. * @param int|float|null $upper Upper limit
  793. * @return bool Success
  794. */
  795. public static function range($check, $lower = null, $upper = null)
  796. {
  797. if (!is_numeric($check)) {
  798. return false;
  799. }
  800. if ((float)$check != $check) {
  801. return false;
  802. }
  803. if (isset($lower, $upper)) {
  804. return ($check >= $lower && $check <= $upper);
  805. }
  806. return is_finite($check);
  807. }
  808. /**
  809. * Checks that a value is a valid URL according to http://www.w3.org/Addressing/URL/url-spec.txt
  810. *
  811. * The regex checks for the following component parts:
  812. *
  813. * - a valid, optional, scheme
  814. * - a valid ip address OR
  815. * a valid domain name as defined by section 2.3.1 of http://www.ietf.org/rfc/rfc1035.txt
  816. * with an optional port number
  817. * - an optional valid path
  818. * - an optional query string (get parameters)
  819. * - an optional fragment (anchor tag)
  820. *
  821. * @param string $check Value to check
  822. * @param bool $strict Require URL to be prefixed by a valid scheme (one of http(s)/ftp(s)/file/news/gopher)
  823. * @return bool Success
  824. */
  825. public static function url($check, $strict = false)
  826. {
  827. static::_populateIp();
  828. $validChars = '([' . preg_quote('!"$&\'()*+,-.@_:;=~[]') . '\/0-9\p{L}\p{N}]|(%[0-9a-f]{2}))';
  829. $regex = '/^(?:(?:https?|ftps?|sftp|file|news|gopher):\/\/)' . (!empty($strict) ? '' : '?') .
  830. '(?:' . static::$_pattern['IPv4'] . '|\[' . static::$_pattern['IPv6'] . '\]|' . static::$_pattern['hostname'] . ')(?::[1-9][0-9]{0,4})?' .
  831. '(?:\/?|\/' . $validChars . '*)?' .
  832. '(?:\?' . $validChars . '*)?' .
  833. '(?:#' . $validChars . '*)?$/iu';
  834. return static::_check($check, $regex);
  835. }
  836. /**
  837. * Checks if a value is in a given list. Comparison is case sensitive by default.
  838. *
  839. * @param string $check Value to check.
  840. * @param array $list List to check against.
  841. * @param bool $caseInsensitive Set to true for case insensitive comparison.
  842. * @return bool Success.
  843. */
  844. public static function inList($check, array $list, $caseInsensitive = false)
  845. {
  846. if ($caseInsensitive) {
  847. $list = array_map('mb_strtolower', $list);
  848. $check = mb_strtolower($check);
  849. } else {
  850. $list = array_map('strval', $list);
  851. }
  852. return in_array((string)$check, $list, true);
  853. }
  854. /**
  855. * Runs an user-defined validation.
  856. *
  857. * @param string|array $check value that will be validated in user-defined methods.
  858. * @param object $object class that holds validation method
  859. * @param string $method class method name for validation to run
  860. * @param array|null $args arguments to send to method
  861. * @return mixed user-defined class class method returns
  862. * @deprecated 3.0.2 You can just set a callable for `rule` key when adding validators.
  863. */
  864. public static function userDefined($check, $object, $method, $args = null)
  865. {
  866. trigger_error(
  867. 'Validation::userDefined() is deprecated. Just set a callable for `rule` key when adding validators instead.',
  868. E_USER_DEPRECATED
  869. );
  870. return $object->$method($check, $args);
  871. }
  872. /**
  873. * Checks that a value is a valid UUID - http://tools.ietf.org/html/rfc4122
  874. *
  875. * @param string $check Value to check
  876. * @return bool Success
  877. */
  878. public static function uuid($check)
  879. {
  880. $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}$/';
  881. return self::_check($check, $regex);
  882. }
  883. /**
  884. * Runs a regular expression match.
  885. *
  886. * @param string $check Value to check against the $regex expression
  887. * @param string $regex Regular expression
  888. * @return bool Success of match
  889. */
  890. protected static function _check($check, $regex)
  891. {
  892. return is_string($regex) && is_scalar($check) && preg_match($regex, $check);
  893. }
  894. /**
  895. * Luhn algorithm
  896. *
  897. * @param string|array $check Value to check.
  898. * @return bool Success
  899. * @see http://en.wikipedia.org/wiki/Luhn_algorithm
  900. */
  901. public static function luhn($check)
  902. {
  903. if (!is_scalar($check) || (int)$check === 0) {
  904. return false;
  905. }
  906. $sum = 0;
  907. $length = strlen($check);
  908. for ($position = 1 - ($length % 2); $position < $length; $position += 2) {
  909. $sum += $check[$position];
  910. }
  911. for ($position = ($length % 2); $position < $length; $position += 2) {
  912. $number = $check[$position] * 2;
  913. $sum += ($number < 10) ? $number : $number - 9;
  914. }
  915. return ($sum % 10 === 0);
  916. }
  917. /**
  918. * Checks the mime type of a file.
  919. *
  920. * Will check the mimetype of files/UploadedFileInterface instances
  921. * by checking the using finfo on the file, not relying on the content-type
  922. * sent by the client.
  923. *
  924. * @param string|array|\Psr\Http\Message\UploadedFileInterface $check Value to check.
  925. * @param array|string $mimeTypes Array of mime types or regex pattern to check.
  926. * @return bool Success
  927. * @throws \RuntimeException when mime type can not be determined.
  928. * @throws \LogicException when ext/fileinfo is missing
  929. */
  930. public static function mimeType($check, $mimeTypes = [])
  931. {
  932. $file = static::getFilename($check);
  933. if ($file === false) {
  934. return false;
  935. }
  936. if (!function_exists('finfo_open')) {
  937. throw new LogicException('ext/fileinfo is required for validating file mime types');
  938. }
  939. if (!is_file($file)) {
  940. throw new RuntimeException('Cannot validate mimetype for a missing file');
  941. }
  942. $finfo = finfo_open(FILEINFO_MIME);
  943. $finfo = finfo_file($finfo, $file);
  944. if (!$finfo) {
  945. throw new RuntimeException('Can not determine the mimetype.');
  946. }
  947. list($mime) = explode(';', $finfo);
  948. if (is_string($mimeTypes)) {
  949. return self::_check($mime, $mimeTypes);
  950. }
  951. foreach ($mimeTypes as $key => $val) {
  952. $mimeTypes[$key] = strtolower($val);
  953. }
  954. return in_array($mime, $mimeTypes);
  955. }
  956. /**
  957. * Helper for reading the file out of the various file implementations
  958. * we accept.
  959. *
  960. * @param string|array|\Psr\Http\Message\UploadedFileInterface $check The data to read a filename out of.
  961. * @return string|bool Either the filename or false on failure.
  962. */
  963. protected static function getFilename($check)
  964. {
  965. if ($check instanceof UploadedFileInterface) {
  966. try {
  967. // Uploaded files throw exceptions on upload errors.
  968. return $check->getStream()->getMetadata('uri');
  969. } catch (RuntimeException $e) {
  970. return false;
  971. }
  972. }
  973. if (is_array($check) && isset($check['tmp_name'])) {
  974. return $check['tmp_name'];
  975. }
  976. return $check;
  977. }
  978. /**
  979. * Checks the filesize
  980. *
  981. * Will check the filesize of files/UploadedFileInterface instances
  982. * by checking the filesize() on disk and not relying on the length
  983. * reported by the client.
  984. *
  985. * @param string|array|\Psr\Http\Message\UploadedFileInterface $check Value to check.
  986. * @param string|null $operator See `Validation::comparison()`.
  987. * @param int|string|null $size Size in bytes or human readable string like '5MB'.
  988. * @return bool Success
  989. */
  990. public static function fileSize($check, $operator = null, $size = null)
  991. {
  992. $file = static::getFilename($check);
  993. if ($file === false) {
  994. return false;
  995. }
  996. if (is_string($size)) {
  997. $size = Text::parseFileSize($size);
  998. }
  999. $filesize = filesize($file);
  1000. return static::comparison($filesize, $operator, $size);
  1001. }
  1002. /**
  1003. * Checking for upload errors
  1004. *
  1005. * @param string|array|\Psr\Http\Message\UploadedFileInterface $check Value to check.
  1006. * @param bool $allowNoFile Set to true to allow UPLOAD_ERR_NO_FILE as a pass.
  1007. * @return bool
  1008. * @see http://www.php.net/manual/en/features.file-upload.errors.php
  1009. */
  1010. public static function uploadError($check, $allowNoFile = false)
  1011. {
  1012. if ($check instanceof UploadedFileInterface) {
  1013. $code = $check->getError();
  1014. } elseif (is_array($check) && isset($check['error'])) {
  1015. $code = $check['error'];
  1016. } else {
  1017. $code = $check;
  1018. }
  1019. if ($allowNoFile) {
  1020. return in_array((int)$code, [UPLOAD_ERR_OK, UPLOAD_ERR_NO_FILE], true);
  1021. }
  1022. return (int)$code === UPLOAD_ERR_OK;
  1023. }
  1024. /**
  1025. * Validate an uploaded file.
  1026. *
  1027. * Helps join `uploadError`, `fileSize` and `mimeType` into
  1028. * one higher level validation method.
  1029. *
  1030. * ### Options
  1031. *
  1032. * - `types` - An array of valid mime types. If empty all types
  1033. * will be accepted. The `type` will not be looked at, instead
  1034. * the file type will be checked with ext/finfo.
  1035. * - `minSize` - The minimum file size in bytes. Defaults to not checking.
  1036. * - `maxSize` - The maximum file size in bytes. Defaults to not checking.
  1037. * - `optional` - Whether or not this file is optional. Defaults to false.
  1038. * If true a missing file will pass the validator regardless of other constraints.
  1039. *
  1040. * @param array $file The uploaded file data from PHP.
  1041. * @param array $options An array of options for the validation.
  1042. * @return bool
  1043. */
  1044. public static function uploadedFile($file, array $options = [])
  1045. {
  1046. $options += [
  1047. 'minSize' => null,
  1048. 'maxSize' => null,
  1049. 'types' => null,
  1050. 'optional' => false,
  1051. ];
  1052. if (!is_array($file) && !($file instanceof UploadedFileInterface)) {
  1053. return false;
  1054. }
  1055. $error = $isUploaded = false;
  1056. if ($file instanceof UploadedFileInterface) {
  1057. $error = $file->getError();
  1058. $isUploaded = true;
  1059. }
  1060. if (is_array($file)) {
  1061. $keys = ['error', 'name', 'size', 'tmp_name', 'type'];
  1062. ksort($file);
  1063. if (array_keys($file) != $keys) {
  1064. return false;
  1065. }
  1066. $error = (int)$file['error'];
  1067. $isUploaded = is_uploaded_file($file['tmp_name']);
  1068. }
  1069. if (!static::uploadError($file, $options['optional'])) {
  1070. return false;
  1071. }
  1072. if ($options['optional'] && $error === UPLOAD_ERR_NO_FILE) {
  1073. return true;
  1074. }
  1075. if (isset($options['minSize']) && !static::fileSize($file, '>=', $options['minSize'])) {
  1076. return false;
  1077. }
  1078. if (isset($options['maxSize']) && !static::fileSize($file, '<=', $options['maxSize'])) {
  1079. return false;
  1080. }
  1081. if (isset($options['types']) && !static::mimeType($file, $options['types'])) {
  1082. return false;
  1083. }
  1084. return $isUploaded;
  1085. }
  1086. /**
  1087. * Validates the size of an uploaded image.
  1088. *
  1089. * @param array $file The uploaded file data from PHP.
  1090. * @param array $options Options to validate width and height.
  1091. * @return bool
  1092. */
  1093. public static function imageSize($file, $options)
  1094. {
  1095. if (!isset($options['height']) && !isset($options['width'])) {
  1096. throw new InvalidArgumentException('Invalid image size validation parameters! Missing `width` and / or `height`.');
  1097. }
  1098. if ($file instanceof UploadedFileInterface) {
  1099. $file = $file->getStream()->getContents();
  1100. } elseif (is_array($file) && isset($file['tmp_name'])) {
  1101. $file = $file['tmp_name'];
  1102. }
  1103. list($width, $height) = getimagesize($file);
  1104. if (isset($options['height'])) {
  1105. $validHeight = self::comparison($height, $options['height'][0], $options['height'][1]);
  1106. }
  1107. if (isset($options['width'])) {
  1108. $validWidth = self::comparison($width, $options['width'][0], $options['width'][1]);
  1109. }
  1110. if (isset($validHeight) && isset($validWidth)) {
  1111. return ($validHeight && $validWidth);
  1112. }
  1113. if (isset($validHeight)) {
  1114. return $validHeight;
  1115. }
  1116. if (isset($validWidth)) {
  1117. return $validWidth;
  1118. }
  1119. throw new InvalidArgumentException('The 2nd argument is missing the `width` and / or `height` options.');
  1120. }
  1121. /**
  1122. * Validates the image width.
  1123. *
  1124. * @param array $file The uploaded file data from PHP.
  1125. * @param string $operator Comparision operator.
  1126. * @param int $width Min or max width.
  1127. * @return bool
  1128. */
  1129. public static function imageWidth($file, $operator, $width)
  1130. {
  1131. return self::imageSize($file, [
  1132. 'width' => [
  1133. $operator,
  1134. $width
  1135. ]
  1136. ]);
  1137. }
  1138. /**
  1139. * Validates the image width.
  1140. *
  1141. * @param array $file The uploaded file data from PHP.
  1142. * @param string $operator Comparision operator.
  1143. * @param int $height Min or max width.
  1144. * @return bool
  1145. */
  1146. public static function imageHeight($file, $operator, $height)
  1147. {
  1148. return self::imageSize($file, [
  1149. 'height' => [
  1150. $operator,
  1151. $height
  1152. ]
  1153. ]);
  1154. }
  1155. /**
  1156. * Validates a geographic coordinate.
  1157. *
  1158. * Supported formats:
  1159. *
  1160. * - `<latitude>, <longitude>` Example: `-25.274398, 133.775136`
  1161. *
  1162. * ### Options
  1163. *
  1164. * - `type` - A string of the coordinate format, right now only `latLong`.
  1165. * - `format` - By default `both`, can be `long` and `lat` as well to validate
  1166. * only a part of the coordinate.
  1167. *
  1168. * @param string $value Geographic location as string
  1169. * @param array $options Options for the validation logic.
  1170. * @return bool
  1171. */
  1172. public static function geoCoordinate($value, array $options = [])
  1173. {
  1174. $options += [
  1175. 'format' => 'both',
  1176. 'type' => 'latLong'
  1177. ];
  1178. if ($options['type'] !== 'latLong') {
  1179. throw new RuntimeException(sprintf(
  1180. 'Unsupported coordinate type "%s". Use "latLong" instead.',
  1181. $options['type']
  1182. ));
  1183. }
  1184. $pattern = '/^' . self::$_pattern['latitude'] . ',\s*' . self::$_pattern['longitude'] . '$/';
  1185. if ($options['format'] === 'long') {
  1186. $pattern = '/^' . self::$_pattern['longitude'] . '$/';
  1187. }
  1188. if ($options['format'] === 'lat') {
  1189. $pattern = '/^' . self::$_pattern['latitude'] . '$/';
  1190. }
  1191. return (bool)preg_match($pattern, $value);
  1192. }
  1193. /**
  1194. * Convenience method for latitude validation.
  1195. *
  1196. * @param string $value Latitude as string
  1197. * @param array $options Options for the validation logic.
  1198. * @return bool
  1199. * @link https://en.wikipedia.org/wiki/Latitude
  1200. * @see \Cake\Validation\Validation::geoCoordinate()
  1201. */
  1202. public static function latitude($value, array $options = [])
  1203. {
  1204. $options['format'] = 'lat';
  1205. return self::geoCoordinate($value, $options);
  1206. }
  1207. /**
  1208. * Convenience method for longitude validation.
  1209. *
  1210. * @param string $value Latitude as string
  1211. * @param array $options Options for the validation logic.
  1212. * @return bool
  1213. * @link https://en.wikipedia.org/wiki/Longitude
  1214. * @see \Cake\Validation\Validation::geoCoordinate()
  1215. */
  1216. public static function longitude($value, array $options = [])
  1217. {
  1218. $options['format'] = 'long';
  1219. return self::geoCoordinate($value, $options);
  1220. }
  1221. /**
  1222. * Check that the input value is within the ascii byte range.
  1223. *
  1224. * This method will reject all non-string values.
  1225. *
  1226. * @param string $value The value to check
  1227. * @return bool
  1228. */
  1229. public static function ascii($value)
  1230. {
  1231. if (!is_string($value)) {
  1232. return false;
  1233. }
  1234. return strlen($value) <= mb_strlen($value, 'utf-8');
  1235. }
  1236. /**
  1237. * Check that the input value is a utf8 string.
  1238. *
  1239. * This method will reject all non-string values.
  1240. *
  1241. * # Options
  1242. *
  1243. * - `extended` - Disallow bytes higher within the basic multilingual plane.
  1244. * MySQL's older utf8 encoding type does not allow characters above
  1245. * the basic multilingual plane. Defaults to false.
  1246. *
  1247. * @param string $value The value to check
  1248. * @param array $options An array of options. See above for the supported options.
  1249. * @return bool
  1250. */
  1251. public static function utf8($value, array $options = [])
  1252. {
  1253. if (!is_string($value)) {
  1254. return false;
  1255. }
  1256. $options += ['extended' => false];
  1257. if ($options['extended']) {
  1258. return true;
  1259. }
  1260. return preg_match('/[\x{10000}-\x{10FFFF}]/u', $value) === 0;
  1261. }
  1262. /**
  1263. * Check that the input value is an integer
  1264. *
  1265. * This method will accept strings that contain only integer data
  1266. * as well.
  1267. *
  1268. * @param string $value The value to check
  1269. * @return bool
  1270. */
  1271. public static function isInteger($value)
  1272. {
  1273. if (!is_scalar($value) || is_float($value)) {
  1274. return false;
  1275. }
  1276. if (is_int($value)) {
  1277. return true;
  1278. }
  1279. return (bool)preg_match('/^-?[0-9]+$/', $value);
  1280. }
  1281. /**
  1282. * Check that the input value is an array.
  1283. *
  1284. * @param array $value The value to check
  1285. * @return bool
  1286. */
  1287. public static function isArray($value)
  1288. {
  1289. return is_array($value);
  1290. }
  1291. /**
  1292. * Converts an array representing a date or datetime into a ISO string.
  1293. * The arrays are typically sent for validation from a form generated by
  1294. * the CakePHP FormHelper.
  1295. *
  1296. * @param array $value The array representing a date or datetime.
  1297. * @return string
  1298. */
  1299. protected static function _getDateString($value)
  1300. {
  1301. $formatted = '';
  1302. if (isset($value['year'], $value['month'], $value['day']) &&
  1303. (is_numeric($value['year']) && is_numeric($value['month']) && is_numeric($value['day']))
  1304. ) {
  1305. $formatted .= sprintf('%d-%02d-%02d ', $value['year'], $value['month'], $value['day']);
  1306. }
  1307. if (isset($value['hour'])) {
  1308. if (isset($value['meridian']) && (int)$value['hour'] === 12) {
  1309. $value['hour'] = 0;
  1310. }
  1311. if (isset($value['meridian'])) {
  1312. $value['hour'] = strtolower($value['meridian']) === 'am' ? $value['hour'] : $value['hour'] + 12;
  1313. }
  1314. $value += ['minute' => 0, 'second' => 0];
  1315. if (is_numeric($value['hour']) && is_numeric($value['minute']) && is_numeric($value['second'])) {
  1316. $formatted .= sprintf('%02d:%02d:%02d', $value['hour'], $value['minute'], $value['second']);
  1317. }
  1318. }
  1319. return trim($formatted);
  1320. }
  1321. /**
  1322. * Lazily populate the IP address patterns used for validations
  1323. *
  1324. * @return void
  1325. */
  1326. protected static function _populateIp()
  1327. {
  1328. if (!isset(static::$_pattern['IPv6'])) {
  1329. $pattern = '((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}';
  1330. $pattern .= '(:|((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})';
  1331. $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})';
  1332. $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}:)';
  1333. $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}))';
  1334. $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}';
  1335. $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|';
  1336. $pattern .= '((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}';
  1337. $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2}))';
  1338. $pattern .= '{3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4})';
  1339. $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})?)';
  1340. $pattern .= '|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]';
  1341. $pattern .= '\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4})';
  1342. $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})))(%.+)?';
  1343. static::$_pattern['IPv6'] = $pattern;
  1344. }
  1345. if (!isset(static::$_pattern['IPv4'])) {
  1346. $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])';
  1347. static::$_pattern['IPv4'] = $pattern;
  1348. }
  1349. }
  1350. /**
  1351. * Reset internal variables for another validation run.
  1352. *
  1353. * @return void
  1354. */
  1355. protected static function _reset()
  1356. {
  1357. static::$errors = [];
  1358. }
  1359. }