Debian Codegraph @

vendor/pear/mail/Mail/RFC822.php

raw
1 <?php
2 /**
3 * RFC 822 Email address list validation Utility
4 *
5 * PHP version 5
6 *
7 * LICENSE:
8 *
9 * Copyright (c) 2001-2017, Chuck Hagenbuch & 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 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 *
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 *
23 * 3. Neither the name of the copyright holder nor the names of its
24 * contributors may be used to endorse or promote products derived from
25 * this software without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 *
39 * @category Mail
40 * @package Mail
41 * @author Richard Heyes <[email protected]>
42 * @author Chuck Hagenbuch <[email protected]
43 * @copyright 2001-2017 Richard Heyes
44 * @license http://opensource.org/licenses/BSD-3-Clause New BSD License
45 * @version CVS: $Id$
46 * @link http://pear.php.net/package/Mail/
47 */
48
49 /**
50 * RFC 822 Email address list validation Utility
51 *
52 * What is it?
53 *
54 * This class will take an address string, and parse it into it's consituent
55 * parts, be that either addresses, groups, or combinations. Nested groups
56 * are not supported. The structure it returns is pretty straight forward,
57 * and is similar to that provided by the imap_rfc822_parse_adrlist(). Use
58 * print_r() to view the structure.
59 *
60 * How do I use it?
61 *
62 * $address_string = 'My Group: "Richard" <richard@localhost> (A comment), [email protected] (Ted Bloggs), Barney;';
63 * $parser = new Mail_RFC822();
64 * $structure = $parser->parseAddressList($address_string, 'example.com', true);
65 * print_r($structure);
66 *
67 * @author Richard Heyes <[email protected]>
68 * @author Chuck Hagenbuch <[email protected]>
69 * @version $Revision$
70 * @license BSD
71 * @package Mail
72 */
73 class Mail_RFC822 {
74
75 /**
76 * The address being parsed by the RFC822 object.
77 * @var string $address
78 */
79 var $address = '';
80
81 /**
82 * The default domain to use for unqualified addresses.
83 * @var string $default_domain
84 */
85 var $default_domain = 'localhost';
86
87 /**
88 * Should we return a nested array showing groups, or flatten everything?
89 * @var boolean $nestGroups
90 */
91 var $nestGroups = true;
92
93 /**
94 * Whether or not to validate atoms for non-ascii characters.
95 * @var boolean $validate
96 */
97 var $validate = true;
98
99 /**
100 * The array of raw addresses built up as we parse.
101 * @var array $addresses
102 */
103 var $addresses = array();
104
105 /**
106 * The final array of parsed address information that we build up.
107 * @var array $structure
108 */
109 var $structure = array();
110
111 /**
112 * The current error message, if any.
113 * @var string $error
114 */
115 var $error = null;
116
117 /**
118 * An internal counter/pointer.
119 * @var integer $index
120 */
121 var $index = null;
122
123 /**
124 * The number of groups that have been found in the address list.
125 * @var integer $num_groups
126 * @access public
127 */
128 var $num_groups = 0;
129
130 /**
131 * A variable so that we can tell whether or not we're inside a
132 * Mail_RFC822 object.
133 * @var boolean $mailRFC822
134 */
135 var $mailRFC822 = true;
136
137 /**
138 * A limit after which processing stops
139 * @var int $limit
140 */
141 var $limit = null;
142
143 /**
144 * Sets up the object. The address must either be set here or when
145 * calling parseAddressList(). One or the other.
146 *
147 * @param string $address The address(es) to validate.
148 * @param string $default_domain Default domain/host etc. If not supplied, will be set to localhost.
149 * @param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
150 * @param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
151 *
152 * @return object Mail_RFC822 A new Mail_RFC822 object.
153 */
154 public function __construct($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
155 {
156 if (isset($address)) $this->address = $address;
157 if (isset($default_domain)) $this->default_domain = $default_domain;
158 if (isset($nest_groups)) $this->nestGroups = $nest_groups;
159 if (isset($validate)) $this->validate = $validate;
160 if (isset($limit)) $this->limit = $limit;
161 }
162
163 /**
164 * Starts the whole process. The address must either be set here
165 * or when creating the object. One or the other.
166 *
167 * @param string $address The address(es) to validate.
168 * @param string $default_domain Default domain/host etc.
169 * @param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
170 * @param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
171 *
172 * @return array A structured array of addresses.
173 */
174 public function parseAddressList($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
175 {
176 if (version_compare(PHP_VERSION, '8.0.0', '<')) {
177 if (!isset($this) || !isset($this->mailRFC822)) {
178 $warn = "Calling non-static methods statically is no longer supported since PHP 8";
179 trigger_error($warn, E_USER_NOTICE);
180 $obj = new Mail_RFC822($address, $default_domain, $nest_groups, $validate, $limit);
181 return $obj->parseAddressList();
182 }
183 }
184
185 if (isset($address)) $this->address = $address;
186 if (isset($default_domain)) $this->default_domain = $default_domain;
187 if (isset($nest_groups)) $this->nestGroups = $nest_groups;
188 if (isset($validate)) $this->validate = $validate;
189 if (isset($limit)) $this->limit = $limit;
190
191 $this->structure = array();
192 $this->addresses = array();
193 $this->error = null;
194 $this->index = null;
195
196 // Unfold any long lines in $this->address.
197 $this->address = preg_replace('/\r?\n/', "\r\n", $this->address);
198 $this->address = preg_replace('/\r\n(\t| )+/', ' ', $this->address);
199
200 while ($this->address = $this->_splitAddresses($this->address));
201
202 if ($this->address === false || isset($this->error)) {
203 require_once 'PEAR.php';
204 return PEAR::raiseError($this->error);
205 }
206
207 // Validate each address individually. If we encounter an invalid
208 // address, stop iterating and return an error immediately.
209 foreach ($this->addresses as $address) {
210 $valid = $this->_validateAddress($address);
211
212 if ($valid === false || isset($this->error)) {
213 require_once 'PEAR.php';
214 return PEAR::raiseError($this->error);
215 }
216
217 if (!$this->nestGroups) {
218 $this->structure = array_merge($this->structure, $valid);
219 } else {
220 $this->structure[] = $valid;
221 }
222 }
223
224 return $this->structure;
225 }
226
227 /**
228 * Splits an address into separate addresses.
229 *
230 * @param string $address The addresses to split.
231 * @return boolean Success or failure.
232 */
233 protected function _splitAddresses($address)
234 {
235 $is_group = false;
236 $split_char = ',';
237
238 if (!empty($this->limit) && count($this->addresses) == $this->limit) {
239 return '';
240 }
241
242 if ($this->_isGroup($address) && !isset($this->error)) {
243 $split_char = ';';
244 $is_group = true;
245 } elseif (!isset($this->error)) {
246 $split_char = ',';
247 $is_group = false;
248 } elseif (isset($this->error)) {
249 return false;
250 }
251
252 // Split the string based on the above ten or so lines.
253 $parts = explode($split_char, $address);
254 $string = $this->_splitCheck($parts, $split_char);
255
256 // If a group...
257 if ($is_group) {
258 // If $string does not contain a colon outside of
259 // brackets/quotes etc then something's fubar.
260
261 // First check there's a colon at all:
262 if (strpos($string, ':') === false) {
263 $this->error = 'Invalid address: ' . $string;
264 return false;
265 }
266
267 // Now check it's outside of brackets/quotes:
268 if (!$this->_splitCheck(explode(':', $string), ':')) {
269 return false;
270 }
271
272 // We must have a group at this point, so increase the counter:
273 $this->num_groups++;
274 }
275
276 // $string now contains the first full address/group.
277 // Add to the addresses array.
278 $this->addresses[] = array(
279 'address' => trim($string),
280 'group' => $is_group
281 );
282
283 // Remove the now stored address from the initial line, the +1
284 // is to account for the explode character.
285 $address = trim(substr($address, strlen($string) + 1));
286
287 // If the next char is a comma and this was a group, then
288 // there are more addresses, otherwise, if there are any more
289 // chars, then there is another address.
290 if ($is_group && substr($address, 0, 1) == ','){
291 $address = trim(substr($address, 1));
292 return $address;
293
294 } elseif (strlen($address) > 0) {
295 return $address;
296
297 } else {
298 return '';
299 }
300
301 // If you got here then something's off
302 return false;
303 }
304
305 /**
306 * Checks for a group at the start of the string.
307 *
308 * @param string $address The address to check.
309 * @return boolean Whether or not there is a group at the start of the string.
310 */
311 protected function _isGroup($address)
312 {
313 // First comma not in quotes, angles or escaped:
314 $parts = explode(',', $address);
315 $string = $this->_splitCheck($parts, ',');
316
317 // Now we have the first address, we can reliably check for a
318 // group by searching for a colon that's not escaped or in
319 // quotes or angle brackets.
320 if (count($parts = explode(':', $string)) > 1) {
321 $string2 = $this->_splitCheck($parts, ':');
322 return ($string2 !== $string);
323 } else {
324 return false;
325 }
326 }
327
328 /**
329 * A common function that will check an exploded string.
330 *
331 * @param array $parts The exloded string.
332 * @param string $char The char that was exploded on.
333 * @return mixed False if the string contains unclosed quotes/brackets, or the string on success.
334 */
335 protected function _splitCheck($parts, $char)
336 {
337 $string = $parts[0];
338
339 for ($i = 0; $i < count($parts); $i++) {
340 if ($this->_hasUnclosedQuotes($string)
341 || $this->_hasUnclosedBrackets($string, '<>')
342 || $this->_hasUnclosedBrackets($string, '[]')
343 || $this->_hasUnclosedBrackets($string, '()')
344 || substr($string, -1) == '\\') {
345 if (isset($parts[$i + 1])) {
346 $string = $string . $char . $parts[$i + 1];
347 } else {
348 $this->error = 'Invalid address spec. Unclosed bracket or quotes';
349 return false;
350 }
351 } else {
352 $this->index = $i;
353 break;
354 }
355 }
356
357 return $string;
358 }
359
360 /**
361 * Checks if a string has unclosed quotes or not.
362 *
363 * @param string $string The string to check.
364 * @return boolean True if there are unclosed quotes inside the string,
365 * false otherwise.
366 */
367 protected function _hasUnclosedQuotes($string)
368 {
369 $string = trim($string);
370 $iMax = strlen($string);
371 $in_quote = false;
372 $i = $slashes = 0;
373
374 for (; $i < $iMax; ++$i) {
375 switch ($string[$i]) {
376 case '\\':
377 ++$slashes;
378 break;
379
380 case '"':
381 if ($slashes % 2 == 0) {
382 $in_quote = !$in_quote;
383 }
384 // Fall through to default action below.
385
386 default:
387 $slashes = 0;
388 break;
389 }
390 }
391
392 return $in_quote;
393 }
394
395 /**
396 * Checks if a string has an unclosed brackets or not. IMPORTANT:
397 * This function handles both angle brackets and square brackets;
398 *
399 * @param string $string The string to check.
400 * @param string $chars The characters to check for.
401 * @return boolean True if there are unclosed brackets inside the string, false otherwise.
402 */
403 protected function _hasUnclosedBrackets($string, $chars)
404 {
405 $num_angle_start = substr_count($string, $chars[0]);
406 $num_angle_end = substr_count($string, $chars[1]);
407
408 $this->_hasUnclosedBracketsSub($string, $num_angle_start, $chars[0]);
409 $this->_hasUnclosedBracketsSub($string, $num_angle_end, $chars[1]);
410
411 if ($num_angle_start < $num_angle_end) {
412 $this->error = 'Invalid address spec. Unmatched quote or bracket (' . $chars . ')';
413 return false;
414 } else {
415 return ($num_angle_start > $num_angle_end);
416 }
417 }
418
419 /**
420 * Sub function that is used only by hasUnclosedBrackets().
421 *
422 * @param string $string The string to check.
423 * @param integer &$num The number of occurences.
424 * @param string $char The character to count.
425 * @return integer The number of occurences of $char in $string, adjusted for backslashes.
426 */
427 protected function _hasUnclosedBracketsSub($string, &$num, $char)
428 {
429 $parts = explode($char, $string);
430 for ($i = 0; $i < count($parts); $i++){
431 if (substr($parts[$i], -1) == '\\' || $this->_hasUnclosedQuotes($parts[$i]))
432 $num--;
433 if (isset($parts[$i + 1]))
434 $parts[$i + 1] = $parts[$i] . $char . $parts[$i + 1];
435 }
436
437 return $num;
438 }
439
440 /**
441 * Function to begin checking the address.
442 *
443 * @param string $address The address to validate.
444 * @return mixed False on failure, or a structured array of address information on success.
445 */
446 protected function _validateAddress($address)
447 {
448 $structure = null;
449 $is_group = false;
450 $addresses = array();
451
452 if ($address['group']) {
453 $is_group = true;
454
455 // Get the group part of the name
456 $parts = explode(':', $address['address']);
457 $groupname = $this->_splitCheck($parts, ':');
458 $structure = array();
459
460 // And validate the group part of the name.
461 if (!$this->_validatePhrase($groupname)){
462 $this->error = 'Group name did not validate.';
463 return false;
464 } else {
465 // Don't include groups if we are not nesting
466 // them. This avoids returning invalid addresses.
467 if ($this->nestGroups) {
468 $structure = new stdClass;
469 $structure->groupname = $groupname;
470 }
471 }
472
473 $address['address'] = ltrim(substr($address['address'], strlen($groupname . ':')));
474 }
475
476 // If a group then split on comma and put into an array.
477 // Otherwise, Just put the whole address in an array.
478 if ($is_group) {
479 while (strlen($address['address']) > 0) {
480 $parts = explode(',', $address['address']);
481 $addresses[] = $this->_splitCheck($parts, ',');
482 $address['address'] = trim(substr($address['address'], strlen(end($addresses) . ',')));
483 }
484 } else {
485 $addresses[] = $address['address'];
486 }
487
488 // Trim the whitespace from all of the address strings.
489 $addresses = array_map('trim', $addresses);
490
491 // Validate each mailbox.
492 // Format could be one of: name <[email protected]>
493 // [email protected]
494 // geezer
495 // ... or any other format valid by RFC 822.
496 for ($i = 0; $i < count($addresses); $i++) {
497 if (!$this->validateMailbox($addresses[$i])) {
498 if (empty($this->error)) {
499 $this->error = 'Validation failed for: ' . $addresses[$i];
500 }
501 return false;
502 }
503 }
504
505 // Nested format
506 if ($this->nestGroups) {
507 if ($is_group) {
508 $structure->addresses = $addresses;
509 } else {
510 $structure = $addresses[0];
511 }
512
513 // Flat format
514 } else {
515 if ($is_group) {
516 $structure = array_merge($structure, $addresses);
517 } else {
518 $structure = $addresses;
519 }
520 }
521
522 return $structure;
523 }
524
525 /**
526 * Function to validate a phrase.
527 *
528 * @param string $phrase The phrase to check.
529 * @return boolean Success or failure.
530 */
531 protected function _validatePhrase($phrase)
532 {
533 // Splits on one or more Tab or space.
534 $parts = preg_split('/[ \\x09]+/', $phrase, -1, PREG_SPLIT_NO_EMPTY);
535
536 $phrase_parts = array();
537 while (count($parts) > 0){
538 $phrase_parts[] = $this->_splitCheck($parts, ' ');
539 for ($i = 0; $i < $this->index + 1; $i++)
540 array_shift($parts);
541 }
542
543 foreach ($phrase_parts as $part) {
544 // If quoted string:
545 if (substr($part, 0, 1) == '"') {
546 if (!$this->_validateQuotedString($part)) {
547 return false;
548 }
549 continue;
550 }
551
552 // Otherwise it's an atom:
553 if (!$this->_validateAtom($part)) return false;
554 }
555
556 return true;
557 }
558
559 /**
560 * Function to validate an atom which from rfc822 is:
561 * atom = 1*<any CHAR except specials, SPACE and CTLs>
562 *
563 * If validation ($this->validate) has been turned off, then
564 * validateAtom() doesn't actually check anything. This is so that you
565 * can split a list of addresses up before encoding personal names
566 * (umlauts, etc.), for example.
567 *
568 * @param string $atom The string to check.
569 * @return boolean Success or failure.
570 */
571 protected function _validateAtom($atom)
572 {
573 if (!$this->validate) {
574 // Validation has been turned off; assume the atom is okay.
575 return true;
576 }
577
578 // Check for any char from ASCII 0 - ASCII 127
579 if (!preg_match('/^[\\x00-\\x7E]+$/i', $atom, $matches)) {
580 return false;
581 }
582
583 // Check for specials:
584 if (preg_match('/[][()<>@,;\\:". ]/', $atom)) {
585 return false;
586 }
587
588 // Check for control characters (ASCII 0-31):
589 if (preg_match('/[\\x00-\\x1F]+/', $atom)) {
590 return false;
591 }
592
593 return true;
594 }
595
596 /**
597 * Function to validate quoted string, which is:
598 * quoted-string = <"> *(qtext/quoted-pair) <">
599 *
600 * @param string $qstring The string to check
601 * @return boolean Success or failure.
602 */
603 protected function _validateQuotedString($qstring)
604 {
605 // Leading and trailing "
606 $qstring = substr($qstring, 1, -1);
607
608 // Perform check, removing quoted characters first.
609 return !preg_match('/[\x0D\\\\"]/', preg_replace('/\\\\./', '', $qstring));
610 }
611
612 /**
613 * Function to validate a mailbox, which is:
614 * mailbox = addr-spec ; simple address
615 * / phrase route-addr ; name and route-addr
616 *
617 * @param string &$mailbox The string to check.
618 * @return boolean Success or failure.
619 */
620 public function validateMailbox(&$mailbox)
621 {
622 // A couple of defaults.
623 $phrase = '';
624 $comment = '';
625 $comments = array();
626 $addr_spec = null;
627
628 // Catch any RFC822 comments and store them separately.
629 $_mailbox = $mailbox;
630 while (strlen(trim($_mailbox)) > 0) {
631 $parts = explode('(', $_mailbox);
632 $before_comment = $this->_splitCheck($parts, '(');
633 if ($before_comment != $_mailbox) {
634 // First char should be a (.
635 $comment = substr(str_replace($before_comment, '', $_mailbox), 1);
636 $parts = explode(')', $comment);
637 $comment = $this->_splitCheck($parts, ')');
638 $comments[] = $comment;
639
640 // +2 is for the brackets
641 $_mailbox = substr($_mailbox, strpos($_mailbox, '('.$comment)+strlen($comment)+2);
642 } else {
643 break;
644 }
645 }
646
647 foreach ($comments as $comment) {
648 $mailbox = str_replace("($comment)", '', $mailbox);
649 }
650
651 $mailbox = trim($mailbox);
652
653 // Check for name + route-addr
654 if (substr($mailbox, -1) == '>' && substr($mailbox, 0, 1) != '<') {
655 $parts = explode('<', $mailbox);
656 $name = $this->_splitCheck($parts, '<');
657
658 $phrase = trim($name);
659 $route_addr = trim(substr($mailbox, strlen($name.'<'), -1));
660
661 if ($this->_validatePhrase($phrase) === false || ($route_addr = $this->_validateRouteAddr($route_addr)) === false) {
662 return false;
663 }
664
665 // Only got addr-spec
666 } else {
667 // First snip angle brackets if present.
668 if (substr($mailbox, 0, 1) == '<' && substr($mailbox, -1) == '>') {
669 $addr_spec = substr($mailbox, 1, -1);
670 } else {
671 $addr_spec = $mailbox;
672 }
673
674 if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
675 return false;
676 }
677 }
678
679 // Construct the object that will be returned.
680 $mbox = new stdClass();
681
682 // Add the phrase (even if empty) and comments
683 $mbox->personal = $phrase;
684 $mbox->comment = isset($comments) ? $comments : array();
685
686 if (isset($route_addr)) {
687 $mbox->mailbox = $route_addr['local_part'];
688 $mbox->host = $route_addr['domain'];
689 $route_addr['adl'] !== '' ? $mbox->adl = $route_addr['adl'] : '';
690 } else {
691 $mbox->mailbox = $addr_spec['local_part'];
692 $mbox->host = $addr_spec['domain'];
693 }
694
695 $mailbox = $mbox;
696 return true;
697 }
698
699 /**
700 * This function validates a route-addr which is:
701 * route-addr = "<" [route] addr-spec ">"
702 *
703 * Angle brackets have already been removed at the point of
704 * getting to this function.
705 *
706 * @param string $route_addr The string to check.
707 * @return mixed False on failure, or an array containing validated address/route information on success.
708 */
709 protected function _validateRouteAddr($route_addr)
710 {
711 // Check for colon.
712 if (strpos($route_addr, ':') !== false) {
713 $parts = explode(':', $route_addr);
714 $route = $this->_splitCheck($parts, ':');
715 } else {
716 $route = $route_addr;
717 }
718
719 // If $route is same as $route_addr then the colon was in
720 // quotes or brackets or, of course, non existent.
721 if ($route === $route_addr){
722 unset($route);
723 $addr_spec = $route_addr;
724 if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
725 return false;
726 }
727 } else {
728 // Validate route part.
729 if (($route = $this->_validateRoute($route)) === false) {
730 return false;
731 }
732
733 $addr_spec = substr($route_addr, strlen($route . ':'));
734
735 // Validate addr-spec part.
736 if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
737 return false;
738 }
739 }
740
741 if (isset($route)) {
742 $return['adl'] = $route;
743 } else {
744 $return['adl'] = '';
745 }
746
747 $return = array_merge($return, $addr_spec);
748 return $return;
749 }
750
751 /**
752 * Function to validate a route, which is:
753 * route = 1#("@" domain) ":"
754 *
755 * @param string $route The string to check.
756 * @return mixed False on failure, or the validated $route on success.
757 */
758 protected function _validateRoute($route)
759 {
760 // Split on comma.
761 $domains = explode(',', trim($route));
762
763 foreach ($domains as $domain) {
764 $domain = str_replace('@', '', trim($domain));
765 if (!$this->_validateDomain($domain)) return false;
766 }
767
768 return $route;
769 }
770
771 /**
772 * Function to validate a domain, though this is not quite what
773 * you expect of a strict internet domain.
774 *
775 * domain = sub-domain *("." sub-domain)
776 *
777 * @param string $domain The string to check.
778 * @return mixed False on failure, or the validated domain on success.
779 */
780 protected function _validateDomain($domain)
781 {
782 // Note the different use of $subdomains and $sub_domains
783 $subdomains = explode('.', $domain);
784 $sub_domains = array();
785
786 while (count($subdomains) > 0) {
787 $sub_domains[] = $this->_splitCheck($subdomains, '.');
788 for ($i = 0; $i < $this->index + 1; $i++)
789 array_shift($subdomains);
790 }
791
792 foreach ($sub_domains as $sub_domain) {
793 if (!$this->_validateSubdomain(trim($sub_domain)))
794 return false;
795 }
796
797 // Managed to get here, so return input.
798 return $domain;
799 }
800
801 /**
802 * Function to validate a subdomain:
803 * subdomain = domain-ref / domain-literal
804 *
805 * @param string $subdomain The string to check.
806 * @return boolean Success or failure.
807 */
808 protected function _validateSubdomain($subdomain)
809 {
810 if (preg_match('|^\[(.*)]$|', $subdomain, $arr)){
811 if (!$this->_validateDliteral($arr[1])) return false;
812 } else {
813 if (!$this->_validateAtom($subdomain)) return false;
814 }
815
816 // Got here, so return successful.
817 return true;
818 }
819
820 /**
821 * Function to validate a domain literal:
822 * domain-literal = "[" *(dtext / quoted-pair) "]"
823 *
824 * @param string $dliteral The string to check.
825 * @return boolean Success or failure.
826 */
827 protected function _validateDliteral($dliteral)
828 {
829 return !preg_match('/(.)[][\x0D\\\\]/', $dliteral, $matches) && ((! isset($matches[1])) || $matches[1] != '\\');
830 }
831
832 /**
833 * Function to validate an addr-spec.
834 *
835 * addr-spec = local-part "@" domain
836 *
837 * @param string $addr_spec The string to check.
838 * @return mixed False on failure, or the validated addr-spec on success.
839 */
840 protected function _validateAddrSpec($addr_spec)
841 {
842 $addr_spec = trim($addr_spec);
843
844 // Split on @ sign if there is one.
845 if (strpos($addr_spec, '@') !== false) {
846 $parts = explode('@', $addr_spec);
847 $local_part = $this->_splitCheck($parts, '@');
848 $domain = substr($addr_spec, strlen($local_part . '@'));
849
850 // No @ sign so assume the default domain.
851 } else {
852 $local_part = $addr_spec;
853 $domain = $this->default_domain;
854 }
855
856 if (($local_part = $this->_validateLocalPart($local_part)) === false) return false;
857 if (($domain = $this->_validateDomain($domain)) === false) return false;
858
859 // Got here so return successful.
860 return array('local_part' => $local_part, 'domain' => $domain);
861 }
862
863 /**
864 * Function to validate the local part of an address:
865 * local-part = word *("." word)
866 *
867 * @param string $local_part
868 * @return mixed False on failure, or the validated local part on success.
869 */
870 protected function _validateLocalPart($local_part)
871 {
872 $parts = explode('.', $local_part);
873 $words = array();
874
875 // Split the local_part into words.
876 while (count($parts) > 0) {
877 $words[] = $this->_splitCheck($parts, '.');
878 for ($i = 0; $i < $this->index + 1; $i++) {
879 array_shift($parts);
880 }
881 }
882
883 // Validate each word.
884 foreach ($words as $word) {
885 // word cannot be empty (#17317)
886 if ($word === '') {
887 return false;
888 }
889 // If this word contains an unquoted space, it is invalid. (6.2.4)
890 if (strpos($word, ' ') && $word[0] !== '"')
891 {
892 return false;
893 }
894
895 if ($this->_validatePhrase(trim($word)) === false) return false;
896 }
897
898 // Managed to get here, so return the input.
899 return $local_part;
900 }
901
902 /**
903 * Returns an approximate count of how many addresses are in the
904 * given string. This is APPROXIMATE as it only splits based on a
905 * comma which has no preceding backslash. Could be useful as
906 * large amounts of addresses will end up producing *large*
907 * structures when used with parseAddressList().
908 *
909 * @param string $data Addresses to count
910 * @return int Approximate count
911 */
912 public function approximateCount($data)
913 {
914 return count(preg_split('/(?<!\\\\),/', $data));
915 }
916
917 /**
918 * This is a email validating function separate to the rest of the
919 * class. It simply validates whether an email is of the common
920 * internet form: <user>@<domain>. This can be sufficient for most
921 * people. Optional stricter mode can be utilised which restricts
922 * mailbox characters allowed to alphanumeric, full stop, hyphen
923 * and underscore.
924 *
925 * @param string $data Address to check
926 * @param boolean $strict Optional stricter mode
927 * @return mixed False if it fails, an indexed array
928 * username/domain if it matches
929 */
930 public function isValidInetAddress($data, $strict = false)
931 {
932 $regex = $strict ? '/^([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i' : '/^([*+!.&#$|\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i';
933 if (preg_match($regex, trim($data), $matches)) {
934 return array($matches[1], $matches[2]);
935 } else {
936 return false;
937 }
938 }
939
940 }