PageRenderTime 567ms CodeModel.GetById 19ms RepoModel.GetById 12ms app.codeStats 0ms

/system/classes/kohana/valid.php

https://bitbucket.org/drewsonne/ok-what-next
PHP | 536 lines | 263 code | 60 blank | 213 comment | 28 complexity | 161ca947b7353caf975a06712f2ab9ab MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php defined('SYSPATH') or die('No direct script access.');
  2. /**
  3. * Validation rules.
  4. *
  5. * @package Kohana
  6. * @category Security
  7. * @author Kohana Team
  8. * @copyright (c) 2008-2011 Kohana Team
  9. * @license http://kohanaframework.org/license
  10. */
  11. class Kohana_Valid {
  12. /**
  13. * Checks if a field is not empty.
  14. *
  15. * @return boolean
  16. */
  17. public static function not_empty($value)
  18. {
  19. if (is_object($value) AND $value instanceof ArrayObject)
  20. {
  21. // Get the array from the ArrayObject
  22. $value = $value->getArrayCopy();
  23. }
  24. // Value cannot be NULL, FALSE, '', or an empty array
  25. return ! in_array($value, array(NULL, FALSE, '', array()), TRUE);
  26. }
  27. /**
  28. * Checks a field against a regular expression.
  29. *
  30. * @param string value
  31. * @param string regular expression to match (including delimiters)
  32. * @return boolean
  33. */
  34. public static function regex($value, $expression)
  35. {
  36. return (bool) preg_match($expression, (string) $value);
  37. }
  38. /**
  39. * Checks that a field is long enough.
  40. *
  41. * @param string value
  42. * @param integer minimum length required
  43. * @return boolean
  44. */
  45. public static function min_length($value, $length)
  46. {
  47. return UTF8::strlen($value) >= $length;
  48. }
  49. /**
  50. * Checks that a field is short enough.
  51. *
  52. * @param string value
  53. * @param integer maximum length required
  54. * @return boolean
  55. */
  56. public static function max_length($value, $length)
  57. {
  58. return UTF8::strlen($value) <= $length;
  59. }
  60. /**
  61. * Checks that a field is exactly the right length.
  62. *
  63. * @param string value
  64. * @param integer|array exact length required, or array of valid lengths
  65. * @return boolean
  66. */
  67. public static function exact_length($value, $length)
  68. {
  69. if (is_array($length))
  70. {
  71. foreach($length as $strlen)
  72. {
  73. if (UTF8::strlen($value) === $strlen)
  74. return TRUE;
  75. }
  76. return FALSE;
  77. }
  78. return UTF8::strlen($value) === $length;
  79. }
  80. /**
  81. * Checks that a field is exactly the value required.
  82. *
  83. * @param string value
  84. * @param string required value
  85. * @return boolean
  86. */
  87. public static function equals($value, $required)
  88. {
  89. return ($value === $required);
  90. }
  91. /**
  92. * Check an email address for correct format.
  93. *
  94. * @link http://www.iamcal.com/publish/articles/php/parsing_email/
  95. * @link http://www.w3.org/Protocols/rfc822/
  96. *
  97. * @param string email address
  98. * @param boolean strict RFC compatibility
  99. * @return boolean
  100. */
  101. public static function email($email, $strict = FALSE)
  102. {
  103. if (UTF8::strlen($email) > 254)
  104. {
  105. return FALSE;
  106. }
  107. if ($strict === TRUE)
  108. {
  109. $qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
  110. $dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
  111. $atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
  112. $pair = '\\x5c[\\x00-\\x7f]';
  113. $domain_literal = "\\x5b($dtext|$pair)*\\x5d";
  114. $quoted_string = "\\x22($qtext|$pair)*\\x22";
  115. $sub_domain = "($atom|$domain_literal)";
  116. $word = "($atom|$quoted_string)";
  117. $domain = "$sub_domain(\\x2e$sub_domain)*";
  118. $local_part = "$word(\\x2e$word)*";
  119. $expression = "/^$local_part\\x40$domain$/D";
  120. }
  121. else
  122. {
  123. $expression = '/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})$/iD';
  124. }
  125. return (bool) preg_match($expression, (string) $email);
  126. }
  127. /**
  128. * Validate the domain of an email address by checking if the domain has a
  129. * valid MX record.
  130. *
  131. * @link http://php.net/checkdnsrr not added to Windows until PHP 5.3.0
  132. *
  133. * @param string email address
  134. * @return boolean
  135. */
  136. public static function email_domain($email)
  137. {
  138. if ( ! Valid::not_empty($email))
  139. return FALSE; // Empty fields cause issues with checkdnsrr()
  140. // Check if the email domain has a valid MX record
  141. return (bool) checkdnsrr(preg_replace('/^[^@]++@/', '', $email), 'MX');
  142. }
  143. /**
  144. * Validate a URL.
  145. *
  146. * @param string URL
  147. * @return boolean
  148. */
  149. public static function url($url)
  150. {
  151. // Based on http://www.apps.ietf.org/rfc/rfc1738.html#sec-5
  152. if ( ! preg_match(
  153. '~^
  154. # scheme
  155. [-a-z0-9+.]++://
  156. # username:password (optional)
  157. (?:
  158. [-a-z0-9$_.+!*\'(),;?&=%]++ # username
  159. (?::[-a-z0-9$_.+!*\'(),;?&=%]++)? # password (optional)
  160. @
  161. )?
  162. (?:
  163. # ip address
  164. \d{1,3}+(?:\.\d{1,3}+){3}+
  165. | # or
  166. # hostname (captured)
  167. (
  168. (?!-)[-a-z0-9]{1,63}+(?<!-)
  169. (?:\.(?!-)[-a-z0-9]{1,63}+(?<!-)){0,126}+
  170. )
  171. )
  172. # port (optional)
  173. (?::\d{1,5}+)?
  174. # path (optional)
  175. (?:/.*)?
  176. $~iDx', $url, $matches))
  177. return FALSE;
  178. // We matched an IP address
  179. if ( ! isset($matches[1]))
  180. return TRUE;
  181. // Check maximum length of the whole hostname
  182. // http://en.wikipedia.org/wiki/Domain_name#cite_note-0
  183. if (strlen($matches[1]) > 253)
  184. return FALSE;
  185. // An extra check for the top level domain
  186. // It must start with a letter
  187. $tld = ltrim(substr($matches[1], (int) strrpos($matches[1], '.')), '.');
  188. return ctype_alpha($tld[0]);
  189. }
  190. /**
  191. * Validate an IP.
  192. *
  193. * @param string IP address
  194. * @param boolean allow private IP networks
  195. * @return boolean
  196. */
  197. public static function ip($ip, $allow_private = TRUE)
  198. {
  199. // Do not allow reserved addresses
  200. $flags = FILTER_FLAG_NO_RES_RANGE;
  201. if ($allow_private === FALSE)
  202. {
  203. // Do not allow private or reserved addresses
  204. $flags = $flags | FILTER_FLAG_NO_PRIV_RANGE;
  205. }
  206. return (bool) filter_var($ip, FILTER_VALIDATE_IP, $flags);
  207. }
  208. /**
  209. * Validates a credit card number, with a Luhn check if possible.
  210. *
  211. * @param integer credit card number
  212. * @param string|array card type, or an array of card types
  213. * @return boolean
  214. * @uses Valid::luhn
  215. */
  216. public static function credit_card($number, $type = NULL)
  217. {
  218. // Remove all non-digit characters from the number
  219. if (($number = preg_replace('/\D+/', '', $number)) === '')
  220. return FALSE;
  221. if ($type == NULL)
  222. {
  223. // Use the default type
  224. $type = 'default';
  225. }
  226. elseif (is_array($type))
  227. {
  228. foreach ($type as $t)
  229. {
  230. // Test each type for validity
  231. if (Valid::credit_card($number, $t))
  232. return TRUE;
  233. }
  234. return FALSE;
  235. }
  236. $cards = Kohana::$config->load('credit_cards');
  237. // Check card type
  238. $type = strtolower($type);
  239. if ( ! isset($cards[$type]))
  240. return FALSE;
  241. // Check card number length
  242. $length = strlen($number);
  243. // Validate the card length by the card type
  244. if ( ! in_array($length, preg_split('/\D+/', $cards[$type]['length'])))
  245. return FALSE;
  246. // Check card number prefix
  247. if ( ! preg_match('/^'.$cards[$type]['prefix'].'/', $number))
  248. return FALSE;
  249. // No Luhn check required
  250. if ($cards[$type]['luhn'] == FALSE)
  251. return TRUE;
  252. return Valid::luhn($number);
  253. }
  254. /**
  255. * Validate a number against the [Luhn](http://en.wikipedia.org/wiki/Luhn_algorithm)
  256. * (mod10) formula.
  257. *
  258. * @param string number to check
  259. * @return boolean
  260. */
  261. public static function luhn($number)
  262. {
  263. // Force the value to be a string as this method uses string functions.
  264. // Converting to an integer may pass PHP_INT_MAX and result in an error!
  265. $number = (string) $number;
  266. if ( ! ctype_digit($number))
  267. {
  268. // Luhn can only be used on numbers!
  269. return FALSE;
  270. }
  271. // Check number length
  272. $length = strlen($number);
  273. // Checksum of the card number
  274. $checksum = 0;
  275. for ($i = $length - 1; $i >= 0; $i -= 2)
  276. {
  277. // Add up every 2nd digit, starting from the right
  278. $checksum += substr($number, $i, 1);
  279. }
  280. for ($i = $length - 2; $i >= 0; $i -= 2)
  281. {
  282. // Add up every 2nd digit doubled, starting from the right
  283. $double = substr($number, $i, 1) * 2;
  284. // Subtract 9 from the double where value is greater than 10
  285. $checksum += ($double >= 10) ? ($double - 9) : $double;
  286. }
  287. // If the checksum is a multiple of 10, the number is valid
  288. return ($checksum % 10 === 0);
  289. }
  290. /**
  291. * Checks if a phone number is valid.
  292. *
  293. * @param string phone number to check
  294. * @return boolean
  295. */
  296. public static function phone($number, $lengths = NULL)
  297. {
  298. if ( ! is_array($lengths))
  299. {
  300. $lengths = array(7,10,11);
  301. }
  302. // Remove all non-digit characters from the number
  303. $number = preg_replace('/\D+/', '', $number);
  304. // Check if the number is within range
  305. return in_array(strlen($number), $lengths);
  306. }
  307. /**
  308. * Tests if a string is a valid date string.
  309. *
  310. * @param string date to check
  311. * @return boolean
  312. */
  313. public static function date($str)
  314. {
  315. return (strtotime($str) !== FALSE);
  316. }
  317. /**
  318. * Checks whether a string consists of alphabetical characters only.
  319. *
  320. * @param string input string
  321. * @param boolean trigger UTF-8 compatibility
  322. * @return boolean
  323. */
  324. public static function alpha($str, $utf8 = FALSE)
  325. {
  326. $str = (string) $str;
  327. if ($utf8 === TRUE)
  328. {
  329. return (bool) preg_match('/^\pL++$/uD', $str);
  330. }
  331. else
  332. {
  333. return ctype_alpha($str);
  334. }
  335. }
  336. /**
  337. * Checks whether a string consists of alphabetical characters and numbers only.
  338. *
  339. * @param string input string
  340. * @param boolean trigger UTF-8 compatibility
  341. * @return boolean
  342. */
  343. public static function alpha_numeric($str, $utf8 = FALSE)
  344. {
  345. if ($utf8 === TRUE)
  346. {
  347. return (bool) preg_match('/^[\pL\pN]++$/uD', $str);
  348. }
  349. else
  350. {
  351. return ctype_alnum($str);
  352. }
  353. }
  354. /**
  355. * Checks whether a string consists of alphabetical characters, numbers, underscores and dashes only.
  356. *
  357. * @param string input string
  358. * @param boolean trigger UTF-8 compatibility
  359. * @return boolean
  360. */
  361. public static function alpha_dash($str, $utf8 = FALSE)
  362. {
  363. if ($utf8 === TRUE)
  364. {
  365. $regex = '/^[-\pL\pN_]++$/uD';
  366. }
  367. else
  368. {
  369. $regex = '/^[-a-z0-9_]++$/iD';
  370. }
  371. return (bool) preg_match($regex, $str);
  372. }
  373. /**
  374. * Checks whether a string consists of digits only (no dots or dashes).
  375. *
  376. * @param string input string
  377. * @param boolean trigger UTF-8 compatibility
  378. * @return boolean
  379. */
  380. public static function digit($str, $utf8 = FALSE)
  381. {
  382. if ($utf8 === TRUE)
  383. {
  384. return (bool) preg_match('/^\pN++$/uD', $str);
  385. }
  386. else
  387. {
  388. return (is_int($str) AND $str >= 0) OR ctype_digit($str);
  389. }
  390. }
  391. /**
  392. * Checks whether a string is a valid number (negative and decimal numbers allowed).
  393. *
  394. * Uses {@link http://www.php.net/manual/en/function.localeconv.php locale conversion}
  395. * to allow decimal point to be locale specific.
  396. *
  397. * @param string input string
  398. * @return boolean
  399. */
  400. public static function numeric($str)
  401. {
  402. // Get the decimal point for the current locale
  403. list($decimal) = array_values(localeconv());
  404. // A lookahead is used to make sure the string contains at least one digit (before or after the decimal point)
  405. return (bool) preg_match('/^-?+(?=.*[0-9])[0-9]*+'.preg_quote($decimal).'?+[0-9]*+$/D', (string) $str);
  406. }
  407. /**
  408. * Tests if a number is within a range.
  409. *
  410. * @param string number to check
  411. * @param integer minimum value
  412. * @param integer maximum value
  413. * @return boolean
  414. */
  415. public static function range($number, $min, $max)
  416. {
  417. return ($number >= $min AND $number <= $max);
  418. }
  419. /**
  420. * Checks if a string is a proper decimal format. Optionally, a specific
  421. * number of digits can be checked too.
  422. *
  423. * @param string number to check
  424. * @param integer number of decimal places
  425. * @param integer number of digits
  426. * @return boolean
  427. */
  428. public static function decimal($str, $places = 2, $digits = NULL)
  429. {
  430. if ($digits > 0)
  431. {
  432. // Specific number of digits
  433. $digits = '{'.( (int) $digits).'}';
  434. }
  435. else
  436. {
  437. // Any number of digits
  438. $digits = '+';
  439. }
  440. // Get the decimal point for the current locale
  441. list($decimal) = array_values(localeconv());
  442. return (bool) preg_match('/^[+-]?[0-9]'.$digits.preg_quote($decimal).'[0-9]{'.( (int) $places).'}$/D', $str);
  443. }
  444. /**
  445. * Checks if a string is a proper hexadecimal HTML color value. The validation
  446. * is quite flexible as it does not require an initial "#" and also allows for
  447. * the short notation using only three instead of six hexadecimal characters.
  448. *
  449. * @param string input string
  450. * @return boolean
  451. */
  452. public static function color($str)
  453. {
  454. return (bool) preg_match('/^#?+[0-9a-f]{3}(?:[0-9a-f]{3})?$/iD', $str);
  455. }
  456. /**
  457. * Checks if a field matches the value of another field.
  458. *
  459. * @param array array of values
  460. * @param string field name
  461. * @param string field name to match
  462. * @return boolean
  463. */
  464. public static function matches($array, $field, $match)
  465. {
  466. return ($array[$field] === $array[$match]);
  467. }
  468. } // End Valid