email-validator/composer.json000064400000001655150250177370012356 0ustar00{ "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": "3.0.x-dev" } }, "require": { "php": ">=7.2", "doctrine/lexer": "^1.2|^2", "symfony/polyfill-intl-idn": "^1.15" }, "require-dev": { "phpunit/phpunit": "^8.5.8|^9.3.3", "vimeo/psalm": "^4" }, "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" } } } email-validator/CHANGELOG.md000064400000002024150250177370011434 0ustar00# 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. email-validator/src/EmailLexer.php000064400000022106150250177370013155 0ustar00 */ class EmailLexer extends AbstractLexer { //ASCII values public const S_EMPTY = null; 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 array * * @psalm-var array{value:string, type:null|int, position:int}|array */ protected $previous = []; /** * The last matched/seen token. * * @var array|Token * * @psalm-suppress NonInvariantDocblockPropertyType * @psalm-var array{value:string, type:null|int, position:int}|Token */ public $token; /** * The next token in the input. * * @var array|Token|null * * @psalm-suppress NonInvariantDocblockPropertyType * @psalm-var array{position: int, type: int|null|string, value: int|string}|Token|null */ public $lookahead; /** @psalm-var array{value:'', type:null, position:0} */ private static $nullToken = [ 'value' => '', 'type' => null, 'position' => 0, ]; /** @var string */ private $accumulator = ''; /** @var bool */ private $hasToRecord = false; public function __construct() { $this->previous = $this->token = self::$nullToken; $this->lookahead = null; } public function reset() : void { $this->hasInvalidTokens = false; parent::reset(); $this->previous = $this->token = self::$nullToken; } /** * @param int $type * @throws \UnexpectedValueException * @return boolean * * @psalm-suppress InvalidScalarArgument */ 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 === self::$nullToken) { $this->accumulator .= $this->token['value']; } $this->previous = $this->token instanceof Token ? ['value' => $this->token->value, 'type' => $this->token->type, 'position' => $this->token->position] : $this->token; if($this->lookahead === null) { $this->lookahead = self::$nullToken; } $hasNext = parent::moveNext(); if ($this->hasToRecord) { $this->accumulator .= $this->token['value']; } return $hasNext; } /** * Retrieve token type. Also processes the token value if necessary. * * @param string $value * @throws \InvalidArgumentException * @return integer */ protected function getType(&$value) { $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 array */ public function getPrevious() : array { 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 = ''; } } email-validator/src/Parser/PartParser.php000064400000003042150250177370014443 0ustar00lexer = $lexer; } abstract public function parse() : Result; /** * @return \Egulias\EmailValidator\Warning\Warning[] */ public function getWarnings() { return $this->warnings; } protected function parseFWS() : Result { $foldingWS = new FoldingWhiteSpace($this->lexer); $resultFWS = $foldingWS->parse(); $this->warnings = array_merge($this->warnings, $foldingWS->getWarnings()); return $resultFWS; } protected function checkConsecutiveDots() : Result { if ($this->lexer->token['type'] === EmailLexer::S_DOT && $this->lexer->isNextToken(EmailLexer::S_DOT)) { return new InvalidEmail(new ConsecutiveDot(), $this->lexer->token['value']); } return new ValidEmail(); } protected function escaped() : bool { $previous = $this->lexer->getPrevious(); return $previous && $previous['type'] === EmailLexer::S_BACKSLASH && $this->lexer->token['type'] !== EmailLexer::GENERIC; } } email-validator/src/Parser/CommentStrategy/DomainComment.php000064400000002170150250177370020240 0ustar00isNextToken(EmailLexer::S_DOT))){ // || !$internalLexer->moveNext()) { return false; } return true; } 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->token['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 []; } } email-validator/src/Parser/CommentStrategy/LocalComment.php000064400000002050150250177370020060 0ustar00isNextToken(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->token['value']); } $this->warnings[CFWSNearAt::CODE] = new CFWSNearAt(); return new ValidEmail(); } public function getWarnings(): array { return $this->warnings; } } email-validator/src/Parser/CommentStrategy/CommentStrategy.php000064400000000673150250177370020641 0ustar00lexer->token['value']); } } email-validator/src/Parser/IDRightPart.php000064400000001721150250177370014503 0ustar00 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->token['type']])) { return new InvalidEmail(new ExpectingATEXT('Invalid token in domain: ' . $this->lexer->token['value']), $this->lexer->token['value']); } return new ValidEmail(); } } email-validator/src/Parser/DomainPart.php000064400000024622150250177370014425 0ustar00lexer->clearRecorded(); $this->lexer->startRecording(); $this->lexer->moveNext(); $domainChecks = $this->performDomainStartChecks(); if ($domainChecks->isInvalid()) { return $domainChecks; } if ($this->lexer->token['type'] === EmailLexer::S_AT) { return new InvalidEmail(new ConsecutiveAt(), $this->lexer->token['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->token['value']); } return new ValidEmail(); } private function checkEndOfDomain() : Result { $prev = $this->lexer->getPrevious(); if ($prev['type'] === EmailLexer::S_DOT) { return new InvalidEmail(new DotAtEnd(), $this->lexer->token['value']); } if ($prev['type'] === EmailLexer::S_HYPHEN) { return new InvalidEmail(new DomainHyphened('Hypen found at the end of the domain'), $prev['value']); } if ($this->lexer->token['type'] === 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->token['type'] === EmailLexer::S_OPENPARENTHESIS) { $this->warnings[DeprecatedComment::CODE] = new DeprecatedComment(); } return new ValidEmail(); } private function checkEmptyDomain() : Result { $thereIsNoDomain = $this->lexer->token['type'] === EmailLexer::S_EMPTY || ($this->lexer->token['type'] === EmailLexer::S_SP && !$this->lexer->isNextToken(EmailLexer::GENERIC)); if ($thereIsNoDomain) { return new InvalidEmail(new NoDomainPart(), $this->lexer->token['value']); } return new ValidEmail(); } private function checkInvalidTokensAfterAT() : Result { if ($this->lexer->token['type'] === EmailLexer::S_DOT) { return new InvalidEmail(new DotAtStart(), $this->lexer->token['value']); } if ($this->lexer->token['type'] === EmailLexer::S_HYPHEN) { return new InvalidEmail(new DomainHyphened('After AT'), $this->lexer->token['value']); } return new ValidEmail(); } protected function parseComments(): Result { $commentParser = new Comment($this->lexer, new DomainComment()); $result = $commentParser->parse(); $this->warnings = array_merge($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->token); if ($notAllowedChars->isInvalid()) { return $notAllowedChars; } if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS || $this->lexer->token['type'] === 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->token['type'] === 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->token['value']; if ($this->lexer->token['type'] === EmailLexer::S_DOT && $this->lexer->isNextToken(EmailLexer::GENERIC)) { $tldMissing = false; } $exceptionsResult = $this->checkDomainPartExceptions($prev, $hasComments); if ($exceptionsResult->isInvalid()) { return $exceptionsResult; } $this->lexer->moveNext(); } while (null !== $this->lexer->token['type']); $labelCheck = $this->checkLabelLength(true); if ($labelCheck->isInvalid()) { return $labelCheck; } $this->addTLDWarnings($tldMissing); $this->domainPart = $domain; return new ValidEmail(); } /** * @psalm-param array|Token $token */ private function checkNotAllowedChars($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->token['value']); } $domainLiteralParser = new DomainLiteralParser($this->lexer); $result = $domainLiteralParser->parse(); $this->warnings = array_merge($this->warnings, $domainLiteralParser->getWarnings()); return $result; } protected function checkDomainPartExceptions(array $prev, bool $hasComments) : Result { if ($this->lexer->token['type'] === EmailLexer::S_OPENBRACKET && $prev['type'] !== EmailLexer::S_AT) { return new InvalidEmail(new ExpectingATEXT('OPENBRACKET not after AT'), $this->lexer->token['value']); } if ($this->lexer->token['type'] === EmailLexer::S_HYPHEN && $this->lexer->isNextToken(EmailLexer::S_DOT)) { return new InvalidEmail(new DomainHyphened('Hypen found near DOT'), $this->lexer->token['value']); } if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH && $this->lexer->isNextToken(EmailLexer::GENERIC)) { return new InvalidEmail(new ExpectingATEXT('Escaping following "ATOM"'), $this->lexer->token['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->token['type']])) { return new InvalidEmail(new ExpectingATEXT('Invalid token in domain: ' . $this->lexer->token['value']), $this->lexer->token['value']); } return new ValidEmail(); } private function checkLabelLength(bool $isEndOfDomain = false) : Result { if ($this->lexer->token['type'] === EmailLexer::S_DOT || $isEndOfDomain) { if ($this->isLabelTooLong($this->label)) { return new InvalidEmail(new LabelTooLong(), $this->lexer->token['value']); } $this->label = ''; } $this->label .= $this->lexer->token['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); 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; } } email-validator/src/Parser/DoubleQuote.php000064400000006137150250177370014620 0ustar00checkDQUOTE(); 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->token['type'] !== EmailLexer::S_DQUOTE && null !== $this->lexer->token['type']) { if (isset($special[$this->lexer->token['type']]) && $setSpecialsWarning) { $this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS(); $setSpecialsWarning = false; } if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH && $this->lexer->isNextToken(EmailLexer::S_DQUOTE)) { $this->lexer->moveNext(); } $this->lexer->moveNext(); if (!$this->escaped() && isset($invalid[$this->lexer->token['type']])) { return new InvalidEmail(new ExpectingATEXT("Expecting ATEXT between DQUOTE"), $this->lexer->token['value']); } } $prev = $this->lexer->getPrevious(); if ($prev['type'] === EmailLexer::S_BACKSLASH) { $validQuotedString = $this->checkDQUOTE(); if($validQuotedString->isInvalid()) return $validQuotedString; } if (!$this->lexer->isNextToken(EmailLexer::S_AT) && $prev['type'] !== EmailLexer::S_BACKSLASH) { return new InvalidEmail(new ExpectingATEXT("Expecting ATEXT between DQUOTE"), $this->lexer->token['value']); } return new ValidEmail(); } protected function checkDQUOTE() : Result { $previous = $this->lexer->getPrevious(); if ($this->lexer->isNextToken(EmailLexer::GENERIC) && $previous['type'] === 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->token['value']); } try { $this->lexer->find(EmailLexer::S_DQUOTE); } catch (\Exception $e) { return new InvalidEmail(new UnclosedQuotedString(), $this->lexer->token['value']); } $this->warnings[QuotedString::CODE] = new QuotedString($previous['value'], $this->lexer->token['value']); return new ValidEmail(); } } email-validator/src/Parser/LocalPart.php000064400000012771150250177370014252 0ustar00 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->startRecording(); while ($this->lexer->token['type'] !== EmailLexer::S_AT && null !== $this->lexer->token['type']) { if ($this->hasDotAtStart()) { return new InvalidEmail(new DotAtStart(), $this->lexer->token['value']); } if ($this->lexer->token['type'] === EmailLexer::S_DQUOTE) { $dquoteParsingResult = $this->parseDoubleQuote(); //Invalid double quote parsing if($dquoteParsingResult->isInvalid()) { return $dquoteParsingResult; } } if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS || $this->lexer->token['type'] === EmailLexer::S_CLOSEPARENTHESIS ) { $commentsResult = $this->parseComments(); //Invalid comment parsing if($commentsResult->isInvalid()) { return $commentsResult; } } if ($this->lexer->token['type'] === EmailLexer::S_DOT && $this->lexer->isNextToken(EmailLexer::S_DOT)) { return new InvalidEmail(new ConsecutiveDot(), $this->lexer->token['value']); } if ($this->lexer->token['type'] === EmailLexer::S_DOT && $this->lexer->isNextToken(EmailLexer::S_AT) ) { return new InvalidEmail(new DotAtEnd(), $this->lexer->token['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->token['type']])) { return new InvalidEmail(new ExpectingATEXT('Invalid token found'), $this->lexer->token['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 = array_merge($this->warnings, $foldingWS->getWarnings()); } return $resultFWS; } private function hasDotAtStart() : bool { return $this->lexer->token['type'] === EmailLexer::S_DOT && null === $this->lexer->getPrevious()['type']; } private function parseDoubleQuote() : Result { $dquoteParser = new DoubleQuote($this->lexer); $parseAgain = $dquoteParser->parse(); $this->warnings = array_merge($this->warnings, $dquoteParser->getWarnings()); return $parseAgain; } protected function parseComments(): Result { $commentParser = new Comment($this->lexer, new LocalComment()); $result = $commentParser->parse(); $this->warnings = array_merge($this->warnings, $commentParser->getWarnings()); if($result->isInvalid()) { return $result; } return $result; } private function validateEscaping() : Result { //Backslash found if ($this->lexer->token['type'] !== EmailLexer::S_BACKSLASH) { return new ValidEmail(); } if ($this->lexer->isNextToken(EmailLexer::GENERIC)) { return new InvalidEmail(new ExpectingATEXT('Found ATOM after escaping'), $this->lexer->token['value']); } if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB, EmailLexer::C_DEL))) { return new ValidEmail(); } return new ValidEmail(); } } email-validator/src/Parser/DomainLiteral.php000064400000016065150250177370015115 0ustar00addTagWarnings(); $IPv6TAG = false; $addressLiteral = ''; do { if ($this->lexer->token['type'] === EmailLexer::C_NUL) { return new InvalidEmail(new ExpectingDTEXT(), $this->lexer->token['value']); } $this->addObsoleteWarnings(); if ($this->lexer->isNextTokenAny(array(EmailLexer::S_OPENBRACKET, EmailLexer::S_OPENBRACKET))) { return new InvalidEmail(new ExpectingDTEXT(), $this->lexer->token['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->token['value']); } if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH) { return new InvalidEmail(new UnusualElements($this->lexer->token['value']), $this->lexer->token['value']); } if ($this->lexer->token['type'] === EmailLexer::S_IPV6TAG) { $IPv6TAG = true; } if ($this->lexer->token['type'] === EmailLexer::S_CLOSEBRACKET) { break; } $addressLiteral .= $this->lexer->token['value']; } while ($this->lexer->moveNext()); //Encapsulate $addressLiteral = str_replace('[', '', $addressLiteral); $isAddressLiteralIPv4 = $this->checkIPV4Tag($addressLiteral); if (!$isAddressLiteralIPv4) { return new ValidEmail(); } else { $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['type'] === 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->token['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(); } } } } email-validator/src/Parser/Comment.php000064400000006206150250177370013767 0ustar00lexer = $lexer; $this->commentStrategy = $commentStrategy; } public function parse() : Result { if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) { $this->openedParenthesis++; if($this->noClosingParenthesis()) { return new InvalidEmail(new UnclosedComment(), $this->lexer->token['value']); } } if ($this->lexer->token['type'] === EmailLexer::S_CLOSEPARENTHESIS) { return new InvalidEmail(new UnOpenedComment(), $this->lexer->token['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->token['value']); } if ($this->openedParenthesis < 0) { return new InvalidEmail(new UnOpenedComment(), $this->lexer->token['value']); } $finalValidations = $this->commentStrategy->endOfLoopValidations($this->lexer); $this->warnings = array_merge($this->warnings, $this->commentStrategy->getWarnings()); return $finalValidations; } /** * @return bool */ private function warnEscaping() : bool { //Backslash found if ($this->lexer->token['type'] !== EmailLexer::S_BACKSLASH) { return false; } if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB, EmailLexer::C_DEL))) { return false; } $this->warnings[QuotedPart::CODE] = new QuotedPart($this->lexer->getPrevious()['type'], $this->lexer->token['type']); return true; } private function noClosingParenthesis() : bool { try { $this->lexer->find(EmailLexer::S_CLOSEPARENTHESIS); return false; } catch (\RuntimeException $e) { return true; } } } email-validator/src/Parser/FoldingWhiteSpace.php000064400000005415150250177370015725 0ustar00isFWS()) { return new ValidEmail(); } $previous = $this->lexer->getPrevious(); $resultCRLF = $this->checkCRLFInFWS(); if ($resultCRLF->isInvalid()) { return $resultCRLF; } if ($this->lexer->token['type'] === EmailLexer::S_CR) { return new InvalidEmail(new CRNoLF(), $this->lexer->token['value']); } if ($this->lexer->isNextToken(EmailLexer::GENERIC) && $previous['type'] !== EmailLexer::S_AT) { return new InvalidEmail(new AtextAfterCFWS(), $this->lexer->token['value']); } if ($this->lexer->token['type'] === EmailLexer::S_LF || $this->lexer->token['type'] === EmailLexer::C_NUL) { return new InvalidEmail(new ExpectingCTEXT(), $this->lexer->token['value']); } if ($this->lexer->isNextToken(EmailLexer::S_AT) || $previous['type'] === 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->token['type'] !== EmailLexer::CRLF) { return new ValidEmail(); } if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) { return new InvalidEmail(new CRLFX2(), $this->lexer->token['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->token['value']); } return new ValidEmail(); } protected function isFWS() : bool { if ($this->escaped()) { return false; } return in_array($this->lexer->token['type'], self::FWS_TYPES); } } email-validator/src/EmailValidator.php000064400000002324150250177370014023 0ustar00lexer = 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; } } email-validator/src/EmailParser.php000064400000004542150250177370013336 0ustar00addLongEmailWarning($this->localPart, $this->domainPart); return $result; } protected function preLeftParsing(): Result { if (!$this->hasAtToken()) { return new InvalidEmail(new NoLocalPart(), $this->lexer->token["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 = array_merge($localPartParser->getWarnings(), $this->warnings); return $localPartResult; } private function processDomainPart() : Result { $domainPartParser = new DomainPart($this->lexer); $domainPartResult = $domainPartParser->parse(); $this->domainPart = $domainPartParser->domainPart(); $this->warnings = array_merge($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(); } } } email-validator/src/Warning/LocalTooLong.php000064400000000474150250177370015073 0ustar00message = 'Local part is too long, exceeds 64 chars (octets)'; $this->rfcNumber = 5322; } } email-validator/src/Warning/IPV6DoubleColon.php000064400000000406150250177370015404 0ustar00message = 'Double colon found after IPV6 tag'; $this->rfcNumber = 5322; } } email-validator/src/Warning/IPV6BadChar.php000064400000000400150250177370014455 0ustar00message = 'Bad char in IPV6 domain literal'; $this->rfcNumber = 5322; } } email-validator/src/Warning/DeprecatedComment.php000064400000000331150250177370016112 0ustar00message = 'Deprecated comments'; } } email-validator/src/Warning/Warning.php000064400000001300150250177370014131 0ustar00message; } /** * @return int */ public function code() { return self::CODE; } /** * @return int */ public function RFCNumber() { return $this->rfcNumber; } public function __toString() { return $this->message() . " rfc: " . $this->rfcNumber . "internal code: " . static::CODE; } } email-validator/src/Warning/QuotedPart.php000064400000000545150250177370014626 0ustar00message = "Deprecated Quoted String found between $prevToken and $postToken"; } } email-validator/src/Warning/EmailTooLong.php000064400000000445150250177370015066 0ustar00message = 'Email is too long, exceeds ' . EmailParser::EMAIL_MAX_LENGTH; } } email-validator/src/Warning/AddressLiteral.php000064400000000402150250177370015430 0ustar00message = 'Address literal in domain part'; $this->rfcNumber = 5321; } } email-validator/src/Warning/CFWSNearAt.php000064400000000344150250177370014370 0ustar00message = "Deprecated folding white space near @"; } } email-validator/src/Warning/NoDNSMXRecord.php000064400000000413150250177370015055 0ustar00message = 'No MX DSN record was found for this email'; $this->rfcNumber = 5321; } } email-validator/src/Warning/IPV6MaxGroups.php000064400000000424150250177370015124 0ustar00message = 'Reached the maximum number of IPV6 groups allowed'; $this->rfcNumber = 5321; } } email-validator/src/Warning/IPV6ColonEnd.php000064400000000413150250177370014676 0ustar00message = ':: found at the end of the domain literal'; $this->rfcNumber = 5322; } } email-validator/src/Warning/CFWSWithFWS.php000064400000000364150250177370014513 0ustar00message = 'Folding whites space followed by folding white space'; } } email-validator/src/Warning/TLD.php000064400000000303150250177370013151 0ustar00message = "RFC5321, TLD"; } } email-validator/src/Warning/IPV6ColonStart.php000064400000000417150250177370015271 0ustar00message = ':: found at the start of the domain literal'; $this->rfcNumber = 5322; } } email-validator/src/Warning/QuotedString.php000064400000000534150250177370015164 0ustar00message = "Quoted String found between $prevToken and $postToken"; } } email-validator/src/Warning/DomainLiteral.php000064400000000361150250177370015256 0ustar00message = 'Domain Literal'; $this->rfcNumber = 5322; } } email-validator/src/Warning/IPV6Deprecated.php000064400000000373150250177370015242 0ustar00message = 'Deprecated form of IPV6'; $this->rfcNumber = 5321; } } email-validator/src/Warning/Comment.php000064400000000330150250177370014130 0ustar00message = "Comments found in this email"; } } email-validator/src/Warning/IPV6GroupCount.php000064400000000401150250177370015277 0ustar00message = 'Group count is not IPV6 valid'; $this->rfcNumber = 5322; } } email-validator/src/Warning/ObsoleteDTEXT.php000064400000000403150250177370015114 0ustar00rfcNumber = 5322; $this->message = 'Obsolete DTEXT in domain literal'; } } email-validator/src/Validation/DNSRecords.php000064400000001026150250177370015164 0ustar00records = $records; $this->error = $error; } public function getRecords() : array { return $this->records; } public function withError() : bool { return $this->error; } } email-validator/src/Validation/RFCValidation.php000064400000002405150250177370015645 0ustar00parser = new EmailParser($emailLexer); try { $result = $this->parser->parse($email); $this->warnings = $this->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; } public function getWarnings() : array { return $this->warnings; } } email-validator/src/Validation/NoRFCWarningsValidation.php000064400000001515150250177370017654 0ustar00getWarnings())) { return true; } $this->error = new InvalidEmail(new RFCWarnings(), ''); return false; } /** * {@inheritdoc} */ public function getError() : ?InvalidEmail { return $this->error ?: parent::getError(); } } email-validator/src/Validation/Exception/EmptyValidationList.php000064400000000540150250177370021121 0ustar00parse($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 getWarnings(): array { return $this->warnings; } public function getError(): ?InvalidEmail { return $this->error; } } email-validator/src/Validation/DNSGetRecordWrapper.php000064400000001553150250177370017007 0ustar00dnsGetRecord = $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; } 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), '.') . '.'; return $this->validateDnsRecords($host); } /** * 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, static::DNS_RECORD_TYPES_TO_CHECK); if ($dnsRecordsResult->withError()) { $this->error = new InvalidEmail(new UnableToGetDNSRecord(), ''); return false; } $dnsRecords = $dnsRecordsResult->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; } } email-validator/src/Validation/MultipleValidationWithAnd.php000064400000005603150250177370020310 0ustar00validations = $validations; $this->mode = $mode; } /** * {@inheritdoc} */ public function isValid(string $email, EmailLexer $emailLexer) : bool { $result = true; foreach ($this->validations as $validation) { $emailLexer->reset(); $validationResult = $validation->isValid($email, $emailLexer); $result = $result && $validationResult; $this->warnings = array_merge($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; } /** * {@inheritdoc} */ public function getWarnings() : array { return $this->warnings; } } email-validator/src/Validation/Extra/SpoofCheckValidation.php000064400000002234150250177370020342 0ustar00setChecks(Spoofchecker::SINGLE_SCRIPT); if ($checker->isSuspicious($email)) { $this->error = new SpoofEmail(); } return $this->error === null; } /** * @return InvalidEmail */ public function getError() : ?InvalidEmail { return $this->error; } public function getWarnings() : array { return []; } } email-validator/src/Validation/EmailValidation.php000064400000001422150250177370016260 0ustar00reasons[$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; } } email-validator/src/Result/Reason/UnclosedComment.php000064400000000416150250177370016732 0ustar00element = $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; } } email-validator/src/Result/Reason/ExceptionFound.php000064400000000676150250177370016575 0ustar00exception = $exception; } public function code() : int { return 999; } public function description() : string { return $this->exception->getMessage(); } } email-validator/src/Result/Reason/ExpectingATEXT.php000064400000000501150250177370016362 0ustar00detailedDescription; } } email-validator/src/Result/Reason/LocalOrReservedDomain.php000064400000000447150250177370020022 0ustar00detailedDescription = $details; } } email-validator/src/Result/Reason/DotAtStart.php000064400000000374150250177370015667 0ustar00reason = new ReasonSpoofEmail(); parent::__construct($this->reason, ''); } } email-validator/src/Result/InvalidEmail.php000064400000001433150250177370014742 0ustar00token = $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; } } email-validator/src/Result/Result.php000064400000000764150250177370013670 0ustar00addLongEmailWarning($this->idLeft, $this->idRight); return $result; } protected function preLeftParsing(): Result { if (!$this->hasAtToken()) { return new InvalidEmail(new NoLocalPart(), $this->lexer->token["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 = array_merge($localPartParser->getWarnings(), $this->warnings); return $localPartResult; } private function processIDRight() : Result { $domainPartParser = new IDRightPart($this->lexer); $domainPartResult = $domainPartParser->parse(); $this->idRight = $domainPartParser->domainPart(); $this->warnings = array_merge($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(); } } } email-validator/src/Parser.php000064400000003410150250177370012357 0ustar00lexer = $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->token["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->token['type'] !== EmailLexer::S_AT; } } email-validator/LICENSE000064400000002055150250177370010634 0ustar00Copyright (c) 2013-2022 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. email-validator/CONTRIBUTING.md000064400000014556150250177370012071 0ustar00# 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