Passed
Pull Request — master (#19663)
by Alexander
08:07
created

EmailValidator   A

Complexity

Total Complexity 37

Size/Duplication

Total Lines 206
Duplicated Lines 0 %

Test Coverage

Coverage 67.68%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
eloc 68
dl 0
loc 206
ccs 44
cts 65
cp 0.6768
rs 9.44
c 5
b 0
f 0
wmc 37

9 Methods

Rating   Name   Duplication   Size   Complexity  
A isDNSValid() 0 3 2
A hasDNSRecord() 0 15 5
A idnToAscii() 0 8 2
A idnToAsciiWithFallback() 0 10 5
A clientValidateAttribute() 0 9 2
A init() 0 8 4
C validateValue() 0 36 12
A getClientOptions() 0 16 2
A isEmpty() 0 7 3
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\validators;
9
10
use Yii;
11
use yii\base\ErrorException;
12
use yii\base\InvalidConfigException;
13
use yii\helpers\Json;
14
use yii\web\JsExpression;
15
16
/**
17
 * EmailValidator validates that the attribute value is a valid email address.
18
 *
19
 * @author Qiang Xue <[email protected]>
20
 * @since 2.0
21
 */
22
class EmailValidator extends Validator
23
{
24
    /**
25
     * @var string the regular expression used to validate the attribute value.
26
     * @see https://www.regular-expressions.info/email.html
27
     */
28
    public $pattern = '/^[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/';
29
    /**
30
     * @var string the regular expression used to validate email addresses with the name part.
31
     * This property is used only when [[allowName]] is true.
32
     * @see allowName
33
     */
34
    public $fullPattern = '/^[^@]*<[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?>$/';
35
    /**
36
     * @var string the regular expression used to validate the part before the @ symbol, used if ASCII conversion fails to validate the address.
37
     * @see https://www.regular-expressions.info/email.html
38
     * @since 2.0.42
39
     */
40
    public $patternASCII = '/^[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*$/';
41
    /**
42
     * @var string the regular expression used to validate email addresses with the name part before the @ symbol, used if ASCII conversion fails to validate the address.
43
     * This property is used only when [[allowName]] is true.
44
     * @see allowName
45
     * @since 2.0.42
46
     */
47
    public $fullPatternASCII = '/^[^@]*<[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*$/';
48
    /**
49
     * @var bool whether to allow name in the email address (e.g. "John Smith <[email protected]>"). Defaults to false.
50
     * @see fullPattern
51
     */
52
    public $allowName = false;
53
    /**
54
     * @var bool whether to check whether the email's domain exists and has either an A or MX record.
55
     * Be aware that this check can fail due to temporary DNS problems even if the email address is
56
     * valid and an email would be deliverable. Defaults to false.
57
     */
58
    public $checkDNS = false;
59
    /**
60
     * @var bool whether validation process should take into account IDN (internationalized domain
61
     * names). Defaults to false meaning that validation of emails containing IDN will always fail.
62
     * Note that in order to use IDN validation you have to install and enable `intl` PHP extension,
63
     * otherwise an exception would be thrown.
64
     */
65
    public $enableIDN = false;
66
    /**
67
     * @var bool whether [[enableIDN]] should apply to the local part of the email (left side
68
     * of the `@`). Only applies if [[enableIDN]] is `true`.
69
     * @since 2.0.43
70
     */
71
    public $enableLocalIDN = true;
72
73
74
    /**
75
     * {@inheritdoc}
76
     */
77 42
    public function init()
78
    {
79 42
        parent::init();
80 42
        if ($this->enableIDN && !function_exists('idn_to_ascii')) {
81
            throw new InvalidConfigException('In order to use IDN validation intl extension must be installed and enabled.');
82
        }
83 42
        if ($this->message === null) {
84 42
            $this->message = Yii::t('yii', '{attribute} is not a valid email address.');
85
        }
86 42
    }
87
88
    /**
89
     * {@inheritdoc}
90
     */
91 41
    protected function validateValue($value)
92
    {
93 41
        if (!is_string($value)) {
94 1
            $valid = false;
95 41
        } elseif (!preg_match('/^(?P<name>(?:"?([^"]*)"?\s)?)(?:\s+)?(?:(?P<open><?)((?P<local>.+)@(?P<domain>[^>]+))(?P<close>>?))$/i', $value, $matches)) {
96 4
            $valid = false;
97
        } else {
98 39
            if ($this->enableIDN) {
99 18
                if ($this->enableLocalIDN) {
100 18
                    $matches['local'] = $this->idnToAsciiWithFallback($matches['local']);
101
                }
102 18
                $matches['domain'] = $this->idnToAscii($matches['domain']);
103 18
                $value = $matches['name'] . $matches['open'] . $matches['local'] . '@' . $matches['domain'] . $matches['close'];
104
            }
105
106 39
            if (strlen($matches['local']) > 64) {
107
                // The maximum total length of a user name or other local-part is 64 octets. RFC 5322 section 4.5.3.1.1
108
                // https://datatracker.ietf.org/doc/html/rfc5321#section-4.5.3.1.1
109 1
                $valid = false;
110 39
            } elseif (strlen($matches['local'] . '@' . $matches['domain']) > 254) {
111
                // There is a restriction in RFC 2821 on the length of an address in MAIL and RCPT commands
112
                // of 254 characters. Since addresses that do not fit in those fields are not normally useful, the
113
                // upper limit on address lengths should normally be considered to be 254.
114
                //
115
                // Dominic Sayers, RFC 3696 erratum 1690
116
                // https://www.rfc-editor.org/errata_search.php?eid=1690
117 1
                $valid = false;
118
            } else {
119 39
                $valid = preg_match($this->pattern, $value) || ($this->allowName && preg_match($this->fullPattern, $value));
120 39
                if ($valid && $this->checkDNS) {
121 1
                    $valid = $this->isDNSValid($matches['domain']);
122
                }
123
            }
124
        }
125
126 41
        return $valid ? null : [$this->message, []];
127
    }
128
129
    /**
130
     * @param string $domain
131
     * @return bool if DNS records for domain are valid
132
     * @see https://github.com/yiisoft/yii2/issues/17083
133
     */
134 1
    protected function isDNSValid($domain)
135
    {
136 1
        return $this->hasDNSRecord($domain, true) || $this->hasDNSRecord($domain, false);
137
    }
138
139 1
    private function hasDNSRecord($domain, $isMX)
140
    {
141 1
        $normalizedDomain = $domain . '.';
142 1
        if (!checkdnsrr($normalizedDomain, ($isMX ? 'MX' : 'A'))) {
143 1
            return false;
144
        }
145
146
        try {
147
            // dns_get_record can return false and emit Warning that may or may not be converted to ErrorException
148 1
            $records = dns_get_record($normalizedDomain, ($isMX ? DNS_MX : DNS_A));
149
        } catch (ErrorException $exception) {
150
            return false;
151
        }
152
153 1
        return !empty($records);
154
    }
155
156 18
    private function idnToAscii($idn)
157
    {
158 18
        if (PHP_VERSION_ID < 50600) {
159
            // TODO: drop old PHP versions support
160
            return idn_to_ascii($idn);
161
        }
162
163 18
        return idn_to_ascii($idn, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
164
    }
165
166
    /**
167
     * {@inheritdoc}
168
     */
169
    public function clientValidateAttribute($model, $attribute, $view)
170
    {
171
        ValidationAsset::register($view);
172
        if ($this->enableIDN) {
173
            PunycodeAsset::register($view);
174
        }
175
        $options = $this->getClientOptions($model, $attribute);
176
177
        return 'yii.validation.email(value, messages, ' . Json::htmlEncode($options) . ');';
178
    }
179
180
    /**
181
     * {@inheritdoc}
182
     */
183
    public function getClientOptions($model, $attribute)
184
    {
185
        $options = [
186
            'pattern' => new JsExpression($this->pattern),
187
            'fullPattern' => new JsExpression($this->fullPattern),
188
            'allowName' => $this->allowName,
189
            'message' => $this->formatMessage($this->message, [
190
                'attribute' => $model->getAttributeLabel($attribute),
191
            ]),
192
            'enableIDN' => (bool) $this->enableIDN,
193
        ];
194
        if ($this->skipOnEmpty) {
195
            $options['skipOnEmpty'] = 1;
196
        }
197
198
        return $options;
199
    }
200
201
    /**
202
     * @param string $value
203
     * @return string|bool returns string if it is valid and/or can be converted, bool false if it can't be converted and/or is invalid
204
     * @see https://github.com/yiisoft/yii2/issues/18585
205
     */
206 18
    private function idnToAsciiWithFallback($value)
207
    {
208 18
        $ascii = $this->idnToAscii($value);
209 18
        if ($ascii === false) {
210 11
            if (preg_match($this->patternASCII, $value) || ($this->allowName && preg_match($this->fullPatternASCII, $value))) {
211 6
                return $value;
212
            }
213
        }
214
215 13
        return $ascii;
216
    }
217
218
    /**
219
     * {@inheritdoc}
220
     */
221 3
    public function isEmpty($value)
222
    {
223 3
        if ($this->isEmpty !== null) {
224
            return call_user_func($this->isEmpty, $value);
225
        }
226
227 3
        return $value === null || $value === '';
228
    }
229
}
230