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