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