a23c7b4de3659064b4ec0d585494fe6be62d48ac
4 * Rfc822Header.class.php
6 * This file contains functions needed to handle headers in mime messages.
8 * @copyright 2003-2012 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);
361 * @param string $address
364 function getAddressTokens($address) {
366 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
367 $aReplace = array(' (',' <',' ,',' ;',' :');
368 $address = str_replace($aSpecials,$aReplace,$address);
369 $iCnt = strlen($address);
372 $cChar = $address{$i};
376 $iEnd = strpos($address,'>',$i+
1);
378 $sToken = substr($address,$i);
381 $sToken = substr($address,$i,$iEnd - $i +
1);
384 $sToken = str_replace($aReplace, $aSpecials,$sToken);
385 if ($sToken) $aTokens[] = $sToken;
388 $iEnd = strpos($address,$cChar,$i+
1);
390 // skip escaped quotes
391 $prev_char = $address{$iEnd-1};
392 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
393 $iEnd = strpos($address,$cChar,$iEnd+
1);
395 $prev_char = $address{$iEnd-1};
402 $sToken = substr($address,$i);
405 // also remove the surrounding quotes
406 $sToken = substr($address,$i+
1,$iEnd - $i -1);
409 $sToken = str_replace($aReplace, $aSpecials,$sToken);
410 if ($sToken) $aTokens[] = $sToken;
413 array_pop($aTokens); //remove inserted space
414 $iEnd = strpos($address,')',$i);
416 $sToken = substr($address,$i);
421 while (($iDepth > 0) && (++
$iComment < $iCnt)) {
422 $cCharComment = $address{$iComment};
423 switch($cCharComment) {
438 $sToken = substr($address,$i,$iComment - $i +
1);
441 $sToken = substr($address,$i,$iEnd - $i +
1);
445 // check the next token in case comments appear in the middle of email addresses
446 $prevToken = end($aTokens);
447 if (!in_array($prevToken,$aSpecials,true)) {
448 if ($i+
1<strlen($address) && !in_array($address{$i+
1},$aSpecials,true)) {
449 $iEnd = strpos($address,' ',$i+
1);
451 $sNextToken = trim(substr($address,$i+
1,$iEnd - $i -1));
454 $sNextToken = trim(substr($address,$i+
1));
459 // create token and add it again
460 $sNewToken = $prevToken . $sNextToken;
461 if($sNewToken) $aTokens[] = $sNewToken;
464 $sToken = str_replace($aReplace, $aSpecials,$sToken);
465 if ($sToken) $aTokens[] = $sToken;
474 $iEnd = strpos($address,' ',$i+
1);
476 $sToken = trim(substr($address,$i,$iEnd - $i));
479 $sToken = trim(substr($address,$i));
482 if ($sToken) $aTokens[] = $sToken;
490 * @param array $aStack
491 * @param array $aComment
492 * @param string $sEmail
493 * @param string $sGroup
494 * @return object AddressStructure object
496 function createAddressObject(&$aStack,&$aComment,&$sEmail,$sGroup='') {
497 //$aStack=explode(' ',implode('',$aStack));
499 while (count($aStack) && !$sEmail) {
500 $sEmail = trim(array_pop($aStack));
503 if (count($aStack)) {
504 $sPersonal = trim(implode('',$aStack));
508 if (!$sPersonal && count($aComment)) {
509 $sComment = trim(implode(' ',$aComment));
510 $sPersonal .= $sComment;
512 $oAddr = new AddressStructure();
513 if ($sPersonal && substr($sPersonal,0,2) == '=?') {
514 $oAddr->personal
= encodeHeader($sPersonal);
516 $oAddr->personal
= $sPersonal;
518 // $oAddr->group = $sGroup;
519 $iPosAt = strpos($sEmail,'@');
521 $oAddr->mailbox
= substr($sEmail, 0, $iPosAt);
522 $oAddr->host
= substr($sEmail, $iPosAt+
1);
524 $oAddr->mailbox
= $sEmail;
525 $oAddr->host
= false;
528 $aStack = $aComment = array();
533 * recursive function for parsing address strings and storing them in an address stucture object.
534 * personal name: encoded: =?charset?Q|B?string?=
537 * email : <mailbox@host>
539 * This function is also used for validating addresses returned from compose
540 * That's also the reason that the function became a little bit huge
541 * @param string $address
542 * @param boolean $ar return array instead of only the first element
543 * @param array $addr_ar (obsolete) array with parsed addresses
544 * @param string $group (obsolete)
545 * @param string $host default domainname in case of addresses without a domainname
546 * @param string $lookup (since) callback function for lookup of address strings which are probably nicks (without @)
547 * @return mixed array with AddressStructure objects or only one address_structure object.
549 function parseAddress($address,$ar=false,$aAddress=array(),$sGroup='',$sHost='',$lookup=false) {
550 $aTokens = $this->getAddressTokens($address);
551 $sPersonal = $sEmail = $sGroup = '';
552 $aStack = $aComment = array();
553 foreach ($aTokens as $sToken) {
563 $aComment[] = substr($sToken,1,-1);
567 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
568 $oAddr = end($aAddress);
569 if(!$oAddr ||
((isset($oAddr)) && !strlen($oAddr->mailbox
) && !$oAddr->personal
)) {
570 $sEmail = $sGroup . ':;';
572 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
574 $aStack = $aComment = array();
578 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
581 $sGroup = trim(implode(' ',$aStack));
582 $sGroup = preg_replace('/\s+/',' ',$sGroup);
586 $sEmail = trim(substr($sToken,1,-1));
591 default: $aStack[] = $sToken; break;
594 /* now do the action again for the last address */
595 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail);
596 /* try to lookup the addresses in case of invalid email addresses */
597 $aProcessedAddress = array();
598 foreach ($aAddress as $oAddr) {
599 $aAddrBookAddress = array();
601 $grouplookup = false;
603 $aAddr = call_user_func_array($lookup,array($oAddr->mailbox
));
604 if (isset($aAddr['email'])) {
605 if (strpos($aAddr['email'],',')) {
607 $aAddrBookAddress = $this->parseAddress($aAddr['email'],true);
609 $iPosAt = strpos($aAddr['email'], '@');
610 if ($iPosAt === FALSE) {
611 $oAddr->mailbox
= $aAddr['email'];
612 $oAddr->host
= FALSE;
614 $oAddr->mailbox
= substr($aAddr['email'], 0, $iPosAt);
615 $oAddr->host
= substr($aAddr['email'], $iPosAt+
1);
617 if (isset($aAddr['name'])) {
618 $oAddr->personal
= $aAddr['name'];
620 $oAddr->personal
= encodeHeader($sPersonal);
625 if (!$grouplookup && !strlen($oAddr->mailbox
)) {
626 $oAddr->mailbox
= trim($sEmail);
627 if ($sHost && strlen($oAddr->mailbox
)) {
628 $oAddr->host
= $sHost;
630 } else if (!$grouplookup && !$oAddr->host
) {
631 if ($sHost && strlen($oAddr->mailbox
)) {
632 $oAddr->host
= $sHost;
636 if (!$aAddrBookAddress && strlen($oAddr->mailbox
)) {
637 $aProcessedAddress[] = $oAddr;
639 $aProcessedAddress = array_merge($aProcessedAddress,$aAddrBookAddress);
643 return $aProcessedAddress;
645 if (isset($aProcessedAddress[0]))
646 return $aProcessedAddress[0];
653 * Normalise the different Priority headers into a uniform value,
654 * namely that of the X-Priority header (1, 3, 5). Supports:
655 * Priority, X-Priority, Importance.
656 * X-MS-Mail-Priority is not parsed because it always coincides
657 * with one of the other headers.
659 * NOTE: this is actually a duplicate from the code in
660 * functions/imap_messages:parseFetch().
661 * I'm not sure if it's ok here to call
663 * @param string $sValue literal priority name
666 function parsePriority($sValue) {
667 // don't use function call inside array_shift.
668 $aValue = preg_split('/\s/',trim($sValue));
669 $value = strtolower(array_shift($aValue));
671 if ( is_numeric($value) ) {
674 if ( $value == 'urgent' ||
$value == 'high' ) {
676 } elseif ( $value == 'non-urgent' ||
$value == 'low' ) {
679 // default is normal priority
684 * @param string $value content type header
686 function parseContentType($value) {
687 $pos = strpos($value, ';');
690 $type = trim(substr($value, 0, $pos));
691 $props = trim(substr($value, $pos+
1));
695 $content_type = new ContentType($type);
697 $properties = $this->parseProperties($props);
698 if (!isset($properties['charset'])) {
699 $properties['charset'] = 'us-ascii';
701 $content_type->properties
= $this->parseProperties($props);
703 $this->content_type
= $content_type;
708 * @param array $aParameters
711 function processParameters($aParameters) {
714 // handle multiline parameters
715 foreach($aParameters as $key => $value) {
716 if ($iPos = strpos($key,'*')) {
717 $sKey = substr($key,0,$iPos);
718 if (!isset($aResults[$sKey])) {
719 $aResults[$sKey] = $value;
720 if (substr($key,-1) == '*') { // parameter contains language/charset info
724 $aResults[$sKey] .= $value;
727 $aResults[$key] = $value;
730 foreach ($aCharset as $key) {
731 $value = $aResults[$key];
732 // extract the charset & language
733 $charset = substr($value,0,strpos($value,"'"));
734 $value = substr($value,strlen($charset)+
1);
735 $language = substr($value,0,strpos($value,"'"));
736 $value = substr($value,strlen($charset)+
1);
737 /* FIXME: What's the status of charset decode with language information ????
738 * Maybe language information contains only ascii text and charset_decode()
739 * only runs sm_encode_html_special_chars() on it. If it contains 8bit information, you
740 * get html encoded text in charset used by selected translation.
742 $value = charset_decode($charset,$value);
743 $aResults[$key] = $value;
749 * @param string $value
752 function parseProperties($value) {
753 $propArray = explode(';', $value);
754 $propResultArray = array();
755 foreach ($propArray as $prop) {
757 $pos = strpos($prop, '=');
759 $key = trim(substr($prop, 0, $pos));
760 $val = trim(substr($prop, $pos+
1));
761 if (strlen($val) > 0 && $val{0} == '"') {
762 $val = substr($val, 1, -1);
764 $propResultArray[$key] = $val;
767 return $this->processParameters($propResultArray);
771 * Fills disposition object in rfc822Header object
772 * @param string $value
774 function parseDisposition($value) {
775 $pos = strpos($value, ';');
778 $name = trim(substr($value, 0, $pos));
779 $props = trim(substr($value, $pos+
1));
783 $props_a = $this->parseProperties($props);
784 $disp = new Disposition($name);
785 $disp->properties
= $props_a;
786 $this->disposition
= $disp;
790 * Fills mlist array keys in rfc822Header object
791 * @param string $field
792 * @param string $value
794 function mlist($field, $value) {
796 $value_a = explode(',', $value);
797 foreach ($value_a as $val) {
799 if ($val{0} == '<') {
800 $val = substr($val, 1, -1);
802 if (substr($val, 0, 7) == 'mailto:') {
803 $res_a['mailto'] = substr($val, 7);
805 $res_a['href'] = $val;
808 $this->mlist
[$field] = $res_a;
812 * Parses the X-Spam-Status header
813 * @param string $value
815 function parseSpamStatus($value) {
816 // Header value looks like this:
817 // 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
819 $spam_status = array();
821 if (preg_match ('/^(No|Yes),\s+score=(-?\d+\.\d+)\s+required=(-?\d+\.\d+)\s+tests=(.*?)\s+autolearn=(.*?)\s+version=(.+?)$/', $value, $matches)) {
823 $spam_status['bad_format'] = 0;
824 $spam_status['value'] = $matches[0];
826 if (isset($matches[1])
827 && strtolower($matches[1]) == 'yes') {
828 $spam_status['is_spam'] = true;
830 $spam_status['is_spam'] = false;
834 $spam_status['score'] = $matches[2];
837 $spam_status['required'] = $matches[3];
841 $tests = explode(',', $matches[4]);
842 foreach ($tests as $test) {
843 $spam_status['tests'][] = trim($test);
847 $spam_status['autolearn'] = $matches[5];
850 $spam_status['version'] = $matches[6];
852 $spam_status['bad_format'] = 1;
853 $spam_status['value'] = $value;
859 * function to get the address strings out of the header.
860 * example1: header->getAddr_s('to').
861 * example2: header->getAddr_s(array('to', 'cc', 'bcc'))
862 * @param mixed $arr string or array of strings
863 * @param string $separator
864 * @param boolean $encoded (since 1.4.0) return encoded or plain text addresses
865 * @param boolean $unconditionally_quote (since 1.4.21/1.5.2) When TRUE, always
866 * quote the personal part,
867 * whether or not it is
868 * encoded, otherwise quoting
869 * is only added if the
870 * personal part is not encoded
873 function getAddr_s($arr, $separator = ', ', $encoded=false, $unconditionally_quote=FALSE) {
876 if (is_array($arr)) {
877 foreach($arr as $arg) {
878 if ($this->getAddr_s($arg, $separator, $encoded, $unconditionally_quote)) {
882 $s = ($s ?
substr($s, 2) : $s);
884 $addr = $this->{$arr};
885 if (is_array($addr)) {
886 foreach ($addr as $addr_o) {
887 if (is_object($addr_o)) {
889 $s .= $addr_o->getEncodedAddress($unconditionally_quote) . $separator;
891 $s .= $addr_o->getAddress(TRUE, FALSE, $unconditionally_quote) . $separator;
895 $s = substr($s, 0, -strlen($separator));
897 if (is_object($addr)) {
899 $s .= $addr->getEncodedAddress($unconditionally_quote);
901 $s .= $addr->getAddress(TRUE, FALSE, $unconditionally_quote);
910 * function to get the array of addresses out of the header.
911 * @param mixed $arg string or array of strings
912 * @param array $excl_arr array of excluded email addresses
913 * @param array $arr array of added email addresses
916 function getAddr_a($arg, $excl_arr = array(), $arr = array()) {
917 if (is_array($arg)) {
918 foreach($arg as $argument) {
919 $arr = $this->getAddr_a($argument, $excl_arr, $arr);
922 $addr = $this->{$arg};
923 if (is_array($addr)) {
924 foreach ($addr as $next_addr) {
925 if (is_object($next_addr)) {
926 if (isset($next_addr->host
) && ($next_addr->host
!= '')) {
927 $email = $next_addr->mailbox
. '@' . $next_addr->host
;
929 $email = $next_addr->mailbox
;
931 $email = strtolower($email);
932 if ($email && !isset($arr[$email]) && !isset($excl_arr[$email])) {
933 $arr[$email] = $next_addr->personal
;
938 if (is_object($addr)) {
939 $email = $addr->mailbox
;
940 $email .= (isset($addr->host
) ?
'@' . $addr->host
: '');
941 $email = strtolower($email);
942 if ($email && !isset($arr[$email]) && !isset($excl_arr[$email])) {
943 $arr[$email] = $addr->personal
;
952 //FIXME: This needs some documentation (inside the function too)! Don't code w/out comments!
953 * @param mixed $address array or string
954 * @param boolean $recurs
955 * @return mixed array, boolean
958 function findAddress($address, $recurs = false) {
960 if (is_array($address)) {
962 foreach($address as $argument) {
963 $match = $this->findAddress($argument, true);
967 if (count($match[0]) && !$result) {
974 if (!is_array($this->cc
)) $this->cc
= array();
975 if (!is_array($this->to
)) $this->to
= array();
976 $srch_addr = $this->parseAddress($address);
978 foreach ($this->to
as $to) {
979 if (strtolower($to->host
) == strtolower($srch_addr->host
)) {
980 if (strtolower($to->mailbox
) == strtolower($srch_addr->mailbox
)) {
981 $results[] = $srch_addr;
982 if (strtolower($to->personal
) == strtolower($srch_addr->personal
)) {
984 return array($results, true);
992 foreach ($this->cc
as $cc) {
993 if (strtolower($cc->host
) == strtolower($srch_addr->host
)) {
994 if (strtolower($cc->mailbox
) == strtolower($srch_addr->mailbox
)) {
995 $results[] = $srch_addr;
996 if (strtolower($cc->personal
) == strtolower($srch_addr->personal
)) {
998 return array($results, true);
1007 return array($results, false);
1008 } elseif (count($result)) {
1019 * @param string $type0 media type
1020 * @param string $type1 media subtype
1021 * @return array media properties
1022 * @todo check use of media type arguments
1024 function getContentType($type0, $type1) {
1025 $type0 = $this->content_type
->type0
;
1026 $type1 = $this->content_type
->type1
;
1027 return $this->content_type
->properties
;