- moved DumpHeaders fn from src/download.php to mime.php
[squirrelmail.git] / class / deliver / Deliver.class.php
1 <?php
2
3 /**
4 * Deliver.class.php
5 *
6 * Copyright (c) 1999-2003 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * This contains all the functions needed to send messages through
10 * a delivery backend.
11 *
12 * $Id$
13 */
14
15 class Deliver {
16
17 function mail($message, $stream=false) {
18 $rfc822_header = $message->rfc822_header;
19 if (count($message->entities)) {
20 $boundary = $this->mimeBoundary();
21 $rfc822_header->content_type->properties['boundary']='"'.$boundary.'"';
22 } else {
23 $boundary='';
24 }
25 $raw_length = 0;
26 $reply_rfc822_header = (isset($message->reply_rfc822_header)
27 ? $message->reply_rfc822_header : '');
28 $header = $this->prepareRFC822_Header($rfc822_header, $reply_rfc822_header, $raw_length);
29
30 if ($stream) {
31 $this->preWriteToStream($header);
32 $this->writeToStream($stream, $header);
33 }
34 $this->writeBody($message, $stream, $raw_length, $boundary);
35 return $raw_length;
36 }
37
38 function writeBody($message, $stream, &$length_raw, $boundary='') {
39 // calculate boundary in case of multidimensional mime structures
40 if ($boundary && $message->entity_id && count($message->entities)) {
41 if (strpos($boundary,'_part_')) {
42 $boundary = substr($boundary,0,strpos($boundary,'_part_'));
43 }
44 $boundary_new = $boundary . '_part_'.$message->entity_id;
45 } else {
46 $boundary_new = $boundary;
47 }
48 if ($boundary && !$message->rfc822_header) {
49 $s = '--'.$boundary."\r\n";
50 $s .= $this->prepareMIME_Header($message, $boundary_new);
51 $length_raw += strlen($s);
52 if ($stream) {
53 $this->preWriteToStream($s);
54 $this->writeToStream($stream, $s);
55 }
56 }
57 $this->writeBodyPart($message, $stream, $length_raw);
58
59 $last = false;
60 for ($i=0, $entCount=count($message->entities);$i<$entCount;$i++) {
61 $msg = $this->writeBody($message->entities[$i], $stream, $length_raw, $boundary_new);
62 if ($i == $entCount-1) $last = true;
63 }
64 if ($boundary && $last) {
65 $s = "--".$boundary_new."--\r\n\r\n";
66 $length_raw += strlen($s);
67 if ($stream) {
68 $this->preWriteToStream($s);
69 $this->writeToStream($stream, $s);
70 }
71 }
72 }
73
74 function writeBodyPart($message, $stream, &$length) {
75 if ($message->mime_header) {
76 $type0 = $message->mime_header->type0;
77 } else {
78 $type0 = $message->rfc822_header->content_type->type0;
79 }
80
81 $body_part_trailing = $last = '';
82 switch ($type0)
83 {
84 case 'text':
85 case 'message':
86 if ($message->body_part) {
87 $body_part = $message->body_part;
88 $length += $this->clean_crlf($body_part);
89 if ($stream) {
90 $this->preWriteToStream($body_part);
91 $this->writeToStream($stream, $body_part);
92 }
93 $last = $body_part;
94 } elseif ($message->att_local_name) {
95 $filename = $message->att_local_name;
96 $file = fopen ($filename, 'rb');
97 while ($body_part = fgets($file, 4096)) {
98 $length += $this->clean_crlf($body_part);
99 if ($stream) {
100 $this->preWriteToStream($body_part);
101 $this->writeToStream($stream, $body_part);
102 }
103 $last = $body_part;
104 }
105 fclose($file);
106 }
107 break;
108 default:
109 if ($message->body_part) {
110 $body_part = $message->body_part;
111 $length += $this->clean_crlf($body_part);
112 if ($stream) {
113 $this->writeToStream($stream, $body_part);
114 }
115 } elseif ($message->att_local_name) {
116 $filename = $message->att_local_name;
117 $file = fopen ($filename, 'rb');
118 $encoded = '';
119 while ($tmp = fread($file, 570)) {
120 $body_part = chunk_split(base64_encode($tmp));
121 $length += $this->clean_crlf($body_part);
122 if ($stream) {
123 $this->writeToStream($stream, $body_part);
124 }
125 }
126 fclose($file);
127 }
128 break;
129 }
130 $body_part_trailing = '';
131 if ($last && substr($last,-1) != "\n") {
132 $body_part_trailing = "\r\n";
133 }
134 if ($body_part_trailing) {
135 $length += strlen($body_part_trailing);
136 if ($stream) {
137 $this->preWriteToStream($body_part_trailing);
138 $this->writeToStream($stream, $body_part_trailing);
139 }
140 }
141 }
142
143 function clean_crlf(&$s) {
144 $s = str_replace("\r\n", "\n", $s);
145 $s = str_replace("\r", "\n", $s);
146 $s = str_replace("\n", "\r\n", $s);
147 return strlen($s);
148 }
149
150 function strip_crlf(&$s) {
151 $s = str_replace("\r\n ", '', $s);
152 $s = str_replace("\r", '', $s);
153 $s = str_replace("\n", '', $s);
154 }
155
156 function preWriteToStream(&$s) {
157 }
158
159 function writeToStream($stream, $data) {
160 fputs($stream, $data);
161 }
162
163 function initStream($message, $length=0, $host='', $port='', $user='', $pass='') {
164 return $stream;
165 }
166
167 function getBcc() {
168 return false;
169 }
170
171 function prepareMIME_Header($message, $boundary) {
172 $mime_header = $message->mime_header;
173 $rn="\r\n";
174 $header = array();
175
176 $contenttype = 'Content-Type: '. $mime_header->type0 .'/'.
177 $mime_header->type1;
178 if (count($message->entities)) {
179 $contenttype .= ";\r\n " . 'boundary="'.$boundary.'"';
180 }
181 if (isset($mime_header->parameters['name'])) {
182 $contenttype .= '; name="'.
183 encodeHeader($mime_header->parameters['name']). '"';
184 }
185 if (isset($mime_header->parameters['charset'])) {
186 $charset = $mime_header->parameters['charset'];
187 $contenttype .= '; charset="'.
188 encodeHeader($charset). '"';
189 }
190
191 $header[] = $contenttype . $rn;
192 if ($mime_header->description) {
193 $header[] .= 'Content-Description: ' . $mime_header->description . $rn;
194 }
195 if ($mime_header->encoding) {
196 $encoding = $mime_header->encoding;
197 $header[] .= 'Content-Transfer-Encoding: ' . $mime_header->encoding . $rn;
198 } else {
199 if ($mime_header->type0 == 'text' || $mime_header->type0 == 'message') {
200 $header[] .= 'Content-Transfer-Encoding: 8bit' . $rn;
201 } else {
202 $header[] .= 'Content-Transfer-Encoding: base64' . $rn;
203 }
204 }
205 if ($mime_header->id) {
206 $header[] .= 'Content-ID: ' . $mime_header->id . $rn;
207 }
208 if ($mime_header->disposition) {
209 $disposition = $mime_header->disposition;
210 $contentdisp = 'Content-Disposition: ' . $disposition->name;
211 if ($disposition->getProperty('filename')) {
212 $contentdisp .= '; filename="'.
213 encodeHeader($disposition->getProperty('filename')). '"';
214 }
215 $header[] = $contentdisp . $rn;
216 }
217 if ($mime_header->md5) {
218 $header[] .= 'Content-MD5: ' . $mime_header->md5 . $rn;
219 }
220 if ($mime_header->language) {
221 $header[] .= 'Content-Language: ' . $mime_header->language . $rn;
222 }
223
224 $cnt = count($header);
225 $hdr_s = '';
226 for ($i = 0 ; $i < $cnt ; $i++) {
227 $hdr_s .= $this->foldLine($header[$i], 78,str_pad('',4));
228 }
229 $header = $hdr_s;
230 $header .= $rn; /* One blank line to separate mimeheader and body-entity */
231 return $header;
232 }
233
234 function prepareRFC822_Header($rfc822_header, $reply_rfc822_header, &$raw_length) {
235 global $domain, $version, $username;
236
237 /* if server var SERVER_NAME not available, use $domain */
238 if(!sqGetGlobalVar('SERVER_NAME', $SERVER_NAME, SQ_SERVER)) {
239 $SERVER_NAME = $domain;
240 }
241
242 sqGetGlobalVar('REMOTE_ADDR', $REMOTE_ADDR, SQ_SERVER);
243 sqGetGlobalVar('REMOTE_PORT', $REMOTE_PORT, SQ_SERVER);
244 sqGetGlobalVar('REMOTE_HOST', $REMOTE_HOST, SQ_SERVER);
245 sqGetGlobalVar('HTTP_VIA', $HTTP_VIA, SQ_SERVER);
246 sqGetGlobalVar('HTTP_X_FORWARDED_FOR', $HTTP_X_FORWARDED_FOR, SQ_SERVER);
247
248 $rn = "\r\n";
249
250 /* This creates an RFC 822 date */
251 $date = date('D, j M Y H:i:s ', mktime()) . $this->timezone();
252 /* Create a message-id */
253 $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
254 $message_id .= time() . '.squirrel@' . $REMOTE_ADDR .'>';
255 /* Make an RFC822 Received: line */
256 if (isset($REMOTE_HOST)) {
257 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
258 } else {
259 $received_from = $REMOTE_ADDR;
260 }
261 if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
262 if (!isset($HTTP_X_FORWARDED_FOR) || $HTTP_X_FORWARDED_FOR == '') {
263 $HTTP_X_FORWARDED_FOR = 'unknown';
264 }
265 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
266 }
267 $header = array();
268 $header[] = "Received: from $received_from" . $rn;
269 $header[] = " (SquirrelMail authenticated user $username);" . $rn;
270 $header[] = " by $SERVER_NAME with HTTP;" . $rn;
271 $header[] = " $date" . $rn;
272 /* Insert the rest of the header fields */
273 $header[] = 'Message-ID: '. $message_id . $rn;
274 if ($reply_rfc822_header->message_id) {
275 $rep_message_id = $reply_rfc822_header->message_id;
276 // $this->strip_crlf($message_id);
277 $header[] = 'In-Reply-To: '.$rep_message_id . $rn;
278 $references = $this->calculate_references($reply_rfc822_header);
279 $header[] = 'References: '.$references . $rn;
280 }
281 $header[] = "Date: $date" . $rn;
282 $header[] = 'Subject: '.encodeHeader($rfc822_header->subject) . $rn;
283 $header[] = 'From: '. $rfc822_header->getAddr_s('from',',',true) . $rn;
284 /* RFC2822 if from contains more then 1 address */
285 if (count($rfc822_header->from) > 1) {
286 $header[] = 'Sender: '. $rfc822_header->getAddr_s('sender',',',true) . $rn;
287 }
288 if (count($rfc822_header->to)) {
289 $header[] = 'To: '. $rfc822_header->getAddr_s('to',',',true) . $rn;
290 }
291 if (count($rfc822_header->cc)) {
292 $header[] = 'Cc: '. $rfc822_header->getAddr_s('cc',',',true) . $rn;
293 }
294 if (count($rfc822_header->reply_to)) {
295 $header[] = 'Reply-To: '. $rfc822_header->getAddr_s('reply_to',',',true) . $rn;
296 }
297 /* Sendmail should return true. Default = false */
298 $bcc = $this->getBcc();
299 if (count($rfc822_header->bcc)) {
300 $s = 'Bcc: '. $rfc822_header->getAddr_s('bcc',',',true) . $rn;
301 if (!$bcc) {
302 $s = $this->foldLine($s, 78, str_pad('',4));
303 $raw_length += strlen($s);
304 } else {
305 $header[] = $s;
306 }
307 }
308 /* Identify SquirrelMail */
309 $header[] = 'User-Agent: SquirrelMail/' . $version . $rn;
310 // Spamassassin complains about no X-Mailer in combination with X-Priority
311 $header[] = 'X-Mailer: SquirrelMail/' . $version . $rn;
312 /* Do the MIME-stuff */
313 $header[] = 'MIME-Version: 1.0' . $rn;
314 $contenttype = 'Content-Type: '. $rfc822_header->content_type->type0 .'/'.
315 $rfc822_header->content_type->type1;
316 if (count($rfc822_header->content_type->properties)) {
317 foreach ($rfc822_header->content_type->properties as $k => $v) {
318 if ($k && $v) {
319 $contenttype .= ';' .$k.'='.$v;
320 }
321 }
322 }
323 $header[] = $contenttype . $rn;
324 if ($encoding = $rfc822_header->encoding) {
325 $header[] .= 'Content-Transfer-Encoding: ' . $encoding . $rn;
326 }
327 if ($rfc822_header->dnt) {
328 $dnt = $rfc822_header->getAddr_s('dnt');
329 /* Pegasus Mail */
330 $header[] = 'X-Confirm-Reading-To: '.$dnt. $rn;
331 /* RFC 2298 */
332 $header[] = 'Disposition-Notification-To: '.$dnt. $rn;
333 }
334 if ($rfc822_header->priority) {
335 $prio = $rfc822_header->priority;
336 $header[] = 'X-Priority: '. $prio. $rn;
337 switch($prio)
338 {
339 case 1: $header[] = 'Importance: High'. $rn; break;
340 case 3: $header[] = 'Importance: Normal'. $rn; break;
341 case 5: $header[] = 'Importance: Low'. $rn; break;
342 default: break;
343 }
344 }
345 /* Insert headers from the $more_headers array */
346 if(count($rfc822_header->more_headers)) {
347 reset($rfc822_header->more_headers);
348 foreach ($rfc822_header->more_headers as $k => $v) {
349 $header[] = $k.': '.$v .$rn;
350 }
351 }
352 $cnt = count($header);
353 $hdr_s = '';
354
355 for ($i = 0 ; $i < $cnt ; $i++) {
356 $sKey = substr($header[$i],0,strpos($header[$i],':'));
357 switch ($sKey)
358 {
359 case 'Message-ID':
360 case 'In-Reply_To':
361 $hdr_s .= $header[$i];
362 break;
363 case 'References':
364 $sRefs = substr($header[$i],12);
365 $aRefs = explode(' ',$sRefs);
366 $sLine = 'References:';
367 foreach ($aRefs as $sReference) {
368 if (strlen($sLine)+strlen($sReference) >76) {
369 $hdr_s .= $sLine;
370 $sLine = $rn . ' ' . $sReference;
371 } else {
372 $sLine .= ' '. $sReference;
373 }
374 }
375 $hdr_s .= $sLine;
376 break;
377 default: $hdr_s .= $this->foldLine($header[$i], 78, str_pad('',4)); break;
378 }
379 }
380 $header = $hdr_s;
381 $header .= $rn; /* One blank line to separate header and body */
382 $raw_length += strlen($header);
383 return $header;
384 }
385
386 /*
387 * function for cleanly folding of headerlines
388 */
389 function foldLine($line, $length, $pre='') {
390 $line = substr($line,0, -2);
391 $length -= 2; /* do not fold between \r and \n */
392 $cnt = strlen($line);
393 if ($cnt > $length) { /* try folding */
394 $fold_string = "\r\n " . $pre;
395 $bFirstFold = false;
396 $aFoldLine = array();
397 while (strlen($line) > $length) {
398 $fold = false;
399 /* handle encoded parts */
400 if (preg_match('/(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(\s+|.*)/Ui',$line,$regs)) {
401 $fold_tmp = $regs[1];
402 if (!trim($regs[5])) {
403 $fold_tmp .= $regs[5];
404 }
405 $iPosEnc = strpos($line,$fold_tmp);
406 $iLengthEnc = strlen($fold_tmp);
407 $iPosEncEnd = $iPosEnc+$iLengthEnc;
408 if ($iPosEnc < $length && (($iPosEncEnd) > $length)) {
409 $fold = true;
410 /* fold just before the start of the encoded string */
411 if ($iPosEnc) {
412 $aFoldLine[] = substr($line,0,$iPosEnc);
413 }
414 $line = substr($line,$iPosEnc);
415 if (!$bFirstFold) {
416 $bFirstFold = true;
417 $length -= strlen($fold_string);
418 }
419 if ($iLengthEnc > $length) { /* place the encoded
420 string on a separate line and do not fold inside it*/
421 /* minimize foldstring */
422 $fold_string = "\r\n ";
423 $aFoldLine[] = substr($line,0,$iLengthEnc);
424 $line = substr($line,$iLengthEnc);
425 }
426 } else if ($iPosEnc < $length) { /* the encoded string fits into the foldlength */
427 /*remainder */
428 $sLineRem = substr($line,$iPosEncEnd,$length - $iPosEncEnd);
429 if (preg_match('/^(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(.*)/Ui',$sLineRem) || !preg_match('/[=,;\s]/',$sLineRem)) {
430 /*impossible to fold clean in the next part -> fold after the enc string */
431 $aFoldLine[] = substr($line,0,$iPosEncEnd);
432 $line = substr($line,$iPosEncEnd);
433 $fold = true;
434 if (!$bFirstFold) {
435 $bFirstFold = true;
436 $length -= strlen($fold_string);
437 }
438 }
439 }
440 }
441 if (!$fold) {
442 $line_tmp = substr($line,0,$length);
443 $iFoldPos = false;
444 /* try to fold at logical places */
445 switch (true)
446 {
447 case ($iFoldPos = strrpos($line_tmp,',')): break;
448 case ($iFoldPos = strrpos($line_tmp,';')): break;
449 case ($iFoldPos = strrpos($line_tmp,' ')): break;
450 case ($iFoldPos = strrpos($line_tmp,'=')): break;
451 default: break;
452 }
453
454 if (!$iFoldPos) { /* clean folding didn't work */
455 $iFoldPos = $length;
456 }
457 $aFoldLine[] = substr($line,0,$iFoldPos+1);
458 $line = substr($line,$iFoldPos+1);
459 if (!$bFirstFold) {
460 $bFirstFold = true;
461 $length -= strlen($fold_string);
462 }
463 }
464 }
465 /*$reconstruct the line */
466 if ($line) {
467 $aFoldLine[] = $line;
468 }
469 $line = implode($fold_string,$aFoldLine);
470 }
471 return $line."\r\n";
472 }
473
474 function mimeBoundary () {
475 static $mimeBoundaryString;
476
477 if ( !isset( $mimeBoundaryString ) ||
478 $mimeBoundaryString == '') {
479 $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
480 mt_rand( 10000, 99999 );
481 }
482 return $mimeBoundaryString;
483 }
484
485 /* Time offset for correct timezone */
486 function timezone () {
487 global $invert_time;
488
489 $diff_second = date('Z');
490 if ($invert_time) {
491 $diff_second = - $diff_second;
492 }
493 if ($diff_second > 0) {
494 $sign = '+';
495 } else {
496 $sign = '-';
497 }
498 $diff_second = abs($diff_second);
499 $diff_hour = floor ($diff_second / 3600);
500 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
501 $zonename = '('.strftime('%Z').')';
502 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute,
503 $zonename);
504 return ($result);
505 }
506
507 function calculate_references($hdr) {
508 $refer = $hdr->references;
509 $message_id = $hdr->message_id;
510 $in_reply_to = $hdr->in_reply_to;
511 if (strlen($refer) > 2) {
512 $refer .= ' ' . $message_id;
513 } else {
514 if ($in_reply_to) {
515 $refer .= $in_reply_to . ' ' . $message_id;
516 } else {
517 $refer .= $message_id;
518 }
519 }
520 trim($refer);
521 return $refer;
522 }
523 }
524 ?>