Updated PEAR and PEAR packages.
[timetracker.git] / WEB-INF / lib / pear / Mail / RFC822.php
1 <?php
2 /**
3  * RFC 822 Email address list validation Utility
4  *
5  * PHP version 5
6  *
7  * LICENSE:
8  *
9  * Copyright (c) 2001-2010, Richard Heyes
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  *
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
23  *   permission.
24  *
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.
36  *
37  * @category    Mail
38  * @package     Mail
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
43  * @version     CVS: $Id$
44  * @link        http://pear.php.net/package/Mail/
45  */
46
47 /**
48  * RFC 822 Email address list validation Utility
49  *
50  * What is it?
51  *
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.
57  *
58  * How do I use it?
59  *
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);
63  *
64  * @author  Richard Heyes <richard@phpguru.org>
65  * @author  Chuck Hagenbuch <chuck@horde.org>
66  * @version $Revision$
67  * @license BSD
68  * @package Mail
69  */
70 class Mail_RFC822 {
71
72     /**
73      * The address being parsed by the RFC822 object.
74      * @var string $address
75      */
76     var $address = '';
77
78     /**
79      * The default domain to use for unqualified addresses.
80      * @var string $default_domain
81      */
82     var $default_domain = 'localhost';
83
84     /**
85      * Should we return a nested array showing groups, or flatten everything?
86      * @var boolean $nestGroups
87      */
88     var $nestGroups = true;
89
90     /**
91      * Whether or not to validate atoms for non-ascii characters.
92      * @var boolean $validate
93      */
94     var $validate = true;
95
96     /**
97      * The array of raw addresses built up as we parse.
98      * @var array $addresses
99      */
100     var $addresses = array();
101
102     /**
103      * The final array of parsed address information that we build up.
104      * @var array $structure
105      */
106     var $structure = array();
107
108     /**
109      * The current error message, if any.
110      * @var string $error
111      */
112     var $error = null;
113
114     /**
115      * An internal counter/pointer.
116      * @var integer $index
117      */
118     var $index = null;
119
120     /**
121      * The number of groups that have been found in the address list.
122      * @var integer $num_groups
123      * @access public
124      */
125     var $num_groups = 0;
126
127     /**
128      * A variable so that we can tell whether or not we're inside a
129      * Mail_RFC822 object.
130      * @var boolean $mailRFC822
131      */
132     var $mailRFC822 = true;
133
134     /**
135     * A limit after which processing stops
136     * @var int $limit
137     */
138     var $limit = null;
139
140     /**
141      * Sets up the object. The address must either be set here or when
142      * calling parseAddressList(). One or the other.
143      *
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.
148      *
149      * @return object Mail_RFC822 A new Mail_RFC822 object.
150      */
151     public function __construct($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
152     {
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;
158     }
159
160     /**
161      * Starts the whole process. The address must either be set here
162      * or when creating the object. One or the other.
163      *
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.
168      *
169      * @return array A structured array of addresses.
170      */
171     public function parseAddressList($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
172     {
173         if (!isset($this) || !isset($this->mailRFC822)) {
174             $obj = new Mail_RFC822($address, $default_domain, $nest_groups, $validate, $limit);
175             return $obj->parseAddressList();
176         }
177
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;
183
184         $this->structure  = array();
185         $this->addresses  = array();
186         $this->error      = null;
187         $this->index      = null;
188
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);
192
193         while ($this->address = $this->_splitAddresses($this->address));
194
195         if ($this->address === false || isset($this->error)) {
196             require_once 'PEAR.php';
197             return PEAR::raiseError($this->error);
198         }
199
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);
204
205             if ($valid === false || isset($this->error)) {
206                 require_once 'PEAR.php';
207                 return PEAR::raiseError($this->error);
208             }
209
210             if (!$this->nestGroups) {
211                 $this->structure = array_merge($this->structure, $valid);
212             } else {
213                 $this->structure[] = $valid;
214             }
215         }
216
217         return $this->structure;
218     }
219
220     /**
221      * Splits an address into separate addresses.
222      *
223      * @param string $address The addresses to split.
224      * @return boolean Success or failure.
225      */
226     protected function _splitAddresses($address)
227     {
228         if (!empty($this->limit) && count($this->addresses) == $this->limit) {
229             return '';
230         }
231
232         if ($this->_isGroup($address) && !isset($this->error)) {
233             $split_char = ';';
234             $is_group   = true;
235         } elseif (!isset($this->error)) {
236             $split_char = ',';
237             $is_group   = false;
238         } elseif (isset($this->error)) {
239             return false;
240         }
241
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);
245
246         // If a group...
247         if ($is_group) {
248             // If $string does not contain a colon outside of
249             // brackets/quotes etc then something's fubar.
250
251             // First check there's a colon at all:
252             if (strpos($string, ':') === false) {
253                 $this->error = 'Invalid address: ' . $string;
254                 return false;
255             }
256
257             // Now check it's outside of brackets/quotes:
258             if (!$this->_splitCheck(explode(':', $string), ':')) {
259                 return false;
260             }
261
262             // We must have a group at this point, so increase the counter:
263             $this->num_groups++;
264         }
265
266         // $string now contains the first full address/group.
267         // Add to the addresses array.
268         $this->addresses[] = array(
269                                    'address' => trim($string),
270                                    'group'   => $is_group
271                                    );
272
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));
276
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));
282             return $address;
283
284         } elseif (strlen($address) > 0) {
285             return $address;
286
287         } else {
288             return '';
289         }
290
291         // If you got here then something's off
292         return false;
293     }
294
295     /**
296      * Checks for a group at the start of the string.
297      *
298      * @param string $address The address to check.
299      * @return boolean Whether or not there is a group at the start of the string.
300      */
301     protected function _isGroup($address)
302     {
303         // First comma not in quotes, angles or escaped:
304         $parts  = explode(',', $address);
305         $string = $this->_splitCheck($parts, ',');
306
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);
313         } else {
314             return false;
315         }
316     }
317
318     /**
319      * A common function that will check an exploded string.
320      *
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.
324      */
325     protected function _splitCheck($parts, $char)
326     {
327         $string = $parts[0];
328
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];
337                 } else {
338                     $this->error = 'Invalid address spec. Unclosed bracket or quotes';
339                     return false;
340                 }
341             } else {
342                 $this->index = $i;
343                 break;
344             }
345         }
346
347         return $string;
348     }
349
350     /**
351      * Checks if a string has unclosed quotes or not.
352      *
353      * @param string $string  The string to check.
354      * @return boolean  True if there are unclosed quotes inside the string,
355      *                  false otherwise.
356      */
357     protected function _hasUnclosedQuotes($string)
358     {
359         $string = trim($string);
360         $iMax = strlen($string);
361         $in_quote = false;
362         $i = $slashes = 0;
363
364         for (; $i < $iMax; ++$i) {
365             switch ($string[$i]) {
366             case '\\':
367                 ++$slashes;
368                 break;
369
370             case '"':
371                 if ($slashes % 2 == 0) {
372                     $in_quote = !$in_quote;
373                 }
374                 // Fall through to default action below.
375
376             default:
377                 $slashes = 0;
378                 break;
379             }
380         }
381
382         return $in_quote;
383     }
384
385     /**
386      * Checks if a string has an unclosed brackets or not. IMPORTANT:
387      * This function handles both angle brackets and square brackets;
388      *
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.
392      */
393     protected function _hasUnclosedBrackets($string, $chars)
394     {
395         $num_angle_start = substr_count($string, $chars[0]);
396         $num_angle_end   = substr_count($string, $chars[1]);
397
398         $this->_hasUnclosedBracketsSub($string, $num_angle_start, $chars[0]);
399         $this->_hasUnclosedBracketsSub($string, $num_angle_end, $chars[1]);
400
401         if ($num_angle_start < $num_angle_end) {
402             $this->error = 'Invalid address spec. Unmatched quote or bracket (' . $chars . ')';
403             return false;
404         } else {
405             return ($num_angle_start > $num_angle_end);
406         }
407     }
408
409     /**
410      * Sub function that is used only by hasUnclosedBrackets().
411      *
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.
416      */
417     protected function _hasUnclosedBracketsSub($string, &$num, $char)
418     {
419         $parts = explode($char, $string);
420         for ($i = 0; $i < count($parts); $i++){
421             if (substr($parts[$i], -1) == '\\' || $this->_hasUnclosedQuotes($parts[$i]))
422                 $num--;
423             if (isset($parts[$i + 1]))
424                 $parts[$i + 1] = $parts[$i] . $char . $parts[$i + 1];
425         }
426
427         return $num;
428     }
429
430     /**
431      * Function to begin checking the address.
432      *
433      * @param string $address The address to validate.
434      * @return mixed False on failure, or a structured array of address information on success.
435      */
436     protected function _validateAddress($address)
437     {
438         $is_group = false;
439         $addresses = array();
440
441         if ($address['group']) {
442             $is_group = true;
443
444             // Get the group part of the name
445             $parts     = explode(':', $address['address']);
446             $groupname = $this->_splitCheck($parts, ':');
447             $structure = array();
448
449             // And validate the group part of the name.
450             if (!$this->_validatePhrase($groupname)){
451                 $this->error = 'Group name did not validate.';
452                 return false;
453             } else {
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;
459                 }
460             }
461
462             $address['address'] = ltrim(substr($address['address'], strlen($groupname . ':')));
463         }
464
465         // If a group then split on comma and put into an array.
466         // Otherwise, Just put the whole address in an array.
467         if ($is_group) {
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) . ',')));
472             }
473         } else {
474             $addresses[] = $address['address'];
475         }
476
477         // Trim the whitespace from all of the address strings.
478         array_map('trim', $addresses);
479
480         // Validate each mailbox.
481         // Format could be one of: name <geezer@domain.com>
482         //                         geezer@domain.com
483         //                         geezer
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];
489                 }
490                 return false;
491             }
492         }
493
494         // Nested format
495         if ($this->nestGroups) {
496             if ($is_group) {
497                 $structure->addresses = $addresses;
498             } else {
499                 $structure = $addresses[0];
500             }
501
502         // Flat format
503         } else {
504             if ($is_group) {
505                 $structure = array_merge($structure, $addresses);
506             } else {
507                 $structure = $addresses;
508             }
509         }
510
511         return $structure;
512     }
513
514     /**
515      * Function to validate a phrase.
516      *
517      * @param string $phrase The phrase to check.
518      * @return boolean Success or failure.
519      */
520     protected function _validatePhrase($phrase)
521     {
522         // Splits on one or more Tab or space.
523         $parts = preg_split('/[ \\x09]+/', $phrase, -1, PREG_SPLIT_NO_EMPTY);
524
525         $phrase_parts = array();
526         while (count($parts) > 0){
527             $phrase_parts[] = $this->_splitCheck($parts, ' ');
528             for ($i = 0; $i < $this->index + 1; $i++)
529                 array_shift($parts);
530         }
531
532         foreach ($phrase_parts as $part) {
533             // If quoted string:
534             if (substr($part, 0, 1) == '"') {
535                 if (!$this->_validateQuotedString($part)) {
536                     return false;
537                 }
538                 continue;
539             }
540
541             // Otherwise it's an atom:
542             if (!$this->_validateAtom($part)) return false;
543         }
544
545         return true;
546     }
547
548     /**
549      * Function to validate an atom which from rfc822 is:
550      * atom = 1*<any CHAR except specials, SPACE and CTLs>
551      *
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.
556      *
557      * @param string $atom The string to check.
558      * @return boolean Success or failure.
559      */
560     protected function _validateAtom($atom)
561     {
562         if (!$this->validate) {
563             // Validation has been turned off; assume the atom is okay.
564             return true;
565         }
566
567         // Check for any char from ASCII 0 - ASCII 127
568         if (!preg_match('/^[\\x00-\\x7E]+$/i', $atom, $matches)) {
569             return false;
570         }
571
572         // Check for specials:
573         if (preg_match('/[][()<>@,;\\:". ]/', $atom)) {
574             return false;
575         }
576
577         // Check for control characters (ASCII 0-31):
578         if (preg_match('/[\\x00-\\x1F]+/', $atom)) {
579             return false;
580         }
581
582         return true;
583     }
584
585     /**
586      * Function to validate quoted string, which is:
587      * quoted-string = <"> *(qtext/quoted-pair) <">
588      *
589      * @param string $qstring The string to check
590      * @return boolean Success or failure.
591      */
592     protected function _validateQuotedString($qstring)
593     {
594         // Leading and trailing "
595         $qstring = substr($qstring, 1, -1);
596
597         // Perform check, removing quoted characters first.
598         return !preg_match('/[\x0D\\\\"]/', preg_replace('/\\\\./', '', $qstring));
599     }
600
601     /**
602      * Function to validate a mailbox, which is:
603      * mailbox =   addr-spec         ; simple address
604      *           / phrase route-addr ; name and route-addr
605      *
606      * @param string &$mailbox The string to check.
607      * @return boolean Success or failure.
608      */
609     public function validateMailbox(&$mailbox)
610     {
611         // A couple of defaults.
612         $phrase  = '';
613         $comment = '';
614         $comments = array();
615
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;
627
628                 // +2 is for the brackets
629                 $_mailbox = substr($_mailbox, strpos($_mailbox, '('.$comment)+strlen($comment)+2);
630             } else {
631                 break;
632             }
633         }
634
635         foreach ($comments as $comment) {
636             $mailbox = str_replace("($comment)", '', $mailbox);
637         }
638
639         $mailbox = trim($mailbox);
640
641         // Check for name + route-addr
642         if (substr($mailbox, -1) == '>' && substr($mailbox, 0, 1) != '<') {
643             $parts  = explode('<', $mailbox);
644             $name   = $this->_splitCheck($parts, '<');
645
646             $phrase     = trim($name);
647             $route_addr = trim(substr($mailbox, strlen($name.'<'), -1));
648
649             if ($this->_validatePhrase($phrase) === false || ($route_addr = $this->_validateRouteAddr($route_addr)) === false) {
650                 return false;
651             }
652
653         // Only got addr-spec
654         } else {
655             // First snip angle brackets if present.
656             if (substr($mailbox, 0, 1) == '<' && substr($mailbox, -1) == '>') {
657                 $addr_spec = substr($mailbox, 1, -1);
658             } else {
659                 $addr_spec = $mailbox;
660             }
661
662             if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
663                 return false;
664             }
665         }
666
667         // Construct the object that will be returned.
668         $mbox = new stdClass();
669
670         // Add the phrase (even if empty) and comments
671         $mbox->personal = $phrase;
672         $mbox->comment  = isset($comments) ? $comments : array();
673
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'] : '';
678         } else {
679             $mbox->mailbox = $addr_spec['local_part'];
680             $mbox->host    = $addr_spec['domain'];
681         }
682
683         $mailbox = $mbox;
684         return true;
685     }
686
687     /**
688      * This function validates a route-addr which is:
689      * route-addr = "<" [route] addr-spec ">"
690      *
691      * Angle brackets have already been removed at the point of
692      * getting to this function.
693      *
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.
696      */
697     protected function _validateRouteAddr($route_addr)
698     {
699         // Check for colon.
700         if (strpos($route_addr, ':') !== false) {
701             $parts = explode(':', $route_addr);
702             $route = $this->_splitCheck($parts, ':');
703         } else {
704             $route = $route_addr;
705         }
706
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){
710             unset($route);
711             $addr_spec = $route_addr;
712             if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
713                 return false;
714             }
715         } else {
716             // Validate route part.
717             if (($route = $this->_validateRoute($route)) === false) {
718                 return false;
719             }
720
721             $addr_spec = substr($route_addr, strlen($route . ':'));
722
723             // Validate addr-spec part.
724             if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
725                 return false;
726             }
727         }
728
729         if (isset($route)) {
730             $return['adl'] = $route;
731         } else {
732             $return['adl'] = '';
733         }
734
735         $return = array_merge($return, $addr_spec);
736         return $return;
737     }
738
739     /**
740      * Function to validate a route, which is:
741      * route = 1#("@" domain) ":"
742      *
743      * @param string $route The string to check.
744      * @return mixed False on failure, or the validated $route on success.
745      */
746     protected function _validateRoute($route)
747     {
748         // Split on comma.
749         $domains = explode(',', trim($route));
750
751         foreach ($domains as $domain) {
752             $domain = str_replace('@', '', trim($domain));
753             if (!$this->_validateDomain($domain)) return false;
754         }
755
756         return $route;
757     }
758
759     /**
760      * Function to validate a domain, though this is not quite what
761      * you expect of a strict internet domain.
762      *
763      * domain = sub-domain *("." sub-domain)
764      *
765      * @param string $domain The string to check.
766      * @return mixed False on failure, or the validated domain on success.
767      */
768     protected function _validateDomain($domain)
769     {
770         // Note the different use of $subdomains and $sub_domains
771         $subdomains = explode('.', $domain);
772
773         while (count($subdomains) > 0) {
774             $sub_domains[] = $this->_splitCheck($subdomains, '.');
775             for ($i = 0; $i < $this->index + 1; $i++)
776                 array_shift($subdomains);
777         }
778
779         foreach ($sub_domains as $sub_domain) {
780             if (!$this->_validateSubdomain(trim($sub_domain)))
781                 return false;
782         }
783
784         // Managed to get here, so return input.
785         return $domain;
786     }
787
788     /**
789      * Function to validate a subdomain:
790      *   subdomain = domain-ref / domain-literal
791      *
792      * @param string $subdomain The string to check.
793      * @return boolean Success or failure.
794      */
795     protected function _validateSubdomain($subdomain)
796     {
797         if (preg_match('|^\[(.*)]$|', $subdomain, $arr)){
798             if (!$this->_validateDliteral($arr[1])) return false;
799         } else {
800             if (!$this->_validateAtom($subdomain)) return false;
801         }
802
803         // Got here, so return successful.
804         return true;
805     }
806
807     /**
808      * Function to validate a domain literal:
809      *   domain-literal =  "[" *(dtext / quoted-pair) "]"
810      *
811      * @param string $dliteral The string to check.
812      * @return boolean Success or failure.
813      */
814     protected function _validateDliteral($dliteral)
815     {
816         return !preg_match('/(.)[][\x0D\\\\]/', $dliteral, $matches) && $matches[1] != '\\';
817     }
818
819     /**
820      * Function to validate an addr-spec.
821      *
822      * addr-spec = local-part "@" domain
823      *
824      * @param string $addr_spec The string to check.
825      * @return mixed False on failure, or the validated addr-spec on success.
826      */
827     protected function _validateAddrSpec($addr_spec)
828     {
829         $addr_spec = trim($addr_spec);
830
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 . '@'));
836
837         // No @ sign so assume the default domain.
838         } else {
839             $local_part = $addr_spec;
840             $domain     = $this->default_domain;
841         }
842
843         if (($local_part = $this->_validateLocalPart($local_part)) === false) return false;
844         if (($domain     = $this->_validateDomain($domain)) === false) return false;
845
846         // Got here so return successful.
847         return array('local_part' => $local_part, 'domain' => $domain);
848     }
849
850     /**
851      * Function to validate the local part of an address:
852      *   local-part = word *("." word)
853      *
854      * @param string $local_part
855      * @return mixed False on failure, or the validated local part on success.
856      */
857     protected function _validateLocalPart($local_part)
858     {
859         $parts = explode('.', $local_part);
860         $words = array();
861
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++) {
866                 array_shift($parts);
867             }
868         }
869
870         // Validate each word.
871         foreach ($words as $word) {
872             // word cannot be empty (#17317)
873             if ($word === '') {
874                 return false;
875             }
876             // If this word contains an unquoted space, it is invalid. (6.2.4)
877             if (strpos($word, ' ') && $word[0] !== '"')
878             {
879                 return false;
880             }
881
882             if ($this->_validatePhrase(trim($word)) === false) return false;
883         }
884
885         // Managed to get here, so return the input.
886         return $local_part;
887     }
888
889     /**
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().
895      *
896      * @param  string $data Addresses to count
897      * @return int          Approximate count
898      */
899     public function approximateCount($data)
900     {
901         return count(preg_split('/(?<!\\\\),/', $data));
902     }
903
904     /**
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
910      * and underscore.
911      *
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
916      */
917     public function isValidInetAddress($data, $strict = false)
918     {
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]);
922         } else {
923             return false;
924         }
925     }
926
927 }