Refactor how IMAP messages are "sent"
[squirrelmail.git] / class / deliver / Deliver.class.php
CommitLineData
4960ec8e 1<?php
4b4abf93 2
69298c28 3/**
4 * Deliver.class.php
5 *
69298c28 6 * This contains all the functions needed to send messages through
7 * a delivery backend.
8 *
4b4abf93 9 * @author Marc Groot Koerkamp
4b5049de 10 * @copyright &copy; 1999-2007 The SquirrelMail Project Team
4b4abf93 11 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
883d9cd3 12 * @version $Id$
72b004e6 13 * @package squirrelmail
69298c28 14 */
15
72b004e6 16/**
17 * Deliver Class - called to actually deliver the message
18 *
19 * This class is called by compose.php and other code that needs
20 * to send messages. All delivery functionality should be centralized
21 * in this class.
22 *
23 * Do not place UI code in this class, as UI code should be placed in templates
24 * going forward.
25 *
26 * @author Marc Groot Koerkamp
27 * @package squirrelmail
28 */
4960ec8e 29class Deliver {
30
72b004e6 31 /**
32 * function mail - send the message parts to the SMTP stream
33 *
0fdb0aa1 34 * @param Message $message Message object to send
35 * @param resource $stream Handle to the SMTP stream
e2ccf284 36 * (when FALSE, nothing will be
37 * written to the stream; this can
38 * be used to determine the actual
39 * number of bytes that will be
40 * written to the stream)
0fdb0aa1 41 * @param string $reply_id Identifies message being replied to
42 * (OPTIONAL; caller should ONLY specify
43 * a value for this when the message
44 * being sent is a reply)
45 * @param string $reply_ent_id Identifies message being replied to
46 * in the case it was an embedded/attached
47 * message inside another (OPTIONAL; caller
48 * should ONLY specify a value for this
49 * when the message being sent is a reply)
e2ccf284 50 * @param mixed $extra Any implementation-specific variables
51 * can be passed in here and used in
52 * an overloaded version of this method
53 * if needed.
72b004e6 54 *
e2ccf284 55 * @return integer $raw_length The number of bytes written (or that would
56 * have been written) to the output stream
72b004e6 57 */
e2ccf284 58 function mail($message, $stream=false, $reply_id=0, $reply_ent_id=0,
59 $extra=NULL) {
60
78f39e78 61 $rfc822_header = $message->rfc822_header;
62 if (count($message->entities)) {
63 $boundary = $this->mimeBoundary();
64 $rfc822_header->content_type->properties['boundary']='"'.$boundary.'"';
65 } else {
66 $boundary='';
67 }
68 $raw_length = 0;
0fdb0aa1 69
70
71 // calculate reply header if needed
72 //
73 if ($reply_id) {
74 global $imapConnection, $username, $imapServerAddress,
75 $imapPort, $mailbox;
e2ccf284 76
77 if (!is_resource($imapConnection))
0fdb0aa1 78 $imapConnection = sqimap_login($username, FALSE,
79 $imapServerAddress, $imapPort, 0);
80
81 sqimap_mailbox_select($imapConnection, $mailbox);
82 $reply_message = sqimap_get_message($imapConnection, $reply_id, $mailbox);
83
84 if ($reply_ent_id) {
85 /* redefine the messsage in case of message/rfc822 */
86 $reply_message = $message->getEntity($reply_ent_id);
87 /* message is an entity which contains the envelope and type0=message
88 * and type1=rfc822. The actual entities are childs from
89 * $reply_message->entities[0]. That's where the encoding and is located
90 */
91
92 $orig_header = $reply_message->rfc822_header; /* here is the envelope located */
93
94 } else {
95 $orig_header = $reply_message->rfc822_header;
96 }
97 }
98 $message->reply_rfc822_header = $orig_header;
99
100
72b004e6 101 $reply_rfc822_header = (isset($message->reply_rfc822_header)
78f39e78 102 ? $message->reply_rfc822_header : '');
103 $header = $this->prepareRFC822_Header($rfc822_header, $reply_rfc822_header, $raw_length);
75b14a70 104
e2ccf284 105 $this->send_mail($message, $header, $boundary, $stream, $raw_length, $extra);
106
107 return $raw_length;
108 }
109
110 /**
111 * function send_mail - send the message parts to the IMAP stream
112 *
113 * @param Message $message Message object to send
114 * @param string $header Headers ready to send
115 * @param string $boundary Message parts boundary
116 * @param resource $stream Handle to the SMTP stream
117 * (when FALSE, nothing will be
118 * written to the stream; this can
119 * be used to determine the actual
120 * number of bytes that will be
121 * written to the stream)
122 * @param int &$raw_length The number of bytes written (or that
123 * would have been written) to the
124 * output stream - NOTE that this is
125 * passed by reference
126 * @param mixed $extra Any implementation-specific variables
127 * can be passed in here and used in
128 * an overloaded version of this method
129 * if needed.
130 *
131 * @return void
132 *
133 */
134 function send_mail($message, $header, $boundary, $stream=false,
135 &$raw_length, $extra=NULL) {
136
137
78f39e78 138 if ($stream) {
59387d1c 139 $this->preWriteToStream($header);
140 $this->writeToStream($stream, $header);
78f39e78 141 }
142 $this->writeBody($message, $stream, $raw_length, $boundary);
3b53d87f 143 }
78f39e78 144
72b004e6 145 /**
146 * function writeBody - generate and write the mime boundaries around each part to the stream
147 *
148 * Recursively formats and writes the MIME boundaries of the $message
149 * to the output stream.
150 *
151 * @param Message $message Message object to transform
152 * @param resource $stream SMTP output stream
e2ccf284 153 * (when FALSE, nothing will be
154 * written to the stream; this can
155 * be used to determine the actual
156 * number of bytes that will be
157 * written to the stream)
72b004e6 158 * @param integer &$length_raw raw length of the message (part)
159 * as returned by mail fn
160 * @param string $boundary custom boundary to call, usually for subparts
161 *
3a70ee56 162 * @return void
72b004e6 163 */
3b53d87f 164 function writeBody($message, $stream, &$length_raw, $boundary='') {
caf6a9a4 165 // calculate boundary in case of multidimensional mime structures
166 if ($boundary && $message->entity_id && count($message->entities)) {
167 if (strpos($boundary,'_part_')) {
168 $boundary = substr($boundary,0,strpos($boundary,'_part_'));
ba86230e 169
593d083d 170 // the next four lines use strrev to reverse any nested boundaries
171 // because RFC 2046 (5.1.1) says that if a line starts with the outer
172 // boundary string (doesn't matter what the line ends with), that
173 // can be considered a match for the outer boundary; thus the nested
174 // boundary needs to be unique from the outer one
ba86230e 175 //
176 } else if (strpos($boundary,'_trap_')) {
177 $boundary = substr(strrev($boundary),0,strpos(strrev($boundary),'_part_'));
caf6a9a4 178 }
ba86230e 179 $boundary_new = strrev($boundary . '_part_'.$message->entity_id);
caf6a9a4 180 } else {
181 $boundary_new = $boundary;
182 }
1274f430 183 if ($boundary && !$message->rfc822_header) {
78f39e78 184 $s = '--'.$boundary."\r\n";
caf6a9a4 185 $s .= $this->prepareMIME_Header($message, $boundary_new);
78f39e78 186 $length_raw += strlen($s);
187 if ($stream) {
3b53d87f 188 $this->preWriteToStream($s);
78f39e78 189 $this->writeToStream($stream, $s);
190 }
191 }
192 $this->writeBodyPart($message, $stream, $length_raw);
72b004e6 193
78f39e78 194 $last = false;
195 for ($i=0, $entCount=count($message->entities);$i<$entCount;$i++) {
caf6a9a4 196 $msg = $this->writeBody($message->entities[$i], $stream, $length_raw, $boundary_new);
78f39e78 197 if ($i == $entCount-1) $last = true;
198 }
1274f430 199 if ($boundary && $last) {
dcc5c913 200 $s = "--".$boundary_new."--\r\n\r\n";
78f39e78 201 $length_raw += strlen($s);
202 if ($stream) {
3b53d87f 203 $this->preWriteToStream($s);
78f39e78 204 $this->writeToStream($stream, $s);
205 }
206 }
3b53d87f 207 }
208
72b004e6 209 /**
210 * function writeBodyPart - write each individual mimepart
211 *
212 * Recursively called by WriteBody to write each mime part to the SMTP stream
213 *
214 * @param Message $message Message object to transform
215 * @param resource $stream SMTP output stream
e2ccf284 216 * (when FALSE, nothing will be
217 * written to the stream; this can
218 * be used to determine the actual
219 * number of bytes that will be
220 * written to the stream)
72b004e6 221 * @param integer &$length length of the message part
222 * as returned by mail fn
223 *
3a70ee56 224 * @return void
72b004e6 225 */
3b53d87f 226 function writeBodyPart($message, $stream, &$length) {
1274f430 227 if ($message->mime_header) {
78f39e78 228 $type0 = $message->mime_header->type0;
229 } else {
230 $type0 = $message->rfc822_header->content_type->type0;
231 }
232
233 $body_part_trailing = $last = '';
234 switch ($type0)
235 {
236 case 'text':
237 case 'message':
238 if ($message->body_part) {
239 $body_part = $message->body_part;
4cf85ddd 240 // remove NUL characters
241 $body_part = str_replace("\0",'',$body_part);
78f39e78 242 $length += $this->clean_crlf($body_part);
243 if ($stream) {
72b004e6 244 $this->preWriteToStream($body_part);
78f39e78 245 $this->writeToStream($stream, $body_part);
246 }
247 $last = $body_part;
248 } elseif ($message->att_local_name) {
1f270d3c 249 global $username, $attachment_dir;
250 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
78f39e78 251 $filename = $message->att_local_name;
1f270d3c 252 $file = fopen ($hashed_attachment_dir . '/' . $filename, 'rb');
78f39e78 253 while ($body_part = fgets($file, 4096)) {
257dea3f 254 // remove NUL characters
255 $body_part = str_replace("\0",'',$body_part);
78f39e78 256 $length += $this->clean_crlf($body_part);
257 if ($stream) {
258 $this->preWriteToStream($body_part);
259 $this->writeToStream($stream, $body_part);
260 }
261 $last = $body_part;
262 }
263 fclose($file);
264 }
265 break;
266 default:
267 if ($message->body_part) {
268 $body_part = $message->body_part;
257dea3f 269 // remove NUL characters
270 $body_part = str_replace("\0",'',$body_part);
78f39e78 271 $length += $this->clean_crlf($body_part);
272 if ($stream) {
273 $this->writeToStream($stream, $body_part);
274 }
275 } elseif ($message->att_local_name) {
1f270d3c 276 global $username, $attachment_dir;
277 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
78f39e78 278 $filename = $message->att_local_name;
1f270d3c 279 $file = fopen ($hashed_attachment_dir . '/' . $filename, 'rb');
78f39e78 280 while ($tmp = fread($file, 570)) {
27ff4efb 281 $body_part = chunk_split(base64_encode($tmp));
282 // Up to 4.3.10 chunk_split always appends a newline,
283 // while in 4.3.11 it doesn't if the string to split
284 // is shorter than the chunk length.
285 if( substr($body_part, -1 , 1 ) != "\n" )
286 $body_part .= "\n";
78f39e78 287 $length += $this->clean_crlf($body_part);
288 if ($stream) {
289 $this->writeToStream($stream, $body_part);
290 }
291 }
292 fclose($file);
3b53d87f 293 }
78f39e78 294 break;
295 }
296 $body_part_trailing = '';
297 if ($last && substr($last,-1) != "\n") {
298 $body_part_trailing = "\r\n";
299 }
300 if ($body_part_trailing) {
301 $length += strlen($body_part_trailing);
302 if ($stream) {
303 $this->preWriteToStream($body_part_trailing);
304 $this->writeToStream($stream, $body_part_trailing);
305 }
306 }
3b53d87f 307 }
78f39e78 308
72b004e6 309 /**
310 * function clean_crlf - change linefeeds and newlines to legal characters
311 *
312 * The SMTP format only allows CRLF as line terminators.
313 * This function replaces illegal teminators with the correct terminator.
314 *
315 * @param string &$s string to clean linefeeds on
316 *
3a70ee56 317 * @return void
72b004e6 318 */
69298c28 319 function clean_crlf(&$s) {
3b53d87f 320 $s = str_replace("\r\n", "\n", $s);
321 $s = str_replace("\r", "\n", $s);
322 $s = str_replace("\n", "\r\n", $s);
78f39e78 323 return strlen($s);
3b53d87f 324 }
78f39e78 325
72b004e6 326 /**
327 * function strip_crlf - strip linefeeds and newlines from a string
328 *
329 * The SMTP format only allows CRLF as line terminators.
330 * This function strips all line terminators from the string.
331 *
332 * @param string &$s string to clean linefeeds on
333 *
3a70ee56 334 * @return void
72b004e6 335 */
e4f9307a 336 function strip_crlf(&$s) {
337 $s = str_replace("\r\n ", '', $s);
78f39e78 338 $s = str_replace("\r", '', $s);
339 $s = str_replace("\n", '', $s);
e4f9307a 340 }
3b53d87f 341
72b004e6 342 /**
343 * function preWriteToStream - reserved for extended functionality
344 *
345 * This function is not yet implemented.
346 * Reserved for extended functionality.
347 *
348 * @param string &$s string to operate on
349 *
3a70ee56 350 * @return void
72b004e6 351 */
69298c28 352 function preWriteToStream(&$s) {
3b53d87f 353 }
78f39e78 354
72b004e6 355 /**
356 * function writeToStream - write data to the SMTP stream
357 *
358 * @param resource $stream SMTP output stream
359 * @param string $data string with data to send to the SMTP stream
360 *
3a70ee56 361 * @return void
72b004e6 362 */
3b53d87f 363 function writeToStream($stream, $data) {
78f39e78 364 fputs($stream, $data);
3b53d87f 365 }
78f39e78 366
72b004e6 367 /**
368 * function initStream - reserved for extended functionality
369 *
370 * This function is not yet implemented.
371 * Reserved for extended functionality.
372 *
373 * @param Message $message Message object
374 * @param string $host host name or IP to connect to
375 * @param string $user username to log into the SMTP server with
376 * @param string $pass password to log into the SMTP server with
377 * @param integer $length
378 *
3a70ee56 379 * @return handle $stream file handle resource to SMTP stream
72b004e6 380 */
3b53d87f 381 function initStream($message, $length=0, $host='', $port='', $user='', $pass='') {
78f39e78 382 return $stream;
3b53d87f 383 }
72b004e6 384
385 /**
386 * function getBCC - reserved for extended functionality
387 *
388 * This function is not yet implemented.
389 * Reserved for extended functionality.
390 *
391 */
392 function getBCC() {
78f39e78 393 return false;
59387d1c 394 }
3b53d87f 395
72b004e6 396 /**
397 * function prepareMIME_Header - creates the mime header
398 *
399 * @param Message $message Message object to act on
400 * @param string $boundary mime boundary from fn MimeBoundary
401 *
3a70ee56 402 * @return string $header properly formatted mime header
72b004e6 403 */
3b53d87f 404 function prepareMIME_Header($message, $boundary) {
78f39e78 405 $mime_header = $message->mime_header;
406 $rn="\r\n";
407 $header = array();
1274f430 408
78f39e78 409 $contenttype = 'Content-Type: '. $mime_header->type0 .'/'.
410 $mime_header->type1;
411 if (count($message->entities)) {
fcce1b3c 412 $contenttype .= ';' . 'boundary="'.$boundary.'"';
78f39e78 413 }
414 if (isset($mime_header->parameters['name'])) {
415 $contenttype .= '; name="'.
416 encodeHeader($mime_header->parameters['name']). '"';
417 }
418 if (isset($mime_header->parameters['charset'])) {
419 $charset = $mime_header->parameters['charset'];
420 $contenttype .= '; charset="'.
421 encodeHeader($charset). '"';
422 }
1274f430 423
78f39e78 424 $header[] = $contenttype . $rn;
425 if ($mime_header->description) {
eb72e151 426 $header[] = 'Content-Description: ' . $mime_header->description . $rn;
78f39e78 427 }
428 if ($mime_header->encoding) {
eb72e151 429 $header[] = 'Content-Transfer-Encoding: ' . $mime_header->encoding . $rn;
78f39e78 430 } else {
431 if ($mime_header->type0 == 'text' || $mime_header->type0 == 'message') {
eb72e151 432 $header[] = 'Content-Transfer-Encoding: 8bit' . $rn;
78f39e78 433 } else {
eb72e151 434 $header[] = 'Content-Transfer-Encoding: base64' . $rn;
78f39e78 435 }
436 }
437 if ($mime_header->id) {
eb72e151 438 $header[] = 'Content-ID: ' . $mime_header->id . $rn;
78f39e78 439 }
440 if ($mime_header->disposition) {
441 $disposition = $mime_header->disposition;
442 $contentdisp = 'Content-Disposition: ' . $disposition->name;
443 if ($disposition->getProperty('filename')) {
444 $contentdisp .= '; filename="'.
445 encodeHeader($disposition->getProperty('filename')). '"';
446 }
72b004e6 447 $header[] = $contentdisp . $rn;
78f39e78 448 }
449 if ($mime_header->md5) {
eb72e151 450 $header[] = 'Content-MD5: ' . $mime_header->md5 . $rn;
78f39e78 451 }
452 if ($mime_header->language) {
eb72e151 453 $header[] = 'Content-Language: ' . $mime_header->language . $rn;
78f39e78 454 }
4960ec8e 455
78f39e78 456 $cnt = count($header);
457 $hdr_s = '';
458 for ($i = 0 ; $i < $cnt ; $i++) {
459 $hdr_s .= $this->foldLine($header[$i], 78,str_pad('',4));
460 }
461 $header = $hdr_s;
462 $header .= $rn; /* One blank line to separate mimeheader and body-entity */
463 return $header;
464 }
4960ec8e 465
72b004e6 466 /**
467 * function prepareRFC822_Header - prepares the RFC822 header string from Rfc822Header object(s)
468 *
469 * This function takes the Rfc822Header object(s) and formats them
470 * into the RFC822Header string to send to the SMTP server as part
471 * of the SMTP message.
472 *
473 * @param Rfc822Header $rfc822_header
474 * @param Rfc822Header $reply_rfc822_header
475 * @param integer &$raw_length length of the message
476 *
3a70ee56 477 * @return string $header
72b004e6 478 */
75b14a70 479 function prepareRFC822_Header($rfc822_header, $reply_rfc822_header, &$raw_length) {
b37e457f 480 global $domain, $username, $encode_header_key,
e930c9fe 481 $edit_identity, $hide_auth_header;
60a46e65 482
78f39e78 483 /* if server var SERVER_NAME not available, use $domain */
60a46e65 484 if(!sqGetGlobalVar('SERVER_NAME', $SERVER_NAME, SQ_SERVER)) {
485 $SERVER_NAME = $domain;
78f39e78 486 }
60a46e65 487
78f39e78 488 sqGetGlobalVar('REMOTE_ADDR', $REMOTE_ADDR, SQ_SERVER);
489 sqGetGlobalVar('REMOTE_PORT', $REMOTE_PORT, SQ_SERVER);
490 sqGetGlobalVar('REMOTE_HOST', $REMOTE_HOST, SQ_SERVER);
491 sqGetGlobalVar('HTTP_VIA', $HTTP_VIA, SQ_SERVER);
492 sqGetGlobalVar('HTTP_X_FORWARDED_FOR', $HTTP_X_FORWARDED_FOR, SQ_SERVER);
60a46e65 493
78f39e78 494 $rn = "\r\n";
223872cb 495
78f39e78 496 /* This creates an RFC 822 date */
867fed37 497 $date = date('D, j M Y H:i:s ', time()) . $this->timezone();
78f39e78 498 /* Create a message-id */
432db2fc 499 $message_id = '<' . $REMOTE_PORT . '.';
500 if (isset($encode_header_key) && trim($encode_header_key)!='') {
501 // use encrypted form of remote address
502 $message_id.= OneTimePadEncrypt($this->ip2hex($REMOTE_ADDR),base64_encode($encode_header_key));
503 } else {
504 $message_id.= $REMOTE_ADDR;
505 }
506 $message_id .= '.' . time() . '.squirrel@' . $SERVER_NAME .'>';
78f39e78 507 /* Make an RFC822 Received: line */
508 if (isset($REMOTE_HOST)) {
509 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
510 } else {
511 $received_from = $REMOTE_ADDR;
512 }
513 if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
514 if (!isset($HTTP_X_FORWARDED_FOR) || $HTTP_X_FORWARDED_FOR == '') {
515 $HTTP_X_FORWARDED_FOR = 'unknown';
516 }
517 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
518 }
519 $header = array();
432db2fc 520
521 /**
522 * SquirrelMail header
523 *
524 * This Received: header provides information that allows to track
525 * user and machine that was used to send email. Don't remove it
526 * unless you understand all possible forging issues or your
527 * webmail installation does not prevent changes in user's email address.
528 * See SquirrelMail bug tracker #847107 for more details about it.
bb08da84 529 *
530 * Add $hide_squirrelmail_header as a candidate for config_local.php
531 * to allow completely hiding SquirrelMail participation in message
539a323f 532 * processing; This is dangerous, especially if users can modify their
e930c9fe 533 * account information, as it makes mapping a sent message back to the
534 * original sender almost impossible.
432db2fc 535 */
e930c9fe 536 $show_sm_header = ( defined('hide_squirrelmail_header') ? ! hide_squirrelmail_header : 1 );
bb08da84 537
538 if ( $show_sm_header ) {
539 if (isset($encode_header_key) &&
432db2fc 540 trim($encode_header_key)!='') {
541 // use encoded headers, if encryption key is set and not empty
b81efcb4 542 $header[] = 'X-Squirrel-UserHash: '.OneTimePadEncrypt($username,base64_encode($encode_header_key)).$rn;
543 $header[] = 'X-Squirrel-FromHash: '.OneTimePadEncrypt($this->ip2hex($REMOTE_ADDR),base64_encode($encode_header_key)).$rn;
432db2fc 544 if (isset($HTTP_X_FORWARDED_FOR))
b81efcb4 545 $header[] = 'X-Squirrel-ProxyHash:'.OneTimePadEncrypt($this->ip2hex($HTTP_X_FORWARDED_FOR),base64_encode($encode_header_key)).$rn;
bb08da84 546 } else {
432db2fc 547 // use default received headers
548 $header[] = "Received: from $received_from" . $rn;
549 if ($edit_identity || ! isset($hide_auth_header) || ! $hide_auth_header)
550 $header[] = " (SquirrelMail authenticated user $username)" . $rn;
551 $header[] = " by $SERVER_NAME with HTTP;" . $rn;
552 $header[] = " $date" . $rn;
bb08da84 553 }
35aaf666 554 }
432db2fc 555
59387d1c 556 /* Insert the rest of the header fields */
557 $header[] = 'Message-ID: '. $message_id . $rn;
ea87de81 558 if (is_object($reply_rfc822_header) &&
b4316b34 559 isset($reply_rfc822_header->message_id) &&
560 $reply_rfc822_header->message_id) {
78f39e78 561 $rep_message_id = $reply_rfc822_header->message_id;
562 // $this->strip_crlf($message_id);
563 $header[] = 'In-Reply-To: '.$rep_message_id . $rn;
564 $references = $this->calculate_references($reply_rfc822_header);
565 $header[] = 'References: '.$references . $rn;
566 }
567 $header[] = "Date: $date" . $rn;
59387d1c 568 $header[] = 'Subject: '.encodeHeader($rfc822_header->subject) . $rn;
ac47827c 569 $header[] = 'From: '. $rfc822_header->getAddr_s('from',",$rn ",true) . $rn;
570
ea87de81 571 // folding address list [From|To|Cc|Bcc] happens by using ",$rn<space>"
572 // as delimiter
ac47827c 573 // Do not use foldLine for that.
574
575 // RFC2822 if from contains more then 1 address
59387d1c 576 if (count($rfc822_header->from) > 1) {
215de78c 577 $header[] = 'Sender: '. $rfc822_header->getAddr_s('sender',',',true) . $rn;
78f39e78 578 }
579 if (count($rfc822_header->to)) {
ac47827c 580 $header[] = 'To: '. $rfc822_header->getAddr_s('to',",$rn ",true) . $rn;
78f39e78 581 }
582 if (count($rfc822_header->cc)) {
ac47827c 583 $header[] = 'Cc: '. $rfc822_header->getAddr_s('cc',",$rn ",true) . $rn;
78f39e78 584 }
585 if (count($rfc822_header->reply_to)) {
215de78c 586 $header[] = 'Reply-To: '. $rfc822_header->getAddr_s('reply_to',',',true) . $rn;
78f39e78 587 }
588 /* Sendmail should return true. Default = false */
589 $bcc = $this->getBcc();
590 if (count($rfc822_header->bcc)) {
ac47827c 591 $s = 'Bcc: '. $rfc822_header->getAddr_s('bcc',",$rn ",true) . $rn;
78f39e78 592 if (!$bcc) {
78f39e78 593 $raw_length += strlen($s);
594 } else {
595 $header[] = $s;
596 }
597 }
72b004e6 598 /* Identify SquirrelMail */
b37e457f 599 $header[] = 'User-Agent: SquirrelMail/' . SM_VERSION . $rn;
78f39e78 600 /* Do the MIME-stuff */
601 $header[] = 'MIME-Version: 1.0' . $rn;
602 $contenttype = 'Content-Type: '. $rfc822_header->content_type->type0 .'/'.
59387d1c 603 $rfc822_header->content_type->type1;
78f39e78 604 if (count($rfc822_header->content_type->properties)) {
605 foreach ($rfc822_header->content_type->properties as $k => $v) {
606 if ($k && $v) {
72b004e6 607 $contenttype .= ';' .$k.'='.$v;
78f39e78 608 }
609 }
610 }
59387d1c 611 $header[] = $contenttype . $rn;
78f39e78 612 if ($encoding = $rfc822_header->encoding) {
23301b33 613 $header[] = 'Content-Transfer-Encoding: ' . $encoding . $rn;
72b004e6 614 }
539a323f 615 if (isset($rfc822_header->dnt) && $rfc822_header->dnt) {
72b004e6 616 $dnt = $rfc822_header->getAddr_s('dnt');
78f39e78 617 /* Pegasus Mail */
618 $header[] = 'X-Confirm-Reading-To: '.$dnt. $rn;
619 /* RFC 2298 */
620 $header[] = 'Disposition-Notification-To: '.$dnt. $rn;
621 }
622 if ($rfc822_header->priority) {
d1db3699 623 switch($rfc822_header->priority)
78f39e78 624 {
d1db3699 625 case 1:
91e0dccc 626 $header[] = 'X-Priority: 1 (Highest)'.$rn;
627 $header[] = 'Importance: High'. $rn; break;
d1db3699 628 case 5:
91e0dccc 629 $header[] = 'X-Priority: 5 (Lowest)'.$rn;
630 $header[] = 'Importance: Low'. $rn; break;
78f39e78 631 default: break;
632 }
633 }
72b004e6 634 /* Insert headers from the $more_headers array */
78f39e78 635 if(count($rfc822_header->more_headers)) {
636 reset($rfc822_header->more_headers);
637 foreach ($rfc822_header->more_headers as $k => $v) {
638 $header[] = $k.': '.$v .$rn;
639 }
640 }
641 $cnt = count($header);
642 $hdr_s = '';
5d2a7b15 643
78f39e78 644 for ($i = 0 ; $i < $cnt ; $i++) {
5d2a7b15 645 $sKey = substr($header[$i],0,strpos($header[$i],':'));
646 switch ($sKey)
647 {
648 case 'Message-ID':
649 case 'In-Reply_To':
650 $hdr_s .= $header[$i];
651 break;
652 case 'References':
653 $sRefs = substr($header[$i],12);
654 $aRefs = explode(' ',$sRefs);
655 $sLine = 'References:';
656 foreach ($aRefs as $sReference) {
cc201b46 657 if ( trim($sReference) == '' ) {
658 /* Don't add spaces. */
659 } elseif (strlen($sLine)+strlen($sReference) >76) {
5d2a7b15 660 $hdr_s .= $sLine;
661 $sLine = $rn . ' ' . $sReference;
662 } else {
663 $sLine .= ' '. $sReference;
664 }
665 }
666 $hdr_s .= $sLine;
667 break;
ac47827c 668 case 'To':
669 case 'Cc':
670 case 'Bcc':
671 case 'From':
672 $hdr_s .= $header[$i];
673 break;
5d2a7b15 674 default: $hdr_s .= $this->foldLine($header[$i], 78, str_pad('',4)); break;
675 }
78f39e78 676 }
78f39e78 677 $header = $hdr_s;
678 $header .= $rn; /* One blank line to separate header and body */
679 $raw_length += strlen($header);
680 return $header;
4960ec8e 681 }
682
72b004e6 683 /**
684 * function foldLine - for cleanly folding of headerlines
685 *
686 * @param string $line
687 * @param integer $length length to fold the line at
688 * @param string $pre prefix the line with...
689 *
3a70ee56 690 * @return string $line folded line with trailing CRLF
72b004e6 691 */
1274f430 692 function foldLine($line, $length, $pre='') {
e4f9307a 693 $line = substr($line,0, -2);
fb1d6cb6 694 $length -= 2; /* do not fold between \r and \n */
695 $cnt = strlen($line);
696 if ($cnt > $length) { /* try folding */
697 $fold_string = "\r\n " . $pre;
698 $bFirstFold = false;
699 $aFoldLine = array();
700 while (strlen($line) > $length) {
701 $fold = false;
702 /* handle encoded parts */
7060c7f0 703 if (preg_match('/(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(\s+|.*)/Ui',$line,$regs)) {
fb1d6cb6 704 $fold_tmp = $regs[1];
7060c7f0 705 if (!trim($regs[5])) {
706 $fold_tmp .= $regs[5];
707 }
fb1d6cb6 708 $iPosEnc = strpos($line,$fold_tmp);
709 $iLengthEnc = strlen($fold_tmp);
c422e824 710 $iPosEncEnd = $iPosEnc+$iLengthEnc;
711 if ($iPosEnc < $length && (($iPosEncEnd) > $length)) {
fb1d6cb6 712 $fold = true;
713 /* fold just before the start of the encoded string */
7060c7f0 714 if ($iPosEnc) {
715 $aFoldLine[] = substr($line,0,$iPosEnc);
716 }
fb1d6cb6 717 $line = substr($line,$iPosEnc);
718 if (!$bFirstFold) {
719 $bFirstFold = true;
720 $length -= strlen($fold_string);
721 }
722 if ($iLengthEnc > $length) { /* place the encoded
723 string on a separate line and do not fold inside it*/
223872cb 724 /* minimize foldstring */
725 $fold_string = "\r\n ";
726 $aFoldLine[] = substr($line,0,$iLengthEnc);
727 $line = substr($line,$iLengthEnc);
72b004e6 728 }
c422e824 729 } else if ($iPosEnc < $length) { /* the encoded string fits into the foldlength */
fb1d6cb6 730 /*remainder */
fb1d6cb6 731 $sLineRem = substr($line,$iPosEncEnd,$length - $iPosEncEnd);
c422e824 732 if (preg_match('/^(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(.*)/Ui',$sLineRem) || !preg_match('/[=,;\s]/',$sLineRem)) {
fb1d6cb6 733 /*impossible to fold clean in the next part -> fold after the enc string */
7060c7f0 734 $aFoldLine[] = substr($line,0,$iPosEncEnd);
735 $line = substr($line,$iPosEncEnd);
fb1d6cb6 736 $fold = true;
737 if (!$bFirstFold) {
738 $bFirstFold = true;
739 $length -= strlen($fold_string);
740 }
72b004e6 741 }
fb1d6cb6 742 }
743 }
744 if (!$fold) {
745 $line_tmp = substr($line,0,$length);
746 $iFoldPos = false;
747 /* try to fold at logical places */
748 switch (true)
749 {
750 case ($iFoldPos = strrpos($line_tmp,',')): break;
751 case ($iFoldPos = strrpos($line_tmp,';')): break;
752 case ($iFoldPos = strrpos($line_tmp,' ')): break;
753 case ($iFoldPos = strrpos($line_tmp,'=')): break;
754 default: break;
755 }
72b004e6 756
fb1d6cb6 757 if (!$iFoldPos) { /* clean folding didn't work */
758 $iFoldPos = $length;
759 }
760 $aFoldLine[] = substr($line,0,$iFoldPos+1);
761 $line = substr($line,$iFoldPos+1);
762 if (!$bFirstFold) {
763 $bFirstFold = true;
764 $length -= strlen($fold_string);
765 }
766 }
767 }
768 /*$reconstruct the line */
769 if ($line) {
770 $aFoldLine[] = $line;
771 }
772 $line = implode($fold_string,$aFoldLine);
773 }
774 return $line."\r\n";
775 }
3b53d87f 776
72b004e6 777 /**
778 * function mimeBoundary - calculates the mime boundary to use
779 *
780 * This function will generate a random mime boundary base part
781 * for the message if the boundary has not already been set.
782 *
3a70ee56 783 * @return string $mimeBoundaryString random mime boundary string
72b004e6 784 */
59387d1c 785 function mimeBoundary () {
78f39e78 786 static $mimeBoundaryString;
3b53d87f 787
78f39e78 788 if ( !isset( $mimeBoundaryString ) ||
789 $mimeBoundaryString == '') {
790 $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
791 mt_rand( 10000, 99999 );
792 }
793 return $mimeBoundaryString;
3b53d87f 794 }
795
72b004e6 796 /**
797 * function timezone - Time offset for correct timezone
798 *
3a70ee56 799 * @return string $result with timezone and offset
72b004e6 800 */
59387d1c 801 function timezone () {
78f39e78 802 global $invert_time;
803
804 $diff_second = date('Z');
805 if ($invert_time) {
806 $diff_second = - $diff_second;
807 }
808 if ($diff_second > 0) {
809 $sign = '+';
810 } else {
811 $sign = '-';
812 }
813 $diff_second = abs($diff_second);
814 $diff_hour = floor ($diff_second / 3600);
815 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
816 $zonename = '('.strftime('%Z').')';
72b004e6 817 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute,
3b53d87f 818 $zonename);
78f39e78 819 return ($result);
59387d1c 820 }
3b53d87f 821
72b004e6 822 /**
f2ac3325 823 * function calculate_references - calculate correct References string
824 * Adds the current message ID, and makes sure it doesn't grow forever,
825 * to that extent it drops message-ID's in a smart way until the string
826 * length is under the recommended value of 1000 ("References: <986>\r\n").
827 * It always keeps the first and the last three ID's.
72b004e6 828 *
829 * @param Rfc822Header $hdr message header to calculate from
830 *
f2ac3325 831 * @return string $refer concatenated and trimmed References string
72b004e6 832 */
1274f430 833 function calculate_references($hdr) {
f2ac3325 834 $aReferences = preg_split('/\s+/', $hdr->references);
78f39e78 835 $message_id = $hdr->message_id;
836 $in_reply_to = $hdr->in_reply_to;
539a323f 837
f2ac3325 838 // if References already exists, add the current message ID at the end.
839 // no References exists; if we know a IRT, add that aswell
840 if (count($aReferences) == 0 && $in_reply_to) {
841 $aReferences[] = $in_reply_to;
842 }
843 $aReferences[] = $message_id;
844
845 // sanitize the array: trim whitespace, remove dupes
86e6a9eb 846 array_walk($aReferences, 'sq_trim_value');
f2ac3325 847 $aReferences = array_unique($aReferences);
848
849 while ( count($aReferences) > 4 && strlen(implode(' ', $aReferences)) >= 986 ) {
850 $aReferences = array_merge(array_slice($aReferences,0,1),array_slice($aReferences,2));
78f39e78 851 }
f2ac3325 852 return implode(' ', $aReferences);
853 }
854
855 /**
432db2fc 856 * Converts ip address to hexadecimal string
857 *
858 * Function is used to convert ipv4 and ipv6 addresses to hex strings.
859 * It removes all delimiter symbols from ip addresses, converts decimal
860 * ipv4 numbers to hex and pads strings in order to present full length
ea87de81 861 * address. ipv4 addresses are represented as 8 byte strings, ipv6 addresses
432db2fc 862 * are represented as 32 byte string.
863 *
864 * If function fails to detect address format, it returns unprocessed string.
865 * @param string $string ip address string
866 * @return string processed ip address string
94511d23 867 * @since 1.5.1 and 1.4.5
432db2fc 868 */
869 function ip2hex($string) {
870 if (preg_match("/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/",$string,$match)) {
871 // ipv4 address
872 $ret = str_pad(dechex($match[1]),2,'0',STR_PAD_LEFT)
873 . str_pad(dechex($match[2]),2,'0',STR_PAD_LEFT)
874 . str_pad(dechex($match[3]),2,'0',STR_PAD_LEFT)
875 . str_pad(dechex($match[4]),2,'0',STR_PAD_LEFT);
876 } elseif (preg_match("/^([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)$/i",$string,$match)) {
877 // full ipv6 address
878 $ret = str_pad($match[1],4,'0',STR_PAD_LEFT)
879 . str_pad($match[2],4,'0',STR_PAD_LEFT)
880 . str_pad($match[3],4,'0',STR_PAD_LEFT)
881 . str_pad($match[4],4,'0',STR_PAD_LEFT)
882 . str_pad($match[5],4,'0',STR_PAD_LEFT)
883 . str_pad($match[6],4,'0',STR_PAD_LEFT)
884 . str_pad($match[7],4,'0',STR_PAD_LEFT)
885 . str_pad($match[8],4,'0',STR_PAD_LEFT);
886 } elseif (preg_match("/^\:\:([0-9a-h\:]+)$/i",$string,$match)) {
887 // short ipv6 with all starting symbols nulled
888 $aAddr=explode(':',$match[1]);
889 $ret='';
890 foreach ($aAddr as $addr) {
891 $ret.=str_pad($addr,4,'0',STR_PAD_LEFT);
892 }
893 $ret=str_pad($ret,32,'0',STR_PAD_LEFT);
894 } elseif (preg_match("/^([0-9a-h\:]+)::([0-9a-h\:]+)$/i",$string,$match)) {
895 // short ipv6 with middle part nulled
896 $aStart=explode(':',$match[1]);
897 $sStart='';
898 foreach($aStart as $addr) {
899 $sStart.=str_pad($addr,4,'0',STR_PAD_LEFT);
900 }
901 $aEnd = explode(':',$match[2]);
902 $sEnd='';
903 foreach($aEnd as $addr) {
904 $sEnd.=str_pad($addr,4,'0',STR_PAD_LEFT);
905 }
906 $ret = $sStart
907 . str_pad('',(32 - strlen($sStart . $sEnd)),'0',STR_PAD_LEFT)
908 . $sEnd;
909 } else {
910 // unknown addressing
911 $ret = $string;
912 }
913 return $ret;
914 }
59387d1c 915}