45ed6ab8375faaa5033d7f57d713ed9e8f137991
6 * This contains all the functions needed to send messages through
9 * @author Marc Groot Koerkamp
10 * @copyright © 1999-2007 The SquirrelMail Project Team
11 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
13 * @package squirrelmail
17 * Deliver Class - called to actually deliver the message
19 * This class is called by compose.php and other code that needs
20 * to send messages. All delivery functionality should be centralized
23 * Do not place UI code in this class, as UI code should be placed in templates
26 * @author Marc Groot Koerkamp
27 * @package squirrelmail
32 * function mail - send the message parts to the SMTP stream
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)
46 * @return integer $raw_length
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.'"';
59 // calculate reply header if needed
62 global $imapConnection, $username, $imapServerAddress,
65 $imapConnection = sqimap_login($username, FALSE,
66 $imapServerAddress, $imapPort, 0);
68 sqimap_mailbox_select($imapConnection, $mailbox);
69 $reply_message = sqimap_get_message($imapConnection, $reply_id, $mailbox);
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
79 $orig_header = $reply_message->rfc822_header
; /* here is the envelope located */
82 $orig_header = $reply_message->rfc822_header
;
85 $message->reply_rfc822_header
= $orig_header;
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);
93 $this->preWriteToStream($header);
94 $this->writeToStream($stream, $header);
96 $this->writeBody($message, $stream, $raw_length, $boundary);
101 * function writeBody - generate and write the mime boundaries around each part to the stream
103 * Recursively formats and writes the MIME boundaries of the $message
104 * to the output stream.
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
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_'));
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
126 } else if (strpos($boundary,'_trap_')) {
127 $boundary = substr(strrev($boundary),0,strpos(strrev($boundary),'_part_'));
129 $boundary_new = strrev($boundary . '_part_'.$message->entity_id
);
131 $boundary_new = $boundary;
133 if ($boundary && !$message->rfc822_header
) {
134 $s = '--'.$boundary."\r\n";
135 $s .= $this->prepareMIME_Header($message, $boundary_new);
136 $length_raw +
= strlen($s);
138 $this->preWriteToStream($s);
139 $this->writeToStream($stream, $s);
142 $this->writeBodyPart($message, $stream, $length_raw);
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;
149 if ($boundary && $last) {
150 $s = "--".$boundary_new."--\r\n\r\n";
151 $length_raw +
= strlen($s);
153 $this->preWriteToStream($s);
154 $this->writeToStream($stream, $s);
160 * function writeBodyPart - write each individual mimepart
162 * Recursively called by WriteBody to write each mime part to the SMTP stream
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
171 function writeBodyPart($message, $stream, &$length) {
172 if ($message->mime_header
) {
173 $type0 = $message->mime_header
->type0
;
175 $type0 = $message->rfc822_header
->content_type
->type0
;
178 $body_part_trailing = $last = '';
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);
189 $this->preWriteToStream($body_part);
190 $this->writeToStream($stream, $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);
203 $this->preWriteToStream($body_part);
204 $this->writeToStream($stream, $body_part);
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);
218 $this->writeToStream($stream, $body_part);
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" )
232 $length +
= $this->clean_crlf($body_part);
234 $this->writeToStream($stream, $body_part);
241 $body_part_trailing = '';
242 if ($last && substr($last,-1) != "\n") {
243 $body_part_trailing = "\r\n";
245 if ($body_part_trailing) {
246 $length +
= strlen($body_part_trailing);
248 $this->preWriteToStream($body_part_trailing);
249 $this->writeToStream($stream, $body_part_trailing);
255 * function clean_crlf - change linefeeds and newlines to legal characters
257 * The SMTP format only allows CRLF as line terminators.
258 * This function replaces illegal teminators with the correct terminator.
260 * @param string &$s string to clean linefeeds on
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);
272 * function strip_crlf - strip linefeeds and newlines from a string
274 * The SMTP format only allows CRLF as line terminators.
275 * This function strips all line terminators from the string.
277 * @param string &$s string to clean linefeeds on
281 function strip_crlf(&$s) {
282 $s = str_replace("\r\n ", '', $s);
283 $s = str_replace("\r", '', $s);
284 $s = str_replace("\n", '', $s);
288 * function preWriteToStream - reserved for extended functionality
290 * This function is not yet implemented.
291 * Reserved for extended functionality.
293 * @param string &$s string to operate on
297 function preWriteToStream(&$s) {
301 * function writeToStream - write data to the SMTP stream
303 * @param resource $stream SMTP output stream
304 * @param string $data string with data to send to the SMTP stream
308 function writeToStream($stream, $data) {
309 fputs($stream, $data);
313 * function initStream - reserved for extended functionality
315 * This function is not yet implemented.
316 * Reserved for extended functionality.
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
324 * @return handle $stream file handle resource to SMTP stream
326 function initStream($message, $length=0, $host='', $port='', $user='', $pass='') {
331 * function getBCC - reserved for extended functionality
333 * This function is not yet implemented.
334 * Reserved for extended functionality.
342 * function prepareMIME_Header - creates the mime header
344 * @param Message $message Message object to act on
345 * @param string $boundary mime boundary from fn MimeBoundary
347 * @return string $header properly formatted mime header
349 function prepareMIME_Header($message, $boundary) {
350 $mime_header = $message->mime_header
;
354 $contenttype = 'Content-Type: '. $mime_header->type0
.'/'.
356 if (count($message->entities
)) {
357 $contenttype .= ';' . 'boundary="'.$boundary.'"';
359 if (isset($mime_header->parameters
['name'])) {
360 $contenttype .= '; name="'.
361 encodeHeader($mime_header->parameters
['name']). '"';
363 if (isset($mime_header->parameters
['charset'])) {
364 $charset = $mime_header->parameters
['charset'];
365 $contenttype .= '; charset="'.
366 encodeHeader($charset). '"';
369 $header[] = $contenttype . $rn;
370 if ($mime_header->description
) {
371 $header[] = 'Content-Description: ' . $mime_header->description
. $rn;
373 if ($mime_header->encoding
) {
374 $header[] = 'Content-Transfer-Encoding: ' . $mime_header->encoding
. $rn;
376 if ($mime_header->type0
== 'text' ||
$mime_header->type0
== 'message') {
377 $header[] = 'Content-Transfer-Encoding: 8bit' . $rn;
379 $header[] = 'Content-Transfer-Encoding: base64' . $rn;
382 if ($mime_header->id
) {
383 $header[] = 'Content-ID: ' . $mime_header->id
. $rn;
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')). '"';
392 $header[] = $contentdisp . $rn;
394 if ($mime_header->md5
) {
395 $header[] = 'Content-MD5: ' . $mime_header->md5
. $rn;
397 if ($mime_header->language
) {
398 $header[] = 'Content-Language: ' . $mime_header->language
. $rn;
401 $cnt = count($header);
403 for ($i = 0 ; $i < $cnt ; $i++
) {
404 $hdr_s .= $this->foldLine($header[$i], 78,str_pad('',4));
407 $header .= $rn; /* One blank line to separate mimeheader and body-entity */
412 * function prepareRFC822_Header - prepares the RFC822 header string from Rfc822Header object(s)
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.
418 * @param Rfc822Header $rfc822_header
419 * @param Rfc822Header $reply_rfc822_header
420 * @param integer &$raw_length length of the message
422 * @return string $header
424 function prepareRFC822_Header($rfc822_header, $reply_rfc822_header, &$raw_length) {
425 global $domain, $username, $encode_header_key,
426 $edit_identity, $hide_auth_header;
428 /* if server var SERVER_NAME not available, use $domain */
429 if(!sqGetGlobalVar('SERVER_NAME', $SERVER_NAME, SQ_SERVER
)) {
430 $SERVER_NAME = $domain;
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
);
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));
449 $message_id.= $REMOTE_ADDR;
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])";
456 $received_from = $REMOTE_ADDR;
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';
462 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
467 * SquirrelMail header
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.
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.
481 $show_sm_header = ( defined('hide_squirrelmail_header') ?
! hide_squirrelmail_header
: 1 );
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;
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;
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;
512 $header[] = "Date: $date" . $rn;
513 $header[] = 'Subject: '.encodeHeader($rfc822_header->subject
) . $rn;
514 $header[] = 'From: '. $rfc822_header->getAddr_s('from',",$rn ",true) . $rn;
516 // folding address list [From|To|Cc|Bcc] happens by using ",$rn<space>"
518 // Do not use foldLine for that.
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;
524 if (count($rfc822_header->to
)) {
525 $header[] = 'To: '. $rfc822_header->getAddr_s('to',",$rn ",true) . $rn;
527 if (count($rfc822_header->cc
)) {
528 $header[] = 'Cc: '. $rfc822_header->getAddr_s('cc',",$rn ",true) . $rn;
530 if (count($rfc822_header->reply_to
)) {
531 $header[] = 'Reply-To: '. $rfc822_header->getAddr_s('reply_to',',',true) . $rn;
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;
538 $raw_length +
= strlen($s);
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) {
552 $contenttype .= ';' .$k.'='.$v;
556 $header[] = $contenttype . $rn;
557 if ($encoding = $rfc822_header->encoding
) {
558 $header[] = 'Content-Transfer-Encoding: ' . $encoding . $rn;
560 if (isset($rfc822_header->dnt
) && $rfc822_header->dnt
) {
561 $dnt = $rfc822_header->getAddr_s('dnt');
563 $header[] = 'X-Confirm-Reading-To: '.$dnt. $rn;
565 $header[] = 'Disposition-Notification-To: '.$dnt. $rn;
567 if ($rfc822_header->priority
) {
568 switch($rfc822_header->priority
)
571 $header[] = 'X-Priority: 1 (Highest)'.$rn;
572 $header[] = 'Importance: High'. $rn; break;
574 $header[] = 'X-Priority: 5 (Lowest)'.$rn;
575 $header[] = 'Importance: Low'. $rn; break;
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;
586 $cnt = count($header);
589 for ($i = 0 ; $i < $cnt ; $i++
) {
590 $sKey = substr($header[$i],0,strpos($header[$i],':'));
595 $hdr_s .= $header[$i];
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) {
606 $sLine = $rn . ' ' . $sReference;
608 $sLine .= ' '. $sReference;
617 $hdr_s .= $header[$i];
619 default: $hdr_s .= $this->foldLine($header[$i], 78, str_pad('',4)); break;
623 $header .= $rn; /* One blank line to separate header and body */
624 $raw_length +
= strlen($header);
629 * function foldLine - for cleanly folding of headerlines
631 * @param string $line
632 * @param integer $length length to fold the line at
633 * @param string $pre prefix the line with...
635 * @return string $line folded line with trailing CRLF
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;
644 $aFoldLine = array();
645 while (strlen($line) > $length) {
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];
653 $iPosEnc = strpos($line,$fold_tmp);
654 $iLengthEnc = strlen($fold_tmp);
655 $iPosEncEnd = $iPosEnc+
$iLengthEnc;
656 if ($iPosEnc < $length && (($iPosEncEnd) > $length)) {
658 /* fold just before the start of the encoded string */
660 $aFoldLine[] = substr($line,0,$iPosEnc);
662 $line = substr($line,$iPosEnc);
665 $length -= strlen($fold_string);
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);
674 } else if ($iPosEnc < $length) { /* the encoded string fits into the foldlength */
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);
684 $length -= strlen($fold_string);
690 $line_tmp = substr($line,0,$length);
692 /* try to fold at logical places */
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;
702 if (!$iFoldPos) { /* clean folding didn't work */
705 $aFoldLine[] = substr($line,0,$iFoldPos+
1);
706 $line = substr($line,$iFoldPos+
1);
709 $length -= strlen($fold_string);
713 /*$reconstruct the line */
715 $aFoldLine[] = $line;
717 $line = implode($fold_string,$aFoldLine);
723 * function mimeBoundary - calculates the mime boundary to use
725 * This function will generate a random mime boundary base part
726 * for the message if the boundary has not already been set.
728 * @return string $mimeBoundaryString random mime boundary string
730 function mimeBoundary () {
731 static $mimeBoundaryString;
733 if ( !isset( $mimeBoundaryString ) ||
734 $mimeBoundaryString == '') {
735 $mimeBoundaryString = '----=_' . date( 'YmdHis' ) . '_' .
736 mt_rand( 10000, 99999 );
738 return $mimeBoundaryString;
742 * function timezone - Time offset for correct timezone
744 * @return string $result with timezone and offset
746 function timezone () {
749 $diff_second = date('Z');
751 $diff_second = - $diff_second;
753 if ($diff_second > 0) {
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,
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.
774 * @param Rfc822Header $hdr message header to calculate from
776 * @return string $refer concatenated and trimmed References string
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
;
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;
788 $aReferences[] = $message_id;
790 // sanitize the array: trim whitespace, remove dupes
791 array_walk($aReferences, 'sq_trim_value');
792 $aReferences = array_unique($aReferences);
794 while ( count($aReferences) > 4 && strlen(implode(' ', $aReferences)) >= 986 ) {
795 $aReferences = array_merge(array_slice($aReferences,0,1),array_slice($aReferences,2));
797 return implode(' ', $aReferences);
801 * Converts ip address to hexadecimal string
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.
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
814 function ip2hex($string) {
815 if (preg_match("/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/",$string,$match)) {
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)) {
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]);
835 foreach ($aAddr as $addr) {
836 $ret.=str_pad($addr,4,'0',STR_PAD_LEFT
);
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]);
843 foreach($aStart as $addr) {
844 $sStart.=str_pad($addr,4,'0',STR_PAD_LEFT
);
846 $aEnd = explode(':',$match[2]);
848 foreach($aEnd as $addr) {
849 $sEnd.=str_pad($addr,4,'0',STR_PAD_LEFT
);
852 . str_pad('',(32 - strlen($sStart . $sEnd)),'0',STR_PAD_LEFT
)
855 // unknown addressing