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 $boundary_new = $boundary . '_part_'.$message->entity_id
;
82 $boundary_new = $boundary;
84 if ($boundary && !$message->rfc822_header
) {
85 $s = '--'.$boundary."\r\n";
86 $s .= $this->prepareMIME_Header($message, $boundary_new);
87 $length_raw +
= strlen($s);
89 $this->preWriteToStream($s);
90 $this->writeToStream($stream, $s);
93 $this->writeBodyPart($message, $stream, $length_raw);
96 for ($i=0, $entCount=count($message->entities
);$i<$entCount;$i++
) {
97 $msg = $this->writeBody($message->entities
[$i], $stream, $length_raw, $boundary_new);
98 if ($i == $entCount-1) $last = true;
100 if ($boundary && $last) {
101 $s = "--".$boundary_new."--\r\n\r\n";
102 $length_raw +
= strlen($s);
104 $this->preWriteToStream($s);
105 $this->writeToStream($stream, $s);
111 * function writeBodyPart - write each individual mimepart
113 * Recursively called by WriteBody to write each mime part to the SMTP stream
115 * @param Message $message Message object to transform
116 * @param resource $stream SMTP output stream
117 * @param integer &$length length of the message part
118 * as returned by mail fn
122 function writeBodyPart($message, $stream, &$length) {
123 if ($message->mime_header
) {
124 $type0 = $message->mime_header
->type0
;
126 $type0 = $message->rfc822_header
->content_type
->type0
;
129 $body_part_trailing = $last = '';
134 if ($message->body_part
) {
135 $body_part = $message->body_part
;
136 $length +
= $this->clean_crlf($body_part);
138 $this->preWriteToStream($body_part);
139 $this->writeToStream($stream, $body_part);
142 } elseif ($message->att_local_name
) {
143 $filename = $message->att_local_name
;
144 $file = fopen ($filename, 'rb');
145 while ($body_part = fgets($file, 4096)) {
146 $length +
= $this->clean_crlf($body_part);
148 $this->preWriteToStream($body_part);
149 $this->writeToStream($stream, $body_part);
157 if ($message->body_part
) {
158 $body_part = $message->body_part
;
159 $length +
= $this->clean_crlf($body_part);
161 $this->writeToStream($stream, $body_part);
163 } elseif ($message->att_local_name
) {
164 $filename = $message->att_local_name
;
165 $file = fopen ($filename, 'rb');
166 while ($tmp = fread($file, 570)) {
167 $body_part = chunk_split(base64_encode($tmp));
168 $length +
= $this->clean_crlf($body_part);
170 $this->writeToStream($stream, $body_part);
177 $body_part_trailing = '';
178 if ($last && substr($last,-1) != "\n") {
179 $body_part_trailing = "\r\n";
181 if ($body_part_trailing) {
182 $length +
= strlen($body_part_trailing);
184 $this->preWriteToStream($body_part_trailing);
185 $this->writeToStream($stream, $body_part_trailing);
191 * function clean_crlf - change linefeeds and newlines to legal characters
193 * The SMTP format only allows CRLF as line terminators.
194 * This function replaces illegal teminators with the correct terminator.
196 * @param string &$s string to clean linefeeds on
200 function clean_crlf(&$s) {
201 $s = str_replace("\r\n", "\n", $s);
202 $s = str_replace("\r", "\n", $s);
203 $s = str_replace("\n", "\r\n", $s);
208 * function strip_crlf - strip linefeeds and newlines from a string
210 * The SMTP format only allows CRLF as line terminators.
211 * This function strips all line terminators from the string.
213 * @param string &$s string to clean linefeeds on
217 function strip_crlf(&$s) {
218 $s = str_replace("\r\n ", '', $s);
219 $s = str_replace("\r", '', $s);
220 $s = str_replace("\n", '', $s);
224 * function preWriteToStream - reserved for extended functionality
226 * This function is not yet implemented.
227 * Reserved for extended functionality.
229 * @param string &$s string to operate on
233 function preWriteToStream(&$s) {
237 * function writeToStream - write data to the SMTP stream
239 * @param resource $stream SMTP output stream
240 * @param string $data string with data to send to the SMTP stream
244 function writeToStream($stream, $data) {
245 fputs($stream, $data);
249 * function initStream - reserved for extended functionality
251 * This function is not yet implemented.
252 * Reserved for extended functionality.
254 * @param Message $message Message object
255 * @param string $host host name or IP to connect to
256 * @param string $user username to log into the SMTP server with
257 * @param string $pass password to log into the SMTP server with
258 * @param integer $length
260 * @return handle $stream file handle resource to SMTP stream
262 function initStream($message, $length=0, $host='', $port='', $user='', $pass='') {
267 * function getBCC - reserved for extended functionality
269 * This function is not yet implemented.
270 * Reserved for extended functionality.
278 * function prepareMIME_Header - creates the mime header
280 * @param Message $message Message object to act on
281 * @param string $boundary mime boundary from fn MimeBoundary
283 * @return string $header properly formatted mime header
285 function prepareMIME_Header($message, $boundary) {
286 $mime_header = $message->mime_header
;
290 $contenttype = 'Content-Type: '. $mime_header->type0
.'/'.
292 if (count($message->entities
)) {
293 $contenttype .= ";\r\n " . 'boundary="'.$boundary.'"';
295 if (isset($mime_header->parameters
['name'])) {
296 $contenttype .= '; name="'.
297 encodeHeader($mime_header->parameters
['name']). '"';
299 if (isset($mime_header->parameters
['charset'])) {
300 $charset = $mime_header->parameters
['charset'];
301 $contenttype .= '; charset="'.
302 encodeHeader($charset). '"';
305 $header[] = $contenttype . $rn;
306 if ($mime_header->description
) {
307 $header[] = 'Content-Description: ' . $mime_header->description
. $rn;
309 if ($mime_header->encoding
) {
310 $header[] = 'Content-Transfer-Encoding: ' . $mime_header->encoding
. $rn;
312 if ($mime_header->type0
== 'text' ||
$mime_header->type0
== 'message') {
313 $header[] = 'Content-Transfer-Encoding: 8bit' . $rn;
315 $header[] = 'Content-Transfer-Encoding: base64' . $rn;
318 if ($mime_header->id
) {
319 $header[] = 'Content-ID: ' . $mime_header->id
. $rn;
321 if ($mime_header->disposition
) {
322 $disposition = $mime_header->disposition
;
323 $contentdisp = 'Content-Disposition: ' . $disposition->name
;
324 if ($disposition->getProperty('filename')) {
325 $contentdisp .= '; filename="'.
326 encodeHeader($disposition->getProperty('filename')). '"';
328 $header[] = $contentdisp . $rn;
330 if ($mime_header->md5
) {
331 $header[] = 'Content-MD5: ' . $mime_header->md5
. $rn;
333 if ($mime_header->language
) {
334 $header[] = 'Content-Language: ' . $mime_header->language
. $rn;
337 $cnt = count($header);
339 for ($i = 0 ; $i < $cnt ; $i++
) {
340 $hdr_s .= $this->foldLine($header[$i], 78,str_pad('',4));
343 $header .= $rn; /* One blank line to separate mimeheader and body-entity */
348 * function prepareRFC822_Header - prepares the RFC822 header string from Rfc822Header object(s)
350 * This function takes the Rfc822Header object(s) and formats them
351 * into the RFC822Header string to send to the SMTP server as part
352 * of the SMTP message.
354 * @param Rfc822Header $rfc822_header
355 * @param Rfc822Header $reply_rfc822_header
356 * @param integer &$raw_length length of the message
358 * @return string $header
360 function prepareRFC822_Header($rfc822_header, $reply_rfc822_header, &$raw_length) {
361 global $domain, $version, $username, $skip_SM_header;
363 /* if server var SERVER_NAME not available, use $domain */
364 if(!sqGetGlobalVar('SERVER_NAME', $SERVER_NAME, SQ_SERVER
)) {
365 $SERVER_NAME = $domain;
368 sqGetGlobalVar('REMOTE_ADDR', $REMOTE_ADDR, SQ_SERVER
);
369 sqGetGlobalVar('REMOTE_PORT', $REMOTE_PORT, SQ_SERVER
);
370 sqGetGlobalVar('REMOTE_HOST', $REMOTE_HOST, SQ_SERVER
);
371 sqGetGlobalVar('HTTP_VIA', $HTTP_VIA, SQ_SERVER
);
372 sqGetGlobalVar('HTTP_X_FORWARDED_FOR', $HTTP_X_FORWARDED_FOR, SQ_SERVER
);
376 /* This creates an RFC 822 date */
377 $date = date('D, j M Y H:i:s ', mktime()) . $this->timezone();
378 /* Create a message-id */
379 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
380 $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';
381 /* Make an RFC822 Received: line */
382 if (isset($REMOTE_HOST)) {
383 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
385 $received_from = $REMOTE_ADDR;
387 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
388 if (!isset($HTTP_X_FORWARDED_FOR) ||
$HTTP_X_FORWARDED_FOR == '') {
389 $HTTP_X_FORWARDED_FOR = 'unknown';
391 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
394 if ( !isset($skip_SM_header) ||
!$skip_SM_header )
396 $header[] = "Received: from $received_from" . $rn;
397 $header[] = " (SquirrelMail authenticated user $username)" . $rn;
398 $header[] = " by $SERVER_NAME with HTTP;" . $rn;
399 $header[] = " $date" . $rn;
401 /* Insert the rest of the header fields */
402 $header[] = 'Message-ID: '. $message_id . $rn;
403 if ($reply_rfc822_header->message_id
) {
404 $rep_message_id = $reply_rfc822_header->message_id
;
405 // $this->strip_crlf($message_id);
406 $header[] = 'In-Reply-To: '.$rep_message_id . $rn;
407 $references = $this->calculate_references($reply_rfc822_header);
408 $header[] = 'References: '.$references . $rn;
410 $header[] = "Date: $date" . $rn;
411 $header[] = 'Subject: '.encodeHeader($rfc822_header->subject
) . $rn;
412 $header[] = 'From: '. $rfc822_header->getAddr_s('from',",$rn ",true) . $rn;
414 // folding address list [From|To|Cc|Bcc] happens by using ",$rn<space>" as delimiter
415 // Do not use foldLine for that.
417 // RFC2822 if from contains more then 1 address
418 if (count($rfc822_header->from
) > 1) {
419 $header[] = 'Sender: '. $rfc822_header->getAddr_s('sender',',',true) . $rn;
421 if (count($rfc822_header->to
)) {
422 $header[] = 'To: '. $rfc822_header->getAddr_s('to',",$rn ",true) . $rn;
424 if (count($rfc822_header->cc
)) {
425 $header[] = 'Cc: '. $rfc822_header->getAddr_s('cc',",$rn ",true) . $rn;
427 if (count($rfc822_header->reply_to
)) {
428 $header[] = 'Reply-To: '. $rfc822_header->getAddr_s('reply_to',',',true) . $rn;
430 /* Sendmail should return true. Default = false */
431 $bcc = $this->getBcc();
432 if (count($rfc822_header->bcc
)) {
433 $s = 'Bcc: '. $rfc822_header->getAddr_s('bcc',",$rn ",true) . $rn;
435 $raw_length +
= strlen($s);
440 /* Identify SquirrelMail */
441 $header[] = 'User-Agent: SquirrelMail/' . $version . $rn;
442 /* Do the MIME-stuff */
443 $header[] = 'MIME-Version: 1.0' . $rn;
444 $contenttype = 'Content-Type: '. $rfc822_header->content_type
->type0
.'/'.
445 $rfc822_header->content_type
->type1
;
446 if (count($rfc822_header->content_type
->properties
)) {
447 foreach ($rfc822_header->content_type
->properties
as $k => $v) {
449 $contenttype .= ';' .$k.'='.$v;
453 $header[] = $contenttype . $rn;
454 if ($encoding = $rfc822_header->encoding
) {
455 $header[] = 'Content-Transfer-Encoding: ' . $encoding . $rn;
457 if ($rfc822_header->dnt
) {
458 $dnt = $rfc822_header->getAddr_s('dnt');
460 $header[] = 'X-Confirm-Reading-To: '.$dnt. $rn;
462 $header[] = 'Disposition-Notification-To: '.$dnt. $rn;
464 if ($rfc822_header->priority
) {
465 switch($rfc822_header->priority
)
468 $header[] = 'X-Priority: 1 (Highest)'.$rn;
469 $header[] = 'Importance: High'. $rn; break;
471 $header[] = 'X-Priority: 5 (Lowest)'.$rn;
472 $header[] = 'Importance: Low'. $rn; break;
476 /* Insert headers from the $more_headers array */
477 if(count($rfc822_header->more_headers
)) {
478 reset($rfc822_header->more_headers
);
479 foreach ($rfc822_header->more_headers
as $k => $v) {
480 $header[] = $k.': '.$v .$rn;
483 $cnt = count($header);
486 for ($i = 0 ; $i < $cnt ; $i++
) {
487 $sKey = substr($header[$i],0,strpos($header[$i],':'));
492 $hdr_s .= $header[$i];
495 $sRefs = substr($header[$i],12);
496 $aRefs = explode(' ',$sRefs);
497 $sLine = 'References:';
498 foreach ($aRefs as $sReference) {
499 if (strlen($sLine)+
strlen($sReference) >76) {
501 $sLine = $rn . ' ' . $sReference;
503 $sLine .= ' '. $sReference;
512 $hdr_s .= $header[$i];
514 default: $hdr_s .= $this->foldLine($header[$i], 78, str_pad('',4)); break;
518 $header .= $rn; /* One blank line to separate header and body */
519 $raw_length +
= strlen($header);
524 * function foldLine - for cleanly folding of headerlines
526 * @param string $line
527 * @param integer $length length to fold the line at
528 * @param string $pre prefix the line with...
530 * @return string $line folded line with trailing CRLF
532 function foldLine($line, $length, $pre='') {
533 $line = substr($line,0, -2);
534 $length -= 2; /* do not fold between \r and \n */
535 $cnt = strlen($line);
536 if ($cnt > $length) { /* try folding */
537 $fold_string = "\r\n " . $pre;
539 $aFoldLine = array();
540 while (strlen($line) > $length) {
542 /* handle encoded parts */
543 if (preg_match('/(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(\s+|.*)/Ui',$line,$regs)) {
544 $fold_tmp = $regs[1];
545 if (!trim($regs[5])) {
546 $fold_tmp .= $regs[5];
548 $iPosEnc = strpos($line,$fold_tmp);
549 $iLengthEnc = strlen($fold_tmp);
550 $iPosEncEnd = $iPosEnc+
$iLengthEnc;
551 if ($iPosEnc < $length && (($iPosEncEnd) > $length)) {
553 /* fold just before the start of the encoded string */
555 $aFoldLine[] = substr($line,0,$iPosEnc);
557 $line = substr($line,$iPosEnc);
560 $length -= strlen($fold_string);
562 if ($iLengthEnc > $length) { /* place the encoded
563 string on a separate line and do not fold inside it*/
564 /* minimize foldstring */
565 $fold_string = "\r\n ";
566 $aFoldLine[] = substr($line,0,$iLengthEnc);
567 $line = substr($line,$iLengthEnc);
569 } else if ($iPosEnc < $length) { /* the encoded string fits into the foldlength */
571 $sLineRem = substr($line,$iPosEncEnd,$length - $iPosEncEnd);
572 if (preg_match('/^(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(.*)/Ui',$sLineRem) ||
!preg_match('/[=,;\s]/',$sLineRem)) {
573 /*impossible to fold clean in the next part -> fold after the enc string */
574 $aFoldLine[] = substr($line,0,$iPosEncEnd);
575 $line = substr($line,$iPosEncEnd);
579 $length -= strlen($fold_string);
585 $line_tmp = substr($line,0,$length);
587 /* try to fold at logical places */
590 case ($iFoldPos = strrpos($line_tmp,',')): break;
591 case ($iFoldPos = strrpos($line_tmp,';')): break;
592 case ($iFoldPos = strrpos($line_tmp,' ')): break;
593 case ($iFoldPos = strrpos($line_tmp,'=')): break;
597 if (!$iFoldPos) { /* clean folding didn't work */
600 $aFoldLine[] = substr($line,0,$iFoldPos+
1);
601 $line = substr($line,$iFoldPos+
1);
604 $length -= strlen($fold_string);
608 /*$reconstruct the line */
610 $aFoldLine[] = $line;
612 $line = implode($fold_string,$aFoldLine);
618 * function mimeBoundary - calculates the mime boundary to use
620 * This function will generate a random mime boundary base part
621 * for the message if the boundary has not already been set.
623 * @return string $mimeBoundaryString random mime boundary string
625 function mimeBoundary () {
626 static $mimeBoundaryString;
628 if ( !isset( $mimeBoundaryString ) ||
629 $mimeBoundaryString == '') {
630 $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
631 mt_rand( 10000, 99999 );
633 return $mimeBoundaryString;
637 * function timezone - Time offset for correct timezone
639 * @return string $result with timezone and offset
641 function timezone () {
644 $diff_second = date('Z');
646 $diff_second = - $diff_second;
648 if ($diff_second > 0) {
653 $diff_second = abs($diff_second);
654 $diff_hour = floor ($diff_second / 3600);
655 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
656 $zonename = '('.strftime('%Z').')';
657 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute,
663 * function calculate_references - calculate correct Referer string
665 * @param Rfc822Header $hdr message header to calculate from
667 * @return string $refer concatenated and trimmed Referer string
669 function calculate_references($hdr) {
670 $refer = $hdr->references
;
671 $message_id = $hdr->message_id
;
672 $in_reply_to = $hdr->in_reply_to
;
673 if (strlen($refer) > 2) {
674 $refer .= ' ' . $message_id;
677 $refer .= $in_reply_to . ' ' . $message_id;
679 $refer .= $message_id;