PKZ wwnnemail-validator/CONTRIBUTING.mdnuW+A# Contributing When contributing to this repository make sure to follow the Pull request process below. Reduce to the minimum 3rd party dependencies. Please note we have a [code of conduct](#Code of Conduct), please follow it in all your interactions with the project. ## Pull Request Process When doing a PR to v2 remember that you also have to do the PR port to v3, or tests confirming the bug is not reproducible. 1. Supported version is v3. If you are fixing a bug in v2, please port to v3 2. Use the title as a brief description of the changes 3. Describe the changes you are proposing 1. If adding an extra validation state the benefits of adding it and the problem is solving 2. Document in the readme, by adding it to the list 4. Provide appropriate tests for the code you are submitting: aim to keep the existing coverage percentage. 5. Add your Twitter handle (if you have) so we can thank you there. ## License By contributing, you agree that your contributions will be licensed under its MIT License. ## Code of Conduct ### Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ### Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ### Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ### Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ### Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at . All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. #### Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: #### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. #### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. #### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. #### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ### Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations PKZ.--email-validator/LICENSEnuW+ACopyright (c) 2013-2023 Eduardo Gulias Davis Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PKZ|_7- - 'email-validator/src/MessageIDParser.phpnuW+AaddLongEmailWarning($this->idLeft, $this->idRight); return $result; } protected function preLeftParsing(): Result { if (!$this->hasAtToken()) { return new InvalidEmail(new NoLocalPart(), $this->lexer->current->value); } return new ValidEmail(); } protected function parseLeftFromAt(): Result { return $this->processIDLeft(); } protected function parseRightFromAt(): Result { return $this->processIDRight(); } private function processIDLeft(): Result { $localPartParser = new IDLeftPart($this->lexer); $localPartResult = $localPartParser->parse(); $this->idLeft = $localPartParser->localPart(); $this->warnings = [...$localPartParser->getWarnings(), ...$this->warnings]; return $localPartResult; } private function processIDRight(): Result { $domainPartParser = new IDRightPart($this->lexer); $domainPartResult = $domainPartParser->parse(); $this->idRight = $domainPartParser->domainPart(); $this->warnings = [...$domainPartParser->getWarnings(), ...$this->warnings]; return $domainPartResult; } public function getLeftPart(): string { return $this->idLeft; } public function getRightPart(): string { return $this->idRight; } private function addLongEmailWarning(string $localPart, string $parsedDomainPart): void { if (strlen($localPart . '@' . $parsedDomainPart) > self::EMAILID_MAX_LENGTH) { $this->warnings[EmailTooLong::CODE] = new EmailTooLong(); } } } PKZS 4.email-validator/src/Warning/AddressLiteral.phpnuW+Amessage = 'Address literal in domain part'; $this->rfcNumber = 5321; } } PKZH*email-validator/src/Warning/CFWSNearAt.phpnuW+Amessage = "Deprecated folding white space near @"; } } PKZodd,email-validator/src/Warning/QuotedString.phpnuW+Amessage = "Quoted String found between $prevToken and $postToken"; } } PKZUi+email-validator/src/Warning/CFWSWithFWS.phpnuW+Amessage = 'Folding whites space followed by folding white space'; } } PKZY'-email-validator/src/Warning/IPV6MaxGroups.phpnuW+Amessage = 'Reached the maximum number of IPV6 groups allowed'; $this->rfcNumber = 5321; } } PKZf%L.email-validator/src/Warning/IPV6GroupCount.phpnuW+Amessage = 'Group count is not IPV6 valid'; $this->rfcNumber = 5322; } } PKZe  -email-validator/src/Warning/NoDNSMXRecord.phpnuW+Amessage = 'No MX DSN record was found for this email'; $this->rfcNumber = 5321; } } PKZ"+email-validator/src/Warning/IPV6BadChar.phpnuW+Amessage = 'Bad char in IPV6 domain literal'; $this->rfcNumber = 5322; } } PKZ/email-validator/src/Warning/IPV6DoubleColon.phpnuW+Amessage = 'Double colon found after IPV6 tag'; $this->rfcNumber = 5322; } } PKZ[q-email-validator/src/Warning/DomainLiteral.phpnuW+Amessage = 'Domain Literal'; $this->rfcNumber = 5322; } } PKZj.email-validator/src/Warning/IPV6ColonStart.phpnuW+Amessage = ':: found at the start of the domain literal'; $this->rfcNumber = 5322; } } PKZF  ,email-validator/src/Warning/IPV6ColonEnd.phpnuW+Amessage = ':: found at the end of the domain literal'; $this->rfcNumber = 5322; } } PKZp!td``*email-validator/src/Warning/QuotedPart.phpnuW+Aname; } if ($postToken instanceof UnitEnum) { $postToken = $postToken->name; } $this->message = "Deprecated Quoted String found between $prevToken and $postToken"; } } PKZ !-email-validator/src/Warning/ObsoleteDTEXT.phpnuW+ArfcNumber = 5322; $this->message = 'Obsolete DTEXT in domain literal'; } } PKZ.e#email-validator/src/Warning/TLD.phpnuW+Amessage = "RFC5321, TLD"; } } PKZ%%,email-validator/src/Warning/EmailTooLong.phpnuW+Amessage = 'Email is too long, exceeds ' . EmailParser::EMAIL_MAX_LENGTH; } } PKZIb.email-validator/src/Warning/IPV6Deprecated.phpnuW+Amessage = 'Deprecated form of IPV6'; $this->rfcNumber = 5321; } } PKZ 'email-validator/src/Warning/Warning.phpnuW+Amessage; } /** * @return int */ public function code() { return self::CODE; } /** * @return int */ public function RFCNumber() { return $this->rfcNumber; } /** * @return string */ public function __toString(): string { return $this->message() . " rfc: " . $this->rfcNumber . "internal code: " . static::CODE; } } PKZ:>'email-validator/src/Warning/Comment.phpnuW+Amessage = "Comments found in this email"; } } PKZK1email-validator/src/Warning/DeprecatedComment.phpnuW+Amessage = 'Deprecated comments'; } } PKZV}5<<,email-validator/src/Warning/LocalTooLong.phpnuW+Amessage = 'Local part is too long, exceeds 64 chars (octets)'; $this->rfcNumber = 5322; } } PKZ6S **-email-validator/src/Result/MultipleErrors.phpnuW+Areasons[$reason->code()] = $reason; } /** * @return Reason[] */ public function getReasons() : array { return $this->reasons; } public function reason() : Reason { return 0 !== count($this->reasons) ? current($this->reasons) : new EmptyReason(); } public function description() : string { $description = ''; foreach($this->reasons as $reason) { $description .= $reason->description() . PHP_EOL; } return $description; } public function code() : int { return 0; } } PKZOI%email-validator/src/Result/Result.phpnuW+Aelement = $element; } public function code() : int { return 201; } public function description() : string { return 'Unusual element found, wourld render invalid in majority of cases. Element found: ' . $this->element; } } PKZZ!,email-validator/src/Result/Reason/CRLFX2.phpnuW+Aexception = $exception; } public function code() : int { return 999; } public function description() : string { return $this->exception->getMessage(); } } PKZd{GG2email-validator/src/Result/Reason/CRLFAtTheEnd.phpnuW+AdetailedDescription; } } PKZ%'hFF5email-validator/src/Result/Reason/UnOpenedComment.phpnuW+AdetailedDescription = $details; } } PKZڷKK+email-validator/src/Result/InvalidEmail.phpnuW+Atoken = $token; $this->reason = $reason; } public function isValid(): bool { return false; } public function isInvalid(): bool { return true; } public function description(): string { return $this->reason->description() . " in char " . $this->token; } public function code(): int { return $this->reason->code(); } public function reason(): Reason { return $this->reason; } } PKZ砐R22)email-validator/src/Result/SpoofEmail.phpnuW+Areason = new ReasonSpoofEmail(); parent::__construct($this->reason, ''); } } PKZjU{{)email-validator/src/Result/ValidEmail.phpnuW+AsetChecks(Spoofchecker::SINGLE_SCRIPT); if ($checker->isSuspicious($email)) { $this->error = new SpoofEmail(); } return $this->error === null; } public function getError() : ?InvalidEmail { return $this->error; } public function getWarnings() : array { return []; } } PKZ<2email-validator/src/Validation/EmailValidation.phpnuW+AdnsGetRecord = $dnsGetRecord; } public function isValid(string $email, EmailLexer $emailLexer): bool { // use the input to check DNS if we cannot extract something similar to a domain $host = $email; // Arguable pattern to extract the domain. Not aiming to validate the domain nor the email if (false !== $lastAtPos = strrpos($email, '@')) { $host = substr($email, $lastAtPos + 1); } // Get the domain parts $hostParts = explode('.', $host); $isLocalDomain = count($hostParts) <= 1; $isReservedTopLevel = in_array($hostParts[(count($hostParts) - 1)], self::RESERVED_DNS_TOP_LEVEL_NAMES, true); // Exclude reserved top level DNS names if ($isLocalDomain || $isReservedTopLevel) { $this->error = new InvalidEmail(new LocalOrReservedDomain(), $host); return false; } return $this->checkDns($host); } public function getError(): ?InvalidEmail { return $this->error; } /** * @return Warning[] */ public function getWarnings(): array { return $this->warnings; } /** * @param string $host * * @return bool */ protected function checkDns($host) { $variant = INTL_IDNA_VARIANT_UTS46; $host = rtrim(idn_to_ascii($host, IDNA_DEFAULT, $variant), '.'); $hostParts = explode('.', $host); $host = array_pop($hostParts); while (count($hostParts) > 0) { $host = array_pop($hostParts) . '.' . $host; if ($this->validateDnsRecords($host)) { return true; } } return false; } /** * Validate the DNS records for given host. * * @param string $host A set of DNS records in the format returned by dns_get_record. * * @return bool True on success. */ private function validateDnsRecords($host): bool { $dnsRecordsResult = $this->dnsGetRecord->getRecords($host, DNS_A + DNS_MX); if ($dnsRecordsResult->withError()) { $this->error = new InvalidEmail(new UnableToGetDNSRecord(), ''); return false; } $dnsRecords = $dnsRecordsResult->getRecords(); // Combined check for A+MX+AAAA can fail with SERVFAIL, even in the presence of valid A/MX records $aaaaRecordsResult = $this->dnsGetRecord->getRecords($host, DNS_AAAA); if (! $aaaaRecordsResult->withError()) { $dnsRecords = array_merge($dnsRecords, $aaaaRecordsResult->getRecords()); } // No MX, A or AAAA DNS records if ($dnsRecords === []) { $this->error = new InvalidEmail(new ReasonNoDNSRecord(), ''); return false; } // For each DNS record foreach ($dnsRecords as $dnsRecord) { if (!$this->validateMXRecord($dnsRecord)) { // No MX records (fallback to A or AAAA records) if (empty($this->mxRecords)) { $this->warnings[NoDNSMXRecord::CODE] = new NoDNSMXRecord(); } return false; } } return true; } /** * Validate an MX record * * @param array $dnsRecord Given DNS record. * * @return bool True if valid. */ private function validateMxRecord($dnsRecord): bool { if (!isset($dnsRecord['type'])) { $this->error = new InvalidEmail(new ReasonNoDNSRecord(), ''); return false; } if ($dnsRecord['type'] !== 'MX') { return true; } // "Null MX" record indicates the domain accepts no mail (https://tools.ietf.org/html/rfc7505) if (empty($dnsRecord['target']) || $dnsRecord['target'] === '.') { $this->error = new InvalidEmail(new DomainAcceptsNoMail(), ""); return false; } $this->mxRecords[] = $dnsRecord; return true; } } PKZN6email-validator/src/Validation/MessageIDValidation.phpnuW+Aparse($email); $this->warnings = $parser->getWarnings(); if ($result->isInvalid()) { /** @psalm-suppress PropertyTypeCoercion */ $this->error = $result; return false; } } catch (\Exception $invalid) { $this->error = new InvalidEmail(new ExceptionFound($invalid), ''); return false; } return true; } /** * @return Warning[] */ public function getWarnings(): array { return $this->warnings; } public function getError(): ?InvalidEmail { return $this->error; } } PKZ'G  <email-validator/src/Validation/MultipleValidationWithAnd.phpnuW+Avalidations as $validation) { $emailLexer->reset(); $validationResult = $validation->isValid($email, $emailLexer); $result = $result && $validationResult; $this->warnings = [...$this->warnings, ...$validation->getWarnings()]; if (!$validationResult) { $this->processError($validation); } if ($this->shouldStop($result)) { break; } } return $result; } private function initErrorStorage(): void { if (null === $this->error) { $this->error = new MultipleErrors(); } } private function processError(EmailValidation $validation): void { if (null !== $validation->getError()) { $this->initErrorStorage(); /** @psalm-suppress PossiblyNullReference */ $this->error->addReason($validation->getError()->reason()); } } private function shouldStop(bool $result): bool { return !$result && $this->mode === self::STOP_ON_ERROR; } /** * Returns the validation errors. */ public function getError(): ?InvalidEmail { return $this->error; } /** * @return Warning[] */ public function getWarnings(): array { return $this->warnings; } } PKZJMM:email-validator/src/Validation/NoRFCWarningsValidation.phpnuW+AgetWarnings())) { return true; } $this->error = new InvalidEmail(new RFCWarnings(), ''); return false; } /** * {@inheritdoc} */ public function getError() : ?InvalidEmail { return $this->error ?: parent::getError(); } } PKZ%7Z-email-validator/src/Validation/DNSRecords.phpnuW+A> $records * @param bool $error */ public function __construct(private readonly array $records, private readonly bool $error = false) { } /** * @return list> */ public function getRecords(): array { return $this->records; } public function withError(): bool { return $this->error; } } PKZL  0email-validator/src/Validation/RFCValidation.phpnuW+Aparse($email); $this->warnings = $parser->getWarnings(); if ($result->isInvalid()) { /** @psalm-suppress PropertyTypeCoercion */ $this->error = $result; return false; } } catch (\Exception $invalid) { $this->error = new InvalidEmail(new ExceptionFound($invalid), ''); return false; } return true; } public function getError(): ?InvalidEmail { return $this->error; } /** * @return Warning[] */ public function getWarnings(): array { return $this->warnings; } } PKZemail-validator/src/Parser.phpnuW+Alexer = $lexer; } public function parse(string $str): Result { $this->lexer->setInput($str); if ($this->lexer->hasInvalidTokens()) { return new InvalidEmail(new ExpectingATEXT("Invalid tokens found"), $this->lexer->current->value); } $preParsingResult = $this->preLeftParsing(); if ($preParsingResult->isInvalid()) { return $preParsingResult; } $localPartResult = $this->parseLeftFromAt(); if ($localPartResult->isInvalid()) { return $localPartResult; } $domainPartResult = $this->parseRightFromAt(); if ($domainPartResult->isInvalid()) { return $domainPartResult; } return new ValidEmail(); } /** * @return Warning\Warning[] */ public function getWarnings(): array { return $this->warnings; } protected function hasAtToken(): bool { $this->lexer->moveNext(); $this->lexer->moveNext(); return !$this->lexer->current->isA(EmailLexer::S_AT); } } PKZ\F F #email-validator/src/EmailParser.phpnuW+AaddLongEmailWarning($this->localPart, $this->domainPart); return $result; } protected function preLeftParsing(): Result { if (!$this->hasAtToken()) { return new InvalidEmail(new NoLocalPart(), $this->lexer->current->value); } return new ValidEmail(); } protected function parseLeftFromAt(): Result { return $this->processLocalPart(); } protected function parseRightFromAt(): Result { return $this->processDomainPart(); } private function processLocalPart(): Result { $localPartParser = new LocalPart($this->lexer); $localPartResult = $localPartParser->parse(); $this->localPart = $localPartParser->localPart(); $this->warnings = [...$localPartParser->getWarnings(), ...$this->warnings]; return $localPartResult; } private function processDomainPart(): Result { $domainPartParser = new DomainPart($this->lexer); $domainPartResult = $domainPartParser->parse(); $this->domainPart = $domainPartParser->domainPart(); $this->warnings = [...$domainPartParser->getWarnings(), ...$this->warnings]; return $domainPartResult; } public function getDomainPart(): string { return $this->domainPart; } public function getLocalPart(): string { return $this->localPart; } private function addLongEmailWarning(string $localPart, string $parsedDomainPart): void { if (strlen($localPart . '@' . $parsedDomainPart) > self::EMAIL_MAX_LENGTH) { $this->warnings[EmailTooLong::CODE] = new EmailTooLong(); } } } PKZhϑ!!"email-validator/src/EmailLexer.phpnuW+A */ class EmailLexer extends AbstractLexer { //ASCII values public const S_EMPTY = -1; public const C_NUL = 0; public const S_HTAB = 9; public const S_LF = 10; public const S_CR = 13; public const S_SP = 32; public const EXCLAMATION = 33; public const S_DQUOTE = 34; public const NUMBER_SIGN = 35; public const DOLLAR = 36; public const PERCENTAGE = 37; public const AMPERSAND = 38; public const S_SQUOTE = 39; public const S_OPENPARENTHESIS = 40; public const S_CLOSEPARENTHESIS = 41; public const ASTERISK = 42; public const S_PLUS = 43; public const S_COMMA = 44; public const S_HYPHEN = 45; public const S_DOT = 46; public const S_SLASH = 47; public const S_COLON = 58; public const S_SEMICOLON = 59; public const S_LOWERTHAN = 60; public const S_EQUAL = 61; public const S_GREATERTHAN = 62; public const QUESTIONMARK = 63; public const S_AT = 64; public const S_OPENBRACKET = 91; public const S_BACKSLASH = 92; public const S_CLOSEBRACKET = 93; public const CARET = 94; public const S_UNDERSCORE = 95; public const S_BACKTICK = 96; public const S_OPENCURLYBRACES = 123; public const S_PIPE = 124; public const S_CLOSECURLYBRACES = 125; public const S_TILDE = 126; public const C_DEL = 127; public const INVERT_QUESTIONMARK = 168; public const INVERT_EXCLAMATION = 173; public const GENERIC = 300; public const S_IPV6TAG = 301; public const INVALID = 302; public const CRLF = 1310; public const S_DOUBLECOLON = 5858; public const ASCII_INVALID_FROM = 127; public const ASCII_INVALID_TO = 199; /** * US-ASCII visible characters not valid for atext (@link http://tools.ietf.org/html/rfc5322#section-3.2.3) * * @var array */ protected $charValue = [ '{' => self::S_OPENCURLYBRACES, '}' => self::S_CLOSECURLYBRACES, '(' => self::S_OPENPARENTHESIS, ')' => self::S_CLOSEPARENTHESIS, '<' => self::S_LOWERTHAN, '>' => self::S_GREATERTHAN, '[' => self::S_OPENBRACKET, ']' => self::S_CLOSEBRACKET, ':' => self::S_COLON, ';' => self::S_SEMICOLON, '@' => self::S_AT, '\\' => self::S_BACKSLASH, '/' => self::S_SLASH, ',' => self::S_COMMA, '.' => self::S_DOT, "'" => self::S_SQUOTE, "`" => self::S_BACKTICK, '"' => self::S_DQUOTE, '-' => self::S_HYPHEN, '::' => self::S_DOUBLECOLON, ' ' => self::S_SP, "\t" => self::S_HTAB, "\r" => self::S_CR, "\n" => self::S_LF, "\r\n" => self::CRLF, 'IPv6' => self::S_IPV6TAG, '' => self::S_EMPTY, '\0' => self::C_NUL, '*' => self::ASTERISK, '!' => self::EXCLAMATION, '&' => self::AMPERSAND, '^' => self::CARET, '$' => self::DOLLAR, '%' => self::PERCENTAGE, '~' => self::S_TILDE, '|' => self::S_PIPE, '_' => self::S_UNDERSCORE, '=' => self::S_EQUAL, '+' => self::S_PLUS, '¿' => self::INVERT_QUESTIONMARK, '?' => self::QUESTIONMARK, '#' => self::NUMBER_SIGN, '¡' => self::INVERT_EXCLAMATION, ]; public const INVALID_CHARS_REGEX = "/[^\p{S}\p{C}\p{Cc}]+/iu"; public const VALID_UTF8_REGEX = '/\p{Cc}+/u'; public const CATCHABLE_PATTERNS = [ '[a-zA-Z]+[46]?', //ASCII and domain literal '[^\x00-\x7F]', //UTF-8 '[0-9]+', '\r\n', '::', '\s+?', '.', ]; public const NON_CATCHABLE_PATTERNS = [ '[\xA0-\xff]+', ]; public const MODIFIERS = 'iu'; /** @var bool */ protected $hasInvalidTokens = false; /** * @var Token */ protected Token $previous; /** * The last matched/seen token. * * @var Token */ public Token $current; /** * @var Token */ private Token $nullToken; /** @var string */ private $accumulator = ''; /** @var bool */ private $hasToRecord = false; public function __construct() { /** @var Token $nullToken */ $nullToken = new Token('', self::S_EMPTY, 0); $this->nullToken = $nullToken; $this->current = $this->previous = $this->nullToken; $this->lookahead = null; } public function reset(): void { $this->hasInvalidTokens = false; parent::reset(); $this->current = $this->previous = $this->nullToken; } /** * @param int $type * @throws \UnexpectedValueException * @return boolean * */ public function find($type): bool { $search = clone $this; $search->skipUntil($type); if (!$search->lookahead) { throw new \UnexpectedValueException($type . ' not found'); } return true; } /** * moveNext * * @return boolean */ public function moveNext(): bool { if ($this->hasToRecord && $this->previous === $this->nullToken) { $this->accumulator .= $this->current->value; } $this->previous = $this->current; if ($this->lookahead === null) { $this->lookahead = $this->nullToken; } $hasNext = parent::moveNext(); $this->current = $this->token ?? $this->nullToken; if ($this->hasToRecord) { $this->accumulator .= $this->current->value; } return $hasNext; } /** * Retrieve token type. Also processes the token value if necessary. * * @param string $value * @throws \InvalidArgumentException * @return integer */ protected function getType(&$value): int { $encoded = $value; if (mb_detect_encoding($value, 'auto', true) !== 'UTF-8') { $encoded = mb_convert_encoding($value, 'UTF-8', 'Windows-1252'); } if ($this->isValid($encoded)) { return $this->charValue[$encoded]; } if ($this->isNullType($encoded)) { return self::C_NUL; } if ($this->isInvalidChar($encoded)) { $this->hasInvalidTokens = true; return self::INVALID; } return self::GENERIC; } protected function isValid(string $value): bool { return isset($this->charValue[$value]); } protected function isNullType(string $value): bool { return $value === "\0"; } protected function isInvalidChar(string $value): bool { return !preg_match(self::INVALID_CHARS_REGEX, $value); } protected function isUTF8Invalid(string $value): bool { return preg_match(self::VALID_UTF8_REGEX, $value) !== false; } public function hasInvalidTokens(): bool { return $this->hasInvalidTokens; } /** * getPrevious * * @return Token */ public function getPrevious(): Token { return $this->previous; } /** * Lexical catchable patterns. * * @return string[] */ protected function getCatchablePatterns(): array { return self::CATCHABLE_PATTERNS; } /** * Lexical non-catchable patterns. * * @return string[] */ protected function getNonCatchablePatterns(): array { return self::NON_CATCHABLE_PATTERNS; } protected function getModifiers(): string { return self::MODIFIERS; } public function getAccumulatedValues(): string { return $this->accumulator; } public function startRecording(): void { $this->hasToRecord = true; } public function stopRecording(): void { $this->hasToRecord = false; } public function clearRecorded(): void { $this->accumulator = ''; } } PKZ x&email-validator/src/EmailValidator.phpnuW+Alexer = new EmailLexer(); } /** * @param string $email * @param EmailValidation $emailValidation * @return bool */ public function isValid(string $email, EmailValidation $emailValidation) { $isValid = $emailValidation->isValid($email, $this->lexer); $this->warnings = $emailValidation->getWarnings(); $this->error = $emailValidation->getError(); return $isValid; } /** * @return boolean */ public function hasWarnings() { return !empty($this->warnings); } /** * @return array */ public function getWarnings() { return $this->warnings; } /** * @return InvalidEmail|null */ public function getError() { return $this->error; } } PKZ/a)email-validator/src/Parser/IDLeftPart.phpnuW+Alexer->current->value); } } PKZDGG(email-validator/src/Parser/LocalPart.phpnuW+A EmailLexer::S_COMMA, EmailLexer::S_CLOSEBRACKET => EmailLexer::S_CLOSEBRACKET, EmailLexer::S_OPENBRACKET => EmailLexer::S_OPENBRACKET, EmailLexer::S_GREATERTHAN => EmailLexer::S_GREATERTHAN, EmailLexer::S_LOWERTHAN => EmailLexer::S_LOWERTHAN, EmailLexer::S_COLON => EmailLexer::S_COLON, EmailLexer::S_SEMICOLON => EmailLexer::S_SEMICOLON, EmailLexer::INVALID => EmailLexer::INVALID ]; /** * @var string */ private $localPart = ''; public function parse(): Result { $this->lexer->clearRecorded(); $this->lexer->startRecording(); while (!$this->lexer->current->isA(EmailLexer::S_AT) && !$this->lexer->current->isA(EmailLexer::S_EMPTY)) { if ($this->hasDotAtStart()) { return new InvalidEmail(new DotAtStart(), $this->lexer->current->value); } if ($this->lexer->current->isA(EmailLexer::S_DQUOTE)) { $dquoteParsingResult = $this->parseDoubleQuote(); //Invalid double quote parsing if ($dquoteParsingResult->isInvalid()) { return $dquoteParsingResult; } } if ( $this->lexer->current->isA(EmailLexer::S_OPENPARENTHESIS) || $this->lexer->current->isA(EmailLexer::S_CLOSEPARENTHESIS) ) { $commentsResult = $this->parseComments(); //Invalid comment parsing if ($commentsResult->isInvalid()) { return $commentsResult; } } if ($this->lexer->current->isA(EmailLexer::S_DOT) && $this->lexer->isNextToken(EmailLexer::S_DOT)) { return new InvalidEmail(new ConsecutiveDot(), $this->lexer->current->value); } if ( $this->lexer->current->isA(EmailLexer::S_DOT) && $this->lexer->isNextToken(EmailLexer::S_AT) ) { return new InvalidEmail(new DotAtEnd(), $this->lexer->current->value); } $resultEscaping = $this->validateEscaping(); if ($resultEscaping->isInvalid()) { return $resultEscaping; } $resultToken = $this->validateTokens(false); if ($resultToken->isInvalid()) { return $resultToken; } $resultFWS = $this->parseLocalFWS(); if ($resultFWS->isInvalid()) { return $resultFWS; } $this->lexer->moveNext(); } $this->lexer->stopRecording(); $this->localPart = rtrim($this->lexer->getAccumulatedValues(), '@'); if (strlen($this->localPart) > LocalTooLong::LOCAL_PART_LENGTH) { $this->warnings[LocalTooLong::CODE] = new LocalTooLong(); } return new ValidEmail(); } protected function validateTokens(bool $hasComments): Result { if (isset(self::INVALID_TOKENS[$this->lexer->current->type])) { return new InvalidEmail(new ExpectingATEXT('Invalid token found'), $this->lexer->current->value); } return new ValidEmail(); } public function localPart(): string { return $this->localPart; } private function parseLocalFWS(): Result { $foldingWS = new FoldingWhiteSpace($this->lexer); $resultFWS = $foldingWS->parse(); if ($resultFWS->isValid()) { $this->warnings = [...$this->warnings, ...$foldingWS->getWarnings()]; } return $resultFWS; } private function hasDotAtStart(): bool { return $this->lexer->current->isA(EmailLexer::S_DOT) && $this->lexer->getPrevious()->isA(EmailLexer::S_EMPTY); } private function parseDoubleQuote(): Result { $dquoteParser = new DoubleQuote($this->lexer); $parseAgain = $dquoteParser->parse(); $this->warnings = [...$this->warnings, ...$dquoteParser->getWarnings()]; return $parseAgain; } protected function parseComments(): Result { $commentParser = new Comment($this->lexer, new LocalComment()); $result = $commentParser->parse(); $this->warnings = [...$this->warnings, ...$commentParser->getWarnings()]; return $result; } private function validateEscaping(): Result { //Backslash found if (!$this->lexer->current->isA(EmailLexer::S_BACKSLASH)) { return new ValidEmail(); } if ($this->lexer->isNextToken(EmailLexer::GENERIC)) { return new InvalidEmail(new ExpectingATEXT('Found ATOM after escaping'), $this->lexer->current->value); } return new ValidEmail(); } } PKZ Zђ!*!*)email-validator/src/Parser/DomainPart.phpnuW+Alexer->clearRecorded(); $this->lexer->startRecording(); $this->lexer->moveNext(); $domainChecks = $this->performDomainStartChecks(); if ($domainChecks->isInvalid()) { return $domainChecks; } if ($this->lexer->current->isA(EmailLexer::S_AT)) { return new InvalidEmail(new ConsecutiveAt(), $this->lexer->current->value); } $result = $this->doParseDomainPart(); if ($result->isInvalid()) { return $result; } $end = $this->checkEndOfDomain(); if ($end->isInvalid()) { return $end; } $this->lexer->stopRecording(); $this->domainPart = $this->lexer->getAccumulatedValues(); $length = strlen($this->domainPart); if ($length > self::DOMAIN_MAX_LENGTH) { return new InvalidEmail(new DomainTooLong(), $this->lexer->current->value); } return new ValidEmail(); } private function checkEndOfDomain(): Result { $prev = $this->lexer->getPrevious(); if ($prev->isA(EmailLexer::S_DOT)) { return new InvalidEmail(new DotAtEnd(), $this->lexer->current->value); } if ($prev->isA(EmailLexer::S_HYPHEN)) { return new InvalidEmail(new DomainHyphened('Hypen found at the end of the domain'), $prev->value); } if ($this->lexer->current->isA(EmailLexer::S_SP)) { return new InvalidEmail(new CRLFAtTheEnd(), $prev->value); } return new ValidEmail(); } private function performDomainStartChecks(): Result { $invalidTokens = $this->checkInvalidTokensAfterAT(); if ($invalidTokens->isInvalid()) { return $invalidTokens; } $missingDomain = $this->checkEmptyDomain(); if ($missingDomain->isInvalid()) { return $missingDomain; } if ($this->lexer->current->isA(EmailLexer::S_OPENPARENTHESIS)) { $this->warnings[DeprecatedComment::CODE] = new DeprecatedComment(); } return new ValidEmail(); } private function checkEmptyDomain(): Result { $thereIsNoDomain = $this->lexer->current->isA(EmailLexer::S_EMPTY) || ($this->lexer->current->isA(EmailLexer::S_SP) && !$this->lexer->isNextToken(EmailLexer::GENERIC)); if ($thereIsNoDomain) { return new InvalidEmail(new NoDomainPart(), $this->lexer->current->value); } return new ValidEmail(); } private function checkInvalidTokensAfterAT(): Result { if ($this->lexer->current->isA(EmailLexer::S_DOT)) { return new InvalidEmail(new DotAtStart(), $this->lexer->current->value); } if ($this->lexer->current->isA(EmailLexer::S_HYPHEN)) { return new InvalidEmail(new DomainHyphened('After AT'), $this->lexer->current->value); } return new ValidEmail(); } protected function parseComments(): Result { $commentParser = new Comment($this->lexer, new DomainComment()); $result = $commentParser->parse(); $this->warnings = [...$this->warnings, ...$commentParser->getWarnings()]; return $result; } protected function doParseDomainPart(): Result { $tldMissing = true; $hasComments = false; $domain = ''; do { $prev = $this->lexer->getPrevious(); $notAllowedChars = $this->checkNotAllowedChars($this->lexer->current); if ($notAllowedChars->isInvalid()) { return $notAllowedChars; } if ( $this->lexer->current->isA(EmailLexer::S_OPENPARENTHESIS) || $this->lexer->current->isA(EmailLexer::S_CLOSEPARENTHESIS) ) { $hasComments = true; $commentsResult = $this->parseComments(); //Invalid comment parsing if ($commentsResult->isInvalid()) { return $commentsResult; } } $dotsResult = $this->checkConsecutiveDots(); if ($dotsResult->isInvalid()) { return $dotsResult; } if ($this->lexer->current->isA(EmailLexer::S_OPENBRACKET)) { $literalResult = $this->parseDomainLiteral(); $this->addTLDWarnings($tldMissing); return $literalResult; } $labelCheck = $this->checkLabelLength(); if ($labelCheck->isInvalid()) { return $labelCheck; } $FwsResult = $this->parseFWS(); if ($FwsResult->isInvalid()) { return $FwsResult; } $domain .= $this->lexer->current->value; if ($this->lexer->current->isA(EmailLexer::S_DOT) && $this->lexer->isNextToken(EmailLexer::GENERIC)) { $tldMissing = false; } $exceptionsResult = $this->checkDomainPartExceptions($prev, $hasComments); if ($exceptionsResult->isInvalid()) { return $exceptionsResult; } $this->lexer->moveNext(); } while (!$this->lexer->current->isA(EmailLexer::S_EMPTY)); $labelCheck = $this->checkLabelLength(true); if ($labelCheck->isInvalid()) { return $labelCheck; } $this->addTLDWarnings($tldMissing); $this->domainPart = $domain; return new ValidEmail(); } /** * @param Token $token * * @return Result */ private function checkNotAllowedChars(Token $token): Result { $notAllowed = [EmailLexer::S_BACKSLASH => true, EmailLexer::S_SLASH => true]; if (isset($notAllowed[$token->type])) { return new InvalidEmail(new CharNotAllowed(), $token->value); } return new ValidEmail(); } /** * @return Result */ protected function parseDomainLiteral(): Result { try { $this->lexer->find(EmailLexer::S_CLOSEBRACKET); } catch (\RuntimeException $e) { return new InvalidEmail(new ExpectingDomainLiteralClose(), $this->lexer->current->value); } $domainLiteralParser = new DomainLiteralParser($this->lexer); $result = $domainLiteralParser->parse(); $this->warnings = [...$this->warnings, ...$domainLiteralParser->getWarnings()]; return $result; } /** * @param Token $prev * @param bool $hasComments * * @return Result */ protected function checkDomainPartExceptions(Token $prev, bool $hasComments): Result { if ($this->lexer->current->isA(EmailLexer::S_OPENBRACKET) && $prev->type !== EmailLexer::S_AT) { return new InvalidEmail(new ExpectingATEXT('OPENBRACKET not after AT'), $this->lexer->current->value); } if ($this->lexer->current->isA(EmailLexer::S_HYPHEN) && $this->lexer->isNextToken(EmailLexer::S_DOT)) { return new InvalidEmail(new DomainHyphened('Hypen found near DOT'), $this->lexer->current->value); } if ( $this->lexer->current->isA(EmailLexer::S_BACKSLASH) && $this->lexer->isNextToken(EmailLexer::GENERIC) ) { return new InvalidEmail(new ExpectingATEXT('Escaping following "ATOM"'), $this->lexer->current->value); } return $this->validateTokens($hasComments); } protected function validateTokens(bool $hasComments): Result { $validDomainTokens = array( EmailLexer::GENERIC => true, EmailLexer::S_HYPHEN => true, EmailLexer::S_DOT => true, ); if ($hasComments) { $validDomainTokens[EmailLexer::S_OPENPARENTHESIS] = true; $validDomainTokens[EmailLexer::S_CLOSEPARENTHESIS] = true; } if (!isset($validDomainTokens[$this->lexer->current->type])) { return new InvalidEmail(new ExpectingATEXT('Invalid token in domain: ' . $this->lexer->current->value), $this->lexer->current->value); } return new ValidEmail(); } private function checkLabelLength(bool $isEndOfDomain = false): Result { if ($this->lexer->current->isA(EmailLexer::S_DOT) || $isEndOfDomain) { if ($this->isLabelTooLong($this->label)) { return new InvalidEmail(new LabelTooLong(), $this->lexer->current->value); } $this->label = ''; } $this->label .= $this->lexer->current->value; return new ValidEmail(); } private function isLabelTooLong(string $label): bool { if (preg_match('/[^\x00-\x7F]/', $label)) { idn_to_ascii($label, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46, $idnaInfo); /** @psalm-var array{errors: int, ...} $idnaInfo */ return (bool) ($idnaInfo['errors'] & IDNA_ERROR_LABEL_TOO_LONG); } return strlen($label) > self::LABEL_MAX_LENGTH; } private function addTLDWarnings(bool $isTLDMissing): void { if ($isTLDMissing) { $this->warnings[TLD::CODE] = new TLD(); } } public function domainPart(): string { return $this->domainPart; } } PKZ<email-validator/src/Parser/CommentStrategy/DomainComment.phpnuW+AisNextToken(EmailLexer::S_DOT)); } public function endOfLoopValidations(EmailLexer $lexer): Result { //test for end of string if (!$lexer->isNextToken(EmailLexer::S_DOT)) { return new InvalidEmail(new ExpectingATEXT('DOT not found near CLOSEPARENTHESIS'), $lexer->current->value); } //add warning //Address is valid within the message but cannot be used unmodified for the envelope return new ValidEmail(); } public function getWarnings(): array { return []; } } PKZ̳``;email-validator/src/Parser/CommentStrategy/LocalComment.phpnuW+A */ private $warnings = []; public function exitCondition(EmailLexer $lexer, int $openedParenthesis): bool { return !$lexer->isNextToken(EmailLexer::S_AT); } public function endOfLoopValidations(EmailLexer $lexer): Result { if (!$lexer->isNextToken(EmailLexer::S_AT)) { return new InvalidEmail(new ExpectingATEXT('ATEX is not expected after closing comments'), $lexer->current->value); } $this->warnings[CFWSNearAt::CODE] = new CFWSNearAt(); return new ValidEmail(); } public function getWarnings(): array { return $this->warnings; } } PKZS!  >email-validator/src/Parser/CommentStrategy/CommentStrategy.phpnuW+Alexer = $lexer; } abstract public function parse(): Result; /** * @return Warning[] */ public function getWarnings() { return $this->warnings; } protected function parseFWS(): Result { $foldingWS = new FoldingWhiteSpace($this->lexer); $resultFWS = $foldingWS->parse(); $this->warnings = [...$this->warnings, ...$foldingWS->getWarnings()]; return $resultFWS; } protected function checkConsecutiveDots(): Result { if ($this->lexer->current->isA(EmailLexer::S_DOT) && $this->lexer->isNextToken(EmailLexer::S_DOT)) { return new InvalidEmail(new ConsecutiveDot(), $this->lexer->current->value); } return new ValidEmail(); } protected function escaped(): bool { $previous = $this->lexer->getPrevious(); return $previous->isA(EmailLexer::S_BACKSLASH) && !$this->lexer->current->isA(EmailLexer::GENERIC); } } PKZ=< 0email-validator/src/Parser/FoldingWhiteSpace.phpnuW+AisFWS()) { return new ValidEmail(); } $previous = $this->lexer->getPrevious(); $resultCRLF = $this->checkCRLFInFWS(); if ($resultCRLF->isInvalid()) { return $resultCRLF; } if ($this->lexer->current->isA(EmailLexer::S_CR)) { return new InvalidEmail(new CRNoLF(), $this->lexer->current->value); } if ($this->lexer->isNextToken(EmailLexer::GENERIC) && !$previous->isA(EmailLexer::S_AT)) { return new InvalidEmail(new AtextAfterCFWS(), $this->lexer->current->value); } if ($this->lexer->current->isA(EmailLexer::S_LF) || $this->lexer->current->isA(EmailLexer::C_NUL)) { return new InvalidEmail(new ExpectingCTEXT(), $this->lexer->current->value); } if ($this->lexer->isNextToken(EmailLexer::S_AT) || $previous->isA(EmailLexer::S_AT)) { $this->warnings[CFWSNearAt::CODE] = new CFWSNearAt(); } else { $this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS(); } return new ValidEmail(); } protected function checkCRLFInFWS(): Result { if (!$this->lexer->current->isA(EmailLexer::CRLF)) { return new ValidEmail(); } if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) { return new InvalidEmail(new CRLFX2(), $this->lexer->current->value); } //this has no coverage. Condition is repeated from above one if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) { return new InvalidEmail(new CRLFAtTheEnd(), $this->lexer->current->value); } return new ValidEmail(); } protected function isFWS(): bool { if ($this->escaped()) { return false; } return in_array($this->lexer->current->type, self::FWS_TYPES); } } PKZ=,email-validator/src/Parser/DomainLiteral.phpnuW+AaddTagWarnings(); $IPv6TAG = false; $addressLiteral = ''; do { if ($this->lexer->current->isA(EmailLexer::C_NUL)) { return new InvalidEmail(new ExpectingDTEXT(), $this->lexer->current->value); } $this->addObsoleteWarnings(); if ($this->lexer->isNextTokenAny(array(EmailLexer::S_OPENBRACKET, EmailLexer::S_OPENBRACKET))) { return new InvalidEmail(new ExpectingDTEXT(), $this->lexer->current->value); } if ($this->lexer->isNextTokenAny( array(EmailLexer::S_HTAB, EmailLexer::S_SP, EmailLexer::CRLF) )) { $this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS(); $this->parseFWS(); } if ($this->lexer->isNextToken(EmailLexer::S_CR)) { return new InvalidEmail(new CRNoLF(), $this->lexer->current->value); } if ($this->lexer->current->isA(EmailLexer::S_BACKSLASH)) { return new InvalidEmail(new UnusualElements($this->lexer->current->value), $this->lexer->current->value); } if ($this->lexer->current->isA(EmailLexer::S_IPV6TAG)) { $IPv6TAG = true; } if ($this->lexer->current->isA(EmailLexer::S_CLOSEBRACKET)) { break; } $addressLiteral .= $this->lexer->current->value; } while ($this->lexer->moveNext()); //Encapsulate $addressLiteral = str_replace('[', '', $addressLiteral); $isAddressLiteralIPv4 = $this->checkIPV4Tag($addressLiteral); if (!$isAddressLiteralIPv4) { return new ValidEmail(); } $addressLiteral = $this->convertIPv4ToIPv6($addressLiteral); if (!$IPv6TAG) { $this->warnings[WarningDomainLiteral::CODE] = new WarningDomainLiteral(); return new ValidEmail(); } $this->warnings[AddressLiteral::CODE] = new AddressLiteral(); $this->checkIPV6Tag($addressLiteral); return new ValidEmail(); } /** * @param string $addressLiteral * @param int $maxGroups */ public function checkIPV6Tag($addressLiteral, $maxGroups = 8): void { $prev = $this->lexer->getPrevious(); if ($prev->isA(EmailLexer::S_COLON)) { $this->warnings[IPV6ColonEnd::CODE] = new IPV6ColonEnd(); } $IPv6 = substr($addressLiteral, 5); //Daniel Marschall's new IPv6 testing strategy $matchesIP = explode(':', $IPv6); $groupCount = count($matchesIP); $colons = strpos($IPv6, '::'); if (count(preg_grep('/^[0-9A-Fa-f]{0,4}$/', $matchesIP, PREG_GREP_INVERT)) !== 0) { $this->warnings[IPV6BadChar::CODE] = new IPV6BadChar(); } if ($colons === false) { // We need exactly the right number of groups if ($groupCount !== $maxGroups) { $this->warnings[IPV6GroupCount::CODE] = new IPV6GroupCount(); } return; } if ($colons !== strrpos($IPv6, '::')) { $this->warnings[IPV6DoubleColon::CODE] = new IPV6DoubleColon(); return; } if ($colons === 0 || $colons === (strlen($IPv6) - 2)) { // RFC 4291 allows :: at the start or end of an address //with 7 other groups in addition ++$maxGroups; } if ($groupCount > $maxGroups) { $this->warnings[IPV6MaxGroups::CODE] = new IPV6MaxGroups(); } elseif ($groupCount === $maxGroups) { $this->warnings[IPV6Deprecated::CODE] = new IPV6Deprecated(); } } public function convertIPv4ToIPv6(string $addressLiteralIPv4): string { $matchesIP = []; $IPv4Match = preg_match(self::IPV4_REGEX, $addressLiteralIPv4, $matchesIP); // Extract IPv4 part from the end of the address-literal (if there is one) if ($IPv4Match > 0) { $index = (int) strrpos($addressLiteralIPv4, $matchesIP[0]); //There's a match but it is at the start if ($index > 0) { // Convert IPv4 part to IPv6 format for further testing return substr($addressLiteralIPv4, 0, $index) . '0:0'; } } return $addressLiteralIPv4; } /** * @param string $addressLiteral * * @return bool */ protected function checkIPV4Tag($addressLiteral): bool { $matchesIP = []; $IPv4Match = preg_match(self::IPV4_REGEX, $addressLiteral, $matchesIP); // Extract IPv4 part from the end of the address-literal (if there is one) if ($IPv4Match > 0) { $index = strrpos($addressLiteral, $matchesIP[0]); //There's a match but it is at the start if ($index === 0) { $this->warnings[AddressLiteral::CODE] = new AddressLiteral(); return false; } } return true; } private function addObsoleteWarnings(): void { if (in_array($this->lexer->current->type, self::OBSOLETE_WARNINGS)) { $this->warnings[ObsoleteDTEXT::CODE] = new ObsoleteDTEXT(); } } private function addTagWarnings(): void { if ($this->lexer->isNextToken(EmailLexer::S_COLON)) { $this->warnings[IPV6ColonStart::CODE] = new IPV6ColonStart(); } if ($this->lexer->isNextToken(EmailLexer::S_IPV6TAG)) { $lexer = clone $this->lexer; $lexer->moveNext(); if ($lexer->isNextToken(EmailLexer::S_DOUBLECOLON)) { $this->warnings[IPV6ColonStart::CODE] = new IPV6ColonStart(); } } } } PKZ$΁ *email-validator/src/Parser/DoubleQuote.phpnuW+AcheckDQUOTE(); if ($validQuotedString->isInvalid()) { return $validQuotedString; } $special = [ EmailLexer::S_CR => true, EmailLexer::S_HTAB => true, EmailLexer::S_LF => true ]; $invalid = [ EmailLexer::C_NUL => true, EmailLexer::S_HTAB => true, EmailLexer::S_CR => true, EmailLexer::S_LF => true ]; $setSpecialsWarning = true; $this->lexer->moveNext(); while (!$this->lexer->current->isA(EmailLexer::S_DQUOTE) && !$this->lexer->current->isA(EmailLexer::S_EMPTY)) { if (isset($special[$this->lexer->current->type]) && $setSpecialsWarning) { $this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS(); $setSpecialsWarning = false; } if ($this->lexer->current->isA(EmailLexer::S_BACKSLASH) && $this->lexer->isNextToken(EmailLexer::S_DQUOTE)) { $this->lexer->moveNext(); } $this->lexer->moveNext(); if (!$this->escaped() && isset($invalid[$this->lexer->current->type])) { return new InvalidEmail(new ExpectingATEXT("Expecting ATEXT between DQUOTE"), $this->lexer->current->value); } } $prev = $this->lexer->getPrevious(); if ($prev->isA(EmailLexer::S_BACKSLASH)) { $validQuotedString = $this->checkDQUOTE(); if ($validQuotedString->isInvalid()) { return $validQuotedString; } } if (!$this->lexer->isNextToken(EmailLexer::S_AT) && !$prev->isA(EmailLexer::S_BACKSLASH)) { return new InvalidEmail(new ExpectingATEXT("Expecting ATEXT between DQUOTE"), $this->lexer->current->value); } return new ValidEmail(); } protected function checkDQUOTE(): Result { $previous = $this->lexer->getPrevious(); if ($this->lexer->isNextToken(EmailLexer::GENERIC) && $previous->isA(EmailLexer::GENERIC)) { $description = 'https://tools.ietf.org/html/rfc5322#section-3.2.4 - quoted string should be a unit'; return new InvalidEmail(new ExpectingATEXT($description), $this->lexer->current->value); } try { $this->lexer->find(EmailLexer::S_DQUOTE); } catch (\Exception $e) { return new InvalidEmail(new UnclosedQuotedString(), $this->lexer->current->value); } $this->warnings[QuotedString::CODE] = new QuotedString($previous->value, $this->lexer->current->value); return new ValidEmail(); } } PKZ+*email-validator/src/Parser/IDRightPart.phpnuW+A true, EmailLexer::S_SQUOTE => true, EmailLexer::S_BACKTICK => true, EmailLexer::S_SEMICOLON => true, EmailLexer::S_GREATERTHAN => true, EmailLexer::S_LOWERTHAN => true, ]; if (isset($invalidDomainTokens[$this->lexer->current->type])) { return new InvalidEmail(new ExpectingATEXT('Invalid token in domain: ' . $this->lexer->current->value), $this->lexer->current->value); } return new ValidEmail(); } } PKZ&R R &email-validator/src/Parser/Comment.phpnuW+Alexer = $lexer; $this->commentStrategy = $commentStrategy; } public function parse(): Result { if ($this->lexer->current->isA(EmailLexer::S_OPENPARENTHESIS)) { $this->openedParenthesis++; if ($this->noClosingParenthesis()) { return new InvalidEmail(new UnclosedComment(), $this->lexer->current->value); } } if ($this->lexer->current->isA(EmailLexer::S_CLOSEPARENTHESIS)) { return new InvalidEmail(new UnOpenedComment(), $this->lexer->current->value); } $this->warnings[WarningComment::CODE] = new WarningComment(); $moreTokens = true; while ($this->commentStrategy->exitCondition($this->lexer, $this->openedParenthesis) && $moreTokens) { if ($this->lexer->isNextToken(EmailLexer::S_OPENPARENTHESIS)) { $this->openedParenthesis++; } $this->warnEscaping(); if ($this->lexer->isNextToken(EmailLexer::S_CLOSEPARENTHESIS)) { $this->openedParenthesis--; } $moreTokens = $this->lexer->moveNext(); } if ($this->openedParenthesis >= 1) { return new InvalidEmail(new UnclosedComment(), $this->lexer->current->value); } if ($this->openedParenthesis < 0) { return new InvalidEmail(new UnOpenedComment(), $this->lexer->current->value); } $finalValidations = $this->commentStrategy->endOfLoopValidations($this->lexer); $this->warnings = [...$this->warnings, ...$this->commentStrategy->getWarnings()]; return $finalValidations; } /** * @return void */ private function warnEscaping(): void { //Backslash found if (!$this->lexer->current->isA(EmailLexer::S_BACKSLASH)) { return; } if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB, EmailLexer::C_DEL))) { return; } $this->warnings[QuotedPart::CODE] = new QuotedPart($this->lexer->getPrevious()->type, $this->lexer->current->type); } private function noClosingParenthesis(): bool { try { $this->lexer->find(EmailLexer::S_CLOSEPARENTHESIS); return false; } catch (\RuntimeException $e) { return true; } } } PKZh email-validator/composer.jsonnuW+A{ "name": "egulias/email-validator", "description": "A library for validating emails against several RFCs", "homepage": "https://github.com/egulias/EmailValidator", "keywords": ["email", "validation", "validator", "emailvalidation", "emailvalidator"], "license": "MIT", "authors": [ {"name": "Eduardo Gulias Davis"} ], "extra": { "branch-alias": { "dev-master": "4.0.x-dev" } }, "require": { "php": ">=8.1", "doctrine/lexer": "^2.0 || ^3.0", "symfony/polyfill-intl-idn": "^1.26" }, "require-dev": { "phpunit/phpunit": "^10.2", "vimeo/psalm": "^5.12" }, "suggest": { "ext-intl": "PHP Internationalization Libraries are required to use the SpoofChecking validation" }, "autoload": { "psr-4": { "Egulias\\EmailValidator\\": "src" } }, "autoload-dev": { "psr-4": { "Egulias\\EmailValidator\\Tests\\": "tests" } } } PK猬Z.email-validator/CHANGELOG.mdnuW+A# EmailValidator v3 Changelog ## New Features * Access to local part and domain part from EmailParser * Validations outside of the scope of the RFC will be considered "extra" validations, thus opening the door for adding new; will live in their own folder "extra" (as requested in #248, #195, #183). ## Breaking changes * PHP version upgraded to match Symfony's (as of 12/2020). * DNSCheckValidation now fails for missing MX records. While the RFC argues that the existence of only A records to be valid, starting in v3 they will be considered invalid. * Emails domain part are now intenteded to be RFC 1035 compliant, rendering previous valid emails (e.g example@examp&) invalid. ## PHP versions upgrade policy PHP version upgrade requirement will happen via MINOR (3.x) version upgrades of the library, following the adoption level by major frameworks. ## Changes * #235 * #215 * #130 * #258 * #188 * #181 * #217 * #214 * #249 * #236 * #257 * #210 ## Thanks To contributors, be it with PRs, reporting issues or supporting otherwise. PKZ wwnnemail-validator/CONTRIBUTING.mdnuW+APKZ.--email-validator/LICENSEnuW+APKZ|_7- - '1email-validator/src/MessageIDParser.phpnuW+APKZS 4.'email-validator/src/Warning/AddressLiteral.phpnuW+APKZH*)email-validator/src/Warning/CFWSNearAt.phpnuW+APKZodd,S*email-validator/src/Warning/QuotedString.phpnuW+APKZUi+,email-validator/src/Warning/CFWSWithFWS.phpnuW+APKZY'-b-email-validator/src/Warning/IPV6MaxGroups.phpnuW+APKZf%L..email-validator/src/Warning/IPV6GroupCount.phpnuW+APKZe  -20email-validator/src/Warning/NoDNSMXRecord.phpnuW+APKZ"+1email-validator/src/Warning/IPV6BadChar.phpnuW+APKZ/2email-validator/src/Warning/IPV6DoubleColon.phpnuW+APKZ[q-Z4email-validator/src/Warning/DomainLiteral.phpnuW+APKZj.5email-validator/src/Warning/IPV6ColonStart.phpnuW+APKZF  ,7email-validator/src/Warning/IPV6ColonEnd.phpnuW+APKZp!td``*|8email-validator/src/Warning/QuotedPart.phpnuW+APKZ !-6;email-validator/src/Warning/ObsoleteDTEXT.phpnuW+APKZ.e#<email-validator/src/Warning/TLD.phpnuW+APKZ%%,=email-validator/src/Warning/EmailTooLong.phpnuW+APKZIb.-?email-validator/src/Warning/IPV6Deprecated.phpnuW+APKZ '@email-validator/src/Warning/Warning.phpnuW+APKZ:>'Cemail-validator/src/Warning/Comment.phpnuW+APKZK1Eemail-validator/src/Warning/DeprecatedComment.phpnuW+APKZV}5<<,YFemail-validator/src/Warning/LocalTooLong.phpnuW+APKZ6S **-Gemail-validator/src/Result/MultipleErrors.phpnuW+APKZOI%xLemail-validator/src/Result/Result.phpnuW+APKZ  :Nemail-validator/src/Result/Reason/UnclosedQuotedString.phpnuW+APKZx1RPemail-validator/src/Result/Reason/EmptyReason.phpnuW+APKZ,,AQemail-validator/src/Result/Reason/ExpectingDomainLiteralClose.phpnuW+APKZIXc.FSemail-validator/src/Result/Reason/DotAtEnd.phpnuW+APKZ{1Temail-validator/src/Result/Reason/NoLocalPart.phpnuW+APKZk0Uemail-validator/src/Result/Reason/DotAtStart.phpnuW+APKZDN,RWemail-validator/src/Result/Reason/CRNoLF.phpnuW+APKZ& 1Xemail-validator/src/Result/Reason/NoDNSRecord.phpnuW+APKZb5"Zemail-validator/src/Result/Reason/UnusualElements.phpnuW+APKZZ!,~\email-validator/src/Result/Reason/CRLFX2.phpnuW+APKZ`84]email-validator/src/Result/Reason/ConsecutiveDot.phpnuW+APKZJ+n¾4B_email-validator/src/Result/Reason/ExceptionFound.phpnuW+APKZd{GG2daemail-validator/src/Result/Reason/CRLFAtTheEnd.phpnuW+APKZOY4 cemail-validator/src/Result/Reason/AtextAfterCFWS.phpnuW+APKZ83vdemail-validator/src/Result/Reason/CommaInDomain.phpnuW+APKZ`2eemail-validator/src/Result/Reason/LabelTooLong.phpnuW+APKZO}9hgemail-validator/src/Result/Reason/DomainAcceptsNoMail.phpnuW+APKZ4hemail-validator/src/Result/Reason/ExpectingDTEXT.phpnuW+APKZGAA4Pjemail-validator/src/Result/Reason/ExpectingATEXT.phpnuW+APKZ%'hFF5kemail-validator/src/Result/Reason/UnOpenedComment.phpnuW+APKZ   4memail-validator/src/Result/Reason/DomainHyphened.phpnuW+APKZyXgdd:oemail-validator/src/Result/Reason/UnableToGetDNSRecord.phpnuW+APKZ'';pemail-validator/src/Result/Reason/LocalOrReservedDomain.phpnuW+APKZ J4premail-validator/src/Result/Reason/CharNotAllowed.phpnuW+APKZ׵CF3semail-validator/src/Result/Reason/ConsecutiveAt.phpnuW+APKZMf$$7?uemail-validator/src/Result/Reason/CommentsInIDRight.phpnuW+APKZ?4vemail-validator/src/Result/Reason/ExpectingCTEXT.phpnuW+APKZ}`4))0,xemail-validator/src/Result/Reason/SpoofEmail.phpnuW+APKZoZ5yemail-validator/src/Result/Reason/UnclosedComment.phpnuW+APKZ`O3({email-validator/src/Result/Reason/DomainTooLong.phpnuW+APKZ:2|email-validator/src/Result/Reason/NoDomainPart.phpnuW+APKZK9N,~email-validator/src/Result/Reason/Reason.phpnuW+APKZ  1wemail-validator/src/Result/Reason/RFCWarnings.phpnuW+APKZ4email-validator/src/Result/Reason/DetailedReason.phpnuW+APKZڷKK+Demail-validator/src/Result/InvalidEmail.phpnuW+APKZ砐R22)email-validator/src/Result/SpoofEmail.phpnuW+APKZjU{{)uemail-validator/src/Result/ValidEmail.phpnuW+APKZ99=Iemail-validator/src/Validation/Extra/SpoofCheckValidation.phpnuW+APKZ<2email-validator/src/Validation/EmailValidation.phpnuW+APKZG``@cemail-validator/src/Validation/Exception/EmptyValidationList.phpnuW+APKZ]]63email-validator/src/Validation/DNSGetRecordWrapper.phpnuW+APKZ[5_5email-validator/src/Validation/DNSCheckValidation.phpnuW+APKZN6email-validator/src/Validation/MessageIDValidation.phpnuW+APKZ'G  <remail-validator/src/Validation/MultipleValidationWithAnd.phpnuW+APKZJMM:email-validator/src/Validation/NoRFCWarningsValidation.phpnuW+APKZ%7Z-email-validator/src/Validation/DNSRecords.phpnuW+APKZL  0email-validator/src/Validation/RFCValidation.phpnuW+APKZbemail-validator/src/Parser.phpnuW+APKZ\F F #email-validator/src/EmailParser.phpnuW+APKZhϑ!!"Demail-validator/src/EmailLexer.phpnuW+APKZ x&email-validator/src/EmailValidator.phpnuW+APKZ/a)email-validator/src/Parser/IDLeftPart.phpnuW+APKZDGG(email-validator/src/Parser/LocalPart.phpnuW+APKZ Zђ!*!*)7email-validator/src/Parser/DomainPart.phpnuW+APKZ<Demail-validator/src/Parser/CommentStrategy/DomainComment.phpnuW+APKZ̳``;7Iemail-validator/src/Parser/CommentStrategy/LocalComment.phpnuW+APKZS!  >Nemail-validator/src/Parser/CommentStrategy/CommentStrategy.phpnuW+APKZ,w3)}Pemail-validator/src/Parser/PartParser.phpnuW+APKZ=< 0Vemail-validator/src/Parser/FoldingWhiteSpace.phpnuW+APKZ=,#bemail-validator/src/Parser/DomainLiteral.phpnuW+APKZ$΁ *~email-validator/src/Parser/DoubleQuote.phpnuW+APKZ+*[email-validator/src/Parser/IDRightPart.phpnuW+APKZ&R R &email-validator/src/Parser/Comment.phpnuW+APKZh )email-validator/composer.jsonnuW+APK猬Z.email-validator/CHANGELOG.mdnuW+APK[[n'~