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