4 * Rfc822Header.class.php
6 * This file contains functions needed to handle headers in mime messages.
8 * @copyright 2003-2018 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
33 * Original date header as fallback for unparsable dates
36 var $date_unparsed = '';
55 var $reply_to = array();
57 * Mail-Followup-To header
60 var $mail_followup_to = array();
80 var $in_reply_to = '';
99 var $content_type = '';
103 var $disposition = '';
115 * Disposition notification for requesting message delivery notification (MDN)
120 * Delivery notification (DR)
131 var $content_id = '';
135 var $content_desc = '';
139 var $mlist = array();
141 * SpamAssassin 'x-spam-status' header
144 var $x_spam_status = array();
147 * only needed for constructing headers in delivery class
150 var $more_headers = array();
153 * @param mixed $hdr string or array with message headers
155 function parseHeader($hdr) {
156 if (is_array($hdr)) {
157 $hdr = implode('', $hdr);
159 /* First we replace \r\n by \n and unfold the header */
160 /* FIXME: unfolding header with multiple spaces "\n( +)" */
161 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $hdr));
163 /* Now we can make a new header array with */
164 /* each element representing a headerline */
165 $hdr = explode("\n" , $hdr);
166 foreach ($hdr as $line) {
167 $pos = strpos($line, ':');
169 $field = substr($line, 0, $pos);
170 if (!strstr($field,' ')) { /* valid field */
171 $value = trim(substr($line, $pos+
1));
172 $this->parseField($field, $value);
176 if (!is_object($this->content_type
)) {
177 $this->parseContentType('text/plain; charset=us-ascii');
182 * @param string $value
185 function stripComments($value) {
187 $cnt = strlen($value);
188 for ($i = 0; $i < $cnt; ++
$i) {
189 switch ($value{$i}) {
192 while ((++
$i < $cnt) && ($value{$i} != '"')) {
193 if ($value{$i} == '\\') {
197 $result .= $value{$i};
200 $result .= $value{$i};
205 while (($depth > 0) && (++
$i < $cnt)) {
222 $result .= $value{$i};
230 * Parse header field according to field type
231 * @param string $field field name
232 * @param string $value field value
234 function parseField($field, $value) {
235 $field = strtolower($field);
238 $value = $this->stripComments($value);
239 $d = strtr($value, array(' ' => ' '));
240 $d = explode(' ', $d);
241 $this->date
= getTimeStamp($d);
242 $this->date_unparsed
= strtr($value,'<>',' ');
245 $this->subject
= $value;
248 $this->from
= $this->parseAddress($value,true);
251 $this->sender
= $this->parseAddress($value);
254 $this->reply_to
= $this->parseAddress($value, true);
256 case 'mail-followup-to':
257 $this->mail_followup_to
= $this->parseAddress($value, true);
260 $this->to
= $this->parseAddress($value, true);
263 $this->cc
= $this->parseAddress($value, true);
266 $this->bcc
= $this->parseAddress($value, true);
269 $this->in_reply_to
= $value;
272 $value = $this->stripComments($value);
273 $this->message_id
= $value;
276 $value = $this->stripComments($value);
277 $this->references
= $value;
279 case 'x-confirm-reading-to':
280 case 'disposition-notification-to':
281 $value = $this->stripComments($value);
282 $this->dnt
= $this->parseAddress($value);
284 case 'return-receipt-to':
285 $value = $this->stripComments($value);
286 $this->drnt
= $this->parseAddress($value);
289 $value = $this->stripComments($value);
290 $value = str_replace(' ', '', $value);
291 $this->mime
= ($value == '1.0' ?
true : $this->mime
);
294 $value = $this->stripComments($value);
295 $this->parseContentType($value);
297 case 'content-disposition':
298 $value = $this->stripComments($value);
299 $this->parseDisposition($value);
301 case 'content-transfer-encoding':
302 $this->encoding
= $value;
304 case 'content-description':
305 $this->content_desc
= $value;
308 $value = $this->stripComments($value);
309 $this->content_id
= $value;
313 $this->xmailer
= $value;
318 $this->priority
= $this->parsePriority($value);
321 $value = $this->stripComments($value);
322 $this->mlist('post', $value);
325 $value = $this->stripComments($value);
326 $this->mlist('reply', $value);
328 case 'list-subscribe':
329 $value = $this->stripComments($value);
330 $this->mlist('subscribe', $value);
332 case 'list-unsubscribe':
333 $value = $this->stripComments($value);
334 $this->mlist('unsubscribe', $value);
337 $value = $this->stripComments($value);
338 $this->mlist('archive', $value);
341 $value = $this->stripComments($value);
342 $this->mlist('owner', $value);
345 $value = $this->stripComments($value);
346 $this->mlist('help', $value);
349 $value = $this->stripComments($value);
350 $this->mlist('id', $value);
352 case 'x-spam-status':
353 $this->x_spam_status
= $this->parseSpamStatus($value);
355 case 'x-sm-flag-reply':
356 $this->x_sm_flag_reply
= $value;
364 * @param string $address
367 function getAddressTokens($address) {
369 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
370 $aReplace = array(' (',' <',' ,',' ;',' :');
371 $address = str_replace($aSpecials,$aReplace,$address);
372 $iCnt = strlen($address);
375 $cChar = $address{$i};
379 $iEnd = strpos($address,'>',$i+
1);
381 $sToken = substr($address,$i);
384 $sToken = substr($address,$i,$iEnd - $i +
1);
387 $sToken = str_replace($aReplace, $aSpecials,$sToken);
388 if ($sToken) $aTokens[] = $sToken;
391 $iEnd = strpos($address,$cChar,$i+
1);
393 // skip escaped quotes
394 $prev_char = $address{$iEnd-1};
395 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
396 $iEnd = strpos($address,$cChar,$iEnd+
1);
398 $prev_char = $address{$iEnd-1};
405 $sToken = substr($address,$i);
408 // also remove the surrounding quotes
409 $sToken = substr($address,$i+
1,$iEnd - $i -1);
412 $sToken = str_replace($aReplace, $aSpecials,$sToken);
413 if ($sToken) $aTokens[] = $sToken;
416 array_pop($aTokens); //remove inserted space
417 $iEnd = strpos($address,')',$i);
419 $sToken = substr($address,$i);
424 while (($iDepth > 0) && (++
$iComment < $iCnt)) {
425 $cCharComment = $address{$iComment};
426 switch($cCharComment) {
441 $sToken = substr($address,$i,$iComment - $i +
1);
444 $sToken = substr($address,$i,$iEnd - $i +
1);
448 // check the next token in case comments appear in the middle of email addresses
449 $prevToken = end($aTokens);
450 if (!in_array($prevToken,$aSpecials,true)) {
451 if ($i+
1<strlen($address) && !in_array($address{$i+
1},$aSpecials,true)) {
452 $iEnd = strpos($address,' ',$i+
1);
454 $sNextToken = trim(substr($address,$i+
1,$iEnd - $i -1));
457 $sNextToken = trim(substr($address,$i+
1));
462 // create token and add it again
463 $sNewToken = $prevToken . $sNextToken;
464 if($sNewToken) $aTokens[] = $sNewToken;
467 $sToken = str_replace($aReplace, $aSpecials,$sToken);
468 if ($sToken) $aTokens[] = $sToken;
477 $iEnd = strpos($address,' ',$i+
1);
479 $sToken = trim(substr($address,$i,$iEnd - $i));
482 $sToken = trim(substr($address,$i));
485 if ($sToken) $aTokens[] = $sToken;
493 * @param array $aStack
494 * @param array $aComment
495 * @param string $sEmail
496 * @param string $sGroup
497 * @return object AddressStructure object
499 function createAddressObject(&$aStack,&$aComment,&$sEmail,$sGroup='') {
500 //$aStack=explode(' ',implode('',$aStack));
502 while (count($aStack) && !$sEmail) {
503 $sEmail = trim(array_pop($aStack));
506 if (count($aStack)) {
507 $sPersonal = trim(implode('',$aStack));
511 if (!$sPersonal && count($aComment)) {
512 $sComment = trim(implode(' ',$aComment));
513 $sPersonal .= $sComment;
515 $oAddr = new AddressStructure();
516 if ($sPersonal && substr($sPersonal,0,2) == '=?') {
517 $oAddr->personal
= encodeHeader($sPersonal);
519 $oAddr->personal
= $sPersonal;
521 // $oAddr->group = $sGroup;
522 $iPosAt = strpos($sEmail,'@');
524 $oAddr->mailbox
= substr($sEmail, 0, $iPosAt);
525 $oAddr->host
= substr($sEmail, $iPosAt+
1);
527 $oAddr->mailbox
= $sEmail;
528 $oAddr->host
= false;
531 $aStack = $aComment = array();
536 * recursive function for parsing address strings and storing them in an address stucture object.
537 * personal name: encoded: =?charset?Q|B?string?=
540 * email : <mailbox@host>
542 * This function is also used for validating addresses returned from compose
543 * That's also the reason that the function became a little bit huge
544 * @param string $address
545 * @param boolean $ar return array instead of only the first element
546 * @param array $addr_ar (obsolete) array with parsed addresses
547 * @param string $group (obsolete)
548 * @param string $host default domainname in case of addresses without a domainname
549 * @param string $lookup (since) callback function for lookup of address strings which are probably nicks (without @)
550 * @return mixed array with AddressStructure objects or only one address_structure object.
552 function parseAddress($address,$ar=false,$aAddress=array(),$sGroup='',$sHost='',$lookup=false) {
553 $aTokens = $this->getAddressTokens($address);
554 $sPersonal = $sEmail = $sGroup = '';
555 $aStack = $aComment = array();
556 foreach ($aTokens as $sToken) {
566 $aComment[] = substr($sToken,1,-1);
570 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
571 $oAddr = end($aAddress);
572 if(!$oAddr ||
((isset($oAddr)) && !strlen($oAddr->mailbox
) && !$oAddr->personal
)) {
573 $sEmail = $sGroup . ':;';
575 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
577 $aStack = $aComment = array();
581 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
584 $sGroup = trim(implode(' ',$aStack));
585 $sGroup = preg_replace('/\s+/',' ',$sGroup);
589 $sEmail = trim(substr($sToken,1,-1));
594 default: $aStack[] = $sToken; break;
597 /* now do the action again for the last address */
598 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail);
599 /* try to lookup the addresses in case of invalid email addresses */
600 $aProcessedAddress = array();
601 foreach ($aAddress as $oAddr) {
602 $aAddrBookAddress = array();
604 $grouplookup = false;
606 $aAddr = call_user_func_array($lookup,array($oAddr->mailbox
));
607 if (isset($aAddr['email'])) {
608 if (strpos($aAddr['email'],',')) {
610 $aAddrBookAddress = $this->parseAddress($aAddr['email'],true);
612 $iPosAt = strpos($aAddr['email'], '@');
613 if ($iPosAt === FALSE) {
614 $oAddr->mailbox
= $aAddr['email'];
615 $oAddr->host
= FALSE;
617 $oAddr->mailbox
= substr($aAddr['email'], 0, $iPosAt);
618 $oAddr->host
= substr($aAddr['email'], $iPosAt+
1);
620 if (isset($aAddr['name'])) {
621 $oAddr->personal
= $aAddr['name'];
623 $oAddr->personal
= encodeHeader($sPersonal);
628 if (!$grouplookup && !strlen($oAddr->mailbox
)) {
629 $oAddr->mailbox
= trim($sEmail);
630 if ($sHost && strlen($oAddr->mailbox
)) {
631 $oAddr->host
= $sHost;
633 } else if (!$grouplookup && !$oAddr->host
) {
634 if ($sHost && strlen($oAddr->mailbox
)) {
635 $oAddr->host
= $sHost;
639 if (!$aAddrBookAddress && strlen($oAddr->mailbox
)) {
640 $aProcessedAddress[] = $oAddr;
642 $aProcessedAddress = array_merge($aProcessedAddress,$aAddrBookAddress);
646 return $aProcessedAddress;
648 if (isset($aProcessedAddress[0]))
649 return $aProcessedAddress[0];
656 * Normalise the different Priority headers into a uniform value,
657 * namely that of the X-Priority header (1, 3, 5). Supports:
658 * Priority, X-Priority, Importance.
659 * X-MS-Mail-Priority is not parsed because it always coincides
660 * with one of the other headers.
662 * NOTE: this is actually a duplicate from the code in
663 * functions/imap_messages:parseFetch().
664 * I'm not sure if it's ok here to call
666 * @param string $sValue literal priority name
669 function parsePriority($sValue) {
670 // don't use function call inside array_shift.
671 $aValue = preg_split('/\s/',trim($sValue));
672 $value = strtolower(array_shift($aValue));
674 if ( is_numeric($value) ) {
677 if ( $value == 'urgent' ||
$value == 'high' ) {
679 } elseif ( $value == 'non-urgent' ||
$value == 'low' ) {
682 // default is normal priority
687 * @param string $value content type header
689 function parseContentType($value) {
690 $pos = strpos($value, ';');
693 $type = trim(substr($value, 0, $pos));
694 $props = trim(substr($value, $pos+
1));
698 $content_type = new ContentType($type);
700 $properties = $this->parseProperties($props);
701 if (!isset($properties['charset'])) {
702 $properties['charset'] = 'us-ascii';
704 $content_type->properties
= $this->parseProperties($props);
706 $this->content_type
= $content_type;
711 * @param array $aParameters
714 function processParameters($aParameters) {
717 // handle multiline parameters
718 foreach($aParameters as $key => $value) {
719 if ($iPos = strpos($key,'*')) {
720 $sKey = substr($key,0,$iPos);
721 if (!isset($aResults[$sKey])) {
722 $aResults[$sKey] = $value;
723 if (substr($key,-1) == '*') { // parameter contains language/charset info
727 $aResults[$sKey] .= $value;
730 $aResults[$key] = $value;
733 foreach ($aCharset as $key) {
734 $value = $aResults[$key];
735 // extract the charset & language
736 $charset = substr($value,0,strpos($value,"'"));
737 $value = substr($value,strlen($charset)+
1);
738 $language = substr($value,0,strpos($value,"'"));
739 $value = substr($value,strlen($charset)+
1);
740 /* FIXME: What's the status of charset decode with language information ????
741 * Maybe language information contains only ascii text and charset_decode()
742 * only runs sm_encode_html_special_chars() on it. If it contains 8bit information, you
743 * get html encoded text in charset used by selected translation.
745 $value = charset_decode($charset,$value);
746 $aResults[$key] = $value;
752 * @param string $value
755 function parseProperties($value) {
756 $propArray = explode(';', $value);
757 $propResultArray = array();
758 foreach ($propArray as $prop) {
760 $pos = strpos($prop, '=');
762 $key = trim(substr($prop, 0, $pos));
763 $val = trim(substr($prop, $pos+
1));
764 if (strlen($val) > 0 && $val{0} == '"') {
765 $val = substr($val, 1, -1);
767 $propResultArray[$key] = $val;
770 return $this->processParameters($propResultArray);
774 * Fills disposition object in rfc822Header object
775 * @param string $value
777 function parseDisposition($value) {
778 $pos = strpos($value, ';');
781 $name = trim(substr($value, 0, $pos));
782 $props = trim(substr($value, $pos+
1));
786 $props_a = $this->parseProperties($props);
787 $disp = new Disposition($name);
788 $disp->properties
= $props_a;
789 $this->disposition
= $disp;
793 * Fills mlist array keys in rfc822Header object
794 * @param string $field
795 * @param string $value
797 function mlist($field, $value) {
799 $value_a = explode(',', $value);
800 foreach ($value_a as $val) {
802 if ($val{0} == '<') {
803 $val = substr($val, 1, -1);
805 if (substr($val, 0, 7) == 'mailto:') {
806 $res_a['mailto'] = substr($val, 7);
808 $res_a['href'] = $val;
811 $this->mlist
[$field] = $res_a;
815 * Parses the X-Spam-Status header
816 * @param string $value
818 function parseSpamStatus($value) {
819 // Header value looks like this:
820 // 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
822 $spam_status = array();
824 if (preg_match ('/^(No|Yes),\s+score=(-?\d+\.\d+)\s+required=(-?\d+\.\d+)\s+tests=(.*?)\s+autolearn=(.*?)\s+version=(.+?)$/', $value, $matches)) {
826 $spam_status['bad_format'] = 0;
827 $spam_status['value'] = $matches[0];
829 if (isset($matches[1])
830 && strtolower($matches[1]) == 'yes') {
831 $spam_status['is_spam'] = true;
833 $spam_status['is_spam'] = false;
837 $spam_status['score'] = $matches[2];
840 $spam_status['required'] = $matches[3];
844 $tests = explode(',', $matches[4]);
845 foreach ($tests as $test) {
846 $spam_status['tests'][] = trim($test);
850 $spam_status['autolearn'] = $matches[5];
853 $spam_status['version'] = $matches[6];
855 $spam_status['bad_format'] = 1;
856 $spam_status['value'] = $value;
862 * function to get the address strings out of the header.
863 * example1: header->getAddr_s('to').
864 * example2: header->getAddr_s(array('to', 'cc', 'bcc'))
865 * @param mixed $arr string or array of strings
866 * @param string $separator
867 * @param boolean $encoded (since 1.4.0) return encoded or plain text addresses
868 * @param boolean $unconditionally_quote (since 1.4.21/1.5.2) When TRUE, always
869 * quote the personal part,
870 * whether or not it is
871 * encoded, otherwise quoting
872 * is only added if the
873 * personal part is not encoded
876 function getAddr_s($arr, $separator = ', ', $encoded=false, $unconditionally_quote=FALSE) {
879 if (is_array($arr)) {
880 foreach($arr as $arg) {
881 if ($this->getAddr_s($arg, $separator, $encoded, $unconditionally_quote)) {
885 $s = ($s ?
substr($s, 2) : $s);
887 $addr = $this->{$arr};
888 if (is_array($addr)) {
889 foreach ($addr as $addr_o) {
890 if (is_object($addr_o)) {
892 $s .= $addr_o->getEncodedAddress($unconditionally_quote) . $separator;
894 $s .= $addr_o->getAddress(TRUE, FALSE, $unconditionally_quote) . $separator;
898 $s = substr($s, 0, -strlen($separator));
900 if (is_object($addr)) {
902 $s .= $addr->getEncodedAddress($unconditionally_quote);
904 $s .= $addr->getAddress(TRUE, FALSE, $unconditionally_quote);
913 * function to get the array of addresses out of the header.
914 * @param mixed $arg string or array of strings
915 * @param array $excl_arr array of excluded email addresses
916 * @param array $arr array of added email addresses
919 function getAddr_a($arg, $excl_arr = array(), $arr = array()) {
920 if (is_array($arg)) {
921 foreach($arg as $argument) {
922 $arr = $this->getAddr_a($argument, $excl_arr, $arr);
925 $addr = $this->{$arg};
926 if (is_array($addr)) {
927 foreach ($addr as $next_addr) {
928 if (is_object($next_addr)) {
929 if (isset($next_addr->host
) && ($next_addr->host
!= '')) {
930 $email = $next_addr->mailbox
. '@' . $next_addr->host
;
932 $email = $next_addr->mailbox
;
934 $email = strtolower($email);
935 if ($email && !isset($arr[$email]) && !isset($excl_arr[$email])) {
936 $arr[$email] = $next_addr->personal
;
941 if (is_object($addr)) {
942 $email = $addr->mailbox
;
943 $email .= (isset($addr->host
) ?
'@' . $addr->host
: '');
944 $email = strtolower($email);
945 if ($email && !isset($arr[$email]) && !isset($excl_arr[$email])) {
946 $arr[$email] = $addr->personal
;
955 //FIXME: This needs some documentation (inside the function too)! Don't code w/out comments!
956 * Looking at the code years after it was written,
957 * this is my (Paul) best guess as to what this
958 * function does (note that docs previously claimed
959 * that this function returns boolean or an array,
960 * but it no longer appears to return an array - an
963 * Inspects the TO and CC headers of the message
964 * represented by this object, looking for the
965 * address(es) given by $address
967 * If $address is a string:
968 * Serves as a test (returns boolean) as to
969 * whether or not the given address is found
970 * anywhere in the TO or CC headers
972 * If $address is an array:
973 * Looks through this list of addresses and
974 * returns the array index (an integer even
975 * if the array is given with keys of a
976 * different type) of the first matching
977 * $address found in this message's
978 * TO or CC headers, unless there is an exact
979 * match (meaning that the "personal
980 * information" in addition to the email
981 * address also matches), in which case that
982 * index (the first one found) is returned
984 * @param mixed $address Address(es) to search for in this
985 * message's TO and CC headers - please
986 * see above how the format of this
987 * argument affects the return value
989 * @param boolean $recurs FOR INTERNAL USE ONLY
991 * @return mixed Boolean when $address is a scalar,
992 * indicating whether or not the address
993 * was found in the TO or CC headers.
994 * An integer when $address is an array,
995 * containing the index of the value in
996 * that array that was found in the TO
997 * or CC headers, or boolean FALSE if
998 * there were no matches at all
1002 function findAddress($address, $recurs = false) {
1004 if (is_array($address)) {
1006 foreach($address as $argument) {
1007 $match = $this->findAddress($argument, true);
1008 if ($match[1]) { // this indicates when the personal information matched
1011 if (count($match[0]) && $result === FALSE) {
1018 if (!is_array($this->cc
)) $this->cc
= array();
1019 if (!is_array($this->to
)) $this->to
= array();
1020 $srch_addr = $this->parseAddress($address);
1022 foreach ($this->to
as $to) {
1023 if (strtolower($to->host
) == strtolower($srch_addr->host
)) {
1024 if (strtolower($to->mailbox
) == strtolower($srch_addr->mailbox
)) {
1025 $results[] = $srch_addr;
1026 if (strtolower($to->personal
) == strtolower($srch_addr->personal
)) {
1028 return array($results, true);
1036 foreach ($this->cc
as $cc) {
1037 if (strtolower($cc->host
) == strtolower($srch_addr->host
)) {
1038 if (strtolower($cc->mailbox
) == strtolower($srch_addr->mailbox
)) {
1039 $results[] = $srch_addr;
1040 if (strtolower($cc->personal
) == strtolower($srch_addr->personal
)) {
1042 return array($results, true);
1051 return array($results, false);
1052 } elseif (count($results)) {
1063 * @param string $type0 media type
1064 * @param string $type1 media subtype
1065 * @return array media properties
1066 * @todo check use of media type arguments
1068 function getContentType($type0, $type1) {
1069 $type0 = $this->content_type
->type0
;
1070 $type1 = $this->content_type
->type1
;
1071 return $this->content_type
->properties
;