<?php
/**
* Filename.......: class.html.mime.mail.inc
* Project........: HTML Mime mail class
* Last Modified..: $Date: 2002/07/24 13:14:10 $
* CVS Revision...: $Revision: 1.4 $
* Copyright......: 2001, 2002 Richard Heyes
*/

require_once(dirname(__FILE__) . '/mimePart.php');

class htmlMimeMail
{
    /**
    * The html part of the message
    * @var string
    */
    var $html;

    /**
    * The text part of the message(only used in TEXT only messages)
    * @var string
    */
    var $text;

    /**
    * The main body of the message after building
    * @var string
    */
    var $output;

    /**
    * The alternative text to the HTML part (only used in HTML messages)
    * @var string
    */
    var $html_text;

    /**
    * An array of embedded images/objects
    * @var array
    */
    var $html_images;

    /**
    * An array of recognised image types for the findHtmlImages() method
    * @var array
    */
    var $image_types;

    /**
    * Parameters that affect the build process
    * @var array
    */
    var $build_params;

    /**
    * Array of attachments
    * @var array
    */
    var $attachments;

    /**
    * The main message headers
    * @var array
    */
    var $headers;

    /**
    * Whether the message has been built or not
    * @var boolean
    */
    var $is_built;
    
    /**
    * The return path address. If not set the From:
    * address is used instead
    * @var string
    */
    var $return_path;
    
    /**
    * Array of information needed for smtp sending
    * @var array
    */
    var $smtp_params;

/**
* Constructor function. Sets the headers
* if supplied.
*/

