Source for file Deliver.class.php

Documentation is available at 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 1999-2020 The SquirrelMail Project Team
  11.  * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  12.  * @version $Id: Deliver.class.php 14840 2020-01-07 07:42:38Z pdontthink $
  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.      *                                NOTE that this is passed by
  36.      *                                reference and will be modified
  37.      *                                upon return with updated
  38.      *                                fields such as Message ID, References,
  39.      *                                In-Reply-To and Date headers.
  40.      * @param resource $stream       Handle to the outgoing stream
  41.      *                                (when FALSE, nothing will be
  42.      *                                written to the stream; this can
  43.      *                                be used to determine the actual
  44.      *                                number of bytes that will be
  45.      *                                written to the stream)
  46.      * @param string   $reply_id     Identifies message being replied to
  47.      *                                (OPTIONAL; caller should ONLY specify
  48.      *                                a value for this when the message
  49.      *                                being sent is a reply)
  50.      * @param string   $reply_ent_id Identifies message being replied to
  51.      *                                in the case it was an embedded/attached
  52.      *                                message inside another (OPTIONAL; caller
  53.      *                                should ONLY specify a value for this
  54.      *                                when the message being sent is a reply)
  55.      * @param resource $imap_stream  If there is an open IMAP stream in
  56.      *                                the caller's context, it should be
  57.      *                                passed in here.  This is OPTIONAL,
  58.      *                                as one will be created if not given,
  59.      *                                but as some IMAP servers may baulk
  60.      *                                at opening more than one connection
  61.      *                                at a time, the caller should always
  62.      *                                abide if possible.  Currently, this
  63.      *                                stream is only used when $reply_id
  64.      *                                is also non-zero, but that is subject
  65.      *                                to change.
  66.      * @param mixed    $extra        Any implementation-specific variables
  67.      *                                can be passed in here and used in
  68.      *                                an overloaded version of this method
  69.      *                                if needed.
  70.      *
  71.      * @return integer The number of bytes written (or that would have been
  72.      *                  written) to the output stream.
  73.      *
  74.      */
  75.     function mail(&$message$stream=false$reply_id=0$reply_ent_id=0
  76.                   $imap_stream=NULL$extra=NULL{
  77.  
  78.         $rfc822_header &$message->rfc822_header;
  79.  
  80.         if (count($message->entities)) {
  81.             $boundary $this->mimeBoundary();
  82.             $rfc822_header->content_type->properties['boundary']='"'.$boundary.'"';
  83.         else {
  84.             $boundary='';
  85.         }
  86.         $raw_length 0;
  87.  
  88.  
  89.         // calculate reply header if needed
  90.         //
  91.         if ($reply_id{
  92.             global $imapConnection$username$key$imapServerAddress
  93.                    $imapPort$imap_stream_options$mailbox;
  94.  
  95.             // try our best to use an existing IMAP handle
  96.             //
  97.             $close_imap_stream FALSE;
  98.             if (is_resource($imap_stream)) {
  99.                 $my_imap_stream $imap_stream;
  100.  
  101.             else if (is_resource($imapConnection)) {
  102.                 $my_imap_stream $imapConnection;
  103.  
  104.             else {
  105.                 $close_imap_stream TRUE;
  106.                 $my_imap_stream sqimap_login($username$key$imapServerAddress,
  107.                                                $imapPort0$imap_stream_options);
  108.             
  109.  
  110.             sqimap_mailbox_select($my_imap_stream$mailbox);
  111.             $reply_message sqimap_get_message($my_imap_stream$reply_id$mailbox);
  112.  
  113.             if ($close_imap_stream{
  114.                 sqimap_logout($my_imap_stream);
  115.             }
  116.  
  117.             if ($reply_ent_id{
  118.                 /* redefine the messsage in case of message/rfc822 */
  119.                 $reply_message $message->getEntity($reply_ent_id);
  120.                 /* message is an entity which contains the envelope and type0=message
  121.                  * and type1=rfc822. The actual entities are childs from
  122.                  * $reply_message->entities[0]. That's where the encoding and is located
  123.                  */
  124.  
  125.                 $orig_header $reply_message->rfc822_header/* here is the envelope located */
  126.  
  127.             else {
  128.                 $orig_header $reply_message->rfc822_header;
  129.             }
  130.             $message->reply_rfc822_header $orig_header;            
  131.         }
  132.  
  133.  
  134.         $reply_rfc822_header (isset($message->reply_rfc822_header)
  135.                              ? $message->reply_rfc822_header '');
  136.         $header $this->prepareRFC822_Header($rfc822_header$reply_rfc822_header$raw_length);
  137.  
  138.         $this->send_mail($message$header$boundary$stream$raw_length$extra);
  139.  
  140.         return $raw_length;
  141.     }
  142.  
  143.     /**
  144.      * function send_mail - send the message parts to the IMAP stream
  145.      *
  146.      * @param Message  $message      Message object to send
  147.      * @param string   $header       Headers ready to send
  148.      * @param string   $boundary     Message parts boundary
  149.      * @param resource $stream       Handle to the SMTP stream
  150.      *                                (when FALSE, nothing will be
  151.      *                                written to the stream; this can
  152.      *                                be used to determine the actual
  153.      *                                number of bytes that will be
  154.      *                                written to the stream)
  155.      * @param int     &$raw_length   The number of bytes written (or that
  156.      *                                would have been written) to the
  157.      *                                output stream - NOTE that this is
  158.      *                                passed by reference
  159.      * @param mixed    $extra        Any implementation-specific variables
  160.      *                                can be passed in here and used in
  161.      *                                an overloaded version of this method
  162.      *                                if needed.
  163.      *
  164.      * @return void 
  165.      *
  166.      */
  167.     function send_mail($message$header$boundary$stream=false
  168.                        &$raw_length$extra=NULL{
  169.  
  170.         if ($stream{
  171.             $this->preWriteToStream($header);
  172.             $this->writeToStream($stream$header);
  173.         }
  174.         $this->writeBody($message$stream$raw_length$boundary);
  175.     }
  176.  
  177.     /**
  178.      * function writeBody - generate and write the mime boundaries around each part to the stream
  179.      *
  180.      * Recursively formats and writes the MIME boundaries of the $message
  181.      * to the output stream.
  182.      *
  183.      * @param Message   $message      Message object to transform
  184.      * @param resource  $stream       SMTP output stream
  185.      *                                 (when FALSE, nothing will be
  186.      *                                 written to the stream; this can
  187.      *                                 be used to determine the actual
  188.      *                                 number of bytes that will be
  189.      *                                 written to the stream)
  190.      * @param integer  &$length_raw   raw length of the message (part)
  191.      *                                 as returned by mail fn
  192.      * @param string    $boundary     custom boundary to call, usually for subparts
  193.      *
  194.      * @return void 
  195.      */
  196.     function writeBody($message$stream&$length_raw$boundary=''{
  197.         // calculate boundary in case of multidimensional mime structures
  198.         if ($boundary && $message->entity_id && count($message->entities)) {
  199.             if (strpos($boundary,'_part_')) {
  200.                 $boundary substr($boundary,0,strpos($boundary,'_part_'));
  201.  
  202.             // the next four lines use strrev to reverse any nested boundaries
  203.             // because RFC 2046 (5.1.1) says that if a line starts with the outer
  204.             // boundary string (doesn't matter what the line ends with), that
  205.             // can be considered a match for the outer boundary; thus the nested
  206.             // boundary needs to be unique from the outer one
  207.             //
  208.             else if (strpos($boundary,'_trap_')) {
  209.                 $boundary substr(strrev($boundary),0,strpos(strrev($boundary),'_part_'));
  210.             }
  211.             $boundary_new strrev($boundary '_part_'.$message->entity_id);
  212.         else {
  213.             $boundary_new $boundary;
  214.         }
  215.         if ($boundary && !$message->rfc822_header{
  216.             $s '--'.$boundary."\r\n";
  217.             $s .= $this->prepareMIME_Header($message$boundary_new);
  218.             $length_raw += strlen($s);
  219.             if ($stream{
  220.                 $this->preWriteToStream($s);
  221.                 $this->writeToStream($stream$s);
  222.             }
  223.         }
  224.         $this->writeBodyPart($message$stream$length_raw);
  225.  
  226.         $last false;
  227.         for ($i=0$entCount=count($message->entities);$i<$entCount;$i++{
  228.             $msg $this->writeBody($message->entities[$i]$stream$length_raw$boundary_new);
  229.             if ($i == $entCount-1$last true;
  230.         }
  231.         if ($boundary && $last{
  232.             $s "--".$boundary_new."--\r\n\r\n";
  233.             $length_raw += strlen($s);
  234.             if ($stream{
  235.                 $this->preWriteToStream($s);
  236.                 $this->writeToStream($stream$s);
  237.             }
  238.         }
  239.     }
  240.  
  241.     /**
  242.      * function writeBodyPart - write each individual mimepart
  243.      *
  244.      * Recursively called by WriteBody to write each mime part to the SMTP stream
  245.      *
  246.      * @param Message   $message      Message object to transform
  247.      * @param resource  $stream       SMTP output stream
  248.      *                                 (when FALSE, nothing will be
  249.      *                                 written to the stream; this can
  250.      *                                 be used to determine the actual
  251.      *                                 number of bytes that will be
  252.      *                                 written to the stream)
  253.      * @param integer  &$length       length of the message part
  254.      *                                 as returned by mail fn
  255.      *
  256.      * @return void 
  257.      */
  258.     function writeBodyPart($message$stream&$length{
  259.         if ($message->mime_header{
  260.             $type0 $message->mime_header->type0;
  261.         else {
  262.             $type0 $message->rfc822_header->content_type->type0;
  263.         }
  264.  
  265.         $body_part_trailing $last '';
  266.         switch ($type0)
  267.         {
  268.         case 'text':
  269.         case 'message':
  270.             if ($message->body_part{
  271.                 $body_part $message->body_part;
  272.                 // remove NUL characters
  273.                 $body_part str_replace("\0",'',$body_part);
  274.                 $length += $this->clean_crlf($body_part);
  275.                 if ($stream{
  276.                     $this->preWriteToStream($body_part);
  277.                     $this->writeToStream($stream$body_part);
  278.                 }
  279.                 $last $body_part;
  280.             elseif ($message->att_local_name{
  281.                 global $username$attachment_dir;
  282.                 $hashed_attachment_dir getHashedDir($username$attachment_dir);
  283.                 $filename $message->att_local_name;
  284.  
  285.                 // inspect attached file for lines longer than allowed by RFC,
  286.                 // in which case we'll be using base64 encoding (so we can split
  287.                 // the lines up without corrupting them) instead of 8bit unencoded...
  288.                 // (see RFC 2822/2.1.1)
  289.                 //
  290.                 // using 990 because someone somewhere is folding lines at
  291.                 // 990 instead of 998 and I'm too lazy to find who it is
  292.                 //
  293.                 $file_has_long_lines file_has_long_lines($hashed_attachment_dir
  294.                                                            . '/' $filename990);
  295.  
  296.                 $file fopen ($hashed_attachment_dir '/' $filename'rb');
  297.  
  298.                 // long lines were found, need to use base64 encoding
  299.                 //
  300.                 if ($file_has_long_lines{
  301.                     while ($tmp fread($file570)) {
  302.                         $body_part chunk_split(base64_encode($tmp));
  303.                         // Up to 4.3.10 chunk_split always appends a newline,
  304.                         // while in 4.3.11 it doesn't if the string to split
  305.                         // is shorter than the chunk length.
  306.                         ifsubstr($body_part-!= "\n" )
  307.                             $body_part .= "\n";
  308.                         $length += $this->clean_crlf($body_part);
  309.                         if ($stream{
  310.                             $this->writeToStream($stream$body_part);
  311.                         }
  312.                     }
  313.                 }
  314.  
  315.                 // no excessively long lines - normal 8bit
  316.                 //
  317.                 else {
  318.                     while ($body_part fgets($file4096)) {
  319.                         $length += $this->clean_crlf($body_part);
  320.                         if ($stream{
  321.                             $this->preWriteToStream($body_part);
  322.                             $this->writeToStream($stream$body_part);
  323.                         }
  324.                         $last $body_part;
  325.                     }
  326.                 }
  327.  
  328.                 fclose($file);
  329.             }
  330.             break;
  331.         default:
  332.             if ($message->body_part{
  333.                 $body_part $message->body_part;
  334.                 $length += $this->clean_crlf($body_part);
  335.                 if ($stream{
  336.                     $this->writeToStream($stream$body_part);
  337.                 }
  338.             elseif ($message->att_local_name{
  339.                 global $username$attachment_dir;
  340.                 $hashed_attachment_dir getHashedDir($username$attachment_dir);
  341.                 $filename $message->att_local_name;
  342.                 $file fopen ($hashed_attachment_dir '/' $filename'rb');
  343.                 
  344.                 while ($tmp fread($file570)) {
  345.                     $body_part chunk_split(base64_encode($tmp));
  346.                     // Up to 4.3.10 chunk_split always appends a newline,
  347.                     // while in 4.3.11 it doesn't if the string to split
  348.                     // is shorter than the chunk length.
  349.                     ifsubstr($body_part-!= "\n" )
  350.                         $body_part .= "\n";
  351.                     $length += $this->clean_crlf($body_part);
  352.                     if ($stream{
  353.                         $this->writeToStream($stream$body_part);
  354.                     }
  355.                 }
  356.                 fclose($file);
  357.             }
  358.             break;
  359.         }
  360.         $body_part_trailing '';
  361.         if ($last && substr($last,-1!= "\n"{
  362.             $body_part_trailing "\r\n";
  363.         }
  364.         if ($body_part_trailing{
  365.             $length += strlen($body_part_trailing);
  366.             if ($stream{
  367.                 $this->preWriteToStream($body_part_trailing);
  368.                 $this->writeToStream($stream$body_part_trailing);
  369.             }
  370.         }
  371.     }
  372.  
  373.     /**
  374.      * function clean_crlf - change linefeeds and newlines to legal characters
  375.      *
  376.      * The SMTP format only allows CRLF as line terminators.
  377.      * This function replaces illegal teminators with the correct terminator.
  378.      *
  379.      * @param string &$s string to clean linefeeds on
  380.      *
  381.      * @return void 
  382.      */
  383.     function clean_crlf(&$s{
  384.         $s str_replace("\r\n""\n"$s);
  385.         $s str_replace("\r""\n"$s);
  386.         $s str_replace("\n""\r\n"$s);
  387.         return strlen($s);
  388.     }
  389.  
  390.     /**
  391.      * function strip_crlf - strip linefeeds and newlines from a string
  392.      *
  393.      * The SMTP format only allows CRLF as line terminators.
  394.      * This function strips all line terminators from the string.
  395.      *
  396.      * @param string &$s string to clean linefeeds on
  397.      *
  398.      * @return void 
  399.      */
  400.     function strip_crlf(&$s{
  401.         $s str_replace("\r\n "''$s);
  402.         $s str_replace("\r"''$s);
  403.         $s str_replace("\n"''$s);
  404.     }
  405.  
  406.     /**
  407.      * function preWriteToStream - reserved for extended functionality
  408.      *
  409.      * This function is not yet implemented.
  410.      * Reserved for extended functionality.
  411.      *
  412.      * @param string &$s string to operate on
  413.      *
  414.      * @return void 
  415.      */
  416.     function preWriteToStream(&$s{
  417.     }
  418.  
  419.     /**
  420.      * function writeToStream - write data to the SMTP stream
  421.      *
  422.      * @param resource $stream  SMTP output stream
  423.      * @param string   $data    string with data to send to the SMTP stream
  424.      *
  425.      * @return void 
  426.      */
  427.     function writeToStream($stream$data{
  428.         fputs($stream$data);
  429.     }
  430.  
  431.     /**
  432.      * function initStream - reserved for extended functionality
  433.      *
  434.      * This function is not yet implemented.
  435.      * Reserved for extended functionality.
  436.      * UPDATE: It is implemented in Deliver_SMTP and Deliver_SendMail classes,
  437.      *         but it remains unimplemented in this base class (and thus not
  438.      *         in Deliver_IMAP or other child classes that don't define it)
  439.      *
  440.      * NOTE: some parameters are specific to the child class
  441.      *       that is implementing this method
  442.      *
  443.      * @param Message $message  Message object
  444.      * @param string  $domain 
  445.      * @param integer $length 
  446.      * @param string  $host     host name or IP to connect to
  447.      * @param integer $port 
  448.      * @param string  $user     username to log into the SMTP server with
  449.      * @param string  $pass     password to log into the SMTP server with
  450.      * @param boolean $authpop  whether or not to use POP-before-SMTP authorization
  451.      * @param string  $pop_host host name or IP to connect to for POP-before-SMTP authorization
  452.      * @param array   $stream_options Stream context options (OPTIONAL), see http://www.php.net/manual/context.php and especially http://www.php.net/manual/context.ssl.php
  453.      *
  454.      * @return handle $stream file handle resource to SMTP stream
  455.      */
  456.     function initStream($message$domain$length=0$host=''$port=''$user=''$pass=''$authpop=false$pop_host=''$stream_options=array()) {
  457.         return $stream;
  458.     }
  459.  
  460.     /**
  461.      * function getBCC - reserved for extended functionality
  462.      *
  463.      * This function is not yet implemented.
  464.      * Reserved for extended functionality.
  465.      *
  466.      */
  467.     function getBCC({
  468.         return false;
  469.     }
  470.  
  471.     /**
  472.      * function prepareMIME_Header - creates the mime header
  473.      *
  474.      * @param Message $message  Message object to act on
  475.      * @param string  $boundary mime boundary from fn MimeBoundary
  476.      *
  477.      * @return string $header properly formatted mime header
  478.      */
  479.     function prepareMIME_Header($message$boundary{
  480.         $mime_header $message->mime_header;
  481.         $rn="\r\n";
  482.         $header array();
  483.  
  484.         $contenttype 'Content-Type: '$mime_header->type0 .'/'.
  485.                         $mime_header->type1;
  486.         if (count($message->entities)) {
  487.             $contenttype .= ';' 'boundary="'.$boundary.'"';
  488.         }
  489.         if (isset($mime_header->parameters['name'])) {
  490.             $contenttype .= '; name="'.
  491.             encodeHeader($mime_header->parameters['name'])'"';
  492.         }
  493.         if (isset($mime_header->parameters['charset'])) {
  494.             $charset $mime_header->parameters['charset'];
  495.             $contenttype .= '; charset="'.
  496.             encodeHeader($charset)'"';
  497.         }
  498.  
  499.         $header[$contenttype $rn;
  500.         if ($mime_header->description{
  501.             $header['Content-Description: ' $mime_header->description $rn;
  502.         }
  503.         if ($mime_header->encoding{
  504.             $encoding $mime_header->encoding;
  505.             $header['Content-Transfer-Encoding: ' $mime_header->encoding $rn;
  506.         else {
  507.  
  508.             // inspect attached file for lines longer than allowed by RFC,
  509.             // in which case we'll be using base64 encoding (so we can split
  510.             // the lines up without corrupting them) instead of 8bit unencoded...
  511.             // (see RFC 2822/2.1.1)
  512.             //
  513.             if (!empty($message->att_local_name)) // is this redundant? I have no idea
  514.                 global $username$attachment_dir;
  515.                 $hashed_attachment_dir getHashedDir($username$attachment_dir);
  516.                 $filename $hashed_attachment_dir '/' $message->att_local_name;
  517.  
  518.                 // using 990 because someone somewhere is folding lines at
  519.                 // 990 instead of 998 and I'm too lazy to find who it is
  520.                 //
  521.                 $file_has_long_lines file_has_long_lines($filename990);
  522.             else
  523.                 $file_has_long_lines FALSE;
  524.  
  525.             if ($mime_header->type0 == 'multipart' || $mime_header->type0 == 'alternative'{
  526.                 /* no-op; no encoding needed */
  527.             else if (($mime_header->type0 == 'text' || $mime_header->type0 == 'message')
  528.                     && !$file_has_long_lines{
  529.                 $header['Content-Transfer-Encoding: 8bit' .  $rn;
  530.             else {
  531.                 $header['Content-Transfer-Encoding: base64' .  $rn;
  532.             }
  533.         }
  534.         if ($mime_header->id{
  535.             $header['Content-ID: ' $mime_header->id $rn;
  536.         }
  537.         if ($mime_header->disposition{
  538.             $disposition $mime_header->disposition;
  539.             $contentdisp 'Content-Disposition: ' $disposition->name;
  540.             if ($disposition->getProperty('filename')) {
  541.                 $contentdisp .= '; filename="'.
  542.                 encodeHeader($disposition->getProperty('filename'))'"';
  543.             }
  544.             $header[$contentdisp $rn;
  545.         }
  546.         if ($mime_header->md5{
  547.             $header['Content-MD5: ' $mime_header->md5 $rn;
  548.         }
  549.         if ($mime_header->language{
  550.             $header['Content-Language: ' $mime_header->language $rn;
  551.         }
  552.  
  553.         $cnt count($header);
  554.         $hdr_s '';
  555.         for ($i $i $cnt $i++)    {
  556.             $hdr_s .= $this->foldLine($header[$i]);
  557.         }
  558.         $header $hdr_s;
  559.         $header .= $rn/* One blank line to separate mimeheader and body-entity */
  560.         return $header;
  561.     }
  562.  
  563.     /**
  564.      * function prepareRFC822_Header - prepares the RFC822 header string from Rfc822Header object(s)
  565.      *
  566.      * This function takes the Rfc822Header object(s) and formats them
  567.      * into the RFC822Header string to send to the SMTP server as part
  568.      * of the SMTP message.
  569.      *
  570.      * @param Rfc822Header  $rfc822_header 
  571.      * @param Rfc822Header  $reply_rfc822_header 
  572.      * @param integer      &$raw_length length of the message
  573.      *
  574.      * @return string $header
  575.      */
  576.     function prepareRFC822_Header(&$rfc822_header$reply_rfc822_header&$raw_length{
  577.         global $domain$version$username$encode_header_key$hide_auth_header;
  578.  
  579.         if (isset($hide_auth_header)) $hide_auth_header=false;
  580.  
  581.         /* if server var SERVER_NAME not available, use $domain */
  582.         if(!sqGetGlobalVar('SERVER_NAME'$SERVER_NAMESQ_SERVER)) {
  583.             $SERVER_NAME $domain;
  584.         }
  585.  
  586.         sqGetGlobalVar('REMOTE_ADDR'$REMOTE_ADDRSQ_SERVER);
  587.         sqGetGlobalVar('REMOTE_PORT'$REMOTE_PORTSQ_SERVER);
  588.         sqGetGlobalVar('REMOTE_HOST'$REMOTE_HOSTSQ_SERVER);
  589.         sqGetGlobalVar('HTTP_VIA',    $HTTP_VIA,    SQ_SERVER);
  590.         sqGetGlobalVar('HTTP_X_FORWARDED_FOR'$HTTP_X_FORWARDED_FORSQ_SERVER);
  591.  
  592.         $rn "\r\n";
  593.  
  594.         /* This creates an RFC 822 date */
  595.         $now time();
  596.         $now_date date('D, j M Y H:i:s '$now$this->timezone();
  597.         // TODO: Do we really want to preserve possibly old date?  Date header should always have "now"... but here is not where this decision should be made -- the caller really should blank out $rfc822_header->date even for drafts being re-edited or sent
  598.         if (!empty($rfc822_header->date&& $rfc822_header->date != -1)
  599.             $message_date date('D, j M Y H:i:s '$rfc822_header->date$this->timezone();
  600.         else {
  601.             $message_date $now_date;
  602.             $rfc822_header->date $now;
  603.         }
  604.  
  605.         /* Create a message-id */
  606.         $message_id 'MESSAGE ID GENERATION ERROR! PLEASE CONTACT SQUIRRELMAIL DEVELOPERS';
  607.         if (empty($rfc822_header->message_id)) {
  608.             $message_id '<'
  609.                         . md5(GenerateRandomString(16''7uniqid(mt_rand(),true))
  610.                         . '.squirrel@' $SERVER_NAME .'>';
  611.         }
  612.  
  613.         /* Make an RFC822 Received: line */
  614.         if (isset($REMOTE_HOST)) {
  615.             $received_from "$REMOTE_HOST ([$REMOTE_ADDR])";
  616.         else {
  617.             $received_from $REMOTE_ADDR;
  618.         }
  619.         if (isset($HTTP_VIA|| isset ($HTTP_X_FORWARDED_FOR)) {
  620.             if (!isset($HTTP_X_FORWARDED_FOR|| $HTTP_X_FORWARDED_FOR == ''{
  621.                 $HTTP_X_FORWARDED_FOR 'unknown';
  622.             }
  623.             $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
  624.         }
  625.         $header array();
  626.  
  627.         /**
  628.          * SquirrelMail header
  629.          *
  630.          * This Received: header provides information that allows to track
  631.          * user and machine that was used to send email. Don't remove it
  632.          * unless you understand all possible forging issues or your
  633.          * webmail installation does not prevent changes in user's email address.
  634.          * See SquirrelMail bug tracker #847107 for more details about it.
  635.          *
  636.          * Add hide_squirrelmail_header as a candidate for config_local.php
  637.          * (must be defined as a constant:  define('hide_squirrelmail_header', 1);
  638.          * to allow completely hiding SquirrelMail participation in message
  639.          * processing; This is dangerous, especially if users can modify their
  640.          * account information, as it makes mapping a sent message back to the
  641.          * original sender almost impossible.
  642.          */
  643.         $show_sm_header defined('hide_squirrelmail_header'hide_squirrelmail_header );
  644.  
  645.         // FIXME: The following headers may generate slightly differently between the message sent to the destination and that stored in the Sent folder because this code will be called before both actions.  This is not necessarily a big problem, but other headers such as Message-ID and Date are preserved between both actions
  646.         if $show_sm_header {
  647.           if (isset($encode_header_key&&
  648.             trim($encode_header_key)!=''{
  649.             // use encoded headers, if encryption key is set and not empty
  650.             $header['X-Squirrel-UserHash: '.OneTimePadEncrypt($username,base64_encode($encode_header_key)).$rn;
  651.             $header['X-Squirrel-FromHash: '.OneTimePadEncrypt($this->ip2hex($REMOTE_ADDR),base64_encode($encode_header_key)).$rn;
  652.             if (isset($HTTP_X_FORWARDED_FOR))
  653.                 $header['X-Squirrel-ProxyHash:'.OneTimePadEncrypt($this->ip2hex($HTTP_X_FORWARDED_FOR),base64_encode($encode_header_key)).$rn;
  654.           else {
  655.             // use default received headers
  656.             $header["Received: from $received_from$rn;
  657.             if (!isset($hide_auth_header|| !$hide_auth_header)
  658.                 $header["        (SquirrelMail authenticated user $username)$rn;
  659.             $header["        by $SERVER_NAME with HTTP;$rn;
  660.             $header["        $now_date$rn;
  661.           }
  662.         }
  663.  
  664.         /* Insert the rest of the header fields */
  665.  
  666.         if (!empty($rfc822_header->message_id)) {
  667.             $header['Message-ID: '$rfc822_header->message_id $rn;
  668.         else {
  669.             $header['Message-ID: '$message_id $rn;
  670.             $rfc822_header->message_id $message_id;
  671.         }
  672.  
  673.         if (is_object($reply_rfc822_header&&
  674.             isset($reply_rfc822_header->message_id&&
  675.             $reply_rfc822_header->message_id{
  676.             //if ($reply_rfc822_header->message_id) {
  677.             $rep_message_id $reply_rfc822_header->message_id;
  678.             $header['In-Reply-To: '.$rep_message_id $rn;
  679.             $rfc822_header->in_reply_to $rep_message_id;
  680.             $references $this->calculate_references($reply_rfc822_header);
  681.             $header['References: '.$references $rn;
  682.             $rfc822_header->references $references;
  683.         }
  684.  
  685.         $header["Date: $message_date$rn;
  686.  
  687.         $header['Subject: '.encodeHeader($rfc822_header->subject$rn;
  688.  
  689.         // folding address list [From|To|Cc|Bcc] happens by using ",$rn<space>"
  690.         // as delimiter
  691.         // Do not use foldLine for that.
  692.  
  693.         $header['From: '$rfc822_header->getAddr_s('from',",$rn ",true$rn;
  694.  
  695.         // RFC2822 if from contains more then 1 address
  696.         if (count($rfc822_header->from1{
  697.             $header['Sender: '$rfc822_header->getAddr_s('sender',',',true$rn;
  698.         }
  699.         if (count($rfc822_header->to)) {
  700.             $header['To: '$rfc822_header->getAddr_s('to',",$rn ",true$rn;
  701.         }
  702.         if (count($rfc822_header->cc)) {
  703.             $header['Cc: '$rfc822_header->getAddr_s('cc',",$rn ",true$rn;
  704.         }
  705.         if (count($rfc822_header->reply_to)) {
  706.             $header['Reply-To: '$rfc822_header->getAddr_s('reply_to',',',true$rn;
  707.         }
  708.         /* Sendmail should return true. Default = false */
  709.         $bcc $this->getBcc();
  710.         if (count($rfc822_header->bcc)) {
  711.             $s 'Bcc: '$rfc822_header->getAddr_s('bcc',",$rn ",true$rn;
  712.             if (!$bcc{
  713.                 $raw_length += strlen($s);
  714.             else {
  715.                 $header[$s;
  716.             }
  717.         }
  718.         /* Identify SquirrelMail */
  719.         $header['User-Agent: SquirrelMail/' $version $rn;
  720.         /* Do the MIME-stuff */
  721.         $header['MIME-Version: 1.0' $rn;
  722.         $contenttype 'Content-Type: '$rfc822_header->content_type->type0 .'/'.
  723.                                          $rfc822_header->content_type->type1;
  724.         if (count($rfc822_header->content_type->properties)) {
  725.             foreach ($rfc822_header->content_type->properties as $k => $v{
  726.                 if ($k && $v{
  727.                     $contenttype .= ';' .$k.'='.$v;
  728.                 }
  729.             }
  730.         }
  731.         $header[$contenttype $rn;
  732.         if ($encoding $rfc822_header->encoding{
  733.             $header['Content-Transfer-Encoding: ' $encoding .  $rn;
  734.         }
  735.         if ($rfc822_header->dnt{
  736.             $dnt $rfc822_header->getAddr_s('dnt');
  737.             /* Pegasus Mail */
  738.             $header['X-Confirm-Reading-To: '.$dnt$rn;
  739.             /* RFC 2298 */
  740.             $header['Disposition-Notification-To: '.$dnt$rn;
  741.         }
  742.         if ($rfc822_header->priority{
  743.             switch($rfc822_header->priority)
  744.             {
  745.             case 1:
  746.                 $header['X-Priority: 1 (Highest)'.$rn;
  747.                 $header['Importance: High'$rnbreak;
  748.             case 3:
  749.                 $header['X-Priority: 3 (Normal)'.$rn;
  750.                 $header['Importance: Normal'$rnbreak;
  751.             case 5:
  752.                 $header['X-Priority: 5 (Lowest)'.$rn;
  753.                 $header['Importance: Low'$rnbreak;
  754.             defaultbreak;
  755.             }
  756.         }
  757.         /* Insert headers from the $more_headers array */
  758.         if(count($rfc822_header->more_headers)) {
  759.             reset($rfc822_header->more_headers);
  760.             foreach ($rfc822_header->more_headers as $k => $v{
  761.                 $header[$k.': '.$v .$rn;
  762.             }
  763.         }
  764.         $cnt count($header);
  765.         $hdr_s '';
  766.  
  767.         for ($i $i $cnt $i++{
  768.             $sKey substr($header[$i],0,strpos($header[$i],':'));
  769.             switch ($sKey)
  770.             {
  771.             case 'Message-ID':
  772.             case 'In-Reply_To':
  773.                 $hdr_s .= $header[$i];
  774.                 break;
  775.             case 'References':
  776.                 $sRefs substr($header[$i],12);
  777.                 $aRefs explode(' ',$sRefs);
  778.                 $sLine 'References:';
  779.                 foreach ($aRefs as $sReference{
  780.                     if trim($sReference== '' {
  781.                         /* Don't add spaces. */
  782.                     elseif (strlen($sLine)+strlen($sReference>76{
  783.                         $hdr_s .= $sLine;
  784.                         $sLine $rn '    ' $sReference;
  785.                     else {
  786.                         $sLine .= ' '$sReference;
  787.                     }
  788.                 }
  789.                 $hdr_s .= $sLine;
  790.                 break;
  791.             case 'To':
  792.             case 'Cc':
  793.             case 'Bcc':
  794.             case 'From':
  795.                 $hdr_s .= $header[$i];
  796.                 break;
  797.             default$hdr_s .= $this->foldLine($header[$i])break;
  798.             }
  799.         }
  800.         $header $hdr_s;
  801.         $header .= $rn/* One blank line to separate header and body */
  802.         $raw_length += strlen($header);
  803.         return $header;
  804.     }
  805.  
  806.     /**
  807.       * Fold header lines per RFC 2822/2.2.3 and RFC 822/3.1.1
  808.       *
  809.       * Herein "soft" folding/wrapping (with whitespace tokens) is
  810.       * what we refer to as the preferred method of wrapping - that
  811.       * which we'd like to do within the $soft_wrap limit, but if
  812.       * not possible, we will try to do as soon as possible after
  813.       * $soft_wrap up to the $hard_wrap limit.  Encoded words don't
  814.       * need to be detected in this phase, since they cannot contain
  815.       * spaces.
  816.       *
  817.       * "Hard" folding/wrapping (with "hard" tokens) is what we refer
  818.       * to as less ideal wrapping that will be done to keep within
  819.       * the $hard_wrap limit.  This adds other syntactical breaking
  820.       * elements such as commas and encoded words.
  821.       *
  822.       * @param string  $header    The header content being folded
  823.       * @param integer $soft_wrap The desirable maximum line length
  824.       *                            (OPTIONAL; default is 78, per RFC)
  825.       * @param string  $indent    Wrapped lines will already have
  826.       *                            whitespace following the CRLF wrap,
  827.       *                            but you can add more indentation (or
  828.       *                            whatever) with this.  The use of this
  829.       *                            parameter is DISCOURAGED, since it
  830.       *                            can corrupt the redisplay (unfolding)
  831.       *                            of headers whose content is space-
  832.       *                            sensitive, like subjects, etc.
  833.       *                            (OPTIONAL; default is an empty string)
  834.       * @param string  $hard_wrap The absolute maximum line length
  835.       *                            (OPTIONAL; default is 998, per RFC)
  836.       *
  837.       * @return string The folded header content, with a trailing CRLF.
  838.       *
  839.       */
  840.     function foldLine($header$soft_wrap=78$indent=''$hard_wrap=998{
  841.  
  842.         // allow folding after the initial colon and space?
  843.         // (only supported if the header name is within the $soft_wrap limit)
  844.         //
  845.         $allow_fold_after_header_name FALSE;
  846.  
  847.         // the "hard" token list can be altered if desired,
  848.         // for example, by adding ":"
  849.         // (in the future, we can take optional arguments
  850.         // for overriding or adding elements to the "hard"
  851.         // token list if we want to get fancy)
  852.         //
  853.         // the order of these is significant - preferred
  854.         // fold points should be listed first
  855.         //
  856.         // it is advised that the "=" always come first
  857.         // since it also finds encoded words, thus if it
  858.         // comes after some other token that happens to
  859.         // fall within the encoded word, the encoded word
  860.         // could be inadvertently broken in half, which
  861.         // is not allowable per RFC
  862.         //
  863.         $hard_break_tokens array(
  864.             '=',  // includes encoded word detection
  865.             ',',
  866.             ';',
  867.         );
  868.  
  869.         // the order of these is significant too
  870.         //
  871.         $whitespace array(
  872.             ' ',
  873.             "\t",
  874.         );
  875.  
  876.         $CRLF "\r\n";
  877.  
  878.         // switch that helps compact the last line, pasting it at the
  879.         // end of the one before if the one before is already over the
  880.         // soft limit and it wouldn't go over the hard limit
  881.         //
  882.         $pull_last_line_up_if_second_to_last_is_already_over_soft_limit FALSE;
  883.  
  884.  
  885.         // ----- end configurable behaviors -----
  886.  
  887.  
  888.         $folded_header '';
  889.  
  890.         // if we want to prevent a wrap right after the
  891.         // header name, make note of the position here
  892.         //
  893.         if (!$allow_fold_after_header_name
  894.          && ($header_name_end_pos strpos($header':'))
  895.          && strlen($header$header_name_end_pos 1
  896.          && in_array($header{$header_name_end_pos 1}$whitespace))
  897.             $header_name_end_pos++;
  898.  
  899.         // if using an indent string, reduce wrap limits by its size
  900.         //
  901.         if (!empty($indent)) {
  902.             $soft_wrap -= strlen($indent);
  903.             $hard_wrap -= strlen($indent);
  904.         }
  905.  
  906.         while (strlen($header$soft_wrap{
  907.  
  908.             $soft_wrapped_line substr($header0$soft_wrap);
  909.  
  910.             // look for a token as close to the end of the soft wrap limit as possible
  911.             //
  912.             foreach ($whitespace as $token{
  913.  
  914.                 // note that this if statement also fails when $pos === 0,
  915.                 // which is intended, since blank lines are not allowed
  916.                 //
  917.                 if ($pos strrpos($soft_wrapped_line$token))
  918.                 {
  919.  
  920.                     // make sure proposed fold isn't forbidden
  921.                     //
  922.                     if (!$allow_fold_after_header_name
  923.                      && $pos === $header_name_end_pos)
  924.                         continue;
  925.  
  926.                     $new_fold substr($header0$pos);
  927.  
  928.                     // make sure proposed fold doesn't create a blank line
  929.                     //
  930.                     if (!trim($new_fold)) continue;
  931.  
  932.                     // with whitespace breaks, we fold BEFORE the token
  933.                     //
  934.                     $folded_header .= $new_fold $CRLF $indent;
  935.                     $header substr($header$pos);
  936.  
  937.                     // ready for next while() iteration
  938.                     //
  939.                     continue 2;
  940.  
  941.                 }
  942.  
  943.             }
  944.  
  945.             // we were unable to find a wrapping point within the soft
  946.             // wrap limit, so now we'll try to find the first possible
  947.             // soft wrap point within the hard wrap limit
  948.             //
  949.             $hard_wrapped_line substr($header0$hard_wrap);
  950.  
  951.             // look for a *SOFT* token as close to the
  952.             // beginning of the hard wrap limit as possible
  953.             //
  954.             foreach ($whitespace as $token{
  955.  
  956.                 // use while loop instead of if block because it
  957.                 // is possible we don't want the first one we find
  958.                 //
  959.                 $pos $soft_wrap 1// -1 is corrected by +1 on next line
  960.                 while ($pos strpos($hard_wrapped_line$token$pos 1))
  961.                 {
  962.  
  963.                     $new_fold substr($header0$pos);
  964.  
  965.                     // make sure proposed fold doesn't create a blank line
  966.                     //
  967.                     if (!trim($new_fold)) continue;
  968.  
  969.                     // with whitespace breaks, we fold BEFORE the token
  970.                     //
  971.                     $folded_header .= $new_fold $CRLF $indent;
  972.                     $header substr($header$pos);
  973.  
  974.                     // ready for next outter while() iteration
  975.                     //
  976.                     continue 3;
  977.  
  978.                 }
  979.  
  980.             }
  981.  
  982.             // we were still unable to find a soft wrapping point within
  983.             // both the soft and hard wrap limits, so if the length of
  984.             // what is left is no more than the hard wrap limit, we'll
  985.             // simply take the whole thing
  986.             //
  987.             if (strlen($header<= $hard_wrap{
  988.  
  989.                 // if the header has been folded at least once before now,
  990.                 // let's see if we can add the remaining chunk to the last
  991.                 // fold (this is mainly just aesthetic)
  992.                 //
  993.                 if ($pull_last_line_up_if_second_to_last_is_already_over_soft_limit
  994.                  && strlen($folded_header)
  995.                  // last fold is conveniently in $new_fold
  996.                  && strlen($new_foldstrlen($header<= $hard_wrap{
  997.                     // $last_fold = substr(substr($folded_header, 0, -(strlen($CRLF) + strlen($indent))), 
  998.                     // remove CRLF and indentation and paste the rest of the header on
  999.                     $folded_header substr($folded_header0-(strlen($CRLFstrlen($indent))) $header;
  1000.                     $header '';
  1001.                 }
  1002.  
  1003.                 break;
  1004.             }
  1005.  
  1006.             // otherwise, we can't quit yet - look for a "hard" token
  1007.             // as close to the end of the hard wrap limit as possible
  1008.             //
  1009.             foreach ($hard_break_tokens as $token{
  1010.  
  1011.                 // note that this if statement also fails when $pos === 0,
  1012.                 // which is intended, since blank lines are not allowed
  1013.                 //
  1014.                 if ($pos strrpos($hard_wrapped_line$token))
  1015.                 {
  1016.  
  1017.                     // if we found a "=" token, we must determine whether,
  1018.                     // if it is part of an encoded word, it is the beginning
  1019.                     // or middle of one, where we need to readjust $pos a bit
  1020.                     //
  1021.                     if ($token == '='{
  1022.  
  1023.                         // if we found the beginning of an encoded word,
  1024.                         // we want to break BEFORE the token
  1025.                         //
  1026.                         if (preg_match('/^(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)/i',
  1027.                                        substr($header$pos))) {
  1028.                             $pos--;
  1029.                         }
  1030.  
  1031.                         // check if we found this token in the *middle*
  1032.                         // of an encoded word, in which case we have to
  1033.                         // ignore it, pushing back to the token that
  1034.                         // starts the encoded word instead
  1035.                         //
  1036.                         // of course, this is only possible if there is
  1037.                         // more content after the next hard wrap
  1038.                         //
  1039.                         // then look for the end of an encoded word in
  1040.                         // the next part (past the next hard wrap)
  1041.                         //
  1042.                         // then see if it is in fact part of a legitimate
  1043.                         // encoded word
  1044.                         //
  1045.                         else if (strlen($header$hard_wrap
  1046.                          && ($end_pos strpos(substr($header$hard_wrap)'?=')) !== FALSE
  1047.                          && preg_match('/(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)$/i',
  1048.                                        substr($header0$hard_wrap $end_pos 2),
  1049.                                        $matches)) {
  1050.  
  1051.                             $pos $hard_wrap $end_pos strlen($matches[1]1;
  1052.  
  1053.                         }
  1054.  
  1055.                     }
  1056.  
  1057.                     // $pos could have been changed; make sure it's
  1058.                     // not at the beginning of the line, as blank
  1059.                     // lines are not allowed
  1060.                     //
  1061.                     if ($pos === 0continue;
  1062.  
  1063.                     // we are dealing with a simple token break...
  1064.                     //
  1065.                     // for non-whitespace breaks, we fold AFTER the token
  1066.                     // and add a space after the fold if not immediately
  1067.                     // followed by a whitespace character in the next part
  1068.                     //
  1069.                     // $new_fold is used above, it's assumed we update it upon every fold action
  1070.                     $new_fold substr($header0$pos 1);
  1071.                     $folded_header .= $new_fold $CRLF;
  1072.  
  1073.                     // don't go beyond end of $header, though
  1074.                     //
  1075.                     if (strlen($header$pos 1{
  1076.                         $header substr($header$pos 1);
  1077.                         if (!in_array($header{0}$whitespace))
  1078.                             $header ' ' $indent $header;
  1079.                     else {
  1080.                         $header '';
  1081.                     }
  1082.  
  1083.                     // ready for next while() iteration
  1084.                     //
  1085.                     continue 2;
  1086.  
  1087.                 }
  1088.  
  1089.             }
  1090.  
  1091.             // finally, we just couldn't find anything to fold on, so we
  1092.             // have to just cut it off at the hard limit
  1093.             //
  1094.             // $new_fold is used above, it's assumed we update it upon every fold action
  1095.             $new_fold $hard_wrapped_line;
  1096.             $folded_header .= $new_fold $CRLF;
  1097.  
  1098.             // is there more?
  1099.             //
  1100.             if (strlen($headerstrlen($hard_wrapped_line)) {
  1101.                 $header substr($headerstrlen($hard_wrapped_line));
  1102.                 if (!in_array($header{0}$whitespace))
  1103.                     $header ' ' $indent $header;
  1104.             else {
  1105.                 $header '';
  1106.             }
  1107.  
  1108.         }
  1109.  
  1110.  
  1111.         // add any left-overs
  1112.         //
  1113.         $folded_header .= $header;
  1114.  
  1115.  
  1116.         // make sure it ends with a CRLF
  1117.         //
  1118.         if (substr($folded_header-2!= $CRLF$folded_header .= $CRLF;
  1119.  
  1120.  
  1121.         return $folded_header;
  1122.     }
  1123.  
  1124.     /**
  1125.      * function mimeBoundary - calculates the mime boundary to use
  1126.      *
  1127.      * This function will generate a random mime boundary base part
  1128.      * for the message if the boundary has not already been set.
  1129.      *
  1130.      * @return string $mimeBoundaryString random mime boundary string
  1131.      */
  1132.     function mimeBoundary ({
  1133.         static $mimeBoundaryString;
  1134.  
  1135.         if !isset$mimeBoundaryString ||
  1136.             $mimeBoundaryString == ''{
  1137.             $mimeBoundaryString '----=_' date'YmdHis' '_' .
  1138.             mt_rand1000099999 );
  1139.         }
  1140.         return $mimeBoundaryString;
  1141.     }
  1142.  
  1143.     /**
  1144.      * function timezone - Time offset for correct timezone
  1145.      *
  1146.      * @return string $result with timezone and offset
  1147.      */
  1148.     function timezone ({
  1149.         global $invert_time$show_timezone_name;
  1150.  
  1151.         $diff_second date('Z');
  1152.         if ($invert_time{
  1153.             $diff_second = - $diff_second;
  1154.         }
  1155.         if ($diff_second 0{
  1156.             $sign '+';
  1157.         else {
  1158.             $sign '-';
  1159.         }
  1160.         $diff_second abs($diff_second);
  1161.         $diff_hour floor ($diff_second 3600);
  1162.         $diff_minute floor (($diff_second-3600*$diff_hour60);
  1163.  
  1164.         // If an administrator wants to add the timezone name to the
  1165.         // end of the date header, they can set $show_timezone_name
  1166.         // to boolean TRUE in config/config_local.php, but that is
  1167.         // NOT RFC-822 compliant (see section 5.1).  Moreover, some
  1168.         // Windows users reported that strftime('%Z') was returning
  1169.         // the full zone name (not the abbreviation) which in some
  1170.         // cases included 8-bit characters (not allowed as is in headers).
  1171.         // The PHP manual actually does NOT promise what %Z will return
  1172.         // for strftime!:  "The time zone offset/abbreviation option NOT
  1173.         // given by %z (depends on operating system)"
  1174.         //
  1175.         if ($show_timezone_name{
  1176.             $zonename '('.strftime('%Z').')';
  1177.             $result sprintf ("%s%02d%02d %s"$sign$diff_hour$diff_minute$zonename);
  1178.         else {
  1179.             $result sprintf ("%s%02d%02d"$sign$diff_hour$diff_minute);
  1180.         }
  1181.         return ($result);
  1182.     }
  1183.  
  1184.     /**
  1185.      * function calculate_references - calculate correct References string
  1186.      * Adds the current message ID, and makes sure it doesn't grow forever,
  1187.      * to that extent it drops message-ID's in a smart way until the string
  1188.      * length is under the recommended value of 1000 ("References: <986>\r\n").
  1189.      * It always keeps the first and the last three ID's.
  1190.      *
  1191.      * @param   Rfc822Header $hdr    message header to calculate from
  1192.      *
  1193.      * @return  string       $refer  concatenated and trimmed References string
  1194.      */
  1195.     function calculate_references($hdr{
  1196.         $aReferences preg_split('/\s+/'$hdr->references);
  1197.         $message_id $hdr->message_id;
  1198.         $in_reply_to $hdr->in_reply_to;
  1199.     
  1200.         // if References already exists, add the current message ID at the end.
  1201.         // no References exists; if we know a IRT, add that aswell
  1202.         if (count($aReferences== && $in_reply_to{
  1203.             $aReferences[$in_reply_to;
  1204.         }
  1205.         $aReferences[$message_id;
  1206.  
  1207.         // sanitize the array: trim whitespace, remove dupes
  1208.         array_walk($aReferences'sq_trim_value');
  1209.         $aReferences array_unique($aReferences);
  1210.  
  1211.         while count($aReferences&& strlen(implode(' '$aReferences)) >= 986 {
  1212.             $aReferences array_merge(array_slice($aReferences,0,1),array_slice($aReferences,2));
  1213.         }
  1214.         return implode(' '$aReferences);
  1215.     }
  1216.  
  1217.     /**
  1218.      * Converts ip address to hexadecimal string
  1219.      *
  1220.      * Function is used to convert ipv4 and ipv6 addresses to hex strings.
  1221.      * It removes all delimiter symbols from ip addresses, converts decimal
  1222.      * ipv4 numbers to hex and pads strings in order to present full length
  1223.      * address. ipv4 addresses are represented as 8 byte strings, ipv6 addresses
  1224.      * are represented as 32 byte string.
  1225.      *
  1226.      * If function fails to detect address format, it returns unprocessed string.
  1227.      * @param string $string ip address string
  1228.      * @return string processed ip address string
  1229.      * @since 1.5.1 and 1.4.5
  1230.      */
  1231.     function ip2hex($string{
  1232.         if (preg_match("/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/",$string,$match)) {
  1233.             // ipv4 address
  1234.             $ret str_pad(dechex($match[1]),2,'0',STR_PAD_LEFT)
  1235.                 . str_pad(dechex($match[2]),2,'0',STR_PAD_LEFT)
  1236.                 . str_pad(dechex($match[3]),2,'0',STR_PAD_LEFT)
  1237.                 . str_pad(dechex($match[4]),2,'0',STR_PAD_LEFT);
  1238.         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)) {
  1239.             // full ipv6 address
  1240.             $ret str_pad($match[1],4,'0',STR_PAD_LEFT)
  1241.                 . str_pad($match[2],4,'0',STR_PAD_LEFT)
  1242.                 . str_pad($match[3],4,'0',STR_PAD_LEFT)
  1243.                 . str_pad($match[4],4,'0',STR_PAD_LEFT)
  1244.                 . str_pad($match[5],4,'0',STR_PAD_LEFT)
  1245.                 . str_pad($match[6],4,'0',STR_PAD_LEFT)
  1246.                 . str_pad($match[7],4,'0',STR_PAD_LEFT)
  1247.                 . str_pad($match[8],4,'0',STR_PAD_LEFT);
  1248.         elseif (preg_match("/^\:\:([0-9a-h\:]+)$/i",$string,$match)) {
  1249.             // short ipv6 with all starting symbols nulled
  1250.             $aAddr=explode(':',$match[1]);
  1251.             $ret='';
  1252.             foreach ($aAddr as $addr{
  1253.                 $ret.=str_pad($addr,4,'0',STR_PAD_LEFT);
  1254.             }
  1255.             $ret=str_pad($ret,32,'0',STR_PAD_LEFT);
  1256.         elseif (preg_match("/^([0-9a-h\:]+)::([0-9a-h\:]+)$/i",$string,$match)) {
  1257.             // short ipv6 with middle part nulled
  1258.             $aStart=explode(':',$match[1]);
  1259.             $sStart='';
  1260.             foreach($aStart as $addr{
  1261.                 $sStart.=str_pad($addr,4,'0',STR_PAD_LEFT);
  1262.             }
  1263.             $aEnd explode(':',$match[2]);
  1264.             $sEnd='';
  1265.             foreach($aEnd as $addr{
  1266.                 $sEnd.=str_pad($addr,4,'0',STR_PAD_LEFT);
  1267.             }
  1268.             $ret $sStart
  1269.                 . str_pad('',(32 strlen($sStart $sEnd)),'0',STR_PAD_LEFT)
  1270.                 . $sEnd;
  1271.         else {
  1272.             // unknown addressing
  1273.             $ret $string;
  1274.         }
  1275.         return $ret;
  1276.     }
  1277. }

Documentation generated on Mon, 13 Jan 2020 04:24:31 +0100 by phpDocumentor 1.4.3