123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985 |
- <?php
- define('VALIDATE_NUM', '0-9');
- define('VALIDATE_SPACE', '\s');
- define('VALIDATE_ALPHA_LOWER', 'a-z');
- define('VALIDATE_ALPHA_UPPER', 'A-Z');
- define('VALIDATE_ALPHA', VALIDATE_ALPHA_LOWER . VALIDATE_ALPHA_UPPER);
- define('VALIDATE_EALPHA_LOWER', VALIDATE_ALPHA_LOWER . 'áéíóúýàèìòùäëïöüÿâêîôûãñõ¨åæç½ðøþß');
- define('VALIDATE_EALPHA_UPPER', VALIDATE_ALPHA_UPPER . 'ÁÉÍÓÚÝÀÈÌÒÙÄËÏÖܾÂÊÎÔÛÃÑÕ¦ÅÆǼÐØÞ');
- define('VALIDATE_EALPHA', VALIDATE_EALPHA_LOWER . VALIDATE_EALPHA_UPPER);
- define('VALIDATE_PUNCTUATION', VALIDATE_SPACE . '\.,;\:&"\'\?\!\(\)');
- define('VALIDATE_NAME', VALIDATE_EALPHA . VALIDATE_SPACE . "'" . '\-');
- define('VALIDATE_STREET', VALIDATE_NUM . VALIDATE_NAME . "/\\ºª\.");
- define('VALIDATE_ITLD_EMAILS', 1);
- define('VALIDATE_GTLD_EMAILS', 2);
- define('VALIDATE_CCTLD_EMAILS', 4);
- define('VALIDATE_ALL_EMAILS', 8);
- class Validate
- {
-
-
- public $_itld = [
- 'arpa',
- 'root',
- ];
-
- public $_gtld = [
- 'aero',
- 'biz',
- 'cat',
- 'com',
- 'coop',
- 'edu',
- 'gov',
- 'info',
- 'int',
- 'jobs',
- 'mil',
- 'mobi',
- 'museum',
- 'name',
- 'net',
- 'org',
- 'pro',
- 'travel',
- 'asia',
- 'post',
- 'tel',
- 'geo',
- ];
-
- public $_cctld = [
- 'ac',
- 'ad', 'ae', 'af', 'ag',
- 'ai', 'al', 'am', 'an',
- 'ao', 'aq', 'ar', 'as',
- 'at', 'au', 'aw', 'ax',
- 'az', 'ba', 'bb', 'bd',
- 'be', 'bf', 'bg', 'bh',
- 'bi', 'bj', 'bm', 'bn',
- 'bo', 'br', 'bs', 'bt',
- 'bu', 'bv', 'bw', 'by',
- 'bz', 'ca', 'cc', 'cd',
- 'cf', 'cg', 'ch', 'ci',
- 'ck', 'cl', 'cm', 'cn',
- 'co', 'cr', 'cs', 'cu',
- 'cv', 'cx', 'cy', 'cz',
- 'de', 'dj', 'dk', 'dm',
- 'do', 'dz', 'ec', 'ee',
- 'eg', 'eh', 'er', 'es',
- 'et', 'eu', 'fi', 'fj',
- 'fk', 'fm', 'fo', 'fr',
- 'ga', 'gb', 'gd', 'ge',
- 'gf', 'gg', 'gh', 'gi',
- 'gl', 'gm', 'gn', 'gp',
- 'gq', 'gr', 'gs', 'gt',
- 'gu', 'gw', 'gy', 'hk',
- 'hm', 'hn', 'hr', 'ht',
- 'hu', 'id', 'ie', 'il',
- 'im', 'in', 'io', 'iq',
- 'ir', 'is', 'it', 'je',
- 'jm', 'jo', 'jp', 'ke',
- 'kg', 'kh', 'ki', 'km',
- 'kn', 'kp', 'kr', 'kw',
- 'ky', 'kz', 'la', 'lb',
- 'lc', 'li', 'lk', 'lr',
- 'ls', 'lt', 'lu', 'lv',
- 'ly', 'ma', 'mc', 'md',
- 'me', 'mg', 'mh', 'mk',
- 'ml', 'mm', 'mn', 'mo',
- 'mp', 'mq', 'mr', 'ms',
- 'mt', 'mu', 'mv', 'mw',
- 'mx', 'my', 'mz', 'na',
- 'nc', 'ne', 'nf', 'ng',
- 'ni', 'nl', 'no', 'np',
- 'nr', 'nu', 'nz', 'om',
- 'pa', 'pe', 'pf', 'pg',
- 'ph', 'pk', 'pl', 'pm',
- 'pn', 'pr', 'ps', 'pt',
- 'pw', 'py', 'qa', 're',
- 'ro', 'rs', 'ru', 'rw',
- 'sa', 'sb', 'sc', 'sd',
- 'se', 'sg', 'sh', 'si',
- 'sj', 'sk', 'sl', 'sm',
- 'sn', 'so', 'sr', 'st',
- 'su', 'sv', 'sy', 'sz',
- 'tc', 'td', 'tf', 'tg',
- 'th', 'tj', 'tk', 'tl',
- 'tm', 'tn', 'to', 'tp',
- 'tr', 'tt', 'tv', 'tw',
- 'tz', 'ua', 'ug', 'uk',
- 'us', 'uy', 'uz', 'va',
- 'vc', 've', 'vg', 'vi',
- 'vn', 'vu', 'wf', 'ws',
- 'ye', 'yt', 'yu', 'za',
- 'zm', 'zw',
- ];
-
-
- private function __uriRFC4151(string $uri): bool
- {
- $datevalid = false;
- if (preg_match(
- '/^tag:(?<name>.*),(?<date>\d{4}-?\d{0,2}-?\d{0,2}):(?<specific>.*)(.*:)*$/',
- $uri,
- $matches
- )) {
- $date = $matches['date'];
- $date6 = strtotime($date);
- if ((strlen($date) == 4) && $date <= date('Y')) {
- $datevalid = true;
- } elseif ((strlen($date) == 7) && ($date6 < strtotime("now"))) {
- $datevalid = true;
- } elseif ((strlen($date) == 10) && ($date6 < strtotime("now"))) {
- $datevalid = true;
- }
- if (self::email($matches['name'])) {
- $namevalid = true;
- } else {
- $namevalid = self::email('info@' . $matches['name']);
- }
- return $datevalid && $namevalid;
- } else {
- return false;
- }
- }
-
- public function number($number, array $options = []): bool
- {
- $decimal = $dec_prec = $min = $max = null;
- if (is_array($options)) {
- extract($options);
- }
- $dec_prec = $dec_prec ? "{1,$dec_prec}" : '+';
- $dec_regex = $decimal ? "[$decimal][0-9]$dec_prec" : '';
- if (!preg_match("|^[-+]?\s*[0-9]+($dec_regex)?\$|", $number)) {
- return false;
- }
- if ($decimal != '.') {
- $number = strtr($number, $decimal, '.');
- }
- $number = (float)str_replace(' ', '', $number);
- if ($min !== null && $min > $number) {
- return false;
- }
- if ($max !== null && $max < $number) {
- return false;
- }
- return true;
- }
-
- public function __stringToUtf7(string $string): string
- {
- $return = '';
- $utf7 = [
- 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
- 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
- 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
- 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
- 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',
- '3', '4', '5', '6', '7', '8', '9', '+', ','
- ];
- $state = 0;
- if (!empty($string)) {
- $i = 0;
- while ($i <= strlen($string)) {
- $char = substr($string, $i, 1);
- if ($state == 0) {
- if ((ord($char) >= 0x7F) || (ord($char) <= 0x1F)) {
- if ($char) {
- $return .= '&';
- }
- $state = 1;
- } elseif ($char == '&') {
- $return .= '&-';
- } else {
- $return .= $char;
- }
- } elseif (($i == strlen($string) ||
- !((ord($char) >= 0x7F)) || (ord($char) <= 0x1F))) {
- if ($state != 1) {
- if (ord($char) > 64) {
- $return .= '';
- } else {
- $return .= $utf7[ord($char)];
- }
- }
- $return .= '-';
- $state = 0;
- } else {
- switch ($state) {
- case 1:
- $return .= $utf7[ord($char) >> 2];
- $residue = (ord($char) & 0x03) << 4;
- $state = 2;
- break;
- case 2:
- $return .= $utf7[$residue | (ord($char) >> 4)];
- $residue = (ord($char) & 0x0F) << 2;
- $state = 3;
- break;
- case 3:
- $return .= $utf7[$residue | (ord($char) >> 6)];
- $return .= $utf7[ord($char) & 0x3F];
- $state = 1;
- break;
- }
- }
- $i++;
- }
- return $return;
- }
- return '';
- }
-
- private function __emailRFC822(string &$email, array &$options): bool
- {
- static $address = null;
- static $uncomment = null;
- if (!$address) {
-
- $atom = '[^][()<>@,;:\\".\s\000-\037\177-\377]+\s*';
-
-
- $qtext = '[^"\\\\\r]';
-
- $quoted_pair = '\\\\.';
-
-
- $quoted_string = '"(?:' . $qtext . '|' . $quoted_pair . ')*"\s*';
-
- $word = '(?:' . $atom . '|' . $quoted_string . ')';
-
-
- $local_part = $word . '(?:\.\s*' . $word . ')*';
-
-
- $dtext = '[^][\\\\\r]';
-
- $domain_literal = '\[(?:' . $dtext . '|' . $quoted_pair . ')*\]\s*';
-
-
- $sub_domain = '(?:' . $atom . '|' . $domain_literal . ')';
-
- $domain = $sub_domain . '(?:\.\s*' . $sub_domain . ')*';
-
- $addr_spec = $local_part . '@\s*' . $domain;
-
- $route = '@' . $domain . '(?:,@\s*' . $domain . ')*:\s*';
-
- $route_addr = '<\s*(?:' . $route . ')?' . $addr_spec . '>\s*';
-
- $phrase = $word . '+';
-
-
- $mailbox = '(?:' . $addr_spec . '|' . $phrase . $route_addr . ')';
-
- $group = $phrase . ':\s*(?:' . $mailbox . '(?:,\s*' . $mailbox . ')*)?;\s*';
-
-
- $address = '/^\s*(?:' . $mailbox . '|' . $group . ')$/';
- $uncomment =
- '/((?:(?:\\\\"|[^("])*(?:' . $quoted_string .
- ')?)*)((?<!\\\\)\((?:(?2)|.)*?(?<!\\\\)\))/';
- }
-
- $email = preg_replace($uncomment, '$1 ', $email);
- return preg_match($address, $email);
- }
-
- public function _fullTLDValidation(string $email, array $options): bool
- {
- $validate = [];
- if (!empty($options["VALIDATE_ITLD_EMAILS"])) {
- array_push($validate, 'itld');
- }
- if (!empty($options["VALIDATE_GTLD_EMAILS"])) {
- array_push($validate, 'gtld');
- }
- if (!empty($options["VALIDATE_CCTLD_EMAILS"])) {
- array_push($validate, 'cctld');
- }
- if (count($validate) === 0) {
- array_push($validate, 'itld', 'gtld', 'cctld');
- }
- $self = new Validate;
- $toValidate = [];
- foreach ($validate as $valid) {
- $tmpVar = '_' . (string)$valid;
- $toValidate[$valid] = $self->{$tmpVar};
- }
- $e = $self->executeFullEmailValidation($email, $toValidate);
- return $e;
- }
-
- public function executeFullEmailValidation(string $email, array $arrayOfTLDs): bool
- {
- $emailEnding = explode('.', $email);
- $emailEnding = $emailEnding[count($emailEnding) - 1];
- foreach ($arrayOfTLDs as $validator => $keys) {
- if (in_array($emailEnding, $keys)) {
- return true;
- }
- }
- return false;
- }
-
- public function email(string $email, $options = null): bool
- {
- $check_domain = false;
- $use_rfc822 = false;
- if (is_bool($options)) {
- $check_domain = $options;
- } elseif (is_array($options)) {
- extract($options);
- }
-
- $hasIDNA = false;
- if (Validate::_includePathFileExists('Net/IDNA2.php')) {
- include_once('Net/IDNA2.php');
- $hasIDNA = true;
- }
- if ($hasIDNA === true) {
- if (strpos($email, '@') !== false) {
- $tmpEmail = explode('@', $email);
- $domain = array_pop($tmpEmail);
-
-
- $chars = count_chars($domain, 1);
- if (!empty($chars) && max(array_keys($chars)) > 127) {
- $idna =& Net_IDNA2::singleton();
- $domain = $idna->encode($domain);
- }
- array_push($tmpEmail, $domain);
- $email = implode('@', $tmpEmail);
- }
- }
-
- if (isset($fullTLDValidation)) {
-
- $valid = Validate::_fullTLDValidation($email, $options);
- if (!$valid) {
- return false;
- }
- }
-
- $regex = '&^(?: # recipient:
- ("\s*(?:[^"\f\n\r\t\v\b\s]+\s*)+")| #1 quoted name
- ([-\w!\#\$%\&\'*+~/^`|{}]+(?:\.[-\w!\#\$%\&\'*+~/^`|{}]+)*)) #2 OR dot-atom
- @(((\[)? #3 domain, 4 as IPv4, 5 optionally bracketed
- (?:(?:(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9]))\.){3}
- (?:(?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9]))))(?(5)\])|
- ((?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)*[a-z0-9](?:[-a-z0-9]*[a-z0-9])?) #6 domain as hostname
- \.((?:([^- ])[-a-z]*[-a-z]))) #7 TLD
- $&xi';
-
- if ($use_rfc822 ? Validate::__emailRFC822($email, $options) :
- preg_match($regex, $email)) {
- if ($check_domain && function_exists('checkdnsrr')) {
- $domain = preg_replace('/[^-a-z.0-9]/i', '', array_pop(explode('@', $email)));
- if (checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A')) {
- return true;
- }
- return false;
- }
- return true;
- }
- return false;
- }
-
- public function string(string $string, $options): bool
- {
- $format = null;
- $min_length = 0;
- $max_length = 0;
- if (is_array($options)) {
- extract($options);
- }
- if ($format && !preg_match("|^[$format]*\$|s", $string)) {
- return false;
- }
- if ($min_length && strlen($string) < $min_length) {
- return false;
- }
- if ($max_length && strlen($string) > $max_length) {
- return false;
- }
- return true;
- }
-
- public function uri(string $url, ?array $options = null): bool
- {
- $strict = ';/?:@$,';
- $domain_check = false;
- $allowed_schemes = null;
- if (is_array($options)) {
- extract($options);
- }
- if (is_array($allowed_schemes) &&
- in_array("tag", $allowed_schemes)
- ) {
- if (strpos($url, "tag:") === 0) {
- return self::__uriRFC4151($url);
- }
- }
- if (preg_match(
- '&^(?:([a-z][-+.a-z0-9]*):)? # 1. scheme
- (?:// # authority start
- (?:((?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'();:\&=+$,])*)@)? # 2. authority-userinfo
- (?:((?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)*[a-z](?:[a-z0-9]+)?\.?) # 3. authority-hostname OR
- |([0-9]{1,3}(?:\.[0-9]{1,3}){3})) # 4. authority-ipv4
- (?::([0-9]*))?) # 5. authority-port
- ((?:/(?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'():@\&=+$,;])*)*/?)? # 6. path
- (?:\?([^#]*))? # 7. query
- (?:\#((?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'();/?:@\&=+$,])*))? # 8. fragment
- $&xi',
- $url,
- $matches
- )) {
- $scheme = isset($matches[1]) ? $matches[1] : '';
- $authority = isset($matches[3]) ? $matches[3] : '';
- if (is_array($allowed_schemes) &&
- !in_array($scheme, $allowed_schemes)
- ) {
- return false;
- }
- if (!empty($matches[4])) {
- $parts = explode('.', $matches[4]);
- foreach ($parts as $part) {
- if ($part > 255) {
- return false;
- }
- }
- } elseif ($domain_check && function_exists('checkdnsrr')) {
- if (!checkdnsrr($authority, 'A')) {
- return false;
- }
- }
- if ($strict) {
- $strict = '#[' . preg_quote($strict, '#') . ']#';
- if ((!empty($matches[7]) && preg_match($strict, $matches[7]))
- || (!empty($matches[8]) && preg_match($strict, $matches[8]))) {
- return false;
- }
- }
- return true;
- }
- return false;
- }
-
- private function _substr(string &$date, string $num, $opt = false): string
- {
- if ($opt && strlen($date) >= $opt && preg_match('/^[0-9]{' . $opt . '}/', $date, $m)) {
- $ret = $m[0];
- } else {
- $ret = substr($date, 0, $num);
- }
- $date = substr($date, strlen($ret));
- return $ret;
- }
- public function _modf($val, $div)
- {
- if (function_exists('bcmod')) {
- return bcmod($val, $div);
- } elseif (function_exists('fmod')) {
- return fmod($val, $div);
- }
- $r = $val / $div;
- $i = intval($r);
- return intval($val - $i * $div + .1);
- }
-
- public function _multWeights(string $number, array &$weights): int
- {
- if (!is_array($weights)) {
- return -1;
- }
- $sum = 0;
- $count = min(count($weights), strlen($number));
- if ($count == 0) {
- return -1;
- }
- for ($i = 0; $i < $count; ++$i) {
- $sum += intval(substr($number, $i, 1)) * $weights[$i];
- }
- return $sum;
- }
-
- public function _getControlNumber(string $number, array &$weights, int $modulo = 10, int $subtract = 0, bool $allow_high = false): int
- {
-
- $sum = Validate::_multWeights($number, $weights);
- if ($sum == -1) {
- return -1;
- }
- $mod = Validate::_modf($sum, $modulo);
- if ($subtract > $mod && $mod > 0) {
- $mod = $subtract - $mod;
- }
- if ($allow_high === false) {
- $mod %= 10;
- }
- return $mod;
- }
-
- public function _checkControlNumber(string $number, array &$weights, int $modulo = 10, int $subtract = 0): bool
- {
- if (strlen($number) < count($weights)) {
- return false;
- }
- $target_digit = substr($number, count($weights), 1);
- $control_digit = Validate::_getControlNumber($number, $weights, $modulo, $subtract, $modulo > 10);
- if ($control_digit == -1) {
- return false;
- }
- if ($target_digit === 'X' && $control_digit == 10) {
- return true;
- }
- if ($control_digit != $target_digit) {
- return false;
- }
- return true;
- }
-
- public function multiple(array &$data, array &$val_type, bool $remove = false): array
- {
- $keys = array_keys($data);
- $valid = [];
- foreach ($keys as $var_name) {
- if (!isset($val_type[$var_name])) {
- if ($remove) {
- unset($data[$var_name]);
- }
- continue;
- }
- $opt = $val_type[$var_name];
- $methods = get_class_methods('Validate');
- $val2check = $data[$var_name];
-
- if (in_array(strtolower($opt['type']), $methods)) {
-
- $method = $opt['type'];
- unset($opt['type']);
- if (sizeof($opt) == 1 && is_array(reset($opt))) {
- $opt = array_pop($opt);
- }
- $valid[$var_name] = call_user_func(['Validate', $method], $val2check, $opt);
-
- } elseif (strpos($opt['type'], '_') !== false) {
- $validateType = explode('_', $opt['type']);
- $method = array_pop($validateType);
- $class = implode('_', $validateType);
- $classPath = str_replace('_', DIRECTORY_SEPARATOR, $class);
- $class = 'Validate_' . $class;
- if (Validate::_includePathFileExists("Validate/$classPath.php")) {
- include_once "Validate/$classPath.php";
- } else {
- trigger_error("$class isn't installed or you may have some permission issues", E_USER_ERROR);
- }
- $ce = substr(phpversion(), 0, 1) > 4 ?
- class_exists($class, false) : class_exists($class);
- if (!$ce ||
- !in_array($method, get_class_methods($class))
- ) {
- trigger_error(
- "Invalid validation type $class::$method",
- E_USER_WARNING
- );
- continue;
- }
- unset($opt['type']);
- if (sizeof($opt) == 1) {
- $opt = array_pop($opt);
- }
- $valid[$var_name] = call_user_func(
- array($class, $method),
- $data[$var_name],
- $opt
- );
- } else {
- trigger_error(
- "Invalid validation type {$opt['type']}",
- E_USER_WARNING
- );
- }
- }
- return $valid;
- }
-
- private function _includePathFileExists(string $filename): bool
- {
- $paths = explode(":", ini_get("include_path"));
- $result = false;
- foreach ($paths as $val) {
- $result = file_exists($val . "/" . $filename);
- if ($result) {
- break;
- }
- }
- return $result;
- }
- }
|