Passed
Push — master ( 9d5617...725057 )
by Alexander
03:26
created

EmailValidator::idnToAscii()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 8
ccs 0
cts 4
cp 0
crap 6
rs 10
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://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 http://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 http://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 42
    public $enableLocalIDN = true;
72
73 42
74 42
    /**
75
     * {@inheritdoc}
76
     */
77 42
    public function init()
78 42
    {
79
        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
        if ($this->message === null) {
84
            $this->message = Yii::t('yii', '{attribute} is not a valid email address.');
85 41
        }
86
    }
87 41
88 1
    /**
89 41
     * {@inheritdoc}
90 4
     */
91
    protected function validateValue($value)
92 39
    {
93 18
        if (!is_string($value)) {
94 18
            $valid = false;
95 18
        } elseif (!preg_match('/^(?P<name>(?:"?([^"]*)"?\s)?)(?:\s+)?(?:(?P<open><?)((?P<local>.+)@(?P<domain>[^>]+))(?P<close>>?))$/i', $value, $matches)) {
96
            $valid = false;
97
        } else {
98 39
            if ($this->enableIDN) {
99
                if ($this->enableLocalIDN) {
100
                    $matches['local'] = $this->idnToAsciiWithFallback($matches['local']);
101 1
                }
102 39
                $matches['domain'] = $this->idnToAscii($matches['domain']);
103
                $value = $matches['name'] . $matches['open'] . $matches['local'] . '@' . $matches['domain'] . $matches['close'];
104
            }
105
106
            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
                // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.1
109 1
                $valid = false;
110
            } elseif (strlen($matches['local'] . '@' . $matches['domain']) > 254) {
111 39
                // There is a restriction in RFC 2821 on the length of an address in MAIL and RCPT commands
112 39
                // of 254 characters. Since addresses that do not fit in those fields are not normally useful, the
113 1
                // upper limit on address lengths should normally be considered to be 254.
114
                //
115
                // Dominic Sayers, RFC 3696 erratum 1690
116
                // http://www.rfc-editor.org/errata_search.php?eid=1690
117
                $valid = false;
118 41
            } else {
119
                $valid = preg_match($this->pattern, $value) || ($this->allowName && preg_match($this->fullPattern, $value));
120
                if ($valid && $this->checkDNS) {
121
                    $valid = $this->isDNSValid($matches['domain']);
122
                }
123
            }
124
        }
125
126 1
        return $valid ? null : [$this->message, []];
127
    }
128 1
129
    /**
130
     * @param string $domain
131 1
     * @return bool if DNS records for domain are valid
132
     * @see https://github.com/yiisoft/yii2/issues/17083
133 1
     */
134 1
    protected function isDNSValid($domain)
135 1
    {
136
        return $this->hasDNSRecord($domain, true) || $this->hasDNSRecord($domain, false);
137
    }
138
139
    private function hasDNSRecord($domain, $isMX)
140 1
    {
141
        $normalizedDomain = $domain . '.';
142
        if (!checkdnsrr($normalizedDomain, ($isMX ? 'MX' : 'A'))) {
143
            return false;
144
        }
145 1
146
        try {
147
            // dns_get_record can return false and emit Warning that may or may not be converted to ErrorException
148 18
            $records = dns_get_record($normalizedDomain, ($isMX ? DNS_MX : DNS_A));
149
        } catch (ErrorException $exception) {
150 18
            return false;
151
        }
152
153
        return !empty($records);
154
    }
155 18
156
    private function idnToAscii($idn)
157
    {
158
        if (PHP_VERSION_ID < 50600) {
159
            // TODO: drop old PHP versions support
160
            return idn_to_ascii($idn);
161
        }
162
163
        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 18
        return $options;
199
    }
200 18
201 18
    /**
202 11
     * @param string $value
203 6
     * @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
    private function idnToAsciiWithFallback($value)
207 13
    {
208
        $ascii = $this->idnToAscii($value);
209
        if ($ascii === false) {
210
            if (preg_match($this->patternASCII, $value) || ($this->allowName && preg_match($this->fullPatternASCII, $value))) {
211
                return $value;
212
            }
213
        }
214
215
        return $ascii;
216
    }
217
}
218