6 * This contains all the functions needed to send messages through
9 * @author Marc Groot Koerkamp
10 * @copyright 1999-2013 The SquirrelMail Project Team
11 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
13 * @package squirrelmail
17 * Deliver Class - called to actually deliver the message
19 * This class is called by compose.php and other code that needs
20 * to send messages. All delivery functionality should be centralized
23 * Do not place UI code in this class, as UI code should be placed in templates
26 * @author Marc Groot Koerkamp
27 * @package squirrelmail
32 * function mail - send the message parts to the SMTP stream
34 * @param Message $message Message object to send
35 * NOTE that this is passed by
36 * reference and will be modified
37 * upon return with updated
38 * fields such as Message ID, References,
39 * In-Reply-To and Date headers.
40 * @param resource $stream Handle to the outgoing stream
41 * (when FALSE, nothing will be
42 * written to the stream; this can
43 * be used to determine the actual
44 * number of bytes that will be
45 * written to the stream)
46 * @param string $reply_id Identifies message being replied to
47 * (OPTIONAL; caller should ONLY specify
48 * a value for this when the message
49 * being sent is a reply)
50 * @param string $reply_ent_id Identifies message being replied to
51 * in the case it was an embedded/attached
52 * message inside another (OPTIONAL; caller
53 * should ONLY specify a value for this
54 * when the message being sent is a reply)
55 * @param resource $imap_stream If there is an open IMAP stream in
56 * the caller's context, it should be
57 * passed in here. This is OPTIONAL,
58 * as one will be created if not given,
59 * but as some IMAP servers may baulk
60 * at opening more than one connection
61 * at a time, the caller should always
62 * abide if possible. Currently, this
63 * stream is only used when $reply_id
64 * is also non-zero, but that is subject
66 * @param mixed $extra Any implementation-specific variables
67 * can be passed in here and used in
68 * an overloaded version of this method
71 * @return integer The number of bytes written (or that would have been
72 * written) to the output stream.
75 function mail(&$message, $stream=false, $reply_id=0, $reply_ent_id=0,
76 $imap_stream=NULL, $extra=NULL) {
78 $rfc822_header = &$message->rfc822_header
;
80 if (count($message->entities
)) {
81 $boundary = $this->mimeBoundary();
82 $rfc822_header->content_type
->properties
['boundary']='"'.$boundary.'"';
89 // calculate reply header if needed
92 global $imapConnection, $username, $imapServerAddress,
95 // try our best to use an existing IMAP handle
97 $close_imap_stream = FALSE;
98 if (is_resource($imap_stream)) {
99 $my_imap_stream = $imap_stream;
101 } else if (is_resource($imapConnection)) {
102 $my_imap_stream = $imapConnection;
105 $close_imap_stream = TRUE;
106 $my_imap_stream = sqimap_login($username, FALSE,
107 $imapServerAddress, $imapPort, 0);
110 sqimap_mailbox_select($my_imap_stream, $mailbox);
111 $reply_message = sqimap_get_message($my_imap_stream, $reply_id, $mailbox);
113 if ($close_imap_stream) {
114 sqimap_logout($my_imap_stream);
118 /* redefine the messsage in case of message/rfc822 */
119 $reply_message = $message->getEntity($reply_ent_id);
120 /* message is an entity which contains the envelope and type0=message
121 * and type1=rfc822. The actual entities are childs from
122 * $reply_message->entities[0]. That's where the encoding and is located
125 $orig_header = $reply_message->rfc822_header
; /* here is the envelope located */
128 $orig_header = $reply_message->rfc822_header
;
130 $message->reply_rfc822_header
= $orig_header;
134 $reply_rfc822_header = (isset($message->reply_rfc822_header
)
135 ?
$message->reply_rfc822_header
: '');
136 $header = $this->prepareRFC822_Header($rfc822_header, $reply_rfc822_header, $raw_length);
138 $this->send_mail($message, $header, $boundary, $stream, $raw_length, $extra);
144 * function send_mail - send the message parts to the IMAP stream
146 * @param Message $message Message object to send
147 * @param string $header Headers ready to send
148 * @param string $boundary Message parts boundary
149 * @param resource $stream Handle to the SMTP stream
150 * (when FALSE, nothing will be
151 * written to the stream; this can
152 * be used to determine the actual
153 * number of bytes that will be
154 * written to the stream)
155 * @param int &$raw_length The number of bytes written (or that
156 * would have been written) to the
157 * output stream - NOTE that this is
158 * passed by reference
159 * @param mixed $extra Any implementation-specific variables
160 * can be passed in here and used in
161 * an overloaded version of this method
167 function send_mail($message, $header, $boundary, $stream=false,
168 &$raw_length, $extra=NULL) {
172 $this->preWriteToStream($header);
173 $this->writeToStream($stream, $header);
175 $this->writeBody($message, $stream, $raw_length, $boundary);
179 * function writeBody - generate and write the mime boundaries around each part to the stream
181 * Recursively formats and writes the MIME boundaries of the $message
182 * to the output stream.
184 * @param Message $message Message object to transform
185 * @param resource $stream SMTP output stream
186 * (when FALSE, nothing will be
187 * written to the stream; this can
188 * be used to determine the actual
189 * number of bytes that will be
190 * written to the stream)
191 * @param integer &$length_raw raw length of the message (part)
192 * as returned by mail fn
193 * @param string $boundary custom boundary to call, usually for subparts
197 function writeBody($message, $stream, &$length_raw, $boundary='') {
198 // calculate boundary in case of multidimensional mime structures
199 if ($boundary && $message->entity_id
&& count($message->entities
)) {
200 if (strpos($boundary,'_part_')) {
201 $boundary = substr($boundary,0,strpos($boundary,'_part_'));
203 // the next four lines use strrev to reverse any nested boundaries
204 // because RFC 2046 (5.1.1) says that if a line starts with the outer
205 // boundary string (doesn't matter what the line ends with), that
206 // can be considered a match for the outer boundary; thus the nested
207 // boundary needs to be unique from the outer one
209 } else if (strpos($boundary,'_trap_')) {
210 $boundary = substr(strrev($boundary),0,strpos(strrev($boundary),'_part_'));
212 $boundary_new = strrev($boundary . '_part_'.$message->entity_id
);
214 $boundary_new = $boundary;
216 if ($boundary && !$message->rfc822_header
) {
217 $s = '--'.$boundary."\r\n";
218 $s .= $this->prepareMIME_Header($message, $boundary_new);
219 $length_raw +
= strlen($s);
221 $this->preWriteToStream($s);
222 $this->writeToStream($stream, $s);
225 $this->writeBodyPart($message, $stream, $length_raw);
228 for ($i=0, $entCount=count($message->entities
);$i<$entCount;$i++
) {
229 $msg = $this->writeBody($message->entities
[$i], $stream, $length_raw, $boundary_new);
230 if ($i == $entCount-1) $last = true;
232 if ($boundary && $last) {
233 $s = "--".$boundary_new."--\r\n\r\n";
234 $length_raw +
= strlen($s);
236 $this->preWriteToStream($s);
237 $this->writeToStream($stream, $s);
243 * function writeBodyPart - write each individual mimepart
245 * Recursively called by WriteBody to write each mime part to the SMTP stream
247 * @param Message $message Message object to transform
248 * @param resource $stream SMTP output stream
249 * (when FALSE, nothing will be
250 * written to the stream; this can
251 * be used to determine the actual
252 * number of bytes that will be
253 * written to the stream)
254 * @param integer &$length length of the message part
255 * as returned by mail fn
259 function writeBodyPart($message, $stream, &$length) {
260 if ($message->mime_header
) {
261 $type0 = $message->mime_header
->type0
;
263 $type0 = $message->rfc822_header
->content_type
->type0
;
266 $body_part_trailing = $last = '';
271 if ($message->body_part
) {
272 $body_part = $message->body_part
;
273 // remove NUL characters
274 $body_part = str_replace("\0",'',$body_part);
275 $length +
= $this->clean_crlf($body_part);
277 $this->preWriteToStream($body_part);
278 $this->writeToStream($stream, $body_part);
281 } elseif ($message->att_local_name
) {
282 global $username, $attachment_dir;
283 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
284 $filename = $message->att_local_name
;
286 // inspect attached file for lines longer than allowed by RFC,
287 // in which case we'll be using base64 encoding (so we can split
288 // the lines up without corrupting them) instead of 8bit unencoded...
289 // (see RFC 2822/2.1.1)
291 // using 990 because someone somewhere is folding lines at
292 // 990 instead of 998 and I'm too lazy to find who it is
294 $file_has_long_lines = file_has_long_lines($hashed_attachment_dir
295 . '/' . $filename, 990);
297 $file = fopen ($hashed_attachment_dir . '/' . $filename, 'rb');
299 // long lines were found, need to use base64 encoding
301 if ($file_has_long_lines) {
302 while ($tmp = fread($file, 570)) {
303 $body_part = chunk_split(base64_encode($tmp));
304 // Up to 4.3.10 chunk_split always appends a newline,
305 // while in 4.3.11 it doesn't if the string to split
306 // is shorter than the chunk length.
307 if( substr($body_part, -1 , 1 ) != "\n" )
309 $length +
= $this->clean_crlf($body_part);
311 $this->writeToStream($stream, $body_part);
316 // no excessively long lines - normal 8bit
319 while ($body_part = fgets($file, 4096)) {
320 // remove NUL characters
321 $body_part = str_replace("\0",'',$body_part);
322 $length +
= $this->clean_crlf($body_part);
324 $this->preWriteToStream($body_part);
325 $this->writeToStream($stream, $body_part);
335 if ($message->body_part
) {
336 $body_part = $message->body_part
;
337 // remove NUL characters
338 $body_part = str_replace("\0",'',$body_part);
339 $length +
= $this->clean_crlf($body_part);
341 $this->writeToStream($stream, $body_part);
343 } elseif ($message->att_local_name
) {
344 global $username, $attachment_dir;
345 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
346 $filename = $message->att_local_name
;
347 $file = fopen ($hashed_attachment_dir . '/' . $filename, 'rb');
348 while ($tmp = fread($file, 570)) {
349 $body_part = chunk_split(base64_encode($tmp));
350 // Up to 4.3.10 chunk_split always appends a newline,
351 // while in 4.3.11 it doesn't if the string to split
352 // is shorter than the chunk length.
353 if( substr($body_part, -1 , 1 ) != "\n" )
355 $length +
= $this->clean_crlf($body_part);
357 $this->writeToStream($stream, $body_part);
364 $body_part_trailing = '';
365 if ($last && substr($last,-1) != "\n") {
366 $body_part_trailing = "\r\n";
368 if ($body_part_trailing) {
369 $length +
= strlen($body_part_trailing);
371 $this->preWriteToStream($body_part_trailing);
372 $this->writeToStream($stream, $body_part_trailing);
378 * function clean_crlf - change linefeeds and newlines to legal characters
380 * The SMTP format only allows CRLF as line terminators.
381 * This function replaces illegal teminators with the correct terminator.
383 * @param string &$s string to clean linefeeds on
387 function clean_crlf(&$s) {
388 $s = str_replace("\r\n", "\n", $s);
389 $s = str_replace("\r", "\n", $s);
390 $s = str_replace("\n", "\r\n", $s);
395 * function strip_crlf - strip linefeeds and newlines from a string
397 * The SMTP format only allows CRLF as line terminators.
398 * This function strips all line terminators from the string.
400 * @param string &$s string to clean linefeeds on
404 function strip_crlf(&$s) {
405 $s = str_replace("\r\n ", '', $s);
406 $s = str_replace("\r", '', $s);
407 $s = str_replace("\n", '', $s);
411 * function preWriteToStream - reserved for extended functionality
413 * This function is not yet implemented.
414 * Reserved for extended functionality.
416 * @param string &$s string to operate on
420 function preWriteToStream(&$s) {
424 * function writeToStream - write data to the SMTP stream
426 * @param resource $stream SMTP output stream
427 * @param string $data string with data to send to the SMTP stream
431 function writeToStream($stream, $data) {
432 fputs($stream, $data);
436 * function initStream - reserved for extended functionality
438 * This function is not yet implemented.
439 * Reserved for extended functionality.
440 * UPDATE: It is implemented in Deliver_SMTP and Deliver_SendMail classes,
441 * but it remains unimplemented in this base class (and thus not
442 * in Deliver_IMAP or other child classes that don't define it)
444 * NOTE: some parameters are specific to the child class
445 * that is implementing this method
447 * @param Message $message Message object
448 * @param string $domain
449 * @param integer $length
450 * @param string $host host name or IP to connect to
451 * @param integer $port
452 * @param string $user username to log into the SMTP server with
453 * @param string $pass password to log into the SMTP server with
454 * @param boolean $authpop whether or not to use POP-before-SMTP authorization
455 * @param string $pop_host host name or IP to connect to for POP-before-SMTP authorization
457 * @return handle $stream file handle resource to SMTP stream
459 function initStream($message, $domain, $length=0, $host='', $port='', $user='', $pass='', $authpop=false, $pop_host='') {
464 * function getBCC - reserved for extended functionality
466 * This function is not yet implemented.
467 * Reserved for extended functionality.
475 * function prepareMIME_Header - creates the mime header
477 * @param Message $message Message object to act on
478 * @param string $boundary mime boundary from fn MimeBoundary
480 * @return string $header properly formatted mime header
482 function prepareMIME_Header($message, $boundary) {
483 $mime_header = $message->mime_header
;
487 $contenttype = 'Content-Type: '. $mime_header->type0
.'/'.
489 if (count($message->entities
)) {
490 $contenttype .= ';' . 'boundary="'.$boundary.'"';
492 if (isset($mime_header->parameters
['name'])) {
493 $contenttype .= '; name="'.
494 encodeHeader($mime_header->parameters
['name']). '"';
496 if (isset($mime_header->parameters
['charset'])) {
497 $charset = $mime_header->parameters
['charset'];
498 $contenttype .= '; charset="'.
499 encodeHeader($charset). '"';
502 $header[] = $contenttype . $rn;
503 if ($mime_header->description
) {
504 $header[] = 'Content-Description: ' . $mime_header->description
. $rn;
506 if ($mime_header->encoding
) {
507 $header[] = 'Content-Transfer-Encoding: ' . $mime_header->encoding
. $rn;
510 // inspect attached file for lines longer than allowed by RFC,
511 // in which case we'll be using base64 encoding (so we can split
512 // the lines up without corrupting them) instead of 8bit unencoded...
513 // (see RFC 2822/2.1.1)
515 if (!empty($message->att_local_name
)) { // is this redundant? I have no idea
516 global $username, $attachment_dir;
517 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
518 $filename = $hashed_attachment_dir . '/' . $message->att_local_name
;
520 // using 990 because someone somewhere is folding lines at
521 // 990 instead of 998 and I'm too lazy to find who it is
523 $file_has_long_lines = file_has_long_lines($filename, 990);
525 $file_has_long_lines = FALSE;
527 if ($mime_header->type0
== 'multipart' ||
$mime_header->type0
== 'alternative') {
528 /* no-op; no encoding needed */
529 } else if (($mime_header->type0
== 'text' ||
$mime_header->type0
== 'message')
530 && !$file_has_long_lines) {
531 $header[] = 'Content-Transfer-Encoding: 8bit' . $rn;
533 $header[] = 'Content-Transfer-Encoding: base64' . $rn;
536 if ($mime_header->id
) {
537 $header[] = 'Content-ID: ' . $mime_header->id
. $rn;
539 if ($mime_header->disposition
) {
540 $disposition = $mime_header->disposition
;
541 $contentdisp = 'Content-Disposition: ' . $disposition->name
;
542 if ($disposition->getProperty('filename')) {
543 $contentdisp .= '; filename="'.
544 encodeHeader($disposition->getProperty('filename')). '"';
546 $header[] = $contentdisp . $rn;
548 if ($mime_header->md5
) {
549 $header[] = 'Content-MD5: ' . $mime_header->md5
. $rn;
551 if ($mime_header->language
) {
552 $header[] = 'Content-Language: ' . $mime_header->language
. $rn;
555 $cnt = count($header);
557 for ($i = 0 ; $i < $cnt ; $i++
) {
558 $hdr_s .= $this->foldLine($header[$i], 78);
561 $header .= $rn; /* One blank line to separate mimeheader and body-entity */
566 * function prepareRFC822_Header - prepares the RFC822 header string from Rfc822Header object(s)
568 * This function takes the Rfc822Header object(s) and formats them
569 * into the RFC822Header string to send to the SMTP server as part
570 * of the SMTP message.
572 * @param Rfc822Header $rfc822_header
573 * @param Rfc822Header $reply_rfc822_header
574 * @param integer &$raw_length length of the message
576 * @return string $header
578 function prepareRFC822_Header(&$rfc822_header, $reply_rfc822_header, &$raw_length) {
579 global $domain, $username, $encode_header_key,
580 $edit_identity, $hide_auth_header;
582 /* if server var SERVER_NAME not available, or contains
583 ":" (e.g. IPv6) which is illegal in a Message-ID, use $domain */
584 if(!sqGetGlobalVar('SERVER_NAME', $SERVER_NAME, SQ_SERVER
) ||
585 strpos($SERVER_NAME,':') !== FALSE) {
586 $SERVER_NAME = $domain;
589 sqGetGlobalVar('REMOTE_ADDR', $REMOTE_ADDR, SQ_SERVER
);
590 sqGetGlobalVar('REMOTE_PORT', $REMOTE_PORT, SQ_SERVER
);
591 sqGetGlobalVar('REMOTE_HOST', $REMOTE_HOST, SQ_SERVER
);
592 sqGetGlobalVar('HTTP_VIA', $HTTP_VIA, SQ_SERVER
);
593 sqGetGlobalVar('HTTP_X_FORWARDED_FOR', $HTTP_X_FORWARDED_FOR, SQ_SERVER
);
597 /* This creates an RFC 822 date */
598 $date = date('D, j M Y H:i:s ', time()) . $this->timezone();
600 /* Create a message-id */
601 $message_id = 'MESSAGE ID GENERATION ERROR! PLEASE CONTACT SQUIRRELMAIL DEVELOPERS';
602 if (empty($rfc822_header->message_id
)) {
604 . md5(GenerateRandomString(16, '', 7) . uniqid(mt_rand(),true))
605 . '.squirrel@' . $SERVER_NAME .'>';
608 /* Make an RFC822 Received: line */
609 if (isset($REMOTE_HOST)) {
610 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
612 $received_from = $REMOTE_ADDR;
614 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
615 if (!isset($HTTP_X_FORWARDED_FOR) ||
$HTTP_X_FORWARDED_FOR == '') {
616 $HTTP_X_FORWARDED_FOR = 'unknown';
618 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
623 * SquirrelMail header
625 * This Received: header provides information that allows to track
626 * user and machine that was used to send email. Don't remove it
627 * unless you understand all possible forging issues or your
628 * webmail installation does not prevent changes in user's email address.
629 * See SquirrelMail bug tracker #847107 for more details about it.
631 * Add hide_squirrelmail_header as a candidate for config_local.php
632 * (must be defined as a constant: define('hide_squirrelmail_header', 1);
633 * to allow completely hiding SquirrelMail participation in message
634 * processing; This is dangerous, especially if users can modify their
635 * account information, as it makes mapping a sent message back to the
636 * original sender almost impossible.
638 $show_sm_header = ( defined('hide_squirrelmail_header') ?
! hide_squirrelmail_header
: 1 );
640 // FIXME: The following headers may generate slightly differently between the message sent to the destination and that stored in the Sent folder because this code will be called before both actions. This is not necessarily a big problem, but other headers such as Message-ID and Date are preserved between both actions
641 if ( $show_sm_header ) {
642 if (isset($encode_header_key) &&
643 trim($encode_header_key)!='') {
644 // use encoded headers, if encryption key is set and not empty
645 $header[] = 'X-Squirrel-UserHash: '.OneTimePadEncrypt($username,base64_encode($encode_header_key)).$rn;
646 $header[] = 'X-Squirrel-FromHash: '.OneTimePadEncrypt($this->ip2hex($REMOTE_ADDR),base64_encode($encode_header_key)).$rn;
647 if (isset($HTTP_X_FORWARDED_FOR))
648 $header[] = 'X-Squirrel-ProxyHash:'.OneTimePadEncrypt($this->ip2hex($HTTP_X_FORWARDED_FOR),base64_encode($encode_header_key)).$rn;
650 // use default received headers
651 $header[] = "Received: from $received_from" . $rn;
652 if (!isset($hide_auth_header) ||
!$hide_auth_header)
653 $header[] = " (SquirrelMail authenticated user $username)" . $rn;
654 $header[] = " by $SERVER_NAME with HTTP;" . $rn;
655 $header[] = " $date" . $rn;
659 /* Insert the rest of the header fields */
661 if (!empty($rfc822_header->message_id
)) {
662 $header[] = 'Message-ID: '. $rfc822_header->message_id
. $rn;
664 $header[] = 'Message-ID: '. $message_id . $rn;
665 $rfc822_header->message_id
= $message_id;
668 if (is_object($reply_rfc822_header) &&
669 isset($reply_rfc822_header->message_id
) &&
670 $reply_rfc822_header->message_id
) {
671 $rep_message_id = $reply_rfc822_header->message_id
;
672 $header[] = 'In-Reply-To: '.$rep_message_id . $rn;
673 $rfc822_header->in_reply_to
= $rep_message_id;
674 $references = $this->calculate_references($reply_rfc822_header);
675 $header[] = 'References: '.$references . $rn;
676 $rfc822_header->references
= $references;
679 if (!empty($rfc822_header->date
) && $rfc822_header->date
!= -1) {
680 $header[] = 'Date: '. $rfc822_header->date
. $rn;
682 $header[] = "Date: $date" . $rn;
683 $rfc822_header->date
= $date;
686 $header[] = 'Subject: '.encodeHeader($rfc822_header->subject
) . $rn;
687 $header[] = 'From: '. $rfc822_header->getAddr_s('from',",$rn ",true) . $rn;
689 // folding address list [From|To|Cc|Bcc] happens by using ",$rn<space>"
691 // Do not use foldLine for that.
693 // RFC2822 if from contains more then 1 address
694 if (count($rfc822_header->from
) > 1) {
695 $header[] = 'Sender: '. $rfc822_header->getAddr_s('sender',',',true) . $rn;
697 if (count($rfc822_header->to
)) {
698 $header[] = 'To: '. $rfc822_header->getAddr_s('to',",$rn ",true) . $rn;
700 if (count($rfc822_header->cc
)) {
701 $header[] = 'Cc: '. $rfc822_header->getAddr_s('cc',",$rn ",true) . $rn;
703 if (count($rfc822_header->reply_to
)) {
704 $header[] = 'Reply-To: '. $rfc822_header->getAddr_s('reply_to',',',true) . $rn;
706 /* Sendmail should return true. Default = false */
707 $bcc = $this->getBcc();
708 if (count($rfc822_header->bcc
)) {
709 $s = 'Bcc: '. $rfc822_header->getAddr_s('bcc',",$rn ",true) . $rn;
711 $raw_length +
= strlen($s);
716 /* Identify SquirrelMail */
717 $header[] = 'User-Agent: SquirrelMail/' . SM_VERSION
. $rn;
718 /* Do the MIME-stuff */
719 $header[] = 'MIME-Version: 1.0' . $rn;
720 $contenttype = 'Content-Type: '. $rfc822_header->content_type
->type0
.'/'.
721 $rfc822_header->content_type
->type1
;
722 if (count($rfc822_header->content_type
->properties
)) {
723 foreach ($rfc822_header->content_type
->properties
as $k => $v) {
725 $contenttype .= ';' .$k.'='.$v;
729 $header[] = $contenttype . $rn;
730 if ($encoding = $rfc822_header->encoding
) {
731 $header[] = 'Content-Transfer-Encoding: ' . $encoding . $rn;
733 if (isset($rfc822_header->dnt
) && $rfc822_header->dnt
) {
734 $dnt = $rfc822_header->getAddr_s('dnt');
736 $header[] = 'X-Confirm-Reading-To: '.$dnt. $rn;
738 $header[] = 'Disposition-Notification-To: '.$dnt. $rn;
740 if ($rfc822_header->priority
) {
741 switch($rfc822_header->priority
)
744 $header[] = 'X-Priority: 1 (Highest)'.$rn;
745 $header[] = 'Importance: High'. $rn; break;
747 $header[] = 'X-Priority: 5 (Lowest)'.$rn;
748 $header[] = 'Importance: Low'. $rn; break;
752 /* Insert headers from the $more_headers array */
753 if(count($rfc822_header->more_headers
)) {
754 reset($rfc822_header->more_headers
);
755 foreach ($rfc822_header->more_headers
as $k => $v) {
756 $header[] = $k.': '.$v .$rn;
759 $cnt = count($header);
762 for ($i = 0 ; $i < $cnt ; $i++
) {
763 $sKey = substr($header[$i],0,strpos($header[$i],':'));
768 $hdr_s .= $header[$i];
771 $sRefs = substr($header[$i],12);
772 $aRefs = explode(' ',$sRefs);
773 $sLine = 'References:';
774 foreach ($aRefs as $sReference) {
775 if ( trim($sReference) == '' ) {
776 /* Don't add spaces. */
777 } elseif (strlen($sLine)+
strlen($sReference) >76) {
779 $sLine = $rn . ' ' . $sReference;
781 $sLine .= ' '. $sReference;
790 $hdr_s .= $header[$i];
792 default: $hdr_s .= $this->foldLine($header[$i], 78); break;
796 $header .= $rn; /* One blank line to separate header and body */
797 $raw_length +
= strlen($header);
802 * Fold header lines per RFC 2822/2.2.3 and RFC 822/3.1.1
804 * Herein "soft" folding/wrapping (with whitespace tokens) is
805 * what we refer to as the preferred method of wrapping - that
806 * which we'd like to do within the $soft_wrap limit, but if
807 * not possible, we will try to do as soon as possible after
808 * $soft_wrap up to the $hard_wrap limit. Encoded words don't
809 * need to be detected in this phase, since they cannot contain
812 * "Hard" folding/wrapping (with "hard" tokens) is what we refer
813 * to as less ideal wrapping that will be done to keep within
814 * the $hard_wrap limit. This adds other syntactical breaking
815 * elements such as commas and encoded words.
817 * @param string $header The header content being folded
818 * @param integer $soft_wrap The desirable maximum line length
819 * (OPTIONAL; default is 78, per RFC)
820 * @param string $indent Wrapped lines will already have
821 * whitespace following the CRLF wrap,
822 * but you can add more indentation (or
823 * whatever) with this. The use of this
824 * parameter is DISCOURAGED, since it
825 * can corrupt the redisplay (unfolding)
826 * of headers whose content is space-
827 * sensitive, like subjects, etc.
828 * (OPTIONAL; default is an empty string)
829 * @param string $hard_wrap The absolute maximum line length
830 * (OPTIONAL; default is 998, per RFC)
832 * @return string The folded header content, with a trailing CRLF.
835 function foldLine($header, $soft_wrap=78, $indent='', $hard_wrap=998) {
837 // the "hard" token list can be altered if desired,
838 // for example, by adding ":"
839 // (in the future, we can take optional arguments
840 // for overriding or adding elements to the "hard"
841 // token list if we want to get fancy)
843 // the order of these is significant - preferred
844 // fold points should be listed first
846 // it is advised that the "=" always come first
847 // since it also finds encoded words, thus if it
848 // comes after some other token that happens to
849 // fall within the encoded word, the encoded word
850 // could be inadvertently broken in half, which
851 // is not allowable per RFC
853 $hard_break_tokens = array(
854 '=', // includes encoded word detection
859 // the order of these is significant too
870 // if using an indent string, reduce wrap limits by its size
872 if (!empty($indent)) {
873 $soft_wrap -= strlen($indent);
874 $hard_wrap -= strlen($indent);
877 while (strlen($header) > $soft_wrap) {
879 $soft_wrapped_line = substr($header, 0, $soft_wrap);
881 // look for a token as close to the end of the soft wrap limit as possible
883 foreach ($whitespace as $token) {
885 // note that this if statement also fails when $pos === 0,
886 // which is intended, since blank lines are not allowed
888 if ($pos = strrpos($soft_wrapped_line, $token))
890 $new_fold = substr($header, 0, $pos);
892 // make sure proposed fold doesn't create a blank line
894 if (!trim($new_fold)) continue;
896 // with whitespace breaks, we fold BEFORE the token
898 $folded_header .= $new_fold . $CRLF . $indent;
899 $header = substr($header, $pos);
901 // ready for next while() iteration
909 // we were unable to find a wrapping point within the soft
910 // wrap limit, so now we'll try to find the first possible
911 // soft wrap point within the hard wrap limit
913 $hard_wrapped_line = substr($header, 0, $hard_wrap);
915 // look for a *SOFT* token as close to the
916 // beginning of the hard wrap limit as possible
918 foreach ($whitespace as $token) {
920 // use while loop instead of if block because it
921 // is possible we don't want the first one we find
923 $pos = $soft_wrap - 1; // -1 is corrected by +1 on next line
924 while ($pos = strpos($hard_wrapped_line, $token, $pos +
1))
927 $new_fold = substr($header, 0, $pos);
929 // make sure proposed fold doesn't create a blank line
931 if (!trim($new_fold)) continue;
933 // with whitespace breaks, we fold BEFORE the token
935 $folded_header .= $new_fold . $CRLF . $indent;
936 $header = substr($header, $pos);
938 // ready for next outter while() iteration
946 // we were still unable to find a soft wrapping point within
947 // both the soft and hard wrap limits, so if the length of
948 // what is left is no more than the hard wrap limit, we'll
949 // simply take the whole thing
951 if (strlen($header) <= strlen($hard_wrapped_line))
954 // otherwise, we can't quit yet - look for a "hard" token
955 // as close to the end of the hard wrap limit as possible
957 foreach ($hard_break_tokens as $token) {
959 // note that this if statement also fails when $pos === 0,
960 // which is intended, since blank lines are not allowed
962 if ($pos = strrpos($hard_wrapped_line, $token))
965 // if we found a "=" token, we must determine whether,
966 // if it is part of an encoded word, it is the beginning
967 // or middle of one, where we need to readjust $pos a bit
971 // if we found the beginning of an encoded word,
972 // we want to break BEFORE the token
974 if (preg_match('/^(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)/Ui',
975 substr($header, $pos))) {
979 // check if we found this token in the *middle*
980 // of an encoded word, in which case we have to
981 // ignore it, pushing back to the token that
982 // starts the encoded word instead
984 // of course, this is only possible if there is
985 // more content after the next hard wrap
987 // then look for the end of an encoded word in
988 // the next part (past the next hard wrap)
990 // then see if it is in fact part of a legitimate
993 else if (strlen($header) > $hard_wrap
994 && ($end_pos = strpos(substr($header, $hard_wrap), '?=')) !== FALSE
995 && preg_match('/(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)$/Ui',
996 substr($header, 0, $hard_wrap +
$end_pos +
2),
999 $pos = $hard_wrap +
$end_pos +
2 - strlen($matches[1]) - 1;
1005 // $pos could have been changed; make sure it's
1006 // not at the beginning of the line, as blank
1007 // lines are not allowed
1009 if ($pos === 0) continue;
1011 // we are dealing with a simple token break...
1013 // for non-whitespace breaks, we fold AFTER the token
1014 // and add a space after the fold if not immediately
1015 // followed by a whitespace character in the next part
1017 $folded_header .= substr($header, 0, $pos +
1) . $CRLF;
1019 // don't go beyond end of $header, though
1021 if (strlen($header) > $pos +
1) {
1022 $header = substr($header, $pos +
1);
1023 if (!in_array($header{0}, $whitespace))
1024 $header = ' ' . $indent . $header;
1029 // ready for next while() iteration
1037 // finally, we just couldn't find anything to fold on, so we
1038 // have to just cut it off at the hard limit
1040 $folded_header .= $hard_wrapped_line . $CRLF;
1044 if (strlen($header) > strlen($hard_wrapped_line)) {
1045 $header = substr($header, strlen($hard_wrapped_line));
1046 if (!in_array($header{0}, $whitespace))
1047 $header = ' ' . $indent . $header;
1055 // add any left-overs
1057 $folded_header .= $header;
1060 // make sure it ends with a CRLF
1062 if (substr($folded_header, -2) != $CRLF) $folded_header .= $CRLF;
1065 return $folded_header;
1069 * function mimeBoundary - calculates the mime boundary to use
1071 * This function will generate a random mime boundary base part
1072 * for the message if the boundary has not already been set.
1074 * @return string $mimeBoundaryString random mime boundary string
1076 function mimeBoundary () {
1077 static $mimeBoundaryString;
1079 if ( !isset( $mimeBoundaryString ) ||
1080 $mimeBoundaryString == '') {
1081 $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
1082 mt_rand( 10000, 99999 );
1084 return $mimeBoundaryString;
1088 * function timezone - Time offset for correct timezone
1090 * @return string $result with timezone and offset
1092 function timezone () {
1093 global $invert_time, $show_timezone_name;
1095 $diff_second = date('Z');
1097 $diff_second = - $diff_second;
1099 if ($diff_second > 0) {
1104 $diff_second = abs($diff_second);
1105 $diff_hour = floor ($diff_second / 3600);
1106 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
1108 // If an administrator wants to add the timezone name to the
1109 // end of the date header, they can set $show_timezone_name
1110 // to boolean TRUE in config/config_local.php, but that is
1111 // NOT RFC-822 compliant (see section 5.1). Moreover, some
1112 // Windows users reported that strftime('%Z') was returning
1113 // the full zone name (not the abbreviation) which in some
1114 // cases included 8-bit characters (not allowed as is in headers).
1115 // The PHP manual actually does NOT promise what %Z will return
1116 // for strftime!: "The time zone offset/abbreviation option NOT
1117 // given by %z (depends on operating system)"
1119 if ($show_timezone_name) {
1120 $zonename = '('.strftime('%Z').')';
1121 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
1123 $result = sprintf ("%s%02d%02d", $sign, $diff_hour, $diff_minute);
1129 * function calculate_references - calculate correct References string
1130 * Adds the current message ID, and makes sure it doesn't grow forever,
1131 * to that extent it drops message-ID's in a smart way until the string
1132 * length is under the recommended value of 1000 ("References: <986>\r\n").
1133 * It always keeps the first and the last three ID's.
1135 * @param Rfc822Header $hdr message header to calculate from
1137 * @return string $refer concatenated and trimmed References string
1139 function calculate_references($hdr) {
1140 $aReferences = preg_split('/\s+/', $hdr->references
);
1141 $message_id = $hdr->message_id
;
1142 $in_reply_to = $hdr->in_reply_to
;
1144 // if References already exists, add the current message ID at the end.
1145 // no References exists; if we know a IRT, add that aswell
1146 if (count($aReferences) == 0 && $in_reply_to) {
1147 $aReferences[] = $in_reply_to;
1149 $aReferences[] = $message_id;
1151 // sanitize the array: trim whitespace, remove dupes
1152 array_walk($aReferences, 'sq_trim_value');
1153 $aReferences = array_unique($aReferences);
1155 while ( count($aReferences) > 4 && strlen(implode(' ', $aReferences)) >= 986 ) {
1156 $aReferences = array_merge(array_slice($aReferences,0,1),array_slice($aReferences,2));
1158 return implode(' ', $aReferences);
1162 * Converts ip address to hexadecimal string
1164 * Function is used to convert ipv4 and ipv6 addresses to hex strings.
1165 * It removes all delimiter symbols from ip addresses, converts decimal
1166 * ipv4 numbers to hex and pads strings in order to present full length
1167 * address. ipv4 addresses are represented as 8 byte strings, ipv6 addresses
1168 * are represented as 32 byte string.
1170 * If function fails to detect address format, it returns unprocessed string.
1171 * @param string $string ip address string
1172 * @return string processed ip address string
1173 * @since 1.5.1 and 1.4.5
1175 function ip2hex($string) {
1176 if (preg_match("/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/",$string,$match)) {
1178 $ret = str_pad(dechex($match[1]),2,'0',STR_PAD_LEFT
)
1179 . str_pad(dechex($match[2]),2,'0',STR_PAD_LEFT
)
1180 . str_pad(dechex($match[3]),2,'0',STR_PAD_LEFT
)
1181 . str_pad(dechex($match[4]),2,'0',STR_PAD_LEFT
);
1182 } elseif (preg_match("/^([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)$/i",$string,$match)) {
1183 // full ipv6 address
1184 $ret = str_pad($match[1],4,'0',STR_PAD_LEFT
)
1185 . str_pad($match[2],4,'0',STR_PAD_LEFT
)
1186 . str_pad($match[3],4,'0',STR_PAD_LEFT
)
1187 . str_pad($match[4],4,'0',STR_PAD_LEFT
)
1188 . str_pad($match[5],4,'0',STR_PAD_LEFT
)
1189 . str_pad($match[6],4,'0',STR_PAD_LEFT
)
1190 . str_pad($match[7],4,'0',STR_PAD_LEFT
)
1191 . str_pad($match[8],4,'0',STR_PAD_LEFT
);
1192 } elseif (preg_match("/^\:\:([0-9a-h\:]+)$/i",$string,$match)) {
1193 // short ipv6 with all starting symbols nulled
1194 $aAddr=explode(':',$match[1]);
1196 foreach ($aAddr as $addr) {
1197 $ret.=str_pad($addr,4,'0',STR_PAD_LEFT
);
1199 $ret=str_pad($ret,32,'0',STR_PAD_LEFT
);
1200 } elseif (preg_match("/^([0-9a-h\:]+)::([0-9a-h\:]+)$/i",$string,$match)) {
1201 // short ipv6 with middle part nulled
1202 $aStart=explode(':',$match[1]);
1204 foreach($aStart as $addr) {
1205 $sStart.=str_pad($addr,4,'0',STR_PAD_LEFT
);
1207 $aEnd = explode(':',$match[2]);
1209 foreach($aEnd as $addr) {
1210 $sEnd.=str_pad($addr,4,'0',STR_PAD_LEFT
);
1213 . str_pad('',(32 - strlen($sStart . $sEnd)),'0',STR_PAD_LEFT
)
1216 // unknown addressing