5 * Copyright (c) 1999-2004 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
13 * @author Marc Groot Koerkamp
14 * @package squirrelmail
18 * Deliver Class - called to actually deliver the message
20 * This class is called by compose.php and other code that needs
21 * to send messages. All delivery functionality should be centralized
24 * Do not place UI code in this class, as UI code should be placed in templates
27 * @author Marc Groot Koerkamp
28 * @package squirrelmail
33 * function mail - send the message parts to the SMTP stream
35 * @param Message $message Message class to send
36 * @param resource $stream file handle to the SMTP stream
38 * @return integer $raw_length
40 function mail($message, $stream=false) {
41 $rfc822_header = $message->rfc822_header
;
42 if (count($message->entities
)) {
43 $boundary = $this->mimeBoundary();
44 $rfc822_header->content_type
->properties
['boundary']='"'.$boundary.'"';
49 $reply_rfc822_header = (isset($message->reply_rfc822_header
)
50 ?
$message->reply_rfc822_header
: '');
51 $header = $this->prepareRFC822_Header($rfc822_header, $reply_rfc822_header, $raw_length);
54 $this->preWriteToStream($header);
55 $this->writeToStream($stream, $header);
57 $this->writeBody($message, $stream, $raw_length, $boundary);
62 * function writeBody - generate and write the mime boundaries around each part to the stream
64 * Recursively formats and writes the MIME boundaries of the $message
65 * to the output stream.
67 * @param Message $message Message object to transform
68 * @param resource $stream SMTP output stream
69 * @param integer &$length_raw raw length of the message (part)
70 * as returned by mail fn
71 * @param string $boundary custom boundary to call, usually for subparts
75 function writeBody($message, $stream, &$length_raw, $boundary='') {
76 // calculate boundary in case of multidimensional mime structures
77 if ($boundary && $message->entity_id
&& count($message->entities
)) {
78 if (strpos($boundary,'_part_')) {
79 $boundary = substr($boundary,0,strpos($boundary,'_part_'));
81 $boundary_new = $boundary . '_part_'.$message->entity_id
;
83 $boundary_new = $boundary;
85 if ($boundary && !$message->rfc822_header
) {
86 $s = '--'.$boundary."\r\n";
87 $s .= $this->prepareMIME_Header($message, $boundary_new);
88 $length_raw +
= strlen($s);
90 $this->preWriteToStream($s);
91 $this->writeToStream($stream, $s);
94 $this->writeBodyPart($message, $stream, $length_raw);
97 for ($i=0, $entCount=count($message->entities
);$i<$entCount;$i++
) {
98 $msg = $this->writeBody($message->entities
[$i], $stream, $length_raw, $boundary_new);
99 if ($i == $entCount-1) $last = true;
101 if ($boundary && $last) {
102 $s = "--".$boundary_new."--\r\n\r\n";
103 $length_raw +
= strlen($s);
105 $this->preWriteToStream($s);
106 $this->writeToStream($stream, $s);
112 * function writeBodyPart - write each individual mimepart
114 * Recursively called by WriteBody to write each mime part to the SMTP stream
116 * @param Message $message Message object to transform
117 * @param resource $stream SMTP output stream
118 * @param integer &$length length of the message part
119 * as returned by mail fn
123 function writeBodyPart($message, $stream, &$length) {
124 if ($message->mime_header
) {
125 $type0 = $message->mime_header
->type0
;
127 $type0 = $message->rfc822_header
->content_type
->type0
;
130 $body_part_trailing = $last = '';
135 if ($message->body_part
) {
136 $body_part = $message->body_part
;
137 $length +
= $this->clean_crlf($body_part);
139 $this->preWriteToStream($body_part);
140 $this->writeToStream($stream, $body_part);
143 } elseif ($message->att_local_name
) {
144 $filename = $message->att_local_name
;
145 $file = fopen ($filename, 'rb');
146 while ($body_part = fgets($file, 4096)) {
147 $length +
= $this->clean_crlf($body_part);
149 $this->preWriteToStream($body_part);
150 $this->writeToStream($stream, $body_part);
158 if ($message->body_part
) {
159 $body_part = $message->body_part
;
160 $length +
= $this->clean_crlf($body_part);
162 $this->writeToStream($stream, $body_part);
164 } elseif ($message->att_local_name
) {
165 $filename = $message->att_local_name
;
166 $file = fopen ($filename, 'rb');
168 while ($tmp = fread($file, 570)) {
169 $body_part = chunk_split(base64_encode($tmp));
170 $length +
= $this->clean_crlf($body_part);
172 $this->writeToStream($stream, $body_part);
179 $body_part_trailing = '';
180 if ($last && substr($last,-1) != "\n") {
181 $body_part_trailing = "\r\n";
183 if ($body_part_trailing) {
184 $length +
= strlen($body_part_trailing);
186 $this->preWriteToStream($body_part_trailing);
187 $this->writeToStream($stream, $body_part_trailing);
193 * function clean_crlf - change linefeeds and newlines to legal characters
195 * The SMTP format only allows CRLF as line terminators.
196 * This function replaces illegal teminators with the correct terminator.
198 * @param string &$s string to clean linefeeds on
202 function clean_crlf(&$s) {
203 $s = str_replace("\r\n", "\n", $s);
204 $s = str_replace("\r", "\n", $s);
205 $s = str_replace("\n", "\r\n", $s);
210 * function strip_crlf - strip linefeeds and newlines from a string
212 * The SMTP format only allows CRLF as line terminators.
213 * This function strips all line terminators from the string.
215 * @param string &$s string to clean linefeeds on
219 function strip_crlf(&$s) {
220 $s = str_replace("\r\n ", '', $s);
221 $s = str_replace("\r", '', $s);
222 $s = str_replace("\n", '', $s);
226 * function preWriteToStream - reserved for extended functionality
228 * This function is not yet implemented.
229 * Reserved for extended functionality.
231 * @param string &$s string to operate on
235 function preWriteToStream(&$s) {
239 * function writeToStream - write data to the SMTP stream
241 * @param resource $stream SMTP output stream
242 * @param string $data string with data to send to the SMTP stream
246 function writeToStream($stream, $data) {
247 fputs($stream, $data);
251 * function initStream - reserved for extended functionality
253 * This function is not yet implemented.
254 * Reserved for extended functionality.
256 * @param Message $message Message object
257 * @param string $host host name or IP to connect to
258 * @param string $user username to log into the SMTP server with
259 * @param string $pass password to log into the SMTP server with
260 * @param integer $length
262 * @return handle $stream file handle resource to SMTP stream
264 function initStream($message, $length=0, $host='', $port='', $user='', $pass='') {
269 * function getBCC - reserved for extended functionality
271 * This function is not yet implemented.
272 * Reserved for extended functionality.
280 * function prepareMIME_Header - creates the mime header
282 * @param Message $message Message object to act on
283 * @param string $boundary mime boundary from fn MimeBoundary
285 * @return string $header properly formatted mime header
287 function prepareMIME_Header($message, $boundary) {
288 $mime_header = $message->mime_header
;
292 $contenttype = 'Content-Type: '. $mime_header->type0
.'/'.
294 if (count($message->entities
)) {
295 $contenttype .= ";\r\n " . 'boundary="'.$boundary.'"';
297 if (isset($mime_header->parameters
['name'])) {
298 $contenttype .= '; name="'.
299 encodeHeader($mime_header->parameters
['name']). '"';
301 if (isset($mime_header->parameters
['charset'])) {
302 $charset = $mime_header->parameters
['charset'];
303 $contenttype .= '; charset="'.
304 encodeHeader($charset). '"';
307 $header[] = $contenttype . $rn;
308 if ($mime_header->description
) {
309 $header[] .= 'Content-Description: ' . $mime_header->description
. $rn;
311 if ($mime_header->encoding
) {
312 $encoding = $mime_header->encoding
;
313 $header[] .= 'Content-Transfer-Encoding: ' . $mime_header->encoding
. $rn;
315 if ($mime_header->type0
== 'text' ||
$mime_header->type0
== 'message') {
316 $header[] .= 'Content-Transfer-Encoding: 8bit' . $rn;
318 $header[] .= 'Content-Transfer-Encoding: base64' . $rn;
321 if ($mime_header->id
) {
322 $header[] .= 'Content-ID: ' . $mime_header->id
. $rn;
324 if ($mime_header->disposition
) {
325 $disposition = $mime_header->disposition
;
326 $contentdisp = 'Content-Disposition: ' . $disposition->name
;
327 if ($disposition->getProperty('filename')) {
328 $contentdisp .= '; filename="'.
329 encodeHeader($disposition->getProperty('filename')). '"';
331 $header[] = $contentdisp . $rn;
333 if ($mime_header->md5
) {
334 $header[] .= 'Content-MD5: ' . $mime_header->md5
. $rn;
336 if ($mime_header->language
) {
337 $header[] .= 'Content-Language: ' . $mime_header->language
. $rn;
340 $cnt = count($header);
342 for ($i = 0 ; $i < $cnt ; $i++
) {
343 $hdr_s .= $this->foldLine($header[$i], 78,str_pad('',4));
346 $header .= $rn; /* One blank line to separate mimeheader and body-entity */
351 * function prepareRFC822_Header - prepares the RFC822 header string from Rfc822Header object(s)
353 * This function takes the Rfc822Header object(s) and formats them
354 * into the RFC822Header string to send to the SMTP server as part
355 * of the SMTP message.
357 * @param Rfc822Header $rfc822_header
358 * @param Rfc822Header $reply_rfc822_header
359 * @param integer &$raw_length length of the message
361 * @return string $header
363 function prepareRFC822_Header($rfc822_header, $reply_rfc822_header, &$raw_length) {
364 global $domain, $version, $username, $skip_SM_header;
366 /* if server var SERVER_NAME not available, use $domain */
367 if(!sqGetGlobalVar('SERVER_NAME', $SERVER_NAME, SQ_SERVER
)) {
368 $SERVER_NAME = $domain;
371 sqGetGlobalVar('REMOTE_ADDR', $REMOTE_ADDR, SQ_SERVER
);
372 sqGetGlobalVar('REMOTE_PORT', $REMOTE_PORT, SQ_SERVER
);
373 sqGetGlobalVar('REMOTE_HOST', $REMOTE_HOST, SQ_SERVER
);
374 sqGetGlobalVar('HTTP_VIA', $HTTP_VIA, SQ_SERVER
);
375 sqGetGlobalVar('HTTP_X_FORWARDED_FOR', $HTTP_X_FORWARDED_FOR, SQ_SERVER
);
379 /* This creates an RFC 822 date */
380 $date = date('D, j M Y H:i:s ', mktime()) . $this->timezone();
381 /* Create a message-id */
382 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
383 $message_id .= time() . '.squirrel@' . $REMOTE_ADDR .'>';
384 /* Make an RFC822 Received: line */
385 if (isset($REMOTE_HOST)) {
386 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
388 $received_from = $REMOTE_ADDR;
390 if (isset($HTTP_VIA) ||
isset ($HTTP_X_FORWARDED_FOR)) {
391 if (!isset($HTTP_X_FORWARDED_FOR) ||
$HTTP_X_FORWARDED_FOR == '') {
392 $HTTP_X_FORWARDED_FOR = 'unknown';
394 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
397 if ( !isset($skip_SM_header) ||
!$skip_SM_header )
399 $header[] = "Received: from $received_from" . $rn;
400 $header[] = " (SquirrelMail authenticated user $username);" . $rn;
401 $header[] = " by $SERVER_NAME with HTTP;" . $rn;
402 $header[] = " $date" . $rn;
404 /* Insert the rest of the header fields */
405 $header[] = 'Message-ID: '. $message_id . $rn;
406 if ($reply_rfc822_header->message_id
) {
407 $rep_message_id = $reply_rfc822_header->message_id
;
408 // $this->strip_crlf($message_id);
409 $header[] = 'In-Reply-To: '.$rep_message_id . $rn;
410 $references = $this->calculate_references($reply_rfc822_header);
411 $header[] = 'References: '.$references . $rn;
413 $header[] = "Date: $date" . $rn;
414 $header[] = 'Subject: '.encodeHeader($rfc822_header->subject
) . $rn;
415 $header[] = 'From: '. $rfc822_header->getAddr_s('from',',',true) . $rn;
416 /* RFC2822 if from contains more then 1 address */
417 if (count($rfc822_header->from
) > 1) {
418 $header[] = 'Sender: '. $rfc822_header->getAddr_s('sender',',',true) . $rn;
420 if (count($rfc822_header->to
)) {
421 $header[] = 'To: '. $rfc822_header->getAddr_s('to',',',true) . $rn;
423 if (count($rfc822_header->cc
)) {
424 $header[] = 'Cc: '. $rfc822_header->getAddr_s('cc',',',true) . $rn;
426 if (count($rfc822_header->reply_to
)) {
427 $header[] = 'Reply-To: '. $rfc822_header->getAddr_s('reply_to',',',true) . $rn;
429 /* Sendmail should return true. Default = false */
430 $bcc = $this->getBcc();
431 if (count($rfc822_header->bcc
)) {
432 $s = 'Bcc: '. $rfc822_header->getAddr_s('bcc',',',true) . $rn;
434 $s = $this->foldLine($s, 78, str_pad('',4));
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: 3 (Normal)'.$rn;
472 $header[] = 'Importance: Normal'. $rn; break;
474 $header[] = 'X-Priority: 5 (Lowest)'.$rn;
475 $header[] = 'Importance: Low'. $rn; break;
479 /* Insert headers from the $more_headers array */
480 if(count($rfc822_header->more_headers
)) {
481 reset($rfc822_header->more_headers
);
482 foreach ($rfc822_header->more_headers
as $k => $v) {
483 $header[] = $k.': '.$v .$rn;
486 $cnt = count($header);
489 for ($i = 0 ; $i < $cnt ; $i++
) {
490 $sKey = substr($header[$i],0,strpos($header[$i],':'));
495 $hdr_s .= $header[$i];
498 $sRefs = substr($header[$i],12);
499 $aRefs = explode(' ',$sRefs);
500 $sLine = 'References:';
501 foreach ($aRefs as $sReference) {
502 if (strlen($sLine)+
strlen($sReference) >76) {
504 $sLine = $rn . ' ' . $sReference;
506 $sLine .= ' '. $sReference;
511 default: $hdr_s .= $this->foldLine($header[$i], 78, str_pad('',4)); break;
515 $header .= $rn; /* One blank line to separate header and body */
516 $raw_length +
= strlen($header);
521 * function foldLine - for cleanly folding of headerlines
523 * @param string $line
524 * @param integer $length length to fold the line at
525 * @param string $pre prefix the line with...
527 * @return string $line folded line with trailing CRLF
529 function foldLine($line, $length, $pre='') {
530 $line = substr($line,0, -2);
531 $length -= 2; /* do not fold between \r and \n */
532 $cnt = strlen($line);
533 if ($cnt > $length) { /* try folding */
534 $fold_string = "\r\n " . $pre;
536 $aFoldLine = array();
537 while (strlen($line) > $length) {
539 /* handle encoded parts */
540 if (preg_match('/(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(\s+|.*)/Ui',$line,$regs)) {
541 $fold_tmp = $regs[1];
542 if (!trim($regs[5])) {
543 $fold_tmp .= $regs[5];
545 $iPosEnc = strpos($line,$fold_tmp);
546 $iLengthEnc = strlen($fold_tmp);
547 $iPosEncEnd = $iPosEnc+
$iLengthEnc;
548 if ($iPosEnc < $length && (($iPosEncEnd) > $length)) {
550 /* fold just before the start of the encoded string */
552 $aFoldLine[] = substr($line,0,$iPosEnc);
554 $line = substr($line,$iPosEnc);
557 $length -= strlen($fold_string);
559 if ($iLengthEnc > $length) { /* place the encoded
560 string on a separate line and do not fold inside it*/
561 /* minimize foldstring */
562 $fold_string = "\r\n ";
563 $aFoldLine[] = substr($line,0,$iLengthEnc);
564 $line = substr($line,$iLengthEnc);
566 } else if ($iPosEnc < $length) { /* the encoded string fits into the foldlength */
568 $sLineRem = substr($line,$iPosEncEnd,$length - $iPosEncEnd);
569 if (preg_match('/^(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(.*)/Ui',$sLineRem) ||
!preg_match('/[=,;\s]/',$sLineRem)) {
570 /*impossible to fold clean in the next part -> fold after the enc string */
571 $aFoldLine[] = substr($line,0,$iPosEncEnd);
572 $line = substr($line,$iPosEncEnd);
576 $length -= strlen($fold_string);
582 $line_tmp = substr($line,0,$length);
584 /* try to fold at logical places */
587 case ($iFoldPos = strrpos($line_tmp,',')): break;
588 case ($iFoldPos = strrpos($line_tmp,';')): break;
589 case ($iFoldPos = strrpos($line_tmp,' ')): break;
590 case ($iFoldPos = strrpos($line_tmp,'=')): break;
594 if (!$iFoldPos) { /* clean folding didn't work */
597 $aFoldLine[] = substr($line,0,$iFoldPos+
1);
598 $line = substr($line,$iFoldPos+
1);
601 $length -= strlen($fold_string);
605 /*$reconstruct the line */
607 $aFoldLine[] = $line;
609 $line = implode($fold_string,$aFoldLine);
615 * function mimeBoundary - calculates the mime boundary to use
617 * This function will generate a random mime boundary base part
618 * for the message if the boundary has not already been set.
620 * @return string $mimeBoundaryString random mime boundary string
622 function mimeBoundary () {
623 static $mimeBoundaryString;
625 if ( !isset( $mimeBoundaryString ) ||
626 $mimeBoundaryString == '') {
627 $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
628 mt_rand( 10000, 99999 );
630 return $mimeBoundaryString;
634 * function timezone - Time offset for correct timezone
636 * @return string $result with timezone and offset
638 function timezone () {
641 $diff_second = date('Z');
643 $diff_second = - $diff_second;
645 if ($diff_second > 0) {
650 $diff_second = abs($diff_second);
651 $diff_hour = floor ($diff_second / 3600);
652 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
653 $zonename = '('.strftime('%Z').')';
654 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute,
660 * function calculate_references - calculate correct Referer string
662 * @param Rfc822Header $hdr message header to calculate from
664 * @return string $refer concatenated and trimmed Referer string
666 function calculate_references($hdr) {
667 $refer = $hdr->references
;
668 $message_id = $hdr->message_id
;
669 $in_reply_to = $hdr->in_reply_to
;
670 if (strlen($refer) > 2) {
671 $refer .= ' ' . $message_id;
674 $refer .= $in_reply_to . ' ' . $message_id;
676 $refer .= $message_id;