4 * Rfc822Header.class.php
6 * This file contains functions needed to handle headers in mime messages.
8 * @copyright © 2003-2006 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 = '';
120 var $content_id = '';
124 var $content_desc = '';
128 var $mlist = array();
131 * only needed for constructing headers in delivery class
134 var $more_headers = array();
137 * @param mixed $hdr string or array with message headers
139 function parseHeader($hdr) {
140 if (is_array($hdr)) {
141 $hdr = implode('', $hdr);
143 /* First we replace \r\n by \n and unfold the header */
144 /* FIXME: unfolding header with multiple spaces "\n( +)" */
145 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $hdr));
147 /* Now we can make a new header array with */
148 /* each element representing a headerline */
149 $hdr = explode("\n" , $hdr);
150 foreach ($hdr as $line) {
151 $pos = strpos($line, ':');
153 $field = substr($line, 0, $pos);
154 if (!strstr($field,' ')) { /* valid field */
155 $value = trim(substr($line, $pos+
1));
156 $this->parseField($field, $value);
160 if (!is_object($this->content_type
)) {
161 $this->parseContentType('text/plain; charset=us-ascii');
166 * @param string $value
169 function stripComments($value) {
171 $cnt = strlen($value);
172 for ($i = 0; $i < $cnt; ++
$i) {
173 switch ($value{$i}) {
176 while ((++
$i < $cnt) && ($value{$i} != '"')) {
177 if ($value{$i} == '\\') {
181 $result .= $value{$i};
184 $result .= $value{$i};
189 while (($depth > 0) && (++
$i < $cnt)) {
206 $result .= $value{$i};
214 * Parse header field according to field type
215 * @param string $field field name
216 * @param string $value field value
218 function parseField($field, $value) {
219 $field = strtolower($field);
222 $value = $this->stripComments($value);
223 $d = strtr($value, array(' ' => ' '));
224 $d = explode(' ', $d);
225 $this->date
= getTimeStamp($d);
228 $this->subject
= $value;
231 $this->from
= $this->parseAddress($value,true);
234 $this->sender
= $this->parseAddress($value);
237 $this->reply_to
= $this->parseAddress($value, true);
239 case 'mail-followup-to':
240 $this->mail_followup_to
= $this->parseAddress($value, true);
243 $this->to
= $this->parseAddress($value, true);
246 $this->cc
= $this->parseAddress($value, true);
249 $this->bcc
= $this->parseAddress($value, true);
252 $this->in_reply_to
= $value;
255 $value = $this->stripComments($value);
256 $this->message_id
= $value;
259 $value = $this->stripComments($value);
260 $this->references
= $value;
262 case 'x-confirm-reading-to':
263 case 'return-receipt-to':
264 case 'disposition-notification-to':
265 $value = $this->stripComments($value);
266 $this->dnt
= $this->parseAddress($value);
269 $value = $this->stripComments($value);
270 $value = str_replace(' ', '', $value);
271 $this->mime
= ($value == '1.0' ?
true : $this->mime
);
274 $value = $this->stripComments($value);
275 $this->parseContentType($value);
277 case 'content-disposition':
278 $value = $this->stripComments($value);
279 $this->parseDisposition($value);
281 case 'content-transfer-encoding':
282 $this->encoding
= $value;
284 case 'content-description':
285 $this->content_desc
= $value;
288 $value = $this->stripComments($value);
289 $this->content_id
= $value;
293 $this->xmailer
= $value;
298 $this->priority
= $this->parsePriority($value);
301 $value = $this->stripComments($value);
302 $this->mlist('post', $value);
305 $value = $this->stripComments($value);
306 $this->mlist('reply', $value);
308 case 'list-subscribe':
309 $value = $this->stripComments($value);
310 $this->mlist('subscribe', $value);
312 case 'list-unsubscribe':
313 $value = $this->stripComments($value);
314 $this->mlist('unsubscribe', $value);
317 $value = $this->stripComments($value);
318 $this->mlist('archive', $value);
321 $value = $this->stripComments($value);
322 $this->mlist('owner', $value);
325 $value = $this->stripComments($value);
326 $this->mlist('help', $value);
329 $value = $this->stripComments($value);
330 $this->mlist('id', $value);
338 * @param string $address
341 function getAddressTokens($address) {
343 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
344 $aReplace = array(' (',' <',' ,',' ;',' :');
345 $address = str_replace($aSpecials,$aReplace,$address);
346 $iCnt = strlen($address);
349 $cChar = $address{$i};
353 $iEnd = strpos($address,'>',$i+
1);
355 $sToken = substr($address,$i);
358 $sToken = substr($address,$i,$iEnd - $i +
1);
361 $sToken = str_replace($aReplace, $aSpecials,$sToken);
362 if ($sToken) $aTokens[] = $sToken;
365 $iEnd = strpos($address,$cChar,$i+
1);
367 // skip escaped quotes
368 $prev_char = $address{$iEnd-1};
369 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
370 $iEnd = strpos($address,$cChar,$iEnd+
1);
372 $prev_char = $address{$iEnd-1};
379 $sToken = substr($address,$i);
382 // also remove the surrounding quotes
383 $sToken = substr($address,$i+
1,$iEnd - $i -1);
386 $sToken = str_replace($aReplace, $aSpecials,$sToken);
387 if ($sToken) $aTokens[] = $sToken;
390 array_pop($aTokens); //remove inserted space
391 $iEnd = strpos($address,')',$i);
393 $sToken = substr($address,$i);
398 while (($iDepth > 0) && (++
$iComment < $iCnt)) {
399 $cCharComment = $address{$iComment};
400 switch($cCharComment) {
415 $sToken = substr($address,$i,$iComment - $i +
1);
418 $sToken = substr($address,$i,$iEnd - $i +
1);
422 // check the next token in case comments appear in the middle of email addresses
423 $prevToken = end($aTokens);
424 if (!in_array($prevToken,$aSpecials,true)) {
425 if ($i+
1<strlen($address) && !in_array($address{$i+
1},$aSpecials,true)) {
426 $iEnd = strpos($address,' ',$i+
1);
428 $sNextToken = trim(substr($address,$i+
1,$iEnd - $i -1));
431 $sNextToken = trim(substr($address,$i+
1));
436 // create token and add it again
437 $sNewToken = $prevToken . $sNextToken;
438 if($sNewToken) $aTokens[] = $sNewToken;
441 $sToken = str_replace($aReplace, $aSpecials,$sToken);
442 if ($sToken) $aTokens[] = $sToken;
451 $iEnd = strpos($address,' ',$i+
1);
453 $sToken = trim(substr($address,$i,$iEnd - $i));
456 $sToken = trim(substr($address,$i));
459 if ($sToken) $aTokens[] = $sToken;
467 * @param array $aStack
468 * @param array $aComment
469 * @param string $sEmail
470 * @param string $sGroup
471 * @return object AddressStructure object
473 function createAddressObject(&$aStack,&$aComment,&$sEmail,$sGroup='') {
474 //$aStack=explode(' ',implode('',$aStack));
476 while (count($aStack) && !$sEmail) {
477 $sEmail = trim(array_pop($aStack));
480 if (count($aStack)) {
481 $sPersonal = trim(implode('',$aStack));
485 if (!$sPersonal && count($aComment)) {
486 $sComment = trim(implode(' ',$aComment));
487 $sPersonal .= $sComment;
489 $oAddr =& new AddressStructure();
490 if ($sPersonal && substr($sPersonal,0,2) == '=?') {
491 $oAddr->personal
= encodeHeader($sPersonal);
493 $oAddr->personal
= $sPersonal;
495 // $oAddr->group = $sGroup;
496 $iPosAt = strpos($sEmail,'@');
498 $oAddr->mailbox
= substr($sEmail, 0, $iPosAt);
499 $oAddr->host
= substr($sEmail, $iPosAt+
1);
501 $oAddr->mailbox
= $sEmail;
502 $oAddr->host
= false;
505 $aStack = $aComment = array();
510 * recursive function for parsing address strings and storing them in an address stucture object.
511 * personal name: encoded: =?charset?Q|B?string?=
514 * email : <mailbox@host>
516 * This function is also used for validating addresses returned from compose
517 * That's also the reason that the function became a little bit huge
518 * @param string $address
519 * @param boolean $ar return array instead of only the first element
520 * @param array $addr_ar (obsolete) array with parsed addresses
521 * @param string $group (obsolete)
522 * @param string $host default domainname in case of addresses without a domainname
523 * @param string $lookup (since) callback function for lookup of address strings which are probably nicks (without @)
524 * @return mixed array with AddressStructure objects or only one address_structure object.
526 function parseAddress($address,$ar=false,$aAddress=array(),$sGroup='',$sHost='',$lookup=false) {
527 $aTokens = $this->getAddressTokens($address);
528 $sPersonal = $sEmail = $sGroup = '';
529 $aStack = $aComment = array();
530 foreach ($aTokens as $sToken) {
540 $aComment[] = substr($sToken,1,-1);
544 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
545 $oAddr = end($aAddress);
546 if(!$oAddr ||
((isset($oAddr)) && !$oAddr->mailbox
&& !$oAddr->personal
)) {
547 $sEmail = $sGroup . ':;';
549 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
551 $aStack = $aComment = array();
555 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail,$sGroup);
558 $sGroup = trim(implode(' ',$aStack));
559 $sGroup = preg_replace('/\s+/',' ',$sGroup);
563 $sEmail = trim(substr($sToken,1,-1));
568 default: $aStack[] = $sToken; break;
571 /* now do the action again for the last address */
572 $aAddress[] = $this->createAddressObject($aStack,$aComment,$sEmail);
573 /* try to lookup the addresses in case of invalid email addresses */
574 $aProcessedAddress = array();
575 foreach ($aAddress as $oAddr) {
576 $aAddrBookAddress = array();
578 $grouplookup = false;
580 $aAddr = call_user_func_array($lookup,array($oAddr->mailbox
));
581 if (isset($aAddr['email'])) {
582 if (strpos($aAddr['email'],',')) {
584 $aAddrBookAddress = $this->parseAddress($aAddr['email'],true);
586 $iPosAt = strpos($aAddr['email'], '@');
587 $oAddr->mailbox
= substr($aAddr['email'], 0, $iPosAt);
588 $oAddr->host
= substr($aAddr['email'], $iPosAt+
1);
589 if (isset($aAddr['name'])) {
590 $oAddr->personal
= $aAddr['name'];
592 $oAddr->personal
= encodeHeader($sPersonal);
597 if (!$grouplookup && !$oAddr->mailbox
) {
598 $oAddr->mailbox
= trim($sEmail);
599 if ($sHost && $oAddr->mailbox
) {
600 $oAddr->host
= $sHost;
602 } else if (!$grouplookup && !$oAddr->host
) {
603 if ($sHost && $oAddr->mailbox
) {
604 $oAddr->host
= $sHost;
608 if (!$aAddrBookAddress && $oAddr->mailbox
) {
609 $aProcessedAddress[] = $oAddr;
611 $aProcessedAddress = array_merge($aProcessedAddress,$aAddrBookAddress);
615 return $aProcessedAddress;
617 return $aProcessedAddress[0];
622 * Normalise the different Priority headers into a uniform value,
623 * namely that of the X-Priority header (1, 3, 5). Supports:
624 * Priority, X-Priority, Importance.
625 * X-MS-Mail-Priority is not parsed because it always coincides
626 * with one of the other headers.
628 * NOTE: this is actually a duplicate from the function in
629 * functions/imap_messages. I'm not sure if it's ok here to call
631 * @param string $sValue literal priority name
634 function parsePriority($sValue) {
635 // don't use function call inside array_shift.
636 $aValue = split('/\w/',trim($sValue));
637 $value = strtolower(array_shift($aValue));
639 if ( is_numeric($value) ) {
642 if ( $value == 'urgent' ||
$value == 'high' ) {
644 } elseif ( $value == 'non-urgent' ||
$value == 'low' ) {
647 // default is normal priority
652 * @param string $value content type header
654 function parseContentType($value) {
655 $pos = strpos($value, ';');
658 $type = trim(substr($value, 0, $pos));
659 $props = trim(substr($value, $pos+
1));
663 $content_type = new ContentType($type);
665 $properties = $this->parseProperties($props);
666 if (!isset($properties['charset'])) {
667 $properties['charset'] = 'us-ascii';
669 $content_type->properties
= $this->parseProperties($props);
671 $this->content_type
= $content_type;
676 * @param array $aParameters
679 function processParameters($aParameters) {
682 // handle multiline parameters
683 foreach($aParameters as $key => $value) {
684 if ($iPos = strpos($key,'*')) {
685 $sKey = substr($key,0,$iPos);
686 if (!isset($aResults[$sKey])) {
687 $aResults[$sKey] = $value;
688 if (substr($key,-1) == '*') { // parameter contains language/charset info
692 $aResults[$sKey] .= $value;
695 $aResults[$key] = $value;
698 foreach ($aCharset as $key) {
699 $value = $aResults[$key];
700 // extract the charset & language
701 $charset = substr($value,0,strpos($value,"'"));
702 $value = substr($value,strlen($charset)+
1);
703 $language = substr($value,0,strpos($value,"'"));
704 $value = substr($value,strlen($charset)+
1);
705 /* FIXME: What's the status of charset decode with language information ????
706 * Maybe language information contains only ascii text and charset_decode()
707 * only runs htmlspecialchars() on it. If it contains 8bit information, you
708 * get html encoded text in charset used by selected translation.
710 $value = charset_decode($charset,$value);
711 $aResults[$key] = $value;
717 * @param string $value
720 function parseProperties($value) {
721 $propArray = explode(';', $value);
722 $propResultArray = array();
723 foreach ($propArray as $prop) {
725 $pos = strpos($prop, '=');
727 $key = trim(substr($prop, 0, $pos));
728 $val = trim(substr($prop, $pos+
1));
729 if (strlen($val) > 0 && $val{0} == '"') {
730 $val = substr($val, 1, -1);
732 $propResultArray[$key] = $val;
735 return $this->processParameters($propResultArray);
739 * Fills disposition object in rfc822Header object
740 * @param string $value
742 function parseDisposition($value) {
743 $pos = strpos($value, ';');
746 $name = trim(substr($value, 0, $pos));
747 $props = trim(substr($value, $pos+
1));
751 $props_a = $this->parseProperties($props);
752 $disp = new Disposition($name);
753 $disp->properties
= $props_a;
754 $this->disposition
= $disp;
758 * Fills mlist array keys in rfc822Header object
759 * @param string $field
760 * @param string $value
762 function mlist($field, $value) {
764 $value_a = explode(',', $value);
765 foreach ($value_a as $val) {
767 if ($val{0} == '<') {
768 $val = substr($val, 1, -1);
770 if (substr($val, 0, 7) == 'mailto:') {
771 $res_a['mailto'] = substr($val, 7);
773 $res_a['href'] = $val;
776 $this->mlist
[$field] = $res_a;
780 * function to get the address strings out of the header.
781 * example1: header->getAddr_s('to').
782 * example2: header->getAddr_s(array('to', 'cc', 'bcc'))
783 * @param mixed $arr string or array of strings
784 * @param string $separator
785 * @param boolean $encoded (since 1.4.0) return encoded or plain text addresses
788 function getAddr_s($arr, $separator = ',',$encoded=false) {
791 if (is_array($arr)) {
792 foreach($arr as $arg) {
793 if ($this->getAddr_s($arg, $separator, $encoded)) {
797 $s = ($s ?
substr($s, 2) : $s);
799 $addr = $this->{$arr};
800 if (is_array($addr)) {
801 foreach ($addr as $addr_o) {
802 if (is_object($addr_o)) {
804 $s .= $addr_o->getEncodedAddress() . $separator;
806 $s .= $addr_o->getAddress() . $separator;
810 $s = substr($s, 0, -strlen($separator));
812 if (is_object($addr)) {
814 $s .= $addr->getEncodedAddress();
816 $s .= $addr->getAddress();
825 * function to get the array of addresses out of the header.
826 * @param mixed $arg string or array of strings
827 * @param array $excl_arr array of excluded email addresses
828 * @param array $arr array of added email addresses
831 function getAddr_a($arg, $excl_arr = array(), $arr = array()) {
832 if (is_array($arg)) {
833 foreach($arg as $argument) {
834 $arr = $this->getAddr_a($argument, $excl_arr, $arr);
837 $addr = $this->{$arg};
838 if (is_array($addr)) {
839 foreach ($addr as $next_addr) {
840 if (is_object($next_addr)) {
841 if (isset($next_addr->host
) && ($next_addr->host
!= '')) {
842 $email = $next_addr->mailbox
. '@' . $next_addr->host
;
844 $email = $next_addr->mailbox
;
846 $email = strtolower($email);
847 if ($email && !isset($arr[$email]) && !isset($excl_arr[$email])) {
848 $arr[$email] = $next_addr->personal
;
853 if (is_object($addr)) {
854 $email = $addr->mailbox
;
855 $email .= (isset($addr->host
) ?
'@' . $addr->host
: '');
856 $email = strtolower($email);
857 if ($email && !isset($arr[$email]) && !isset($excl_arr[$email])) {
858 $arr[$email] = $addr->personal
;
867 * @param mixed $address array or string
868 * @param boolean $recurs
869 * @return mixed array, boolean
872 function findAddress($address, $recurs = false) {
874 if (is_array($address)) {
876 foreach($address as $argument) {
877 $match = $this->findAddress($argument, true);
881 if (count($match[0]) && !$result) {
888 if (!is_array($this->cc
)) $this->cc
= array();
889 $srch_addr = $this->parseAddress($address);
891 foreach ($this->to
as $to) {
892 if ($to->host
== $srch_addr->host
) {
893 if ($to->mailbox
== $srch_addr->mailbox
) {
894 $results[] = $srch_addr;
895 if ($to->personal
== $srch_addr->personal
) {
897 return array($results, true);
905 foreach ($this->cc
as $cc) {
906 if ($cc->host
== $srch_addr->host
) {
907 if ($cc->mailbox
== $srch_addr->mailbox
) {
908 $results[] = $srch_addr;
909 if ($cc->personal
== $srch_addr->personal
) {
911 return array($results, true);
920 return array($results, false);
921 } elseif (count($result)) {
932 * @param string $type0 media type
933 * @param string $type1 media subtype
934 * @return array media properties
935 * @todo check use of media type arguments
937 function getContentType($type0, $type1) {
938 $type0 = $this->content_type
->type0
;
939 $type1 = $this->content_type
->type1
;
940 return $this->content_type
->properties
;