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