4 * Rfc822Header.class.php
6 * This file contains functions needed to handle headers in mime messages.
8 * @copyright © 2003-2007 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
50 var $reply_to = array();
52 * Mail-Followup-To header
55 var $mail_followup_to = array();
75 var $in_reply_to = '';
94 var $content_type = '';
98 var $disposition = '';
110 * Disposition notification for requesting message delivery notification (MDN)
115 * Delivery notification (DR)
126 var $content_id = '';
130 var $content_desc = '';
134 var $mlist = array();
136 * SpamAssassin 'x-spam-status' header
139 var $x_spam_status = array();
142 * only needed for constructing headers in delivery class
145 var $more_headers = array();
148 * @param mixed $hdr string or array with message headers
150 function parseHeader($hdr) {
151 if (is_array($hdr)) {
152 $hdr = implode('', $hdr);
154 /* First we replace \r\n by \n and unfold the header */
155 /* FIXME: unfolding header with multiple spaces "\n( +)" */
156 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $hdr));
158 /* Now we can make a new header array with */
159 /* each element representing a headerline */
160 $hdr = explode("\n" , $hdr);
161 foreach ($hdr as $line) {
162 $pos = strpos($line, ':');
164 $field = substr($line, 0, $pos);
165 if (!strstr($field,' ')) { /* valid field */
166 $value = trim(substr($line, $pos+
1));
167 $this->parseField($field, $value);
171 if (!is_object($this->content_type
)) {
172 $this->parseContentType('text/plain; charset=us-ascii');
177 * @param string $value
180 function stripComments($value) {
182 $cnt = strlen($value);
183 for ($i = 0; $i < $cnt; ++
$i) {
184 switch ($value{$i}) {
187 while ((++
$i < $cnt) && ($value{$i} != '"')) {
188 if ($value{$i} == '\\') {
192 $result .= $value{$i};
195 $result .= $value{$i};
200 while (($depth > 0) && (++
$i < $cnt)) {
217 $result .= $value{$i};
225 * Parse header field according to field type
226 * @param string $field field name
227 * @param string $value field value
229 function parseField($field, $value) {
230 $field = strtolower($field);
233 $value = $this->stripComments($value);
234 $d = strtr($value, array(' ' => ' '));
235 $d = explode(' ', $d);
236 $this->date
= getTimeStamp($d);
239 $this->subject
= $value;
242 $this->from
= $this->parseAddress($value,true);
245 $this->sender
= $this->parseAddress($value);
248 $this->reply_to
= $this->parseAddress($value, true);
250 case 'mail-followup-to':
251 $this->mail_followup_to
= $this->parseAddress($value, true);
254 $this->to
= $this->parseAddress($value, true);
257 $this->cc
= $this->parseAddress($value, true);
260 $this->bcc
= $this->parseAddress($value, true);
263 $this->in_reply_to
= $value;
266 $value = $this->stripComments($value);
267 $this->message_id
= $value;
270 $value = $this->stripComments($value);
271 $this->references
= $value;
273 case 'x-confirm-reading-to':
274 case 'disposition-notification-to':
275 $value = $this->stripComments($value);
276 $this->dnt
= $this->parseAddress($value);
278 case 'return-receipt-to':
279 $value = $this->stripComments($value);
280 $this->drnt
= $this->parseAddress($value);
283 $value = $this->stripComments($value);
284 $value = str_replace(' ', '', $value);
285 $this->mime
= ($value == '1.0' ?
true : $this->mime
);
288 $value = $this->stripComments($value);
289 $this->parseContentType($value);
291 case 'content-disposition':
292 $value = $this->stripComments($value);
293 $this->parseDisposition($value);
295 case 'content-transfer-encoding':
296 $this->encoding
= $value;
298 case 'content-description':
299 $this->content_desc
= $value;
302 $value = $this->stripComments($value);
303 $this->content_id
= $value;
307 $this->xmailer
= $value;
312 $this->priority
= $this->parsePriority($value);
315 $value = $this->stripComments($value);
316 $this->mlist('post', $value);
319 $value = $this->stripComments($value);
320 $this->mlist('reply', $value);
322 case 'list-subscribe':
323 $value = $this->stripComments($value);
324 $this->mlist('subscribe', $value);
326 case 'list-unsubscribe':
327 $value = $this->stripComments($value);
328 $this->mlist('unsubscribe', $value);
331 $value = $this->stripComments($value);
332 $this->mlist('archive', $value);
335 $value = $this->stripComments($value);
336 $this->mlist('owner', $value);
339 $value = $this->stripComments($value);
340 $this->mlist('help', $value);
343 $value = $this->stripComments($value);
344 $this->mlist('id', $value);
346 case 'x-spam-status':
347 $this->x_spam_status
= $this->parseSpamStatus($value);
355 * @param string $address
358 function getAddressTokens($address) {
360 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
361 $aReplace = array(' (',' <',' ,',' ;',' :');
362 $address = str_replace($aSpecials,$aReplace,$address);
363 $iCnt = strlen($address);
366 $cChar = $address{$i};
370 $iEnd = strpos($address,'>',$i+
1);
372 $sToken = substr($address,$i);
375 $sToken = substr($address,$i,$iEnd - $i +
1);
378 $sToken = str_replace($aReplace, $aSpecials,$sToken);
379 if ($sToken) $aTokens[] = $sToken;
382 $iEnd = strpos($address,$cChar,$i+
1);
384 // skip escaped quotes
385 $prev_char = $address{$iEnd-1};
386 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
387 $iEnd = strpos($address,$cChar,$iEnd+
1);
389 $prev_char = $address{$iEnd-1};
396 $sToken = substr($address,$i);
399 // also remove the surrounding quotes
400 $sToken = substr($address,$i+
1,$iEnd - $i -1);
403 $sToken = str_replace($aReplace, $aSpecials,$sToken);
404 if ($sToken) $aTokens[] = $sToken;
407 array_pop($aTokens); //remove inserted space
408 $iEnd = strpos($address,')',$i);
410 $sToken = substr($address,$i);
415 while (($iDepth > 0) && (++
$iComment < $iCnt)) {
416 $cCharComment = $address{$iComment};
417 switch($cCharComment) {
432 $sToken = substr($address,$i,$iComment - $i +
1);
435 $sToken = substr($address,$i,$iEnd - $i +
1);
439 // check the next token in case comments appear in the middle of email addresses
440 $prevToken = end($aTokens);
441 if (!in_array($prevToken,$aSpecials,true)) {
442 if ($i+
1<strlen($address) && !in_array($address{$i+
1},$aSpecials,true)) {
443 $iEnd = strpos($address,' ',$i+
1);
445 $sNextToken = trim(substr($address,$i+
1,$iEnd - $i -1));
448 $sNextToken = trim(substr($address,$i+
1));
453 // create token and add it again
454 $sNewToken = $prevToken . $sNextToken;
455 if($sNewToken) $aTokens[] = $sNewToken;
458 $sToken = str_replace($aReplace, $aSpecials,$sToken);
459 if ($sToken) $aTokens[] = $sToken;
468 $iEnd = strpos($address,' ',$i+
1);
470 $sToken = trim(substr($address,$i,$iEnd - $i));
473 $sToken = trim(substr($address,$i));
476 if ($sToken) $aTokens[] = $sToken;
484 * @param array $aStack
485 * @param array $aComment
486 * @param string $sEmail
487 * @param string $sGroup
488 * @return object AddressStructure object
490 function createAddressObject(&$aStack,&$aComment,&$sEmail,$sGroup='') {
491 //$aStack=explode(' ',implode('',$aStack));
493 while (count($aStack) && !$sEmail) {
494 $sEmail = trim(array_pop($aStack));
497 if (count($aStack)) {
498 $sPersonal = trim(implode('',$aStack));
502 if (!$sPersonal && count($aComment)) {
503 $sComment = trim(implode(' ',$aComment));
504 $sPersonal .= $sComment;
506 $oAddr =& new AddressStructure();
507 if ($sPersonal && substr($sPersonal,0,2) == '=?') {
508 $oAddr->personal
= encodeHeader($sPersonal);
510 $oAddr->personal
= $sPersonal;
512 // $oAddr->group = $sGroup;
513 $iPosAt = strpos($sEmail,'@');
515 $oAddr->mailbox
= substr($sEmail, 0, $iPosAt);
516 $oAddr->host
= substr($sEmail, $iPosAt+
1);
518 $oAddr->mailbox
= $sEmail;
519 $oAddr->host
= false;
522 $aStack = $aComment = array();
527 * recursive function for parsing address strings and storing them in an address stucture object.
528 * personal name: encoded: =?charset?Q|B?string?=
531 * email : <mailbox@host>
533 * This function is also used for validating addresses returned from compose
534 * That's also the reason that the function became a little bit huge
535 * @param string $address
536 * @param boolean $ar return array instead of only the first element
537 * @param array $addr_ar (obsolete) array with parsed addresses
538 * @param string $group (obsolete)
539 * @param string $host default domainname in case of addresses without a domainname
540 * @param string $lookup (since) callback function for lookup of address strings which are probably nicks (without @)
541 * @return mixed array with AddressStructure objects or only one address_structure object.
543 function parseAddress($address,$ar=false,$aAddress=array(),$sGroup='',$sHost='',$lookup=false) {
544 $aTokens = $this->getAddressTokens($address);
545 $sPersonal = $sEmail = $sGroup = '';
546 $aStack = $aComment = array();
547 foreach ($aTokens as $sToken) {
557 $aComment[] = substr($sToken,1,-1);
561 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
562 $oAddr = end($aAddress);
563 if(!$oAddr ||
((isset($oAddr)) && !$oAddr->mailbox
&& !$oAddr->personal
)) {
564 $sEmail = $sGroup . ':;';
566 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
568 $aStack = $aComment = array();
572 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
575 $sGroup = trim(implode(' ',$aStack));
576 $sGroup = preg_replace('/\s+/',' ',$sGroup);
580 $sEmail = trim(substr($sToken,1,-1));
585 default: $aStack[] = $sToken; break;
588 /* now do the action again for the last address */
589 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail);
590 /* try to lookup the addresses in case of invalid email addresses */
591 $aProcessedAddress = array();
592 foreach ($aAddress as $oAddr) {
593 $aAddrBookAddress = array();
595 $grouplookup = false;
597 $aAddr = call_user_func_array($lookup,array($oAddr->mailbox
));
598 if (isset($aAddr['email'])) {
599 if (strpos($aAddr['email'],',')) {
601 $aAddrBookAddress = $this->parseAddress($aAddr['email'],true);
603 $iPosAt = strpos($aAddr['email'], '@');
604 $oAddr->mailbox
= substr($aAddr['email'], 0, $iPosAt);
605 $oAddr->host
= substr($aAddr['email'], $iPosAt+
1);
606 if (isset($aAddr['name'])) {
607 $oAddr->personal
= $aAddr['name'];
609 $oAddr->personal
= encodeHeader($sPersonal);
614 if (!$grouplookup && !$oAddr->mailbox
) {
615 $oAddr->mailbox
= trim($sEmail);
616 if ($sHost && $oAddr->mailbox
) {
617 $oAddr->host
= $sHost;
619 } else if (!$grouplookup && !$oAddr->host
) {
620 if ($sHost && $oAddr->mailbox
) {
621 $oAddr->host
= $sHost;
625 if (!$aAddrBookAddress && $oAddr->mailbox
) {
626 $aProcessedAddress[] = $oAddr;
628 $aProcessedAddress = array_merge($aProcessedAddress,$aAddrBookAddress);
632 return $aProcessedAddress;
634 return $aProcessedAddress[0];
639 * Normalise the different Priority headers into a uniform value,
640 * namely that of the X-Priority header (1, 3, 5). Supports:
641 * Priority, X-Priority, Importance.
642 * X-MS-Mail-Priority is not parsed because it always coincides
643 * with one of the other headers.
645 * NOTE: this is actually a duplicate from the function in
646 * functions/imap_messages. I'm not sure if it's ok here to call
648 * @param string $sValue literal priority name
651 function parsePriority($sValue) {
652 // don't use function call inside array_shift.
653 $aValue = split('/\w/',trim($sValue));
654 $value = strtolower(array_shift($aValue));
656 if ( is_numeric($value) ) {
659 if ( $value == 'urgent' ||
$value == 'high' ) {
661 } elseif ( $value == 'non-urgent' ||
$value == 'low' ) {
664 // default is normal priority
669 * @param string $value content type header
671 function parseContentType($value) {
672 $pos = strpos($value, ';');
675 $type = trim(substr($value, 0, $pos));
676 $props = trim(substr($value, $pos+
1));
680 $content_type = new ContentType($type);
682 $properties = $this->parseProperties($props);
683 if (!isset($properties['charset'])) {
684 $properties['charset'] = 'us-ascii';
686 $content_type->properties
= $this->parseProperties($props);
688 $this->content_type
= $content_type;
693 * @param array $aParameters
696 function processParameters($aParameters) {
699 // handle multiline parameters
700 foreach($aParameters as $key => $value) {
701 if ($iPos = strpos($key,'*')) {
702 $sKey = substr($key,0,$iPos);
703 if (!isset($aResults[$sKey])) {
704 $aResults[$sKey] = $value;
705 if (substr($key,-1) == '*') { // parameter contains language/charset info
709 $aResults[$sKey] .= $value;
712 $aResults[$key] = $value;
715 foreach ($aCharset as $key) {
716 $value = $aResults[$key];
717 // extract the charset & language
718 $charset = substr($value,0,strpos($value,"'"));
719 $value = substr($value,strlen($charset)+
1);
720 $language = substr($value,0,strpos($value,"'"));
721 $value = substr($value,strlen($charset)+
1);
722 /* FIXME: What's the status of charset decode with language information ????
723 * Maybe language information contains only ascii text and charset_decode()
724 * only runs htmlspecialchars() on it. If it contains 8bit information, you
725 * get html encoded text in charset used by selected translation.
727 $value = charset_decode($charset,$value);
728 $aResults[$key] = $value;
734 * @param string $value
737 function parseProperties($value) {
738 $propArray = explode(';', $value);
739 $propResultArray = array();
740 foreach ($propArray as $prop) {
742 $pos = strpos($prop, '=');
744 $key = trim(substr($prop, 0, $pos));
745 $val = trim(substr($prop, $pos+
1));
746 if (strlen($val) > 0 && $val{0} == '"') {
747 $val = substr($val, 1, -1);
749 $propResultArray[$key] = $val;
752 return $this->processParameters($propResultArray);
756 * Fills disposition object in rfc822Header object
757 * @param string $value
759 function parseDisposition($value) {
760 $pos = strpos($value, ';');
763 $name = trim(substr($value, 0, $pos));
764 $props = trim(substr($value, $pos+
1));
768 $props_a = $this->parseProperties($props);
769 $disp = new Disposition($name);
770 $disp->properties
= $props_a;
771 $this->disposition
= $disp;
775 * Fills mlist array keys in rfc822Header object
776 * @param string $field
777 * @param string $value
779 function mlist($field, $value) {
781 $value_a = explode(',', $value);
782 foreach ($value_a as $val) {
784 if ($val{0} == '<') {
785 $val = substr($val, 1, -1);
787 if (substr($val, 0, 7) == 'mailto:') {
788 $res_a['mailto'] = substr($val, 7);
790 $res_a['href'] = $val;
793 $this->mlist
[$field] = $res_a;
797 * Parses the X-Spam-Status header
798 * @param string $value
800 function parseSpamStatus($value) {
801 // Header value looks like this:
802 // 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
804 $spam_status = array();
806 if (preg_match ('/^(No|Yes),\s+score=(-?\d+\.\d+)\s+required=(-?\d+\.\d+)\s+tests=(.*?)\s+autolearn=(.*?)\s+version=(.+?)$/', $value, $matches)) {
808 $spam_status['bad_format'] = 0;
809 $spam_status['value'] = $matches[0];
811 if (isset($matches[1])
812 && strtolower($matches[1]) == 'yes') {
813 $spam_status['is_spam'] = true;
815 $spam_status['is_spam'] = false;
819 $spam_status['score'] = $matches[2];
822 $spam_status['required'] = $matches[3];
826 $tests = explode(',', $matches[4]);
827 foreach ($tests as $test) {
828 $spam_status['tests'][] = trim($test);
832 $spam_status['autolearn'] = $matches[5];
835 $spam_status['version'] = $matches[6];
837 $spam_status['bad_format'] = 1;
838 $spam_status['value'] = $value;
844 * function to get the address strings out of the header.
845 * example1: header->getAddr_s('to').
846 * example2: header->getAddr_s(array('to', 'cc', 'bcc'))
847 * @param mixed $arr string or array of strings
848 * @param string $separator
849 * @param boolean $encoded (since 1.4.0) return encoded or plain text addresses
852 function getAddr_s($arr, $separator = ',',$encoded=false) {
855 if (is_array($arr)) {
856 foreach($arr as $arg) {
857 if ($this->getAddr_s($arg, $separator, $encoded)) {
861 $s = ($s ?
substr($s, 2) : $s);
863 $addr = $this->{$arr};
864 if (is_array($addr)) {
865 foreach ($addr as $addr_o) {
866 if (is_object($addr_o)) {
868 $s .= $addr_o->getEncodedAddress() . $separator;
870 $s .= $addr_o->getAddress() . $separator;
874 $s = substr($s, 0, -strlen($separator));
876 if (is_object($addr)) {
878 $s .= $addr->getEncodedAddress();
880 $s .= $addr->getAddress();
889 * function to get the array of addresses out of the header.
890 * @param mixed $arg string or array of strings
891 * @param array $excl_arr array of excluded email addresses
892 * @param array $arr array of added email addresses
895 function getAddr_a($arg, $excl_arr = array(), $arr = array()) {
896 if (is_array($arg)) {
897 foreach($arg as $argument) {
898 $arr = $this->getAddr_a($argument, $excl_arr, $arr);
901 $addr = $this->{$arg};
902 if (is_array($addr)) {
903 foreach ($addr as $next_addr) {
904 if (is_object($next_addr)) {
905 if (isset($next_addr->host
) && ($next_addr->host
!= '')) {
906 $email = $next_addr->mailbox
. '@' . $next_addr->host
;
908 $email = $next_addr->mailbox
;
910 $email = strtolower($email);
911 if ($email && !isset($arr[$email]) && !isset($excl_arr[$email])) {
912 $arr[$email] = $next_addr->personal
;
917 if (is_object($addr)) {
918 $email = $addr->mailbox
;
919 $email .= (isset($addr->host
) ?
'@' . $addr->host
: '');
920 $email = strtolower($email);
921 if ($email && !isset($arr[$email]) && !isset($excl_arr[$email])) {
922 $arr[$email] = $addr->personal
;
931 * @param mixed $address array or string
932 * @param boolean $recurs
933 * @return mixed array, boolean
936 function findAddress($address, $recurs = false) {
938 if (is_array($address)) {
940 foreach($address as $argument) {
941 $match = $this->findAddress($argument, true);
945 if (count($match[0]) && !$result) {
952 if (!is_array($this->cc
)) $this->cc
= array();
953 $srch_addr = $this->parseAddress($address);
955 foreach ($this->to
as $to) {
956 if ($to->host
== $srch_addr->host
) {
957 if ($to->mailbox
== $srch_addr->mailbox
) {
958 $results[] = $srch_addr;
959 if ($to->personal
== $srch_addr->personal
) {
961 return array($results, true);
969 foreach ($this->cc
as $cc) {
970 if ($cc->host
== $srch_addr->host
) {
971 if ($cc->mailbox
== $srch_addr->mailbox
) {
972 $results[] = $srch_addr;
973 if ($cc->personal
== $srch_addr->personal
) {
975 return array($results, true);
984 return array($results, false);
985 } elseif (count($result)) {
996 * @param string $type0 media type
997 * @param string $type1 media subtype
998 * @return array media properties
999 * @todo check use of media type arguments
1001 function getContentType($type0, $type1) {
1002 $type0 = $this->content_type
->type0
;
1003 $type1 = $this->content_type
->type1
;
1004 return $this->content_type
->properties
;