8b77b8bb96d29818550e9d0455aa46d68d735beb
4 * Rfc822Header.class.php
6 * This file contains functions needed to handle headers in mime messages.
8 * @copyright 2003-2020 The SquirrelMail Project Team
9 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
11 * @package squirrelmail
18 * input: header_string or array
19 * You must call parseHeader() function after creating object in order to fill object's
21 * @todo FIXME: there is no constructor function and class should ignore all input args.
22 * @package squirrelmail
28 * All headers, unparsed
31 var $raw_headers = array();
38 * Original date header as fallback for unparsable dates
41 var $date_unparsed = '';
60 var $reply_to = array();
62 * Mail-Followup-To header
65 var $mail_followup_to = array();
85 var $in_reply_to = '';
101 * Content Type object
104 var $content_type = '';
108 var $disposition = '';
120 * Disposition notification for requesting message delivery notification (MDN)
125 * Delivery notification (DR)
136 var $content_id = '';
140 var $content_desc = '';
144 var $mlist = array();
146 * SpamAssassin 'x-spam-status' header
149 var $x_spam_status = array();
152 * only needed for constructing headers in delivery class
155 var $more_headers = array();
158 * @param mixed $hdr string or array with message headers
160 function parseHeader($hdr) {
161 if (is_array($hdr)) {
162 $hdr = implode('', $hdr);
164 /* First we replace \r\n by \n and unfold the header */
165 /* FIXME: unfolding header with multiple spaces "\n( +)" */
166 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $hdr));
168 /* Now we can make a new header array with */
169 /* each element representing a headerline */
170 $hdr = explode("\n" , $hdr);
171 foreach ($hdr as $line) {
172 $pos = strpos($line, ':');
174 $this->raw_headers
[] = $line;
175 $field = substr($line, 0, $pos);
176 if (!strstr($field,' ')) { /* valid field */
177 $value = trim(substr($line, $pos+
1));
178 $this->parseField($field, $value);
182 if (!is_object($this->content_type
)) {
183 $this->parseContentType('text/plain; charset=us-ascii');
188 * @param string $value
191 function stripComments($value) {
193 $cnt = strlen($value);
194 for ($i = 0; $i < $cnt; ++
$i) {
195 switch ($value{$i}) {
198 while ((++
$i < $cnt) && ($value{$i} != '"')) {
199 if ($value{$i} == '\\') {
203 $result .= $value{$i};
206 $result .= $value{$i};
211 while (($depth > 0) && (++
$i < $cnt)) {
228 $result .= $value{$i};
236 * Parse header field according to field type
237 * @param string $field field name
238 * @param string $value field value
240 function parseField($field, $value) {
241 $field = strtolower($field);
244 $value = $this->stripComments($value);
245 $d = strtr($value, array(' ' => ' '));
246 $d = explode(' ', $d);
247 $this->date
= getTimeStamp($d);
248 $this->date_unparsed
= strtr($value,'<>',' ');
251 $this->subject
= $value;
254 $this->from
= $this->parseAddress($value,true);
257 $this->sender
= $this->parseAddress($value);
260 $this->reply_to
= $this->parseAddress($value, true);
262 case 'mail-followup-to':
263 $this->mail_followup_to
= $this->parseAddress($value, true);
266 $this->to
= $this->parseAddress($value, true);
269 $this->cc
= $this->parseAddress($value, true);
272 $this->bcc
= $this->parseAddress($value, true);
275 $this->in_reply_to
= $value;
278 $value = $this->stripComments($value);
279 $this->message_id
= $value;
282 $value = $this->stripComments($value);
283 $this->references
= $value;
285 case 'x-confirm-reading-to':
286 case 'disposition-notification-to':
287 $value = $this->stripComments($value);
288 $this->dnt
= $this->parseAddress($value);
290 case 'return-receipt-to':
291 $value = $this->stripComments($value);
292 $this->drnt
= $this->parseAddress($value);
295 $value = $this->stripComments($value);
296 $value = str_replace(' ', '', $value);
297 $this->mime
= ($value == '1.0' ?
true : $this->mime
);
300 $value = $this->stripComments($value);
301 $this->parseContentType($value);
303 case 'content-disposition':
304 $value = $this->stripComments($value);
305 $this->parseDisposition($value);
307 case 'content-transfer-encoding':
308 $this->encoding
= $value;
310 case 'content-description':
311 $this->content_desc
= $value;
314 $value = $this->stripComments($value);
315 $this->content_id
= $value;
319 $this->xmailer
= $value;
324 $this->priority
= $this->parsePriority($value);
327 $value = $this->stripComments($value);
328 $this->mlist('post', $value);
331 $value = $this->stripComments($value);
332 $this->mlist('reply', $value);
334 case 'list-subscribe':
335 $value = $this->stripComments($value);
336 $this->mlist('subscribe', $value);
338 case 'list-unsubscribe':
339 $value = $this->stripComments($value);
340 $this->mlist('unsubscribe', $value);
343 $value = $this->stripComments($value);
344 $this->mlist('archive', $value);
347 $value = $this->stripComments($value);
348 $this->mlist('owner', $value);
351 $value = $this->stripComments($value);
352 $this->mlist('help', $value);
355 $value = $this->stripComments($value);
356 $this->mlist('id', $value);
358 case 'x-spam-status':
360 $this->x_spam_status
= $this->parseSpamStatus($value);
362 case 'x-sm-flag-reply':
363 $this->x_sm_flag_reply
= $value;
371 * @param string $address
374 function getAddressTokens($address) {
376 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
377 $aReplace = array(' (',' <',' ,',' ;',' :');
378 $address = str_replace($aSpecials,$aReplace,$address);
379 $iCnt = strlen($address);
382 $cChar = $address{$i};
386 $iEnd = strpos($address,'>',$i+
1);
388 $sToken = substr($address,$i);
391 $sToken = substr($address,$i,$iEnd - $i +
1);
394 $sToken = str_replace($aReplace, $aSpecials,$sToken);
395 if ($sToken) $aTokens[] = $sToken;
398 $iEnd = strpos($address,$cChar,$i+
1);
400 // skip escaped quotes
401 $prev_char = $address{$iEnd-1};
402 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
403 $iEnd = strpos($address,$cChar,$iEnd+
1);
405 $prev_char = $address{$iEnd-1};
412 $sToken = substr($address,$i);
415 // also remove the surrounding quotes
416 $sToken = substr($address,$i+
1,$iEnd - $i -1);
419 $sToken = str_replace($aReplace, $aSpecials,$sToken);
420 if ($sToken) $aTokens[] = $sToken;
423 array_pop($aTokens); //remove inserted space
424 $iEnd = strpos($address,')',$i);
426 $sToken = substr($address,$i);
431 while (($iDepth > 0) && (++
$iComment < $iCnt)) {
432 $cCharComment = $address{$iComment};
433 switch($cCharComment) {
448 $sToken = substr($address,$i,$iComment - $i +
1);
451 $sToken = substr($address,$i,$iEnd - $i +
1);
455 // check the next token in case comments appear in the middle of email addresses
456 $prevToken = end($aTokens);
457 if (!in_array($prevToken,$aSpecials,true)) {
458 if ($i+
1<strlen($address) && !in_array($address{$i+
1},$aSpecials,true)) {
459 $iEnd = strpos($address,' ',$i+
1);
461 $sNextToken = trim(substr($address,$i+
1,$iEnd - $i -1));
464 $sNextToken = trim(substr($address,$i+
1));
469 // create token and add it again
470 $sNewToken = $prevToken . $sNextToken;
471 if($sNewToken) $aTokens[] = $sNewToken;
474 $sToken = str_replace($aReplace, $aSpecials,$sToken);
475 if ($sToken) $aTokens[] = $sToken;
484 $iEnd = strpos($address,' ',$i+
1);
486 $sToken = trim(substr($address,$i,$iEnd - $i));
489 $sToken = trim(substr($address,$i));
492 if ($sToken) $aTokens[] = $sToken;
500 * @param array $aStack
501 * @param array $aComment
502 * @param string $sEmail
503 * @param string $sGroup
504 * @return object AddressStructure object
506 function createAddressObject(&$aStack,&$aComment,&$sEmail,$sGroup='') {
507 //$aStack=explode(' ',implode('',$aStack));
509 while (count($aStack) && !$sEmail) {
510 $sEmail = trim(array_pop($aStack));
513 if (count($aStack)) {
514 $sPersonal = trim(implode('',$aStack));
518 if (!$sPersonal && count($aComment)) {
519 $sComment = trim(implode(' ',$aComment));
520 $sPersonal .= $sComment;
522 $oAddr = new AddressStructure();
523 if ($sPersonal && substr($sPersonal,0,2) == '=?') {
524 $oAddr->personal
= encodeHeader($sPersonal);
526 $oAddr->personal
= $sPersonal;
528 // $oAddr->group = $sGroup;
529 $iPosAt = strpos($sEmail,'@');
531 $oAddr->mailbox
= substr($sEmail, 0, $iPosAt);
532 $oAddr->host
= substr($sEmail, $iPosAt+
1);
534 $oAddr->mailbox
= $sEmail;
535 $oAddr->host
= false;
538 $aStack = $aComment = array();
543 * recursive function for parsing address strings and storing them in an address stucture object.
544 * personal name: encoded: =?charset?Q|B?string?=
547 * email : <mailbox@host>
549 * This function is also used for validating addresses returned from compose
550 * That's also the reason that the function became a little bit huge
551 * @param string $address
552 * @param boolean $ar return array instead of only the first element
553 * @param array $addr_ar (obsolete) array with parsed addresses
554 * @param string $group (obsolete)
555 * @param string $host default domainname in case of addresses without a domainname
556 * @param string $lookup (since) callback function for lookup of address strings which are probably nicks (without @)
557 * @return mixed array with AddressStructure objects or only one address_structure object.
559 function parseAddress($address,$ar=false,$aAddress=array(),$sGroup='',$sHost='',$lookup=false) {
560 $aTokens = $this->getAddressTokens($address);
561 $sPersonal = $sEmail = $sGroup = '';
562 $aStack = $aComment = array();
563 foreach ($aTokens as $sToken) {
573 $aComment[] = substr($sToken,1,-1);
577 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
578 $oAddr = end($aAddress);
579 if(!$oAddr ||
((isset($oAddr)) && !strlen($oAddr->mailbox
) && !$oAddr->personal
)) {
580 $sEmail = $sGroup . ':;';
582 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
584 $aStack = $aComment = array();
588 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
591 $sGroup = trim(implode(' ',$aStack));
592 $sGroup = preg_replace('/\s+/',' ',$sGroup);
596 $sEmail = trim(substr($sToken,1,-1));
601 default: $aStack[] = $sToken; break;
604 /* now do the action again for the last address */
605 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail);
606 /* try to lookup the addresses in case of invalid email addresses */
607 $aProcessedAddress = array();
608 foreach ($aAddress as $oAddr) {
609 $aAddrBookAddress = array();
611 $grouplookup = false;
613 $aAddr = call_user_func_array($lookup,array($oAddr->mailbox
));
614 if (isset($aAddr['email'])) {
615 if (strpos($aAddr['email'],',')) {
617 $aAddrBookAddress = $this->parseAddress($aAddr['email'],true);
619 $iPosAt = strpos($aAddr['email'], '@');
620 if ($iPosAt === FALSE) {
621 $oAddr->mailbox
= $aAddr['email'];
622 $oAddr->host
= FALSE;
624 $oAddr->mailbox
= substr($aAddr['email'], 0, $iPosAt);
625 $oAddr->host
= substr($aAddr['email'], $iPosAt+
1);
627 if (isset($aAddr['name'])) {
628 $oAddr->personal
= $aAddr['name'];
630 $oAddr->personal
= encodeHeader($sPersonal);
635 if (!$grouplookup && !strlen($oAddr->mailbox
)) {
636 $oAddr->mailbox
= trim($sEmail);
637 if ($sHost && strlen($oAddr->mailbox
)) {
638 $oAddr->host
= $sHost;
640 } else if (!$grouplookup && !$oAddr->host
) {
641 if ($sHost && strlen($oAddr->mailbox
)) {
642 $oAddr->host
= $sHost;
646 if (!$aAddrBookAddress && strlen($oAddr->mailbox
)) {
647 $aProcessedAddress[] = $oAddr;
649 $aProcessedAddress = array_merge($aProcessedAddress,$aAddrBookAddress);
653 return $aProcessedAddress;
655 if (isset($aProcessedAddress[0]))
656 return $aProcessedAddress[0];
663 * Normalise the different Priority headers into a uniform value,
664 * namely that of the X-Priority header (1, 3, 5). Supports:
665 * Priority, X-Priority, Importance.
666 * X-MS-Mail-Priority is not parsed because it always coincides
667 * with one of the other headers.
669 * NOTE: this is actually a duplicate from the code in
670 * functions/imap_messages:parseFetch().
671 * I'm not sure if it's ok here to call
673 * @param string $sValue literal priority name
676 function parsePriority($sValue) {
677 // don't use function call inside array_shift.
678 $aValue = preg_split('/\s/',trim($sValue));
679 $value = strtolower(array_shift($aValue));
681 if ( is_numeric($value) ) {
684 if ( $value == 'urgent' ||
$value == 'high' ) {
686 } elseif ( $value == 'non-urgent' ||
$value == 'low' ) {
689 // default is normal priority
694 * @param string $value content type header
696 function parseContentType($value) {
697 $pos = strpos($value, ';');
700 $type = trim(substr($value, 0, $pos));
701 $props = trim(substr($value, $pos+
1));
705 $content_type = new ContentType($type);
707 $properties = $this->parseProperties($props);
708 if (!isset($properties['charset'])) {
709 $properties['charset'] = 'us-ascii';
711 $content_type->properties
= $this->parseProperties($props);
713 $this->content_type
= $content_type;
718 * @param array $aParameters
721 function processParameters($aParameters) {
724 // handle multiline parameters
725 foreach($aParameters as $key => $value) {
726 if ($iPos = strpos($key,'*')) {
727 $sKey = substr($key,0,$iPos);
728 if (!isset($aResults[$sKey])) {
729 $aResults[$sKey] = $value;
730 if (substr($key,-1) == '*') { // parameter contains language/charset info
734 $aResults[$sKey] .= $value;
737 $aResults[$key] = $value;
740 foreach ($aCharset as $key) {
741 $value = $aResults[$key];
742 // extract the charset & language
743 $charset = substr($value,0,strpos($value,"'"));
744 $value = substr($value,strlen($charset)+
1);
745 $language = substr($value,0,strpos($value,"'"));
746 $value = substr($value,strlen($charset)+
1);
747 /* FIXME: What's the status of charset decode with language information ????
748 * Maybe language information contains only ascii text and charset_decode()
749 * only runs sm_encode_html_special_chars() on it. If it contains 8bit information, you
750 * get html encoded text in charset used by selected translation.
752 $value = charset_decode($charset,$value);
753 $aResults[$key] = $value;
759 * @param string $value
762 function parseProperties($value) {
763 $propArray = explode(';', $value);
764 $propResultArray = array();
765 foreach ($propArray as $prop) {
767 $pos = strpos($prop, '=');
769 $key = trim(substr($prop, 0, $pos));
770 $val = trim(substr($prop, $pos+
1));
771 if (strlen($val) > 0 && $val{0} == '"') {
772 $val = substr($val, 1, -1);
774 $propResultArray[$key] = $val;
777 return $this->processParameters($propResultArray);
781 * Fills disposition object in rfc822Header object
782 * @param string $value
784 function parseDisposition($value) {
785 $pos = strpos($value, ';');
788 $name = trim(substr($value, 0, $pos));
789 $props = trim(substr($value, $pos+
1));
793 $props_a = $this->parseProperties($props);
794 $disp = new Disposition($name);
795 $disp->properties
= $props_a;
796 $this->disposition
= $disp;
800 * Fills mlist array keys in rfc822Header object
801 * @param string $field
802 * @param string $value
804 function mlist($field, $value) {
806 $value_a = explode(',', $value);
807 foreach ($value_a as $val) {
809 if ($val{0} == '<') {
810 $val = substr($val, 1, -1);
812 if (substr($val, 0, 7) == 'mailto:') {
813 $res_a['mailto'] = substr($val, 7);
815 $res_a['href'] = $val;
818 $this->mlist
[$field] = $res_a;
822 * Parses the X-Spam-Status or X-Spam-Score header
823 * @param string $value
825 function parseSpamStatus($value) {
826 // Header value looks like this:
827 // No, score=1.5 required=5.0 tests=MSGID_FROM_MTA_ID,NO_REAL_NAME,UPPERCASE_25_50 autolearn=disabled version=3.1.0-gr0
828 // Update circa 2018, this header can also be simply:
830 // So we make the rest of the line optional (there are likely other permutations, so
831 // each element is made optional except the first two... maybe even that's not flexible enough)
833 // Also now allow parsing of X-Spam-Score header, whose value is just a float
835 $spam_status = array();
837 if (preg_match ('/^(?:(No|Yes),\s+score=)?(-?\d+\.\d+)(?:\s+required=(-?\d+\.\d+))?(?:\s+tests=(.*?))?(?:\s+autolearn=(.*?))?(?:\s+version=(.+?))?$/i', $value, $matches)) {
840 $spam_status['bad_format'] = 0;
841 $spam_status['value'] = $matches[0];
844 if (!empty($matches[1])) {
845 if (strtolower($matches[1]) == 'yes')
846 $spam_status['is_spam'] = true;
848 $spam_status['is_spam'] = false;
852 if (!empty($matches[2]))
853 $spam_status['score'] = $matches[2];
856 if (!empty($matches[3]))
857 $spam_status['required'] = $matches[3];
860 if (isset($matches[4])) {
862 $tests = explode(',', $matches[4]);
863 foreach ($tests as $test) {
864 $spam_status['tests'][] = trim($test);
869 if (isset($matches[5]))
870 $spam_status['autolearn'] = $matches[5];
873 if (isset($matches[6]))
874 $spam_status['version'] = $matches[6];
877 $spam_status['bad_format'] = 1;
878 $spam_status['value'] = $value;
884 * function to get the address strings out of the header.
885 * example1: header->getAddr_s('to').
886 * example2: header->getAddr_s(array('to', 'cc', 'bcc'))
887 * @param mixed $arr string or array of strings
888 * @param string $separator
889 * @param boolean $encoded (since 1.4.0) return encoded or plain text addresses
890 * @param boolean $unconditionally_quote (since 1.4.21/1.5.2) When TRUE, always
891 * quote the personal part,
892 * whether or not it is
893 * encoded, otherwise quoting
894 * is only added if the
895 * personal part is not encoded
898 function getAddr_s($arr, $separator = ', ', $encoded=false, $unconditionally_quote=FALSE) {
901 if (is_array($arr)) {
902 foreach($arr as $arg) {
903 if ($this->getAddr_s($arg, $separator, $encoded, $unconditionally_quote)) {
907 $s = ($s ?
substr($s, 2) : $s);
909 $addr = $this->{$arr};
910 if (is_array($addr)) {
911 foreach ($addr as $addr_o) {
912 if (is_object($addr_o)) {
914 $s .= $addr_o->getEncodedAddress($unconditionally_quote) . $separator;
916 $s .= $addr_o->getAddress(TRUE, FALSE, $unconditionally_quote) . $separator;
920 $s = substr($s, 0, -strlen($separator));
922 if (is_object($addr)) {
924 $s .= $addr->getEncodedAddress($unconditionally_quote);
926 $s .= $addr->getAddress(TRUE, FALSE, $unconditionally_quote);
935 * function to get the array of addresses out of the header.
936 * @param mixed $arg string or array of strings
937 * @param array $excl_arr array of excluded email addresses
938 * @param array $arr array of added email addresses
941 function getAddr_a($arg, $excl_arr = array(), $arr = array()) {
942 if (is_array($arg)) {
943 foreach($arg as $argument) {
944 $arr = $this->getAddr_a($argument, $excl_arr, $arr);
947 $addr = $this->{$arg};
948 if (is_array($addr)) {
949 foreach ($addr as $next_addr) {
950 if (is_object($next_addr)) {
951 if (isset($next_addr->host
) && ($next_addr->host
!= '')) {
952 $email = $next_addr->mailbox
. '@' . $next_addr->host
;
954 $email = $next_addr->mailbox
;
956 $email = strtolower($email);
957 if ($email && !isset($arr[$email]) && !isset($excl_arr[$email])) {
958 $arr[$email] = $next_addr->personal
;
963 if (is_object($addr)) {
964 $email = $addr->mailbox
;
965 $email .= (isset($addr->host
) ?
'@' . $addr->host
: '');
966 $email = strtolower($email);
967 if ($email && !isset($arr[$email]) && !isset($excl_arr[$email])) {
968 $arr[$email] = $addr->personal
;
977 //FIXME: This needs some documentation (inside the function too)! Don't code w/out comments!
978 * Looking at the code years after it was written,
979 * this is my (Paul) best guess as to what this
980 * function does (note that docs previously claimed
981 * that this function returns boolean or an array,
982 * but it no longer appears to return an array - an
985 * Inspects the TO and CC headers of the message
986 * represented by this object, looking for the
987 * address(es) given by $address
989 * If $address is a string:
990 * Serves as a test (returns boolean) as to
991 * whether or not the given address is found
992 * anywhere in the TO or CC headers
994 * If $address is an array:
995 * Looks through this list of addresses and
996 * returns the array index (an integer even
997 * if the array is given with keys of a
998 * different type) of the first matching
999 * $address found in this message's
1000 * TO or CC headers, unless there is an exact
1001 * match (meaning that the "personal
1002 * information" in addition to the email
1003 * address also matches), in which case that
1004 * index (the first one found) is returned
1006 * @param mixed $address Address(es) to search for in this
1007 * message's TO and CC headers - please
1008 * see above how the format of this
1009 * argument affects the return value
1011 * @param boolean $recurs FOR INTERNAL USE ONLY
1013 * @return mixed Boolean when $address is a scalar,
1014 * indicating whether or not the address
1015 * was found in the TO or CC headers.
1016 * An integer when $address is an array,
1017 * containing the index of the value in
1018 * that array that was found in the TO
1019 * or CC headers, or boolean FALSE if
1020 * there were no matches at all
1024 function findAddress($address, $recurs = false) {
1026 if (is_array($address)) {
1028 foreach($address as $argument) {
1029 $match = $this->findAddress($argument, true);
1030 if ($match[1]) { // this indicates when the personal information matched
1033 if (count($match[0]) && $result === FALSE) {
1040 if (!is_array($this->cc
)) $this->cc
= array();
1041 if (!is_array($this->to
)) $this->to
= array();
1042 $srch_addr = $this->parseAddress($address);
1044 foreach ($this->to
as $to) {
1045 if (strtolower($to->host
) == strtolower($srch_addr->host
)) {
1046 if (strtolower($to->mailbox
) == strtolower($srch_addr->mailbox
)) {
1047 $results[] = $srch_addr;
1048 if (strtolower($to->personal
) == strtolower($srch_addr->personal
)) {
1050 return array($results, true);
1058 foreach ($this->cc
as $cc) {
1059 if (strtolower($cc->host
) == strtolower($srch_addr->host
)) {
1060 if (strtolower($cc->mailbox
) == strtolower($srch_addr->mailbox
)) {
1061 $results[] = $srch_addr;
1062 if (strtolower($cc->personal
) == strtolower($srch_addr->personal
)) {
1064 return array($results, true);
1073 return array($results, false);
1074 } elseif (count($results)) {
1085 * @param string $type0 media type
1086 * @param string $type1 media subtype
1087 * @return array media properties
1088 * @todo check use of media type arguments
1090 function getContentType($type0, $type1) {
1091 $type0 = $this->content_type
->type0
;
1092 $type1 = $this->content_type
->type1
;
1093 return $this->content_type
->properties
;