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