    function htmlMimeMail()
    {
        /**
        * Initialise some variables.
        */
        $this->html_images = array();
        $this->headers     = array();
        $this->is_built    = false;

        /**
        * If you want the auto load functionality
        * to find other image/file types, add the
        * extension and content type here.
        */
        $this->image_types = array(
                                    'gif'    => 'image/gif',
                                    'jpg'    => 'image/jpeg',
                                    'jpeg'    => 'image/jpeg',
                                    'jpe'    => 'image/jpeg',
                                    'bmp'    => 'image/bmp',
                                    'png'    => 'image/png',
                                    'tif'    => 'image/tiff',
                                    'tiff'    => 'image/tiff',
                                    'swf'    => 'application/x-shockwave-flash'
                                  );

        /**
        * Set these up
        */
        $this->build_params['html_encoding'] = 'quoted-printable';
        $this->build_params['text_encoding'] = '7bit';
        $this->build_params['html_charset']  = 'ISO-8859-1';
        $this->build_params['text_charset']  = 'ISO-8859-1';
        $this->build_params['head_charset']  = 'ISO-8859-1';
        $this->build_params['text_wrap']     = 998;

        /**
        * Defaults for smtp sending
        */
        if (!empty($GLOBALS['HTTP_SERVER_VARS']['HTTP_HOST'])) {
            $helo = $GLOBALS['HTTP_SERVER_VARS']['HTTP_HOST'];
        } elseif (!empty($GLOBALS['HTTP_SERVER_VARS']['SERVER_NAME'])) {
            $helo = $GLOBALS['HTTP_SERVER_VARS']['SERVER_NAME'];
        } else {
            $helo = 'localhost';
        }

        $this->smtp_params['host'] = 'localhost';
        $this->smtp_params['port'] = 25;
        $this->smtp_params['helo'] = $helo;
        $this->smtp_params['auth'] = false;
        $this->smtp_params['user'] = '';
        $this->smtp_params['pass'] = '';

        /**
        * Make sure the MIME version header is first.
        */
        $this->headers['MIME-Version'] = '1.0';
    }

/**
* This function will read a file in
* from a supplied filename and return
* it. This can then be given as the first
* argument of the the functions
* add_html_image() or add_attachment().
*/
    function getFile($filename)
    {
        $return = '';
        if ($fp = fopen($filename, 'rb')) {
            while (!feof($fp)) {
                $return .= fread($fp, 1024);
            }
            fclose($fp);
            return $return;

        } else {
            return false;
        }
    }

/**
* Accessor to set the CRLF style
*/
    function setCrlf($crlf = "\n")
    {
        if (!defined('CRLF')) {
            define('CRLF', $crlf, true);
        }

        if (!defined('MAIL_MIMEPART_CRLF')) {
            define('MAIL_MIMEPART_CRLF', $crlf, true);
        }
    }

/**
* Accessor to set the SMTP parameters
*/
    function setSMTPParams($host = null, $port = null, $helo = null, $auth = null, $user = null, $pass = null)
    {
        if (!is_null($host)) $this->smtp_params['host'] = $host;
        if (!is_null($port)) $this->smtp_params['port'] = $port;
        if (!is_null($helo)) $this->smtp_params['helo'] = $helo;
        if (!is_null($auth)) $this->smtp_params['auth'] = $auth;
        if (!is_null($user)) $this->smtp_params['user'] = $user;
        if (!is_null($pass)) $this->smtp_params['pass'] = $pass;
    }

/**
* Accessor function to set the text encoding
*/
    function setTextEncoding($encoding = '7bit')
    {
        $this->build_params['text_encoding'] = $encoding;
    }

/**
* Accessor function to set the HTML encoding
*/
    function setHtmlEncoding($encoding = 'quoted-printable')
    {
        $this->build_params['html_encoding'] = $encoding;
    }

/**
* Accessor function to set the text charset
*/
    function setTextCharset($charset = 'ISO-8859-1')
    {
        $this->build_params['text_charset'] = $charset;
    }

/**
* Accessor function to set the HTML charset
*/
    function setHtmlCharset($charset = 'ISO-8859-1')
    {
        $this->build_params['html_charset'] = $charset;
    }

/**
* Accessor function to set the header encoding charset
*/
    function setHeadCharset($charset = 'ISO-8859-1')
    {
        $this->build_params['head_charset'] = $charset;
    }

/**
* Accessor function to set the text wrap count
*/
    function setTextWrap($count = 998)
    {
        $this->build_params['text_wrap'] = $count;
    }

/**
* Accessor to set a header
*/
    function setHeader($name, $value)
    {
        $this->headers[$name] = $value;
    }

/**
* Accessor to add a Subject: header
*/
    function setSubject($subject)
    {
        $this->headers['Subject'] = $subject;
    }

/**
* Accessor to add a From: header
*/
    function setFrom($from)
    {
        $this->headers['From'] = $from;
    }

/**
* Accessor to set the return path
*/
    function setReturnPath($return_path)
    {
        $this->return_path = $return_path;
    }

/**
* Accessor to add a Cc: header
*/
    function setCc($cc)
    {
        $this->headers['Cc'] = $cc;
    }

/**
* Accessor to add a Bcc: header
*/
    function setBcc($bcc)
    {
        $this->headers['Bcc'] = $bcc;
    }

/**
* Adds plain text. Use this function
* when NOT sending html email
*/
    function setText($text = '')
    {
        $this->text = $text;
    }

/**
* Adds a html part to the mail.
* Also replaces image names with
* content-id's.
*/
    function setHtml($html, $text = null, $images_dir = null)
    {
        $this->html      = $html;
        $this->html_text = $text;

        if (isset($images_dir)) {
            $this->_findHtmlImages($images_dir);
        }
    }

/**
* Function for extracting images from
* html source. This function will look
* through the html code supplied by add_html()
* and find any file that ends in one of the
* extensions defined in $obj->image_types.
* If the file exists it will read it in and
* embed it, (not an attachment).
*
* @author Dan Allen
*/
    function _findHtmlImages($images_dir)
    {
        // Build the list of image extensions
        while (list($key,) = each($this->image_types)) {
            $extensions[] = $key;
        }

        preg_match_all('/(?:"|')([^"']+.('.implode('|', $extensions).'))(?:"|')/Ui', $this->html, $images);

        for ($i=0; $i<count($images[1]); $i++) {
            if (file_exists($images_dir . $images[1][$i])) {
                $html_images[] = $images[1][$i];
                $this->html = str_replace($images[1][$i], basename($images[1][$i]), $this->html);
            }
        }

        if (!empty($html_images)) {

            // If duplicate images are embedded, they may show up as attachments, so remove them.
            $html_images = array_unique($html_images);
            sort($html_images);
    
            for ($i=0; $i<count($html_images); $i++) {
                if ($image = $this->getFile($images_dir.$html_images[$i])) {
                    $ext = substr($html_images[$i], strrpos($html_images[$i], '.') + 1);
                    $content_type = $this->image_types[strtolower($ext)];
                    $this->addHtmlImage($image, basename($html_images[$i]), $content_type);
                }
            }
        }
    }

/**
* Adds an image to the list of embedded
* images.
*/
    function addHtmlImage($file, $name = '', $c_type='application/octet-stream')
    {
        $this->html_images[] = array(
                                        'body'   => $file,
                                        'name'   => $name,
                                        'c_type' => $c_type,
                                        'cid'    => md5(uniqid(time()))
                                    );
    }


/**
* Adds a file to the list of attachments.
*/
    function addAttachment($file, $name = '', $c_type='application/octet-stream', $encoding = 'base64')
    {
        $this->attachments[] = array(
                                    'body'        => $file,
                                    'name'        => $name,
                                    'c_type'    => $c_type,
                                    'encoding'    => $encoding
                                  );
    }

/**
* Adds a text subpart to a mime_part object
*/
    function &_addTextPart(&$obj, $text)
    {
        $params['content_type'] = 'text/plain';
        $params['encoding']     = $this->build_params['text_encoding'];
        $params['charset']      = $this->build_params['text_charset'];
        if (is_object($obj)) {
            return $obj->addSubpart($text, $params);
        } else {
            return new Mail_mimePart($text, $params);
        }
    }

