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