ILIAS  release_5-3 Revision v5.3.23-19-g915713cf615
RFC822.php
Go to the documentation of this file.
1<?php
71{
72
77 public $address = '';
78
83 public $default_domain = 'localhost';
84
89 public $nestGroups = true;
90
95 public $validate = true;
96
101 public $addresses = array();
102
107 public $structure = array();
108
113 public $error = null;
114
119 public $index = null;
120
126 public $num_groups = 0;
127
133 public $mailRFC822 = true;
134
139 public $limit = null;
140
153 // php7-workaround alex: constructor
154 public function __construct($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
155 {
156 if (isset($address)) {
157 $this->address = $address;
158 }
159 if (isset($default_domain)) {
160 $this->default_domain = $default_domain;
161 }
162 if (isset($nest_groups)) {
163 $this->nestGroups = $nest_groups;
164 }
165 if (isset($validate)) {
166 $this->validate = $validate;
167 }
168 if (isset($limit)) {
169 $this->limit = $limit;
170 }
171 }
172
185 public function parseAddressList($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
186 {
187 if (!isset($this) || !isset($this->mailRFC822)) {
188 $obj = new Mail_RFC822($address, $default_domain, $nest_groups, $validate, $limit);
189 return $obj->parseAddressList();
190 }
191
192 if (isset($address)) {
193 $this->address = $address;
194 }
195 if (isset($default_domain)) {
196 $this->default_domain = $default_domain;
197 }
198 if (isset($nest_groups)) {
199 $this->nestGroups = $nest_groups;
200 }
201 if (isset($validate)) {
202 $this->validate = $validate;
203 }
204 if (isset($limit)) {
205 $this->limit = $limit;
206 }
207
208 $this->structure = array();
209 $this->addresses = array();
210 $this->error = null;
211 $this->index = null;
212
213 // Unfold any long lines in $this->address.
214 $this->address = preg_replace('/\r?\n/', "\r\n", $this->address);
215 $this->address = preg_replace('/\r\n(\t| )+/', ' ', $this->address);
216
217 while ($this->address = $this->_splitAddresses($this->address));
218
219 if ($this->address === false || isset($this->error)) {
220 // mjansen patch 14 Ap 2016 start
221 require_once 'Services/Mail/exceptions/class.ilMailException.php';
222 throw new ilMailException($this->error);
223 // mjansen patch 14 Ap 2016 end
224 }
225
226 // Validate each address individually. If we encounter an invalid
227 // address, stop iterating and return an error immediately.
228 foreach ($this->addresses as $address) {
229 $valid = $this->_validateAddress($address);
230
231 if ($valid === false || isset($this->error)) {
232 // mjansen patch 14 Ap 2016 start
233 require_once 'Services/Mail/exceptions/class.ilMailException.php';
234 throw new ilMailException($this->error);
235 // mjansen patch 14 Ap 2016 end
236 }
237
238 if (!$this->nestGroups) {
239 $this->structure = array_merge($this->structure, $valid);
240 } else {
241 $this->structure[] = $valid;
242 }
243 }
244
245 return $this->structure;
246 }
247
255 public function _splitAddresses($address)
256 {
257 if (!empty($this->limit) && count($this->addresses) == $this->limit) {
258 return '';
259 }
260
261 if ($this->_isGroup($address) && !isset($this->error)) {
262 $split_char = ';';
263 $is_group = true;
264 } elseif (!isset($this->error)) {
265 $split_char = ',';
266 $is_group = false;
267 } elseif (isset($this->error)) {
268 return false;
269 }
270
271 // Split the string based on the above ten or so lines.
272 $parts = explode($split_char, $address);
273 $string = $this->_splitCheck($parts, $split_char);
274
275 // If a group...
276 if ($is_group) {
277 // If $string does not contain a colon outside of
278 // brackets/quotes etc then something's fubar.
279
280 // First check there's a colon at all:
281 if (strpos($string, ':') === false) {
282 $this->error = 'Invalid address: ' . $string;
283 return false;
284 }
285
286 // Now check it's outside of brackets/quotes:
287 if (!$this->_splitCheck(explode(':', $string), ':')) {
288 return false;
289 }
290
291 // We must have a group at this point, so increase the counter:
292 $this->num_groups++;
293 }
294
295 // $string now contains the first full address/group.
296 // Add to the addresses array.
297 $this->addresses[] = array(
298 'address' => trim($string),
299 'group' => $is_group
300 );
301
302 // Remove the now stored address from the initial line, the +1
303 // is to account for the explode character.
304 $address = trim(substr($address, strlen($string) + 1));
305
306 // If the next char is a comma and this was a group, then
307 // there are more addresses, otherwise, if there are any more
308 // chars, then there is another address.
309 if ($is_group && substr($address, 0, 1) == ',') {
310 $address = trim(substr($address, 1));
311 return $address;
312 } elseif (strlen($address) > 0) {
313 return $address;
314 } else {
315 return '';
316 }
317
318 // If you got here then something's off
319 return false;
320 }
321
329 public function _isGroup($address)
330 {
331 // First comma not in quotes, angles or escaped:
332 $parts = explode(',', $address);
333 $string = $this->_splitCheck($parts, ',');
334
335 // Now we have the first address, we can reliably check for a
336 // group by searching for a colon that's not escaped or in
337 // quotes or angle brackets.
338 if (count($parts = explode(':', $string)) > 1) {
339 $string2 = $this->_splitCheck($parts, ':');
340 return ($string2 !== $string);
341 } else {
342 return false;
343 }
344 }
345
354 public function _splitCheck($parts, $char)
355 {
356 $string = $parts[0];
357
358 for ($i = 0; $i < count($parts); $i++) {
359 if ($this->_hasUnclosedQuotes($string)
360 || $this->_hasUnclosedBrackets($string, '<>')
361 || $this->_hasUnclosedBrackets($string, '[]')
362 || $this->_hasUnclosedBrackets($string, '()')
363 || substr($string, -1) == '\\') {
364 if (isset($parts[$i + 1])) {
365 $string = $string . $char . $parts[$i + 1];
366 } else {
367 $this->error = 'Invalid address spec. Unclosed bracket or quotes';
368 return false;
369 }
370 } else {
371 $this->index = $i;
372 break;
373 }
374 }
375
376 return $string;
377 }
378
387 public function _hasUnclosedQuotes($string)
388 {
389 $string = trim($string);
390 $iMax = strlen($string);
391 $in_quote = false;
392 $i = $slashes = 0;
393
394 for (; $i < $iMax; ++$i) {
395 switch ($string[$i]) {
396 case '\\':
397 ++$slashes;
398 break;
399
400 case '"':
401 if ($slashes % 2 == 0) {
402 $in_quote = !$in_quote;
403 }
404 // Fall through to default action below.
405
406 // no break
407 default:
408 $slashes = 0;
409 break;
410 }
411 }
412
413 return $in_quote;
414 }
415
425 public function _hasUnclosedBrackets($string, $chars)
426 {
427 $num_angle_start = substr_count($string, $chars[0]);
428 $num_angle_end = substr_count($string, $chars[1]);
429
430 $this->_hasUnclosedBracketsSub($string, $num_angle_start, $chars[0]);
431 $this->_hasUnclosedBracketsSub($string, $num_angle_end, $chars[1]);
432
433 if ($num_angle_start < $num_angle_end) {
434 $this->error = 'Invalid address spec. Unmatched quote or bracket (' . $chars . ')';
435 return false;
436 } else {
437 return ($num_angle_start > $num_angle_end);
438 }
439 }
440
450 public function _hasUnclosedBracketsSub($string, &$num, $char)
451 {
452 $parts = explode($char, $string);
453 for ($i = 0; $i < count($parts); $i++) {
454 if (substr($parts[$i], -1) == '\\' || $this->_hasUnclosedQuotes($parts[$i])) {
455 $num--;
456 }
457 if (isset($parts[$i + 1])) {
458 $parts[$i + 1] = $parts[$i] . $char . $parts[$i + 1];
459 }
460 }
461
462 return $num;
463 }
464
472 public function _validateAddress($address)
473 {
474 $is_group = false;
475 $addresses = array();
476
477 if ($address['group']) {
478 $is_group = true;
479
480 // Get the group part of the name
481 $parts = explode(':', $address['address']);
482 $groupname = $this->_splitCheck($parts, ':');
483 $structure = array();
484
485 // And validate the group part of the name.
486 if (!$this->_validatePhrase($groupname)) {
487 $this->error = 'Group name did not validate.';
488 return false;
489 } else {
490 // Don't include groups if we are not nesting
491 // them. This avoids returning invalid addresses.
492 if ($this->nestGroups) {
493 $structure = new stdClass;
494 $structure->groupname = $groupname;
495 }
496 }
497
498 $address['address'] = ltrim(substr($address['address'], strlen($groupname . ':')));
499 }
500
501 // If a group then split on comma and put into an array.
502 // Otherwise, Just put the whole address in an array.
503 if ($is_group) {
504 while (strlen($address['address']) > 0) {
505 $parts = explode(',', $address['address']);
506 $addresses[] = $this->_splitCheck($parts, ',');
507 $address['address'] = trim(substr($address['address'], strlen(end($addresses) . ',')));
508 }
509 } else {
510 $addresses[] = $address['address'];
511 }
512
513 // Check that $addresses is set, if address like this:
514 // Groupname:;
515 // Then errors were appearing.
516 if (!count($addresses)) {
517 $this->error = 'Empty group.';
518 return false;
519 }
520
521 // Trim the whitespace from all of the address strings.
522 array_map('trim', $addresses);
523
524 // Validate each mailbox.
525 // Format could be one of: name <geezer@domain.com>
526 // geezer@domain.com
527 // geezer
528 // ... or any other format valid by RFC 822.
529 for ($i = 0; $i < count($addresses); $i++) {
530 if (!$this->validateMailbox($addresses[$i])) {
531 if (empty($this->error)) {
532 $this->error = 'Validation failed for: ' . $addresses[$i];
533 }
534 return false;
535 }
536 }
537
538 // Nested format
539 if ($this->nestGroups) {
540 if ($is_group) {
541 $structure->addresses = $addresses;
542 } else {
544 }
545
546 // Flat format
547 } else {
548 if ($is_group) {
549 $structure = array_merge($structure, $addresses);
550 } else {
552 }
553 }
554
555 return $structure;
556 }
557
565 public function _validatePhrase($phrase)
566 {
567 // Splits on one or more Tab or space.
568 $parts = preg_split('/[ \\x09]+/', $phrase, -1, PREG_SPLIT_NO_EMPTY);
569
570 $phrase_parts = array();
571 while (count($parts) > 0) {
572 $phrase_parts[] = $this->_splitCheck($parts, ' ');
573 for ($i = 0; $i < $this->index + 1; $i++) {
574 array_shift($parts);
575 }
576 }
577
578 foreach ($phrase_parts as $part) {
579 // If quoted string:
580 if (substr($part, 0, 1) == '"') {
581 if (!$this->_validateQuotedString($part)) {
582 return false;
583 }
584 continue;
585 }
586
587 // Otherwise it's an atom:
588 if (!$this->_validateAtom($part)) {
589 return false;
590 }
591 }
592
593 return true;
594 }
595
609 public function _validateAtom($atom)
610 {
611 if (!$this->validate) {
612 // Validation has been turned off; assume the atom is okay.
613 return true;
614 }
615
616 // Check for any char from ASCII 0 - ASCII 127
617 // mjansen patch 16 Sep 2015 start
618 // Check for specials:
619 if (preg_match('/[][()<>@,;\\:". ]/', $atom)) {
620 return false;
621 }
622
623 // Check for control characters (ASCII 0-31):
624 if (preg_match('/[\\x00-\\x1F]+/', $atom)) {
625 return false;
626 }
627 #16291
628 #17618
629 if (!(bool) preg_match('//u', $atom)) {
630 return false;
631 }
632 // mjansen patch 16 Sep 2015 end
633
634 return true;
635 }
636
645 public function _validateQuotedString($qstring)
646 {
647 // Leading and trailing "
648 $qstring = substr($qstring, 1, -1);
649
650 // Perform check, removing quoted characters first.
651 return !preg_match('/[\x0D\\\\"]/', preg_replace('/\\\\./', '', $qstring));
652 }
653
663 public function validateMailbox(&$mailbox)
664 {
665 // A couple of defaults.
666 $phrase = '';
667 $comment = '';
668 $comments = array();
669
670 // Catch any RFC822 comments and store them separately.
671 $_mailbox = $mailbox;
672 while (strlen(trim($_mailbox)) > 0) {
673 $parts = explode('(', $_mailbox);
674 $before_comment = $this->_splitCheck($parts, '(');
675 if ($before_comment != $_mailbox) {
676 // First char should be a (.
677 $comment = substr(str_replace($before_comment, '', $_mailbox), 1);
678 $parts = explode(')', $comment);
679 $comment = $this->_splitCheck($parts, ')');
680 $comments[] = $comment;
681
682 // +2 is for the brackets
683 $_mailbox = substr($_mailbox, strpos($_mailbox, '(' . $comment)+strlen($comment)+2);
684 } else {
685 break;
686 }
687 }
688
689 foreach ($comments as $comment) {
690 $mailbox = str_replace("($comment)", '', $mailbox);
691 }
692
693 $mailbox = trim($mailbox);
694
695 // Check for name + route-addr
696 if (substr($mailbox, -1) == '>' && substr($mailbox, 0, 1) != '<') {
697 $parts = explode('<', $mailbox);
698 $name = $this->_splitCheck($parts, '<');
699
700 $phrase = trim($name);
701 $route_addr = trim(substr($mailbox, strlen($name . '<'), -1));
702
703 if ($this->_validatePhrase($phrase) === false || ($route_addr = $this->_validateRouteAddr($route_addr)) === false) {
704 return false;
705 }
706
707 // Only got addr-spec
708 } else {
709 // First snip angle brackets if present.
710 if (substr($mailbox, 0, 1) == '<' && substr($mailbox, -1) == '>') {
711 $addr_spec = substr($mailbox, 1, -1);
712 } else {
713 $addr_spec = $mailbox;
714 }
715
716 if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
717 return false;
718 }
719 }
720
721 // Construct the object that will be returned.
722 $mbox = new stdClass();
723
724 // Add the phrase (even if empty) and comments
725 $mbox->personal = $phrase;
726 $mbox->comment = isset($comments) ? $comments : array();
727
728 if (isset($route_addr)) {
729 $mbox->mailbox = $route_addr['local_part'];
730 $mbox->host = $route_addr['domain'];
731 $route_addr['adl'] !== '' ? $mbox->adl = $route_addr['adl'] : '';
732 } else {
733 $mbox->mailbox = $addr_spec['local_part'];
734 $mbox->host = $addr_spec['domain'];
735 }
736
737 $mailbox = $mbox;
738 return true;
739 }
740
752 public function _validateRouteAddr($route_addr)
753 {
754 // Check for colon.
755 if (strpos($route_addr, ':') !== false) {
756 $parts = explode(':', $route_addr);
757 $route = $this->_splitCheck($parts, ':');
758 } else {
759 $route = $route_addr;
760 }
761
762 // If $route is same as $route_addr then the colon was in
763 // quotes or brackets or, of course, non existent.
764 if ($route === $route_addr) {
765 unset($route);
766 $addr_spec = $route_addr;
767 if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
768 return false;
769 }
770 } else {
771 // Validate route part.
772 if (($route = $this->_validateRoute($route)) === false) {
773 return false;
774 }
775
776 $addr_spec = substr($route_addr, strlen($route . ':'));
777
778 // Validate addr-spec part.
779 if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
780 return false;
781 }
782 }
783
784 if (isset($route)) {
785 $return['adl'] = $route;
786 } else {
787 $return['adl'] = '';
788 }
789
790 $return = array_merge($return, $addr_spec);
791 return $return;
792 }
793
802 public function _validateRoute($route)
803 {
804 // Split on comma.
805 $domains = explode(',', trim($route));
806
807 foreach ($domains as $domain) {
808 $domain = str_replace('@', '', trim($domain));
809 if (!$this->_validateDomain($domain)) {
810 return false;
811 }
812 }
813
814 return $route;
815 }
816
827 public function _validateDomain($domain)
828 {
829 // Note the different use of $subdomains and $sub_domains
830 $subdomains = explode('.', $domain);
831
832 while (count($subdomains) > 0) {
833 $sub_domains[] = $this->_splitCheck($subdomains, '.');
834 for ($i = 0; $i < $this->index + 1; $i++) {
835 array_shift($subdomains);
836 }
837 }
838
839 foreach ($sub_domains as $sub_domain) {
840 if (!$this->_validateSubdomain(trim($sub_domain))) {
841 return false;
842 }
843 }
844
845 // Managed to get here, so return input.
846 return $domain;
847 }
848
857 public function _validateSubdomain($subdomain)
858 {
859 if (preg_match('|^\[(.*)]$|', $subdomain, $arr)) {
860 if (!$this->_validateDliteral($arr[1])) {
861 return false;
862 }
863 } else {
864 if (!$this->_validateAtom($subdomain)) {
865 return false;
866 }
867 }
868
869 // Got here, so return successful.
870 return true;
871 }
872
881 public function _validateDliteral($dliteral)
882 {
883 return !preg_match('/(.)[][\x0D\\\\]/', $dliteral, $matches) && $matches[1] != '\\';
884 }
885
895 public function _validateAddrSpec($addr_spec)
896 {
897 $addr_spec = trim($addr_spec);
898
899 // mjansen patch 16 Sep 2016 start
900 $validateState = $this->validate;
901 // mjansen patch 16 Sep 2016 end
902 // Split on @ sign if there is one.
903 if (strpos($addr_spec, '@') !== false) {
904 $parts = explode('@', $addr_spec);
905 $local_part = $this->_splitCheck($parts, '@');
906 $domain = substr($addr_spec, strlen($local_part . '@'));
907 // mjansen patch 16 Sep 2016 start
908 if (substr_count($addr_spec, '@') != 1 && $local_part == '') {
909 $this->validate = false;
910 $local_part = $addr_spec;
912 }
913 // mjansen patch 16 Sep 2016 end
914 // No @ sign so assume the default domain.
915 } else {
916 $local_part = $addr_spec;
918 }
919
920 if (($local_part = $this->_validateLocalPart($local_part)) === false) {
921 return false;
922 }
923 // mjansen patch 16 Sep 2016 start
924 if ($validateState != $this->validate) {
925 $this->validate = $validateState;
926 }
927 // mjansen patch 16 Sep 2016 end
928 if (($domain = $this->_validateDomain($domain)) === false) {
929 return false;
930 }
931
932 // Got here so return successful.
933 return array('local_part' => $local_part, 'domain' => $domain);
934 }
935
944 public function _validateLocalPart($local_part)
945 {
946 $parts = explode('.', $local_part);
947 $words = array();
948
949 // Split the local_part into words.
950 while (count($parts) > 0) {
951 $words[] = $this->_splitCheck($parts, '.');
952 for ($i = 0; $i < $this->index + 1; $i++) {
953 array_shift($parts);
954 }
955 }
956
957 // Validate each word.
958 foreach ($words as $word) {
959 // If this word contains an unquoted space, it is invalid. (6.2.4)
960 if (strpos($word, ' ') && $word[0] !== '"') {
961 // mjansen patch 24 Feb 2016 start
962 // Mantis issue #18018
963 // # http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx/
964 //return false;
965 // mjansen patch 24 Feb 2016 end
966 }
967
968 if ($this->_validatePhrase(trim($word)) === false) {
969 return false;
970 }
971 }
972
973 // Managed to get here, so return the input.
974 return $local_part;
975 }
976
987 public function approximateCount($data)
988 {
989 return count(preg_split('/(?<!\\\\),/', $data));
990 }
991
1005 public function isValidInetAddress($data, $strict = false)
1006 {
1007 $regex = $strict ? '/^([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i' : '/^([*+!.&#$|\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i';
1008 if (preg_match($regex, trim($data), $matches)) {
1009 return array($matches[1], $matches[2]);
1010 } else {
1011 return false;
1012 }
1013 }
1014}
$comment
Definition: buildRTE.php:83
if(!array_key_exists('domain', $_REQUEST)) $domain
Definition: resume.php:8
An exception for terminatinating execution or to throw for unit testing.
$error
The current error message, if any.
Definition: RFC822.php:113
$nestGroups
Should we return a nested array showing groups, or flatten everything?
Definition: RFC822.php:89
_validateSubdomain($subdomain)
Function to validate a subdomain: subdomain = domain-ref / domain-literal.
Definition: RFC822.php:857
_splitCheck($parts, $char)
A common function that will check an exploded string.
Definition: RFC822.php:354
isValidInetAddress($data, $strict=false)
This is a email validating function separate to the rest of the class.
Definition: RFC822.php:1005
_splitAddresses($address)
Splits an address into separate addresses.
Definition: RFC822.php:255
$mailRFC822
A variable so that we can tell whether or not we're inside a Mail_RFC822 object.
Definition: RFC822.php:133
$structure
The final array of parsed address information that we build up.
Definition: RFC822.php:107
$default_domain
The default domain to use for unqualified addresses.
Definition: RFC822.php:83
_validatePhrase($phrase)
Function to validate a phrase.
Definition: RFC822.php:565
_validateQuotedString($qstring)
Function to validate quoted string, which is: quoted-string = <"> *(qtext/quoted-pair) <">
Definition: RFC822.php:645
__construct($address=null, $default_domain=null, $nest_groups=null, $validate=null, $limit=null)
Sets up the object.
Definition: RFC822.php:154
_validateDliteral($dliteral)
Function to validate a domain literal: domain-literal = "[" *(dtext / quoted-pair) "]".
Definition: RFC822.php:881
_validateLocalPart($local_part)
Function to validate the local part of an address: local-part = word *("." word)
Definition: RFC822.php:944
parseAddressList($address=null, $default_domain=null, $nest_groups=null, $validate=null, $limit=null)
Starts the whole process.
Definition: RFC822.php:185
$validate
Whether or not to validate atoms for non-ascii characters.
Definition: RFC822.php:95
_hasUnclosedBracketsSub($string, &$num, $char)
Sub function that is used only by hasUnclosedBrackets().
Definition: RFC822.php:450
_validateAtom($atom)
Function to validate an atom which from rfc822 is: atom = 1*<any CHAR except specials,...
Definition: RFC822.php:609
_validateDomain($domain)
Function to validate a domain, though this is not quite what you expect of a strict internet domain.
Definition: RFC822.php:827
approximateCount($data)
Returns an approximate count of how many addresses are in the given string.
Definition: RFC822.php:987
validateMailbox(&$mailbox)
Function to validate a mailbox, which is: mailbox = addr-spec ; simple address / phrase route-addr ; ...
Definition: RFC822.php:663
_hasUnclosedQuotes($string)
Checks if a string has unclosed quotes or not.
Definition: RFC822.php:387
$addresses
The array of raw addresses built up as we parse.
Definition: RFC822.php:101
_validateAddrSpec($addr_spec)
Function to validate an addr-spec.
Definition: RFC822.php:895
_validateAddress($address)
Function to begin checking the address.
Definition: RFC822.php:472
_isGroup($address)
Checks for a group at the start of the string.
Definition: RFC822.php:329
_hasUnclosedBrackets($string, $chars)
Checks if a string has an unclosed brackets or not.
Definition: RFC822.php:425
$address
The address being parsed by the RFC822 object.
Definition: RFC822.php:77
$index
An internal counter/pointer.
Definition: RFC822.php:119
$num_groups
The number of groups that have been found in the address list.
Definition: RFC822.php:126
_validateRoute($route)
Function to validate a route, which is: route = 1#("@" domain) ":".
Definition: RFC822.php:802
$limit
A limit after which processing stops.
Definition: RFC822.php:139
_validateRouteAddr($route_addr)
This function validates a route-addr which is: route-addr = "<" [route] addr-spec ">".
Definition: RFC822.php:752
error($a_errmsg)
set error message @access public
Class ilMailException.
$i
Definition: disco.tpl.php:19
$valid
if($format !==null) $name
Definition: metadata.php:146