3 * RFC 822 Email address list validation Utility
9 * Copyright (c) 2001-2010, Richard Heyes
10 * All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
16 * o Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * o Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * o The names of the authors may not be used to endorse or promote
22 * products derived from this software without specific prior written
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 * @author Richard Heyes <richard@phpguru.org>
40 * @author Chuck Hagenbuch <chuck@horde.org
41 * @copyright 2001-2010 Richard Heyes
42 * @license http://opensource.org/licenses/bsd-license.php New BSD License
44 * @link http://pear.php.net/package/Mail/
48 * RFC 822 Email address list validation Utility
52 * This class will take an address string, and parse it into it's consituent
53 * parts, be that either addresses, groups, or combinations. Nested groups
54 * are not supported. The structure it returns is pretty straight forward,
55 * and is similar to that provided by the imap_rfc822_parse_adrlist(). Use
56 * print_r() to view the structure.
60 * $address_string = 'My Group: "Richard" <richard@localhost> (A comment), ted@example.com (Ted Bloggs), Barney;';
61 * $structure = Mail_RFC822::parseAddressList($address_string, 'example.com', true)
62 * print_r($structure);
64 * @author Richard Heyes <richard@phpguru.org>
65 * @author Chuck Hagenbuch <chuck@horde.org>
73 * The address being parsed by the RFC822 object.
74 * @var string $address
79 * The default domain to use for unqualified addresses.
80 * @var string $default_domain
82 var $default_domain = 'localhost';
85 * Should we return a nested array showing groups, or flatten everything?
86 * @var boolean $nestGroups
88 var $nestGroups = true;
91 * Whether or not to validate atoms for non-ascii characters.
92 * @var boolean $validate
97 * The array of raw addresses built up as we parse.
98 * @var array $addresses
100 var $addresses = array();
103 * The final array of parsed address information that we build up.
104 * @var array $structure
106 var $structure = array();
109 * The current error message, if any.
115 * An internal counter/pointer.
116 * @var integer $index
121 * The number of groups that have been found in the address list.
122 * @var integer $num_groups
128 * A variable so that we can tell whether or not we're inside a
129 * Mail_RFC822 object.
130 * @var boolean $mailRFC822
132 var $mailRFC822 = true;
135 * A limit after which processing stops
141 * Sets up the object. The address must either be set here or when
142 * calling parseAddressList(). One or the other.
144 * @param string $address The address(es) to validate.
145 * @param string $default_domain Default domain/host etc. If not supplied, will be set to localhost.
146 * @param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
147 * @param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
149 * @return object Mail_RFC822 A new Mail_RFC822 object.
151 public function __construct($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
153 if (isset($address)) $this->address = $address;
154 if (isset($default_domain)) $this->default_domain = $default_domain;
155 if (isset($nest_groups)) $this->nestGroups = $nest_groups;
156 if (isset($validate)) $this->validate = $validate;
157 if (isset($limit)) $this->limit = $limit;
161 * Starts the whole process. The address must either be set here
162 * or when creating the object. One or the other.
164 * @param string $address The address(es) to validate.
165 * @param string $default_domain Default domain/host etc.
166 * @param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
167 * @param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
169 * @return array A structured array of addresses.
171 public function parseAddressList($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
173 if (!isset($this) || !isset($this->mailRFC822)) {
174 $obj = new Mail_RFC822($address, $default_domain, $nest_groups, $validate, $limit);
175 return $obj->parseAddressList();
178 if (isset($address)) $this->address = $address;
179 if (isset($default_domain)) $this->default_domain = $default_domain;
180 if (isset($nest_groups)) $this->nestGroups = $nest_groups;
181 if (isset($validate)) $this->validate = $validate;
182 if (isset($limit)) $this->limit = $limit;
184 $this->structure = array();
185 $this->addresses = array();
189 // Unfold any long lines in $this->address.
190 $this->address = preg_replace('/\r?\n/', "\r\n", $this->address);
191 $this->address = preg_replace('/\r\n(\t| )+/', ' ', $this->address);
193 while ($this->address = $this->_splitAddresses($this->address));
195 if ($this->address === false || isset($this->error)) {
196 require_once 'PEAR.php';
197 return PEAR::raiseError($this->error);
200 // Validate each address individually. If we encounter an invalid
201 // address, stop iterating and return an error immediately.
202 foreach ($this->addresses as $address) {
203 $valid = $this->_validateAddress($address);
205 if ($valid === false || isset($this->error)) {
206 require_once 'PEAR.php';
207 return PEAR::raiseError($this->error);
210 if (!$this->nestGroups) {
211 $this->structure = array_merge($this->structure, $valid);
213 $this->structure[] = $valid;
217 return $this->structure;
221 * Splits an address into separate addresses.
223 * @param string $address The addresses to split.
224 * @return boolean Success or failure.
226 protected function _splitAddresses($address)
228 if (!empty($this->limit) && count($this->addresses) == $this->limit) {
232 if ($this->_isGroup($address) && !isset($this->error)) {
235 } elseif (!isset($this->error)) {
238 } elseif (isset($this->error)) {
242 // Split the string based on the above ten or so lines.
243 $parts = explode($split_char, $address);
244 $string = $this->_splitCheck($parts, $split_char);
248 // If $string does not contain a colon outside of
249 // brackets/quotes etc then something's fubar.
251 // First check there's a colon at all:
252 if (strpos($string, ':') === false) {
253 $this->error = 'Invalid address: ' . $string;
257 // Now check it's outside of brackets/quotes:
258 if (!$this->_splitCheck(explode(':', $string), ':')) {
262 // We must have a group at this point, so increase the counter:
266 // $string now contains the first full address/group.
267 // Add to the addresses array.
268 $this->addresses[] = array(
269 'address' => trim($string),
273 // Remove the now stored address from the initial line, the +1
274 // is to account for the explode character.
275 $address = trim(substr($address, strlen($string) + 1));
277 // If the next char is a comma and this was a group, then
278 // there are more addresses, otherwise, if there are any more
279 // chars, then there is another address.
280 if ($is_group && substr($address, 0, 1) == ','){
281 $address = trim(substr($address, 1));
284 } elseif (strlen($address) > 0) {
291 // If you got here then something's off
296 * Checks for a group at the start of the string.
298 * @param string $address The address to check.
299 * @return boolean Whether or not there is a group at the start of the string.
301 protected function _isGroup($address)
303 // First comma not in quotes, angles or escaped:
304 $parts = explode(',', $address);
305 $string = $this->_splitCheck($parts, ',');
307 // Now we have the first address, we can reliably check for a
308 // group by searching for a colon that's not escaped or in
309 // quotes or angle brackets.
310 if (count($parts = explode(':', $string)) > 1) {
311 $string2 = $this->_splitCheck($parts, ':');
312 return ($string2 !== $string);
319 * A common function that will check an exploded string.
321 * @param array $parts The exloded string.
322 * @param string $char The char that was exploded on.
323 * @return mixed False if the string contains unclosed quotes/brackets, or the string on success.
325 protected function _splitCheck($parts, $char)
329 for ($i = 0; $i < count($parts); $i++) {
330 if ($this->_hasUnclosedQuotes($string)
331 || $this->_hasUnclosedBrackets($string, '<>')
332 || $this->_hasUnclosedBrackets($string, '[]')
333 || $this->_hasUnclosedBrackets($string, '()')
334 || substr($string, -1) == '\\') {
335 if (isset($parts[$i + 1])) {
336 $string = $string . $char . $parts[$i + 1];
338 $this->error = 'Invalid address spec. Unclosed bracket or quotes';
351 * Checks if a string has unclosed quotes or not.
353 * @param string $string The string to check.
354 * @return boolean True if there are unclosed quotes inside the string,
357 protected function _hasUnclosedQuotes($string)
359 $string = trim($string);
360 $iMax = strlen($string);
364 for (; $i < $iMax; ++$i) {
365 switch ($string[$i]) {
371 if ($slashes % 2 == 0) {
372 $in_quote = !$in_quote;
374 // Fall through to default action below.
386 * Checks if a string has an unclosed brackets or not. IMPORTANT:
387 * This function handles both angle brackets and square brackets;
389 * @param string $string The string to check.
390 * @param string $chars The characters to check for.
391 * @return boolean True if there are unclosed brackets inside the string, false otherwise.
393 protected function _hasUnclosedBrackets($string, $chars)
395 $num_angle_start = substr_count($string, $chars[0]);
396 $num_angle_end = substr_count($string, $chars[1]);
398 $this->_hasUnclosedBracketsSub($string, $num_angle_start, $chars[0]);
399 $this->_hasUnclosedBracketsSub($string, $num_angle_end, $chars[1]);
401 if ($num_angle_start < $num_angle_end) {
402 $this->error = 'Invalid address spec. Unmatched quote or bracket (' . $chars . ')';
405 return ($num_angle_start > $num_angle_end);
410 * Sub function that is used only by hasUnclosedBrackets().
412 * @param string $string The string to check.
413 * @param integer &$num The number of occurences.
414 * @param string $char The character to count.
415 * @return integer The number of occurences of $char in $string, adjusted for backslashes.
417 protected function _hasUnclosedBracketsSub($string, &$num, $char)
419 $parts = explode($char, $string);
420 for ($i = 0; $i < count($parts); $i++){
421 if (substr($parts[$i], -1) == '\\' || $this->_hasUnclosedQuotes($parts[$i]))
423 if (isset($parts[$i + 1]))
424 $parts[$i + 1] = $parts[$i] . $char . $parts[$i + 1];
431 * Function to begin checking the address.
433 * @param string $address The address to validate.
434 * @return mixed False on failure, or a structured array of address information on success.
436 protected function _validateAddress($address)
439 $addresses = array();
441 if ($address['group']) {
444 // Get the group part of the name
445 $parts = explode(':', $address['address']);
446 $groupname = $this->_splitCheck($parts, ':');
447 $structure = array();
449 // And validate the group part of the name.
450 if (!$this->_validatePhrase($groupname)){
451 $this->error = 'Group name did not validate.';
454 // Don't include groups if we are not nesting
455 // them. This avoids returning invalid addresses.
456 if ($this->nestGroups) {
457 $structure = new stdClass;
458 $structure->groupname = $groupname;
462 $address['address'] = ltrim(substr($address['address'], strlen($groupname . ':')));
465 // If a group then split on comma and put into an array.
466 // Otherwise, Just put the whole address in an array.
468 while (strlen($address['address']) > 0) {
469 $parts = explode(',', $address['address']);
470 $addresses[] = $this->_splitCheck($parts, ',');
471 $address['address'] = trim(substr($address['address'], strlen(end($addresses) . ',')));
474 $addresses[] = $address['address'];
477 // Trim the whitespace from all of the address strings.
478 array_map('trim', $addresses);
480 // Validate each mailbox.
481 // Format could be one of: name <geezer@domain.com>
484 // ... or any other format valid by RFC 822.
485 for ($i = 0; $i < count($addresses); $i++) {
486 if (!$this->validateMailbox($addresses[$i])) {
487 if (empty($this->error)) {
488 $this->error = 'Validation failed for: ' . $addresses[$i];
495 if ($this->nestGroups) {
497 $structure->addresses = $addresses;
499 $structure = $addresses[0];
505 $structure = array_merge($structure, $addresses);
507 $structure = $addresses;
515 * Function to validate a phrase.
517 * @param string $phrase The phrase to check.
518 * @return boolean Success or failure.
520 protected function _validatePhrase($phrase)
522 // Splits on one or more Tab or space.
523 $parts = preg_split('/[ \\x09]+/', $phrase, -1, PREG_SPLIT_NO_EMPTY);
525 $phrase_parts = array();
526 while (count($parts) > 0){
527 $phrase_parts[] = $this->_splitCheck($parts, ' ');
528 for ($i = 0; $i < $this->index + 1; $i++)
532 foreach ($phrase_parts as $part) {
534 if (substr($part, 0, 1) == '"') {
535 if (!$this->_validateQuotedString($part)) {
541 // Otherwise it's an atom:
542 if (!$this->_validateAtom($part)) return false;
549 * Function to validate an atom which from rfc822 is:
550 * atom = 1*<any CHAR except specials, SPACE and CTLs>
552 * If validation ($this->validate) has been turned off, then
553 * validateAtom() doesn't actually check anything. This is so that you
554 * can split a list of addresses up before encoding personal names
555 * (umlauts, etc.), for example.
557 * @param string $atom The string to check.
558 * @return boolean Success or failure.
560 protected function _validateAtom($atom)
562 if (!$this->validate) {
563 // Validation has been turned off; assume the atom is okay.
567 // Check for any char from ASCII 0 - ASCII 127
568 if (!preg_match('/^[\\x00-\\x7E]+$/i', $atom, $matches)) {
572 // Check for specials:
573 if (preg_match('/[][()<>@,;\\:". ]/', $atom)) {
577 // Check for control characters (ASCII 0-31):
578 if (preg_match('/[\\x00-\\x1F]+/', $atom)) {
586 * Function to validate quoted string, which is:
587 * quoted-string = <"> *(qtext/quoted-pair) <">
589 * @param string $qstring The string to check
590 * @return boolean Success or failure.
592 protected function _validateQuotedString($qstring)
594 // Leading and trailing "
595 $qstring = substr($qstring, 1, -1);
597 // Perform check, removing quoted characters first.
598 return !preg_match('/[\x0D\\\\"]/', preg_replace('/\\\\./', '', $qstring));
602 * Function to validate a mailbox, which is:
603 * mailbox = addr-spec ; simple address
604 * / phrase route-addr ; name and route-addr
606 * @param string &$mailbox The string to check.
607 * @return boolean Success or failure.
609 public function validateMailbox(&$mailbox)
611 // A couple of defaults.
616 // Catch any RFC822 comments and store them separately.
617 $_mailbox = $mailbox;
618 while (strlen(trim($_mailbox)) > 0) {
619 $parts = explode('(', $_mailbox);
620 $before_comment = $this->_splitCheck($parts, '(');
621 if ($before_comment != $_mailbox) {
622 // First char should be a (.
623 $comment = substr(str_replace($before_comment, '', $_mailbox), 1);
624 $parts = explode(')', $comment);
625 $comment = $this->_splitCheck($parts, ')');
626 $comments[] = $comment;
628 // +2 is for the brackets
629 $_mailbox = substr($_mailbox, strpos($_mailbox, '('.$comment)+strlen($comment)+2);
635 foreach ($comments as $comment) {
636 $mailbox = str_replace("($comment)", '', $mailbox);
639 $mailbox = trim($mailbox);
641 // Check for name + route-addr
642 if (substr($mailbox, -1) == '>' && substr($mailbox, 0, 1) != '<') {
643 $parts = explode('<', $mailbox);
644 $name = $this->_splitCheck($parts, '<');
646 $phrase = trim($name);
647 $route_addr = trim(substr($mailbox, strlen($name.'<'), -1));
649 if ($this->_validatePhrase($phrase) === false || ($route_addr = $this->_validateRouteAddr($route_addr)) === false) {
653 // Only got addr-spec
655 // First snip angle brackets if present.
656 if (substr($mailbox, 0, 1) == '<' && substr($mailbox, -1) == '>') {
657 $addr_spec = substr($mailbox, 1, -1);
659 $addr_spec = $mailbox;
662 if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
667 // Construct the object that will be returned.
668 $mbox = new stdClass();
670 // Add the phrase (even if empty) and comments
671 $mbox->personal = $phrase;
672 $mbox->comment = isset($comments) ? $comments : array();
674 if (isset($route_addr)) {
675 $mbox->mailbox = $route_addr['local_part'];
676 $mbox->host = $route_addr['domain'];
677 $route_addr['adl'] !== '' ? $mbox->adl = $route_addr['adl'] : '';
679 $mbox->mailbox = $addr_spec['local_part'];
680 $mbox->host = $addr_spec['domain'];
688 * This function validates a route-addr which is:
689 * route-addr = "<" [route] addr-spec ">"
691 * Angle brackets have already been removed at the point of
692 * getting to this function.
694 * @param string $route_addr The string to check.
695 * @return mixed False on failure, or an array containing validated address/route information on success.
697 protected function _validateRouteAddr($route_addr)
700 if (strpos($route_addr, ':') !== false) {
701 $parts = explode(':', $route_addr);
702 $route = $this->_splitCheck($parts, ':');
704 $route = $route_addr;
707 // If $route is same as $route_addr then the colon was in
708 // quotes or brackets or, of course, non existent.
709 if ($route === $route_addr){
711 $addr_spec = $route_addr;
712 if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
716 // Validate route part.
717 if (($route = $this->_validateRoute($route)) === false) {
721 $addr_spec = substr($route_addr, strlen($route . ':'));
723 // Validate addr-spec part.
724 if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
730 $return['adl'] = $route;
735 $return = array_merge($return, $addr_spec);
740 * Function to validate a route, which is:
741 * route = 1#("@" domain) ":"
743 * @param string $route The string to check.
744 * @return mixed False on failure, or the validated $route on success.
746 protected function _validateRoute($route)
749 $domains = explode(',', trim($route));
751 foreach ($domains as $domain) {
752 $domain = str_replace('@', '', trim($domain));
753 if (!$this->_validateDomain($domain)) return false;
760 * Function to validate a domain, though this is not quite what
761 * you expect of a strict internet domain.
763 * domain = sub-domain *("." sub-domain)
765 * @param string $domain The string to check.
766 * @return mixed False on failure, or the validated domain on success.
768 protected function _validateDomain($domain)
770 // Note the different use of $subdomains and $sub_domains
771 $subdomains = explode('.', $domain);
773 while (count($subdomains) > 0) {
774 $sub_domains[] = $this->_splitCheck($subdomains, '.');
775 for ($i = 0; $i < $this->index + 1; $i++)
776 array_shift($subdomains);
779 foreach ($sub_domains as $sub_domain) {
780 if (!$this->_validateSubdomain(trim($sub_domain)))
784 // Managed to get here, so return input.
789 * Function to validate a subdomain:
790 * subdomain = domain-ref / domain-literal
792 * @param string $subdomain The string to check.
793 * @return boolean Success or failure.
795 protected function _validateSubdomain($subdomain)
797 if (preg_match('|^\[(.*)]$|', $subdomain, $arr)){
798 if (!$this->_validateDliteral($arr[1])) return false;
800 if (!$this->_validateAtom($subdomain)) return false;
803 // Got here, so return successful.
808 * Function to validate a domain literal:
809 * domain-literal = "[" *(dtext / quoted-pair) "]"
811 * @param string $dliteral The string to check.
812 * @return boolean Success or failure.
814 protected function _validateDliteral($dliteral)
816 return !preg_match('/(.)[][\x0D\\\\]/', $dliteral, $matches) && $matches[1] != '\\';
820 * Function to validate an addr-spec.
822 * addr-spec = local-part "@" domain
824 * @param string $addr_spec The string to check.
825 * @return mixed False on failure, or the validated addr-spec on success.
827 protected function _validateAddrSpec($addr_spec)
829 $addr_spec = trim($addr_spec);
831 // Split on @ sign if there is one.
832 if (strpos($addr_spec, '@') !== false) {
833 $parts = explode('@', $addr_spec);
834 $local_part = $this->_splitCheck($parts, '@');
835 $domain = substr($addr_spec, strlen($local_part . '@'));
837 // No @ sign so assume the default domain.
839 $local_part = $addr_spec;
840 $domain = $this->default_domain;
843 if (($local_part = $this->_validateLocalPart($local_part)) === false) return false;
844 if (($domain = $this->_validateDomain($domain)) === false) return false;
846 // Got here so return successful.
847 return array('local_part' => $local_part, 'domain' => $domain);
851 * Function to validate the local part of an address:
852 * local-part = word *("." word)
854 * @param string $local_part
855 * @return mixed False on failure, or the validated local part on success.
857 protected function _validateLocalPart($local_part)
859 $parts = explode('.', $local_part);
862 // Split the local_part into words.
863 while (count($parts) > 0) {
864 $words[] = $this->_splitCheck($parts, '.');
865 for ($i = 0; $i < $this->index + 1; $i++) {
870 // Validate each word.
871 foreach ($words as $word) {
872 // word cannot be empty (#17317)
876 // If this word contains an unquoted space, it is invalid. (6.2.4)
877 if (strpos($word, ' ') && $word[0] !== '"')
882 if ($this->_validatePhrase(trim($word)) === false) return false;
885 // Managed to get here, so return the input.
890 * Returns an approximate count of how many addresses are in the
891 * given string. This is APPROXIMATE as it only splits based on a
892 * comma which has no preceding backslash. Could be useful as
893 * large amounts of addresses will end up producing *large*
894 * structures when used with parseAddressList().
896 * @param string $data Addresses to count
897 * @return int Approximate count
899 public function approximateCount($data)
901 return count(preg_split('/(?<!\\\\),/', $data));
905 * This is a email validating function separate to the rest of the
906 * class. It simply validates whether an email is of the common
907 * internet form: <user>@<domain>. This can be sufficient for most
908 * people. Optional stricter mode can be utilised which restricts
909 * mailbox characters allowed to alphanumeric, full stop, hyphen
912 * @param string $data Address to check
913 * @param boolean $strict Optional stricter mode
914 * @return mixed False if it fails, an indexed array
915 * username/domain if it matches
917 public function isValidInetAddress($data, $strict = false)
919 $regex = $strict ? '/^([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i' : '/^([*+!.&#$|\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i';
920 if (preg_match($regex, trim($data), $matches)) {
921 return array($matches[1], $matches[2]);