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