cc7f3e4c8149108bde17b30f48214898d8e08855
[squirrelmail.git] / class / deliver / Deliver.class.php
1 <?php
2 /**
3 * Deliver.class.php
4 *
5 * Copyright (c) 1999-2003 The SquirrelMail Project Team
6 * Licensed under the GNU GPL. For full terms see the file COPYING.
7 *
8 * This contains all the functions needed to send messages through
9 * a delivery backend.
10 *
11 * $Id$
12 *
13 * @author Marc Groot Koerkamp
14 * @package squirrelmail
15 */
16
17
18 /**
19 * Deliver Class - called to actually deliver the message
20 *
21 * This class is called by compose.php and other code that needs
22 * to send messages. All delivery functionality should be centralized
23 * in this class.
24 *
25 * Do not place UI code in this class, as UI code should be placed in templates
26 * going forward.
27 *
28 * @author Marc Groot Koerkamp
29 * @package squirrelmail
30 */
31 class Deliver {
32
33 /**
34 * function mail - send the message parts to the SMTP stream
35 *
36 * @param Message $message Message class to send
37 * @param resource $stream file handle to the SMTP stream
38 *
39 * @return integer $raw_length
40 */
41 function mail($message, $stream=false) {
42 $rfc822_header = $message->rfc822_header;
43 if (count($message->entities)) {
44 $boundary = $this->mimeBoundary();
45 $rfc822_header->content_type->properties['boundary']='"'.$boundary.'"';
46 } else {
47 $boundary='';
48 }
49 $raw_length = 0;
50 $reply_rfc822_header = (isset($message->reply_rfc822_header)
51 ? $message->reply_rfc822_header : '');
52 $header = $this->prepareRFC822_Header($rfc822_header, $reply_rfc822_header, $raw_length);
53
54 if ($stream) {
55 $this->preWriteToStream($header);
56 $this->writeToStream($stream, $header);
57 }
58 $this->writeBody($message, $stream, $raw_length, $boundary);
59 return $raw_length;
60 }
61
62 /**
63 * function writeBody - generate and write the mime boundaries around each part to the stream
64 *
65 * Recursively formats and writes the MIME boundaries of the $message
66 * to the output stream.
67 *
68 * @param Message $message Message object to transform
69 * @param resource $stream SMTP output stream
70 * @param integer &$length_raw raw length of the message (part)
71 * as returned by mail fn
72 * @param string $boundary custom boundary to call, usually for subparts
73 *
74 * @return void
75 */
76 function writeBody($message, $stream, &$length_raw, $boundary='') {
77 // calculate boundary in case of multidimensional mime structures
78 if ($boundary && $message->entity_id && count($message->entities)) {
79 if (strpos($boundary,'_part_')) {
80 $boundary = substr($boundary,0,strpos($boundary,'_part_'));
81 }
82 $boundary_new = $boundary . '_part_'.$message->entity_id;
83 } else {
84 $boundary_new = $boundary;
85 }
86 if ($boundary && !$message->rfc822_header) {
87 $s = '--'.$boundary."\r\n";
88 $s .= $this->prepareMIME_Header($message, $boundary_new);
89 $length_raw += strlen($s);
90 if ($stream) {
91 $this->preWriteToStream($s);
92 $this->writeToStream($stream, $s);
93 }
94 }
95 $this->writeBodyPart($message, $stream, $length_raw);
96
97 $last = false;
98 for ($i=0, $entCount=count($message->entities);$i<$entCount;$i++) {
99 $msg = $this->writeBody($message->entities[$i], $stream, $length_raw, $boundary_new);
100 if ($i == $entCount-1) $last = true;
101 }
102 if ($boundary && $last) {
103 $s = "--".$boundary_new."--\r\n\r\n";
104 $length_raw += strlen($s);
105 if ($stream) {
106 $this->preWriteToStream($s);
107 $this->writeToStream($stream, $s);
108 }
109 }
110 }
111
112 /**
113 * function writeBodyPart - write each individual mimepart
114 *
115 * Recursively called by WriteBody to write each mime part to the SMTP stream
116 *
117 * @param Message $message Message object to transform
118 * @param resource $stream SMTP output stream
119 * @param integer &$length length of the message part
120 * as returned by mail fn
121 *
122 * @return void
123 */
124 function writeBodyPart($message, $stream, &$length) {
125 if ($message->mime_header) {
126 $type0 = $message->mime_header->type0;
127 } else {
128 $type0 = $message->rfc822_header->content_type->type0;
129 }
130
131 $body_part_trailing = $last = '';
132 switch ($type0)
133 {
134 case 'text':
135 case 'message':
136 if ($message->body_part) {
137 $body_part = $message->body_part;
138 $length += $this->clean_crlf($body_part);
139 if ($stream) {
140 $this->preWriteToStream($body_part);
141 $this->writeToStream($stream, $body_part);
142 }
143 $last = $body_part;
144 } elseif ($message->att_local_name) {
145 $filename = $message->att_local_name;
146 $file = fopen ($filename, 'rb');
147 while ($body_part = fgets($file, 4096)) {
148 $length += $this->clean_crlf($body_part);
149 if ($stream) {
150 $this->preWriteToStream($body_part);
151 $this->writeToStream($stream, $body_part);
152 }
153 $last = $body_part;
154 }
155 fclose($file);
156 }
157 break;
158 default:
159 if ($message->body_part) {
160 $body_part = $message->body_part;
161 $length += $this->clean_crlf($body_part);
162 if ($stream) {
163 $this->writeToStream($stream, $body_part);
164 }
165 } elseif ($message->att_local_name) {
166 $filename = $message->att_local_name;
167 $file = fopen ($filename, 'rb');
168 $encoded = '';
169 while ($tmp = fread($file, 570)) {
170 $body_part = chunk_split(base64_encode($tmp));
171 $length += $this->clean_crlf($body_part);
172 if ($stream) {
173 $this->writeToStream($stream, $body_part);
174 }
175 }
176 fclose($file);
177 }
178 break;
179 }
180 $body_part_trailing = '';
181 if ($last && substr($last,-1) != "\n") {
182 $body_part_trailing = "\r\n";
183 }
184 if ($body_part_trailing) {
185 $length += strlen($body_part_trailing);
186 if ($stream) {
187 $this->preWriteToStream($body_part_trailing);
188 $this->writeToStream($stream, $body_part_trailing);
189 }
190 }
191 }
192
193 /**
194 * function clean_crlf - change linefeeds and newlines to legal characters
195 *
196 * The SMTP format only allows CRLF as line terminators.
197 * This function replaces illegal teminators with the correct terminator.
198 *
199 * @param string &$s string to clean linefeeds on
200 *
201 * @return void
202 */
203 function clean_crlf(&$s) {
204 $s = str_replace("\r\n", "\n", $s);
205 $s = str_replace("\r", "\n", $s);
206 $s = str_replace("\n", "\r\n", $s);
207 return strlen($s);
208 }
209
210 /**
211 * function strip_crlf - strip linefeeds and newlines from a string
212 *
213 * The SMTP format only allows CRLF as line terminators.
214 * This function strips all line terminators from the string.
215 *
216 * @param string &$s string to clean linefeeds on
217 *
218 * @return void
219 */
220 function strip_crlf(&$s) {
221 $s = str_replace("\r\n ", '', $s);
222 $s = str_replace("\r", '', $s);
223 $s = str_replace("\n", '', $s);
224 }
225
226 /**
227 * function preWriteToStream - reserved for extended functionality
228 *
229 * This function is not yet implemented.
230 * Reserved for extended functionality.
231 *
232 * @param string &$s string to operate on
233 *
234 * @return void
235 */
236 function preWriteToStream(&$s) {
237 }
238
239 /**
240 * function writeToStream - write data to the SMTP stream
241 *
242 * @param resource $stream SMTP output stream
243 * @param string $data string with data to send to the SMTP stream
244 *
245 * @return void
246 */
247 function writeToStream($stream, $data) {
248 fputs($stream, $data);
249 }
250
251 /**
252 * function initStream - reserved for extended functionality
253 *
254 * This function is not yet implemented.
255 * Reserved for extended functionality.
256 *
257 * @param Message $message Message object
258 * @param string $host host name or IP to connect to
259 * @param string $user username to log into the SMTP server with
260 * @param string $pass password to log into the SMTP server with
261 * @param integer $length
262 *
263 * @return handle $stream file handle resource to SMTP stream
264 */
265 function initStream($message, $length=0, $host='', $port='', $user='', $pass='') {
266 return $stream;
267 }
268
269 /**
270 * function getBCC - reserved for extended functionality
271 *
272 * This function is not yet implemented.
273 * Reserved for extended functionality.
274 *
275 */
276 function getBCC() {
277 return false;
278 }
279
280 /**
281 * function prepareMIME_Header - creates the mime header
282 *
283 * @param Message $message Message object to act on
284 * @param string $boundary mime boundary from fn MimeBoundary
285 *
286 * @return string $header properly formatted mime header
287 */
288 function prepareMIME_Header($message, $boundary) {
289 $mime_header = $message->mime_header;
290 $rn="\r\n";
291 $header = array();
292
293 $contenttype = 'Content-Type: '. $mime_header->type0 .'/'.
294 $mime_header->type1;
295 if (count($message->entities)) {
296 $contenttype .= ";\r\n " . 'boundary="'.$boundary.'"';
297 }
298 if (isset($mime_header->parameters['name'])) {
299 $contenttype .= '; name="'.
300 encodeHeader($mime_header->parameters['name']). '"';
301 }
302 if (isset($mime_header->parameters['charset'])) {
303 $charset = $mime_header->parameters['charset'];
304 $contenttype .= '; charset="'.
305 encodeHeader($charset). '"';
306 }
307
308 $header[] = $contenttype . $rn;
309 if ($mime_header->description) {
310 $header[] .= 'Content-Description: ' . $mime_header->description . $rn;
311 }
312 if ($mime_header->encoding) {
313 $encoding = $mime_header->encoding;
314 $header[] .= 'Content-Transfer-Encoding: ' . $mime_header->encoding . $rn;
315 } else {
316 if ($mime_header->type0 == 'text' || $mime_header->type0 == 'message') {
317 $header[] .= 'Content-Transfer-Encoding: 8bit' . $rn;
318 } else {
319 $header[] .= 'Content-Transfer-Encoding: base64' . $rn;
320 }
321 }
322 if ($mime_header->id) {
323 $header[] .= 'Content-ID: ' . $mime_header->id . $rn;
324 }
325 if ($mime_header->disposition) {
326 $disposition = $mime_header->disposition;
327 $contentdisp = 'Content-Disposition: ' . $disposition->name;
328 if ($disposition->getProperty('filename')) {
329 $contentdisp .= '; filename="'.
330 encodeHeader($disposition->getProperty('filename')). '"';
331 }
332 $header[] = $contentdisp . $rn;
333 }
334 if ($mime_header->md5) {
335 $header[] .= 'Content-MD5: ' . $mime_header->md5 . $rn;
336 }
337 if ($mime_header->language) {
338 $header[] .= 'Content-Language: ' . $mime_header->language . $rn;
339 }
340
341 $cnt = count($header);
342 $hdr_s = '';
343 for ($i = 0 ; $i < $cnt ; $i++) {
344 $hdr_s .= $this->foldLine($header[$i], 78,str_pad('',4));
345 }
346 $header = $hdr_s;
347 $header .= $rn; /* One blank line to separate mimeheader and body-entity */
348 return $header;
349 }
350
351 /**
352 * function prepareRFC822_Header - prepares the RFC822 header string from Rfc822Header object(s)
353 *
354 * This function takes the Rfc822Header object(s) and formats them
355 * into the RFC822Header string to send to the SMTP server as part
356 * of the SMTP message.
357 *
358 * @param Rfc822Header $rfc822_header
359 * @param Rfc822Header $reply_rfc822_header
360 * @param integer &$raw_length length of the message
361 *
362 * @return string $header
363 */
364 function prepareRFC822_Header($rfc822_header, $reply_rfc822_header, &$raw_length) {
365 global $domain, $version, $username;
366
367 /* if server var SERVER_NAME not available, use $domain */
368 if(!sqGetGlobalVar('SERVER_NAME', $SERVER_NAME, SQ_SERVER)) {
369 $SERVER_NAME = $domain;
370 }
371
372 sqGetGlobalVar('REMOTE_ADDR', $REMOTE_ADDR, SQ_SERVER);
373 sqGetGlobalVar('REMOTE_PORT', $REMOTE_PORT, SQ_SERVER);
374 sqGetGlobalVar('REMOTE_HOST', $REMOTE_HOST, SQ_SERVER);
375 sqGetGlobalVar('HTTP_VIA', $HTTP_VIA, SQ_SERVER);
376 sqGetGlobalVar('HTTP_X_FORWARDED_FOR', $HTTP_X_FORWARDED_FOR, SQ_SERVER);
377
378 $rn = "\r\n";
379
380 /* This creates an RFC 822 date */
381 $date = date('D, j M Y H:i:s ', mktime()) . $this->timezone();
382 /* Create a message-id */
383 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
384 $message_id .= time() . '.squirrel@' . $REMOTE_ADDR .'>';
385 /* Make an RFC822 Received: line */
386 if (isset($REMOTE_HOST)) {
387 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
388 } else {
389 $received_from = $REMOTE_ADDR;
390 }
391 if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
392 if (!isset($HTTP_X_FORWARDED_FOR) || $HTTP_X_FORWARDED_FOR == '') {
393 $HTTP_X_FORWARDED_FOR = 'unknown';
394 }
395 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
396 }
397 $header = array();
398 $header[] = "Received: from $received_from" . $rn;
399 $header[] = " (SquirrelMail authenticated user $username);" . $rn;
400 $header[] = " by $SERVER_NAME with HTTP;" . $rn;
401 $header[] = " $date" . $rn;
402 /* Insert the rest of the header fields */
403 $header[] = 'Message-ID: '. $message_id . $rn;
404 if ($reply_rfc822_header->message_id) {
405 $rep_message_id = $reply_rfc822_header->message_id;
406 // $this->strip_crlf($message_id);
407 $header[] = 'In-Reply-To: '.$rep_message_id . $rn;
408 $references = $this->calculate_references($reply_rfc822_header);
409 $header[] = 'References: '.$references . $rn;
410 }
411 $header[] = "Date: $date" . $rn;
412 $header[] = 'Subject: '.encodeHeader($rfc822_header->subject) . $rn;
413 $header[] = 'From: '. $rfc822_header->getAddr_s('from',',',true) . $rn;
414 /* RFC2822 if from contains more then 1 address */
415 if (count($rfc822_header->from) > 1) {
416 $header[] = 'Sender: '. $rfc822_header->getAddr_s('sender',',',true) . $rn;
417 }
418 if (count($rfc822_header->to)) {
419 $header[] = 'To: '. $rfc822_header->getAddr_s('to',',',true) . $rn;
420 }
421 if (count($rfc822_header->cc)) {
422 $header[] = 'Cc: '. $rfc822_header->getAddr_s('cc',',',true) . $rn;
423 }
424 if (count($rfc822_header->reply_to)) {
425 $header[] = 'Reply-To: '. $rfc822_header->getAddr_s('reply_to',',',true) . $rn;
426 }
427 /* Sendmail should return true. Default = false */
428 $bcc = $this->getBcc();
429 if (count($rfc822_header->bcc)) {
430 $s = 'Bcc: '. $rfc822_header->getAddr_s('bcc',',',true) . $rn;
431 if (!$bcc) {
432 $s = $this->foldLine($s, 78, str_pad('',4));
433 $raw_length += strlen($s);
434 } else {
435 $header[] = $s;
436 }
437 }
438 /* Identify SquirrelMail */
439 $header[] = 'User-Agent: SquirrelMail/' . $version . $rn;
440 // Spamassassin complains about no X-Mailer in combination with X-Priority
441 $header[] = 'X-Mailer: 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) {
448 if ($k && $v) {
449 $contenttype .= ';' .$k.'='.$v;
450 }
451 }
452 }
453 $header[] = $contenttype . $rn;
454 if ($encoding = $rfc822_header->encoding) {
455 $header[] .= 'Content-Transfer-Encoding: ' . $encoding . $rn;
456 }
457 if ($rfc822_header->dnt) {
458 $dnt = $rfc822_header->getAddr_s('dnt');
459 /* Pegasus Mail */
460 $header[] = 'X-Confirm-Reading-To: '.$dnt. $rn;
461 /* RFC 2298 */
462 $header[] = 'Disposition-Notification-To: '.$dnt. $rn;
463 }
464 if ($rfc822_header->priority) {
465 $prio = $rfc822_header->priority;
466 $header[] = 'X-Priority: '. $prio. $rn;
467 switch($prio)
468 {
469 case 1: $header[] = 'Importance: High'. $rn; break;
470 case 3: $header[] = 'Importance: Normal'. $rn; break;
471 case 5: $header[] = 'Importance: Low'. $rn; break;
472 default: break;
473 }
474 }
475 /* Insert headers from the $more_headers array */
476 if(count($rfc822_header->more_headers)) {
477 reset($rfc822_header->more_headers);
478 foreach ($rfc822_header->more_headers as $k => $v) {
479 $header[] = $k.': '.$v .$rn;
480 }
481 }
482 $cnt = count($header);
483 $hdr_s = '';
484
485 for ($i = 0 ; $i < $cnt ; $i++) {
486 $sKey = substr($header[$i],0,strpos($header[$i],':'));
487 switch ($sKey)
488 {
489 case 'Message-ID':
490 case 'In-Reply_To':
491 $hdr_s .= $header[$i];
492 break;
493 case 'References':
494 $sRefs = substr($header[$i],12);
495 $aRefs = explode(' ',$sRefs);
496 $sLine = 'References:';
497 foreach ($aRefs as $sReference) {
498 if (strlen($sLine)+strlen($sReference) >76) {
499 $hdr_s .= $sLine;
500 $sLine = $rn . ' ' . $sReference;
501 } else {
502 $sLine .= ' '. $sReference;
503 }
504 }
505 $hdr_s .= $sLine;
506 break;
507 default: $hdr_s .= $this->foldLine($header[$i], 78, str_pad('',4)); break;
508 }
509 }
510 $header = $hdr_s;
511 $header .= $rn; /* One blank line to separate header and body */
512 $raw_length += strlen($header);
513 return $header;
514 }
515
516 /**
517 * function foldLine - for cleanly folding of headerlines
518 *
519 * @param string $line
520 * @param integer $length length to fold the line at
521 * @param string $pre prefix the line with...
522 *
523 * @return string $line folded line with trailing CRLF
524 */
525 function foldLine($line, $length, $pre='') {
526 $line = substr($line,0, -2);
527 $length -= 2; /* do not fold between \r and \n */
528 $cnt = strlen($line);
529 if ($cnt > $length) { /* try folding */
530 $fold_string = "\r\n " . $pre;
531 $bFirstFold = false;
532 $aFoldLine = array();
533 while (strlen($line) > $length) {
534 $fold = false;
535 /* handle encoded parts */
536 if (preg_match('/(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(\s+|.*)/Ui',$line,$regs)) {
537 $fold_tmp = $regs[1];
538 if (!trim($regs[5])) {
539 $fold_tmp .= $regs[5];
540 }
541 $iPosEnc = strpos($line,$fold_tmp);
542 $iLengthEnc = strlen($fold_tmp);
543 $iPosEncEnd = $iPosEnc+$iLengthEnc;
544 if ($iPosEnc < $length && (($iPosEncEnd) > $length)) {
545 $fold = true;
546 /* fold just before the start of the encoded string */
547 if ($iPosEnc) {
548 $aFoldLine[] = substr($line,0,$iPosEnc);
549 }
550 $line = substr($line,$iPosEnc);
551 if (!$bFirstFold) {
552 $bFirstFold = true;
553 $length -= strlen($fold_string);
554 }
555 if ($iLengthEnc > $length) { /* place the encoded
556 string on a separate line and do not fold inside it*/
557 /* minimize foldstring */
558 $fold_string = "\r\n ";
559 $aFoldLine[] = substr($line,0,$iLengthEnc);
560 $line = substr($line,$iLengthEnc);
561 }
562 } else if ($iPosEnc < $length) { /* the encoded string fits into the foldlength */
563 /*remainder */
564 $sLineRem = substr($line,$iPosEncEnd,$length - $iPosEncEnd);
565 if (preg_match('/^(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(.*)/Ui',$sLineRem) || !preg_match('/[=,;\s]/',$sLineRem)) {
566 /*impossible to fold clean in the next part -> fold after the enc string */
567 $aFoldLine[] = substr($line,0,$iPosEncEnd);
568 $line = substr($line,$iPosEncEnd);
569 $fold = true;
570 if (!$bFirstFold) {
571 $bFirstFold = true;
572 $length -= strlen($fold_string);
573 }
574 }
575 }
576 }
577 if (!$fold) {
578 $line_tmp = substr($line,0,$length);
579 $iFoldPos = false;
580 /* try to fold at logical places */
581 switch (true)
582 {
583 case ($iFoldPos = strrpos($line_tmp,',')): break;
584 case ($iFoldPos = strrpos($line_tmp,';')): break;
585 case ($iFoldPos = strrpos($line_tmp,' ')): break;
586 case ($iFoldPos = strrpos($line_tmp,'=')): break;
587 default: break;
588 }
589
590 if (!$iFoldPos) { /* clean folding didn't work */
591 $iFoldPos = $length;
592 }
593 $aFoldLine[] = substr($line,0,$iFoldPos+1);
594 $line = substr($line,$iFoldPos+1);
595 if (!$bFirstFold) {
596 $bFirstFold = true;
597 $length -= strlen($fold_string);
598 }
599 }
600 }
601 /*$reconstruct the line */
602 if ($line) {
603 $aFoldLine[] = $line;
604 }
605 $line = implode($fold_string,$aFoldLine);
606 }
607 return $line."\r\n";
608 }
609
610 /**
611 * function mimeBoundary - calculates the mime boundary to use
612 *
613 * This function will generate a random mime boundary base part
614 * for the message if the boundary has not already been set.
615 *
616 * @return string $mimeBoundaryString random mime boundary string
617 */
618 function mimeBoundary () {
619 static $mimeBoundaryString;
620
621 if ( !isset( $mimeBoundaryString ) ||
622 $mimeBoundaryString == '') {
623 $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
624 mt_rand( 10000, 99999 );
625 }
626 return $mimeBoundaryString;
627 }
628
629 /**
630 * function timezone - Time offset for correct timezone
631 *
632 * @return string $result with timezone and offset
633 */
634 function timezone () {
635 global $invert_time;
636
637 $diff_second = date('Z');
638 if ($invert_time) {
639 $diff_second = - $diff_second;
640 }
641 if ($diff_second > 0) {
642 $sign = '+';
643 } else {
644 $sign = '-';
645 }
646 $diff_second = abs($diff_second);
647 $diff_hour = floor ($diff_second / 3600);
648 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
649 $zonename = '('.strftime('%Z').')';
650 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute,
651 $zonename);
652 return ($result);
653 }
654
655 /**
656 * function calculate_references - calculate correct Referer string
657 *
658 * @param Rfc822Header $hdr message header to calculate from
659 *
660 * @return string $refer concatenated and trimmed Referer string
661 */
662 function calculate_references($hdr) {
663 $refer = $hdr->references;
664 $message_id = $hdr->message_id;
665 $in_reply_to = $hdr->in_reply_to;
666 if (strlen($refer) > 2) {
667 $refer .= ' ' . $message_id;
668 } else {
669 if ($in_reply_to) {
670 $refer .= $in_reply_to . ' ' . $message_id;
671 } else {
672 $refer .= $message_id;
673 }
674 }
675 trim($refer);
676 return $refer;
677 }
678 }
679 ?>