1: <?php
2: /**
3: * CEmailValidator class file.
4: *
5: * @author Qiang Xue <qiang.xue@gmail.com>
6: * @link http://www.yiiframework.com/
7: * @copyright 2008-2013 Yii Software LLC
8: * @license http://www.yiiframework.com/license/
9: */
10:
11: /**
12: * CEmailValidator validates that the attribute value is a valid email address.
13: *
14: * @author Qiang Xue <qiang.xue@gmail.com>
15: * @package system.validators
16: * @since 1.0
17: */
18: class CEmailValidator extends CValidator
19: {
20: /**
21: * @var string the regular expression used to validate the attribute value.
22: * @see http://www.regular-expressions.info/email.html
23: */
24: 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])?$/';
25: /**
26: * @var string the regular expression used to validate email addresses with the name part.
27: * This property is used only when {@link allowName} is true.
28: * @see allowName
29: */
30: 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])?>$/';
31: /**
32: * @var boolean whether to allow name in the email address (e.g. "Qiang Xue <qiang.xue@gmail.com>"). Defaults to false.
33: * @see fullPattern
34: */
35: public $allowName=false;
36: /**
37: * @var boolean whether to check the MX record for the email address.
38: * Defaults to false. To enable it, you need to make sure the PHP function 'checkdnsrr'
39: * exists in your PHP installation.
40: * Please note that this check may fail due to temporary problems even if email is deliverable.
41: */
42: public $checkMX=false;
43: /**
44: * @var boolean whether to check port 25 for the email address.
45: * Defaults to false. To enable it, ensure that the PHP functions 'dns_get_record' and
46: * 'fsockopen' are available in your PHP installation.
47: * Please note that this check may fail due to temporary problems even if email is deliverable.
48: */
49: public $checkPort=false;
50: /**
51: * @var boolean whether the attribute value can be null or empty. Defaults to true,
52: * meaning that if the attribute is empty, it is considered valid.
53: */
54: public $allowEmpty=true;
55: /**
56: * @var boolean whether validation process should care about IDN (internationalized domain names). Default
57: * value is false which means that validation of emails containing IDN will always fail.
58: * @since 1.1.13
59: */
60: public $validateIDN=false;
61:
62: /**
63: * Validates the attribute of the object.
64: * If there is any error, the error message is added to the object.
65: * @param CModel $object the object being validated
66: * @param string $attribute the attribute being validated
67: */
68: protected function validateAttribute($object,$attribute)
69: {
70: $value=$object->$attribute;
71:
72: if(!$this->validateValue($value))
73: {
74: $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is not a valid email address.');
75: $this->addError($object,$attribute,$message);
76: }
77: }
78:
79: /**
80: * Validates a static value to see if it is a valid email.
81: * Note that this method does not respect {@link allowEmpty} property.
82: * This method is provided so that you can call it directly without going through the model validation rule mechanism.
83: * @param mixed $value the value to be validated
84: * @return boolean whether the value is a valid email
85: * @since 1.1.1
86: */
87: public function validateValue($value)
88: {
89: if($this->allowEmpty && $this->isEmpty($value))
90: return true;
91:
92: if(is_string($value) && $this->validateIDN)
93: $value=$this->encodeIDN($value);
94: // make sure string length is limited to avoid DOS attacks
95: $valid=is_string($value) && strlen($value)<=254 && (preg_match($this->pattern,$value) || $this->allowName && preg_match($this->fullPattern,$value));
96: if($valid)
97: $domain=rtrim(substr($value,strpos($value,'@')+1),'>');
98: if($valid && $this->checkMX && function_exists('checkdnsrr'))
99: $valid=checkdnsrr($domain,'MX');
100: if($valid && $this->checkPort && function_exists('fsockopen') && function_exists('dns_get_record'))
101: $valid=$this->checkMxPorts($domain);
102: return $valid;
103: }
104:
105: /**
106: * Returns the JavaScript needed for performing client-side validation.
107: * @param CModel $object the data object being validated
108: * @param string $attribute the name of the attribute to be validated.
109: * @return string the client-side validation script.
110: * @see CActiveForm::enableClientValidation
111: * @since 1.1.7
112: */
113: public function clientValidateAttribute($object,$attribute)
114: {
115: if($this->validateIDN)
116: {
117: Yii::app()->getClientScript()->registerCoreScript('punycode');
118: // punycode.js works only with the domains - so we have to extract it before punycoding
119: $validateIDN='
120: var info = value.match(/^(.[^@]+)@(.+)$/);
121: if (info)
122: value = info[1] + "@" + punycode.toASCII(info[2]);
123: ';
124: }
125: else
126: $validateIDN='';
127:
128: $message=$this->message!==null ? $this->message : Yii::t('yii','{attribute} is not a valid email address.');
129: $message=strtr($message, array(
130: '{attribute}'=>$object->getAttributeLabel($attribute),
131: ));
132:
133: $condition="!value.match({$this->pattern})";
134: if($this->allowName)
135: $condition.=" && !value.match({$this->fullPattern})";
136:
137: return "
138: $validateIDN
139: if(".($this->allowEmpty ? "jQuery.trim(value)!='' && " : '').$condition.") {
140: messages.push(".CJSON::encode($message).");
141: }
142: ";
143: }
144:
145: /**
146: * Retrieves the list of MX records for $domain and checks if port 25
147: * is opened on any of these.
148: * @since 1.1.11
149: * @param string $domain domain to be checked
150: * @return boolean true if a reachable MX server has been found
151: */
152: protected function checkMxPorts($domain)
153: {
154: $records=dns_get_record($domain, DNS_MX);
155: if($records===false || empty($records))
156: return false;
157: usort($records,array($this,'mxSort'));
158: foreach($records as $record)
159: {
160: $handle=@fsockopen($record['target'],25);
161: if($handle!==false)
162: {
163: fclose($handle);
164: return true;
165: }
166: }
167: return false;
168: }
169:
170: /**
171: * Determines if one MX record has higher priority as another
172: * (i.e. 'pri' is lower). Used by {@link checkMxPorts}.
173: * @since 1.1.11
174: * @param mixed $a first item for comparison
175: * @param mixed $b second item for comparison
176: * @return boolean
177: */
178: protected function mxSort($a, $b)
179: {
180: return $a['pri']-$b['pri'];
181: }
182:
183: /**
184: * Converts given IDN to the punycode.
185: * @param string $value IDN to be converted.
186: * @return string resulting punycode.
187: * @since 1.1.13
188: */
189: private function encodeIDN($value)
190: {
191: if(preg_match_all('/^(.*)@(.*)$/',$value,$matches))
192: {
193: if(function_exists('idn_to_ascii'))
194: $value=$matches[1][0].'@'.idn_to_ascii($matches[2][0]);
195: else
196: {
197: require_once(Yii::getPathOfAlias('system.vendors.Net_IDNA2.Net').DIRECTORY_SEPARATOR.'IDNA2.php');
198: $idna=new Net_IDNA2();
199: $value=$matches[1][0].'@'.@$idna->encode($matches[2][0]);
200: }
201: }
202: return $value;
203: }
204: }
205: