5 * Copyright (c) 1999-2005 The SquirrelMail Project Team
6 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 * This contains all the functions needed to send messages through
12 * @author Marc Groot Koerkamp
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 class to send
35 * @param resource $stream file handle to the SMTP stream
37 * @return integer $raw_length
39 function mail($message, $stream=false) {
40 $rfc822_header = $message->rfc822_header
;
41 if (count($message->entities
)) {
42 $boundary = $this->mimeBoundary();
43 $rfc822_header->content_type
->properties
['boundary']='"'.$boundary.'"';
48 $reply_rfc822_header = (isset($message->reply_rfc822_header
)
49 ?
$message->reply_rfc822_header
: '');
50 $header = $this->prepareRFC822_Header($rfc822_header, $reply_rfc822_header, $raw_length);
53 $this->preWriteToStream($header);
54 $this->writeToStream($stream, $header);
56 $this->writeBody($message, $stream, $raw_length, $boundary);
61 * function writeBody - generate and write the mime boundaries around each part to the stream
63 * Recursively formats and writes the MIME boundaries of the $message
64 * to the output stream.
66 * @param Message $message Message object to transform
67 * @param resource $stream SMTP output stream
68 * @param integer &$length_raw raw length of the message (part)
69 * as returned by mail fn
70 * @param string $boundary custom boundary to call, usually for subparts
74 function writeBody($message, $stream, &$length_raw, $boundary='') {
75 // calculate boundary in case of multidimensional mime structures
76 if ($boundary && $message->entity_id
&& count($message->entities
)) {
77 if (strpos($boundary,'_part_')) {
78 $boundary = substr($boundary,0,strpos($boundary,'_part_'));
80 // the next four lines use strrev to reverse any nested boundaries
81 // because RFC 2046 (5.1.1) says that if a line starts with the outer
82 // boundary string (doesn't matter what the line ends with), that
83 // can be considered a match for the outer boundary; thus the nested
84 // boundary needs to be unique from the outer one
86 } else if (strpos($boundary,'_trap_')) {
87 $boundary = substr(strrev($boundary),0,strpos(strrev($boundary),'_part_'));
89 $boundary_new = strrev($boundary . '_part_'.$message->entity_id
);
91 $boundary_new = $boundary;
93 if ($boundary && !$message->rfc822_header
) {
94 $s = '--'.$boundary."\r\n";
95 $s .= $this->prepareMIME_Header($message, $boundary_new);
96 $length_raw +
= strlen($s);
98 $this->preWriteToStream($s);
99 $this->writeToStream($stream, $s);
102 $this->writeBodyPart($message, $stream, $length_raw);
105 for ($i=0, $entCount=count($message->entities
);$i<$entCount;$i++
) {
106 $msg = $this->writeBody($message->entities
[$i], $stream, $length_raw, $boundary_new);
107 if ($i == $entCount-1) $last = true;
109 if ($boundary && $last) {
110 $s = "--".$boundary_new."--\r\n\r\n";
111 $length_raw +
= strlen($s);
113 $this->preWriteToStream($s);
114 $this->writeToStream($stream, $s);
120 * function writeBodyPart - write each individual mimepart
122 * Recursively called by WriteBody to write each mime part to the SMTP stream
124 * @param Message $message Message object to transform
125 * @param resource $stream SMTP output stream
126 * @param integer &$length length of the message part
127 * as returned by mail fn
131 function writeBodyPart($message, $stream, &$length) {
132 if ($message->mime_header
) {
133 $type0 = $message->mime_header
->type0
;
135 $type0 = $message->rfc822_header
->content_type
->type0
;
138 $body_part_trailing = $last = '';
143 if ($message->body_part
) {
144 $body_part = $message->body_part
;
145 // remove NUL characters
146 $body_part = str_replace("\0",'',$body_part);
147 $length +
= $this->clean_crlf($body_part);
149 $this->preWriteToStream($body_part);
150 $this->writeToStream($stream, $body_part);
153 } elseif ($message->att_local_name
) {
154 $filename = $message->att_local_name
;
155 $file = fopen ($filename, 'rb');
156 while ($body_part = fgets($file, 4096)) {
157 // remove NUL characters
158 $body_part = str_replace("\0",'',$body_part);
159 $length +
= $this->clean_crlf($body_part);
161 $this->preWriteToStream($body_part);
162 $this->writeToStream($stream, $body_part);
170 if ($message->body_part
) {
171 $body_part = $message->body_part
;
172 // remove NUL characters
173 $body_part = str_replace("\0",'',$body_part);
174 $length +
= $this->clean_crlf($body_part);
176 $this->writeToStream($stream, $body_part);
178 } elseif ($message->att_local_name
) {
179 $filename = $message->att_local_name
;
180 $file = fopen ($filename, 'rb');
181 while ($tmp = fread($file, 570)) {
182 $body_part = chunk_split(base64_encode($tmp));
183 $length +
= $this->clean_crlf($body_part);
185 $this->writeToStream($stream, $body_part);
192 $body_part_trailing = '';
193 if ($last && substr($last,-1) != "\n") {
194 $body_part_trailing = "\r\n";
196 if ($body_part_trailing) {
197 $length +
= strlen($body_part_trailing);
199 $this->preWriteToStream($body_part_trailing);
200 $this->writeToStream($stream, $body_part_trailing);
206 * function clean_crlf - change linefeeds and newlines to legal characters
208 * The SMTP format only allows CRLF as line terminators.
209 * This function replaces illegal teminators with the correct terminator.
211 * @param string &$s string to clean linefeeds on
215 function clean_crlf(&$s) {
216 $s = str_replace("\r\n", "\n", $s);
217 $s = str_replace("\r", "\n", $s);
218 $s = str_replace("\n", "\r\n", $s);
223 * function strip_crlf - strip linefeeds and newlines from a string
225 * The SMTP format only allows CRLF as line terminators.
226 * This function strips all line terminators from the string.
228 * @param string &$s string to clean linefeeds on
232 function strip_crlf(&$s) {
233 $s = str_replace("\r\n ", '', $s);
234 $s = str_replace("\r", '', $s);
235 $s = str_replace("\n", '', $s);
239 * function preWriteToStream - reserved for extended functionality
241 * This function is not yet implemented.
242 * Reserved for extended functionality.
244 * @param string &$s string to operate on
248 function preWriteToStream(&$s) {
252 * function writeToStream - write data to the SMTP stream
254 * @param resource $stream SMTP output stream
255 * @param string $data string with data to send to the SMTP stream
259 function writeToStream($stream, $data) {
260 fputs($stream, $data);
264 * function initStream - reserved for extended functionality
266 * This function is not yet implemented.
267 * Reserved for extended functionality.
269 * @param Message $message Message object
270 * @param string $host host name or IP to connect to
271 * @param string $user username to log into the SMTP server with
272 * @param string $pass password to log into the SMTP server with
273 * @param integer $length
275 * @return handle $stream file handle resource to SMTP stream
277 function initStream($message, $length=0, $host='', $port='', $user='', $pass='') {
282 * function getBCC - reserved for extended functionality
284 * This function is not yet implemented.
285 * Reserved for extended functionality.
293 * function prepareMIME_Header - creates the mime header
295 * @param Message $message Message object to act on
296 * @param string $boundary mime boundary from fn MimeBoundary
298 * @return string $header properly formatted mime header
300 function prepareMIME_Header($message, $boundary) {
301 $mime_header = $message->mime_header
;
305 $contenttype = 'Content-Type: '. $mime_header->type0
.'/'.
307 if (count($message->entities
)) {
308 $contenttype .= ';' . 'boundary="'.$boundary.'"';
310 if (isset($mime_header->parameters
['name'])) {
311 $contenttype .= '; name="'.
312 encodeHeader($mime_header->parameters
['name']). '"';
314 if (isset($mime_header->parameters
['charset'])) {
315 $charset = $mime_header->parameters
['charset'];
316 $contenttype .= '; charset="'.
317 encodeHeader($charset). '"';
320 $header[] = $contenttype . $rn;
321 if ($mime_header->description
) {
322 $header[] = 'Content-Description: ' . $mime_header->description
. $rn;
324 if ($mime_header->encoding
) {
325 $header[] = 'Content-Transfer-Encoding: ' . $mime_header->encoding
. $rn;
327 if ($mime_header->type0
== 'text' ||
$mime_header->type0
== 'message') {
328 $header[] = 'Content-Transfer-Encoding: 8bit' . $rn;
330 $header[] = 'Content-Transfer-Encoding: base64' . $rn;
333 if ($mime_header->id
) {
334 $header[] = 'Content-ID: ' . $mime_header->id
. $rn;
336 if ($mime_header->disposition
) {
337 $disposition = $mime_header->disposition
;
338 $contentdisp = 'Content-Disposition: ' . $disposition->name
;
339 if ($disposition->getProperty('filename')) {
340 $contentdisp .= '; filename="'.
341 encodeHeader($disposition->getProperty('filename')). '"';
343 $header[] = $contentdisp . $rn;
345 if ($mime_header->md5
) {
346 $header[] = 'Content-MD5: ' . $mime_header->md5
. $rn;
348 if ($mime_header->language
) {
349 $header[] = 'Content-Language: ' . $mime_header->language
. $rn;
352 $cnt = count($header);
354 for ($i = 0 ; $i < $cnt ; $i++
) {
355 $hdr_s .= $this->foldLine($header[$i], 78,str_pad('',4));
358 $header .= $rn; /* One blank line to separate mimeheader and body-entity */
363 * function prepareRFC822_Header - prepares the RFC822 header string from Rfc822Header object(s)
365 * This function takes the Rfc822Header object(s) and formats them
366 * into the RFC822Header string to send to the SMTP server as part
367 * of the SMTP message.
369 * @param Rfc822Header $rfc822_header
370 * @param Rfc822Header $reply_rfc822_header
371 * @param integer &$raw_length length of the message
373 * @return string $header
375 function prepareRFC822_Header($rfc822_header, $reply_rfc822_header, &$raw_length) {
376 global $domain, $version, $username, $skip_SM_header;
378 /* if server var SERVER_NAME not available, use $domain */
379 if(!sqGetGlobalVar('SERVER_NAME', $SERVER_NAME, SQ_SERVER
)) {
380 $SERVER_NAME = $domain;
383 sqGetGlobalVar('REMOTE_ADDR', $REMOTE_ADDR, SQ_SERVER
);
384 sqGetGlobalVar('REMOTE_PORT', $REMOTE_PORT, SQ_SERVER
);
385 sqGetGlobalVar('REMOTE_HOST', $REMOTE_HOST, SQ_SERVER
);
386 sqGetGlobalVar('HTTP_VIA', $HTTP_VIA, SQ_SERVER
);
387 sqGetGlobalVar('HTTP_X_FORWARDED_FOR', $HTTP_X_FORWARDED_FOR, SQ_SERVER
);
391 /* This creates an RFC 822 date */
392 $date = date('D, j M Y H:i:s ', mktime()) . $this->timezone();
393 /* Create a message-id */
394 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
395 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
396 /* Make an RFC822 Received: line */
397 if (isset($REMOTE_HOST)) {
398 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
400 $received_from = $REMOTE_ADDR;
402 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
403 if (!isset($HTTP_X_FORWARDED_FOR) ||
$HTTP_X_FORWARDED_FOR == '') {
404 $HTTP_X_FORWARDED_FOR = 'unknown';
406 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
409 if ( !isset($skip_SM_header) ||
!$skip_SM_header )
411 $header[] = "Received: from $received_from" . $rn;
412 $header[] = " (SquirrelMail authenticated user $username)" . $rn;
413 $header[] = " by $SERVER_NAME with HTTP;" . $rn;
414 $header[] = " $date" . $rn;
416 /* Insert the rest of the header fields */
417 $header[] = 'Message-ID: '. $message_id . $rn;
418 if ($reply_rfc822_header->message_id
) {
419 $rep_message_id = $reply_rfc822_header->message_id
;
420 // $this->strip_crlf($message_id);
421 $header[] = 'In-Reply-To: '.$rep_message_id . $rn;
422 $references = $this->calculate_references($reply_rfc822_header);
423 $header[] = 'References: '.$references . $rn;
425 $header[] = "Date: $date" . $rn;
426 $header[] = 'Subject: '.encodeHeader($rfc822_header->subject
) . $rn;
427 $header[] = 'From: '. $rfc822_header->getAddr_s('from',",$rn ",true) . $rn;
429 // folding address list [From|To|Cc|Bcc] happens by using ",$rn<space>" as delimiter
430 // Do not use foldLine for that.
432 // RFC2822 if from contains more then 1 address
433 if (count($rfc822_header->from
) > 1) {
434 $header[] = 'Sender: '. $rfc822_header->getAddr_s('sender',',',true) . $rn;
436 if (count($rfc822_header->to
)) {
437 $header[] = 'To: '. $rfc822_header->getAddr_s('to',",$rn ",true) . $rn;
439 if (count($rfc822_header->cc
)) {
440 $header[] = 'Cc: '. $rfc822_header->getAddr_s('cc',",$rn ",true) . $rn;
442 if (count($rfc822_header->reply_to
)) {
443 $header[] = 'Reply-To: '. $rfc822_header->getAddr_s('reply_to',',',true) . $rn;
445 /* Sendmail should return true. Default = false */
446 $bcc = $this->getBcc();
447 if (count($rfc822_header->bcc
)) {
448 $s = 'Bcc: '. $rfc822_header->getAddr_s('bcc',",$rn ",true) . $rn;
450 $raw_length +
= strlen($s);
455 /* Identify SquirrelMail */
456 $header[] = 'User-Agent: SquirrelMail/' . $version . $rn;
457 /* Do the MIME-stuff */
458 $header[] = 'MIME-Version: 1.0' . $rn;
459 $contenttype = 'Content-Type: '. $rfc822_header->content_type
->type0
.'/'.
460 $rfc822_header->content_type
->type1
;
461 if (count($rfc822_header->content_type
->properties
)) {
462 foreach ($rfc822_header->content_type
->properties
as $k => $v) {
464 $contenttype .= ';' .$k.'='.$v;
468 $header[] = $contenttype . $rn;
469 if ($encoding = $rfc822_header->encoding
) {
470 $header[] = 'Content-Transfer-Encoding: ' . $encoding . $rn;
472 if ($rfc822_header->dnt
) {
473 $dnt = $rfc822_header->getAddr_s('dnt');
475 $header[] = 'X-Confirm-Reading-To: '.$dnt. $rn;
477 $header[] = 'Disposition-Notification-To: '.$dnt. $rn;
479 if ($rfc822_header->priority
) {
480 switch($rfc822_header->priority
)
483 $header[] = 'X-Priority: 1 (Highest)'.$rn;
484 $header[] = 'Importance: High'. $rn; break;
486 $header[] = 'X-Priority: 5 (Lowest)'.$rn;
487 $header[] = 'Importance: Low'. $rn; break;
491 /* Insert headers from the $more_headers array */
492 if(count($rfc822_header->more_headers
)) {
493 reset($rfc822_header->more_headers
);
494 foreach ($rfc822_header->more_headers
as $k => $v) {
495 $header[] = $k.': '.$v .$rn;
498 $cnt = count($header);
501 for ($i = 0 ; $i < $cnt ; $i++
) {
502 $sKey = substr($header[$i],0,strpos($header[$i],':'));
507 $hdr_s .= $header[$i];
510 $sRefs = substr($header[$i],12);
511 $aRefs = explode(' ',$sRefs);
512 $sLine = 'References:';
513 foreach ($aRefs as $sReference) {
514 if (strlen($sLine)+
strlen($sReference) >76) {
516 $sLine = $rn . ' ' . $sReference;
518 $sLine .= ' '. $sReference;
527 $hdr_s .= $header[$i];
529 default: $hdr_s .= $this->foldLine($header[$i], 78, str_pad('',4)); break;
533 $header .= $rn; /* One blank line to separate header and body */
534 $raw_length +
= strlen($header);
539 * function foldLine - for cleanly folding of headerlines
541 * @param string $line
542 * @param integer $length length to fold the line at
543 * @param string $pre prefix the line with...
545 * @return string $line folded line with trailing CRLF
547 function foldLine($line, $length, $pre='') {
548 $line = substr($line,0, -2);
549 $length -= 2; /* do not fold between \r and \n */
550 $cnt = strlen($line);
551 if ($cnt > $length) { /* try folding */
552 $fold_string = "\r\n " . $pre;
554 $aFoldLine = array();
555 while (strlen($line) > $length) {
557 /* handle encoded parts */
558 if (preg_match('/(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(\s+|.*)/Ui',$line,$regs)) {
559 $fold_tmp = $regs[1];
560 if (!trim($regs[5])) {
561 $fold_tmp .= $regs[5];
563 $iPosEnc = strpos($line,$fold_tmp);
564 $iLengthEnc = strlen($fold_tmp);
565 $iPosEncEnd = $iPosEnc+
$iLengthEnc;
566 if ($iPosEnc < $length && (($iPosEncEnd) > $length)) {
568 /* fold just before the start of the encoded string */
570 $aFoldLine[] = substr($line,0,$iPosEnc);
572 $line = substr($line,$iPosEnc);
575 $length -= strlen($fold_string);
577 if ($iLengthEnc > $length) { /* place the encoded
578 string on a separate line and do not fold inside it*/
579 /* minimize foldstring */
580 $fold_string = "\r\n ";
581 $aFoldLine[] = substr($line,0,$iLengthEnc);
582 $line = substr($line,$iLengthEnc);
584 } else if ($iPosEnc < $length) { /* the encoded string fits into the foldlength */
586 $sLineRem = substr($line,$iPosEncEnd,$length - $iPosEncEnd);
587 if (preg_match('/^(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(.*)/Ui',$sLineRem) ||
!preg_match('/[=,;\s]/',$sLineRem)) {
588 /*impossible to fold clean in the next part -> fold after the enc string */
589 $aFoldLine[] = substr($line,0,$iPosEncEnd);
590 $line = substr($line,$iPosEncEnd);
594 $length -= strlen($fold_string);
600 $line_tmp = substr($line,0,$length);
602 /* try to fold at logical places */
605 case ($iFoldPos = strrpos($line_tmp,',')): break;
606 case ($iFoldPos = strrpos($line_tmp,';')): break;
607 case ($iFoldPos = strrpos($line_tmp,' ')): break;
608 case ($iFoldPos = strrpos($line_tmp,'=')): break;
612 if (!$iFoldPos) { /* clean folding didn't work */
615 $aFoldLine[] = substr($line,0,$iFoldPos+
1);
616 $line = substr($line,$iFoldPos+
1);
619 $length -= strlen($fold_string);
623 /*$reconstruct the line */
625 $aFoldLine[] = $line;
627 $line = implode($fold_string,$aFoldLine);
633 * function mimeBoundary - calculates the mime boundary to use
635 * This function will generate a random mime boundary base part
636 * for the message if the boundary has not already been set.
638 * @return string $mimeBoundaryString random mime boundary string
640 function mimeBoundary () {
641 static $mimeBoundaryString;
643 if ( !isset( $mimeBoundaryString ) ||
644 $mimeBoundaryString == '') {
645 $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
646 mt_rand( 10000, 99999 );
648 return $mimeBoundaryString;
652 * function timezone - Time offset for correct timezone
654 * @return string $result with timezone and offset
656 function timezone () {
659 $diff_second = date('Z');
661 $diff_second = - $diff_second;
663 if ($diff_second > 0) {
668 $diff_second = abs($diff_second);
669 $diff_hour = floor ($diff_second / 3600);
670 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
671 $zonename = '('.strftime('%Z').')';
672 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute,
678 * function calculate_references - calculate correct Referer string
680 * @param Rfc822Header $hdr message header to calculate from
682 * @return string $refer concatenated and trimmed Referer string
684 function calculate_references($hdr) {
685 $refer = $hdr->references
;
686 $message_id = $hdr->message_id
;
687 $in_reply_to = $hdr->in_reply_to
;
688 if (strlen($refer) > 2) {
689 $refer .= ' ' . $message_id;
692 $refer .= $in_reply_to . ' ' . $message_id;
694 $refer .= $message_id;