|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Atk4\Data\Field; |
| 6 | + |
| 7 | +use Atk4\Data\Field; |
| 8 | +use Atk4\Data\ValidationException; |
| 9 | + |
| 10 | +/** |
| 11 | + * Stores valid email as per configuration. |
| 12 | + * |
| 13 | + * Usage: |
| 14 | + * $user->addField('email', [EmailField::class]); |
| 15 | + * $user->addField('email_mx_check', [EmailField::class, 'dns_check' => true]); |
| 16 | + * $user->addField('email_with_name', [EmailField::class, 'allow_name' => true]); |
| 17 | + */ |
| 18 | +class EmailField extends Field |
| 19 | +{ |
| 20 | + /** @var bool Enable lookup for MX record for email addresses stored */ |
| 21 | + public $dns_check = false; |
| 22 | + |
| 23 | + /** @var bool Allow display name as per RFC2822, eg. format like "Romans <me@example.com>" */ |
| 24 | + public $allow_name = false; |
| 25 | + |
| 26 | + public function normalize($value) |
| 27 | + { |
| 28 | + $value = parent::normalize($value); |
| 29 | + if ($value === null) { |
| 30 | + return $value; |
| 31 | + } |
| 32 | + |
| 33 | + $email = trim($value); |
| 34 | + if ($this->allow_name) { |
| 35 | + $email = preg_replace('/^[^<]*<([^>]*)>/', '\1', $email); |
| 36 | + } |
| 37 | + |
| 38 | + if (strpos($email, '@') === false) { |
| 39 | + throw new ValidationException([$this->name => 'Email address does not have domain'], $this->getOwner()); |
| 40 | + } |
| 41 | + |
| 42 | + [$user, $domain] = explode('@', $email, 2); |
| 43 | + $domain = idn_to_ascii($domain, \IDNA_DEFAULT, \INTL_IDNA_VARIANT_UTS46); // always convert domain to ASCII |
| 44 | + |
| 45 | + if (!filter_var($user . '@' . $domain, \FILTER_VALIDATE_EMAIL)) { |
| 46 | + throw new ValidationException([$this->name => 'Email address format is invalid'], $this->getOwner()); |
| 47 | + } |
| 48 | + |
| 49 | + if ($this->dns_check) { |
| 50 | + if (!$this->hasAnyDnsRecord($domain)) { |
| 51 | + throw new ValidationException([$this->name => 'Email address domain does not exist'], $this->getOwner()); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return parent::normalize($value); |
| 56 | + } |
| 57 | + |
| 58 | + private function hasAnyDnsRecord(string $domain, array $types = ['MX', 'A', 'AAAA', 'CNAME']): bool |
| 59 | + { |
| 60 | + foreach (array_unique(array_map('strtoupper', $types)) as $t) { |
| 61 | + $dnsConsts = [ |
| 62 | + 'MX' => \DNS_MX, |
| 63 | + 'A' => \DNS_A, |
| 64 | + 'AAAA' => \DNS_AAAA, |
| 65 | + 'CNAME' => \DNS_CNAME, |
| 66 | + ]; |
| 67 | + |
| 68 | + $records = @dns_get_record($domain . '.', $dnsConsts[$t]); |
| 69 | + if ($records === false) { // retry once on failure |
| 70 | + $records = dns_get_record($domain . '.', $dnsConsts[$t]); |
| 71 | + } |
| 72 | + if ($records !== false && count($records) > 0) { |
| 73 | + return true; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + return false; |
| 78 | + } |
| 79 | +} |
0 commit comments