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