TYPO3 API  SVNRelease
class.t3lib_htmlmail.php
Go to the documentation of this file.
00001 <?php
00002 /***************************************************************
00003  *  Copyright notice
00004  *
00005  *  (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
00006  *  All rights reserved
00007  *
00008  *  This script is part of the TYPO3 project. The TYPO3 project is
00009  *  free software; you can redistribute it and/or modify
00010  *  it under the terms of the GNU General Public License as published by
00011  *  the Free Software Foundation; either version 2 of the License, or
00012  *  (at your option) any later version.
00013  *
00014  *  The GNU General Public License can be found at
00015  *  http://www.gnu.org/copyleft/gpl.html.
00016  *  A copy is found in the textfile GPL.txt and important notices to the license
00017  *  from the author is found in LICENSE.txt distributed with these scripts.
00018  *
00019  *
00020  *  This script is distributed in the hope that it will be useful,
00021  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00022  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00023  *  GNU General Public License for more details.
00024  *
00025  *  This copyright notice MUST APPEAR in all copies of the script!
00026  ***************************************************************/
00027 /**
00028  * HTML mail class
00029  *
00030  * $Id: class.t3lib_htmlmail.php 10559 2011-02-22 22:27:33Z sgalinsk $
00031  *
00032  * @author  Kasper Skårhøj <kasperYYYY@typo3.com>
00033  */
00034 /**
00035  * [CLASS/FUNCTION INDEX of SCRIPT]
00036  *
00037  *
00038  *
00039  *  193: class t3lib_htmlmail
00040  *  261:     function t3lib_htmlmail ()
00041  *  268:     function start ()
00042  *  305:     function useQuotedPrintable()
00043  *  315:     function useBase64()
00044  *  326:     function use8Bit()
00045  *  338:     function encodeMsg($content)
00046  *  348:     function addPlain ($content)
00047  *  360:     function addAttachment($file)
00048  *  378:     function addHTML ($file)
00049  *  401:     function extractHtmlInit($html,$url)
00050  *  412:     function send($recipient)
00051  *
00052  *            SECTION: Main functions
00053  *  441:     function setHeaders()
00054  *  500:     function setRecipient ($recip)
00055  *  518:     function getHTMLContentType()
00056  *  527:     function setContent()
00057  *  554:     function constructMixed ($boundary)
00058  *  593:     function constructHTML ($boundary)
00059  *  617:     function constructAlternative($boundary)
00060  *  638:     function constructHTML_media ($boundary)
00061  *  691:     function sendTheMail ()
00062  *  757:     function getBoundary()
00063  *  769:     function setPlain ($content)
00064  *  780:     function setHtml ($content)
00065  *  791:     function add_header($header)
00066  *  812:     function add_message($string)
00067  *  823:     function getContent($type)
00068  *  832:     function preview()
00069  *
00070  *            SECTION: Functions for acquiring attachments, HTML, analyzing and so on  **
00071  *  860:     function fetchHTML($file)
00072  *  878:     function fetchHTMLMedia()
00073  *  899:     function extractMediaLinks()
00074  *  976:     function extractHyperLinks()
00075  * 1025:     function extractFramesInfo()
00076  * 1051:     function substMediaNamesInHTML($absolute)
00077  * 1078:     function substHREFsInHTML()
00078  * 1106:     function substHTTPurlsInPlainText($content)
00079  * 1142:     function fixRollOvers()
00080  *
00081  *            SECTION: File and URL-functions
00082  * 1189:     function makeBase64($inputstr)
00083  * 1200:     function getExtendedURL($url)
00084  * 1222:     function addUserPass($url)
00085  * 1238:     function getURL($url)
00086  * 1250:     function getStrippedURL($url)
00087  * 1271:     function getMimeType($url)
00088  * 1300:     function absRef($ref)
00089  * 1320:     function split_fileref($fileref)
00090  * 1347:     function extParseUrl($path)
00091  * 1362:     function tag_regex($tagArray)
00092  * 1384:     function get_tag_attributes($tag)
00093  * 1426:     function quoted_printable($string)
00094  * 1437:     function convertName($name)
00095  *
00096  * TOTAL FUNCTIONS: 49
00097  * (This index is automatically created/updated by the extension "extdeveval")
00098  *
00099  */
00100 /**
00101  * NOTES on MIME mail structures:
00102  *
00103  * Plain + HTML
00104  *   multipart/alternative  (text, html)
00105  *   multipart/alternative  (text, html)
00106  *
00107  * Plain + HTML + image
00108  *   multipart/related (m/a, cids)
00109  *       multipart/alternative (text, html)
00110  *
00111  *   multipart/related  (m/a, cids)
00112  *       multipart/alternative  (text, html)
00113  *
00114  * plain + attachment
00115  *   multipart/mixed
00116  *
00117  * HTML + Attachment:
00118  *   multipart/mixed        (text/html , attachments)
00119  *
00120  * Plain + HTML + Attachments:
00121  *   multipart/mixed        (m/a, attachments)
00122  *       multipart/alternative  (text, html)
00123  *
00124  * Plain + HTML + image + attachment
00125  *
00126  *       Outlook expr.
00127  *   multipart/mixed (m/r, attachments)
00128  *       multipart/related  (m/a, cids)
00129  *           multipart/alternative  (text, html)
00130  *
00131  *
00132  *
00133  * FROM RFC 1521:
00134  *
00135  * 5.1 Quoted-Printable Content-Transfer-Encoding
00136  * The Quoted-Printable encoding is intended to represent data that largely consists of octets that correspond to printable characters in the ASCII character set. It encodes the data in such a way that the resulting octets are unlikely to be modified by mail transport. If the data being encoded are mostly ASCII text, the encoded form of the data remains largely recognizable by humans. A body which is entirely ASCII may also be encoded in Quoted-Printable to ensure the integrity of the data should the message pass through a character- translating, and/or line-wrapping gateway.
00137  *
00138  * In this encoding, octets are to be represented as determined by the following rules:
00139  * Rule #1: (General 8-bit representation) Any octet, except those indicating a line break according to the newline convention of the canonical (standard) form of the data being encoded, may be represented by an "=" followed by a two digit hexadecimal representation of the octet's value. The digits of the hexadecimal alphabet, for this purpose, are "0123456789ABCDEF". Uppercase letters must be used when sending hexadecimal data, though a robust implementation may choose to recognize lowercase letters on receipt. Thus, for example, the value 12 (ASCII form feed) can be represented by "=0C", and the value 61 (ASCII EQUAL SIGN) can be represented by "=3D". Except when the following rules allow an alternative encoding, this rule is mandatory.
00140  * Rule #2: (Literal representation) Octets with decimal values of 33 through 60 inclusive, and 62 through 126, inclusive, MAY be represented as the ASCII characters which correspond to those octets (EXCLAMATION POINT through LESS THAN, and GREATER THAN through TILDE, respectively).
00141  * Rule #3: (White Space): Octets with values of 9 and 32 MAY be represented as ASCII TAB (HT) and SPACE characters, respectively, but MUST NOT be so represented at the end of an encoded line. Any TAB (HT) or SPACE characters on an encoded line MUST thus be followed on that line by a printable character. In particular, an
00142  * "=" at the end of an encoded line, indicating a soft line break (see rule #5) may follow one or more TAB (HT) or SPACE characters. It follows that an octet with value 9 or 32 appearing at the end of an encoded line must be represented according to Rule #1. This rule is necessary because some MTAs (Message Transport Agents, programs which transport messages from one user to another, or perform a part of such transfers) are known to pad lines of text with SPACEs, and others are known to remove "white space" characters from the end of a line. Therefore, when decoding a Quoted-Printable body, any trailing white space on a line must be deleted, as it will necessarily have been added by intermediate transport agents.
00143  * Rule #4 (Line Breaks): A line break in a text body, independent of what its representation is following the canonical representation of the data being encoded, must be represented by a (RFC 822) line break, which is a CRLF sequence, in the Quoted-Printable encoding. Since the canonical representation of types other than text do not generally include the representation of line breaks, no hard line breaks (i.e. line breaks that are intended to be meaningful and to be displayed to the user) should occur in the quoted-printable encoding of such types. Of course, occurrences of "=0D", "=0A", "0A=0D" and "=0D=0A" will eventually be encountered. In general, however, base64 is preferred over quoted-printable for binary data.
00144  * Note that many implementations may elect to encode the local representation of various content types directly, as described in Appendix G. In particular, this may apply to plain text material on systems that use newline conventions other than CRLF delimiters. Such an implementation is permissible, but the generation of line breaks must be generalized to account for the case where alternate representations of newline sequences are used.
00145  * Rule #5 (Soft Line Breaks): The Quoted-Printable encoding REQUIRES that encoded lines be no more than 76 characters long. If longer lines are to be encoded with the Quoted-Printable encoding, 'soft' line breaks must be used. An equal sign as the last character on a encoded line indicates such a non-significant ('soft') line break in the encoded text. Thus if the "raw" form of the line is a single unencoded line that says:
00146  * Now's the time for all folk to come to the aid of their country.
00147  *
00148  * This can be represented, in the Quoted-Printable encoding, as
00149  *
00150  * Now's the time =
00151  * for all folk to come=
00152  * to the aid of their country.
00153  *
00154  * This provides a mechanism with which long lines are encoded in such a way as to be restored by the user agent. The 76 character limit does not count the trailing CRLF, but counts all other characters, including any equal signs.
00155  * Since the hyphen character ("-") is represented as itself in the Quoted-Printable encoding, care must be taken, when encapsulating a quoted-printable encoded body in a multipart entity, to ensure that the encapsulation boundary does not appear anywhere in the encoded body. (A good strategy is to choose a boundary that includes a character sequence such as "=_" which can never appear in a quoted- printable body. See the definition of multipart messages later in this document.)
00156  * NOTE: The quoted-printable encoding represents something of a compromise between readability and reliability in transport. Bodies encoded with the quoted-printable encoding will work reliably over most mail gateways, but may not work perfectly over a few gateways, notably those involving translation into EBCDIC. (In theory, an EBCDIC gateway could decode a quoted-printable body and re-encode it using base64, but such gateways do not yet exist.) A higher level of confidence is offered by the base64 Content-Transfer-Encoding. A way to get reasonably reliable transport through EBCDIC gateways is to also quote the ASCII characters
00157  * !"#$@[\]^`{|}~
00158  * according to rule #1. See Appendix B for more information.
00159  * Because quoted-printable data is generally assumed to be line- oriented, it is to be expected that the representation of the breaks between the lines of quoted printable data may be altered in transport, in the same manner that plain text mail has always been altered in Internet mail when passing between systems with differing newline conventions. If such alterations are likely to constitute a corruption of the data, it is probably more sensible to use the base64 encoding rather than the quoted-printable encoding.
00160  * WARNING TO IMPLEMENTORS: If binary data are encoded in quoted- printable, care must be taken to encode CR and LF characters as "=0D" and "=0A", respectively. In particular, a CRLF sequence in binary data should be encoded as "=0D=0A". Otherwise, if CRLF were represented as a hard line break, it might be incorrectly decoded on
00161  * platforms with different line break conventions.
00162  * For formalists, the syntax of quoted-printable data is described by the following grammar:
00163  *
00164  *  quoted-printable := ([*(ptext / SPACE / TAB) ptext] ["="] CRLF)
00165  *       ; Maximum line length of 76 characters excluding CRLF
00166  *
00167  *  ptext := octet /<any ASCII character except "=", SPACE, or TAB>
00168  *       ; characters not listed as "mail-safe" in Appendix B
00169  *       ; are also not recommended.
00170  *
00171  *  octet := "=" 2(DIGIT / "A" / "B" / "C" / "D" / "E" / "F")
00172  *       ; octet must be used for characters > 127, =, SPACE, or TAB,
00173  *       ; and is recommended for any characters not listed in
00174  *       ; Appendix B as "mail-safe".
00175  */
00176 /**
00177  * HTML mail class
00178  *
00179  * @author  Kasper Skårhøj <kasperYYYY@typo3.com>
00180  * @package TYPO3
00181  * @subpackage  t3lib
00182  */
00183 class t3lib_htmlmail {
00184         // Headerinfo:
00185     var $recipient = '';
00186     var $recipient_copy = ''; // This recipient (or list of...) will also receive the mail. Regard it as a copy.
00187     var $recipient_blindcopy = ''; // This recipient (or list of...) will also receive the mail as a blind copy. Regard it as a copy.
00188     var $subject = '';
00189     var $from_email = '';
00190     var $from_name = '';
00191     var $replyto_email = '';
00192     var $replyto_name = '';
00193     var $organisation = '';
00194     var $priority = 3; // 1 = highest, 5 = lowest, 3 = normal
00195     var $mailer = ''; // X-mailer, set to TYPO3 Major.Minor in constructor
00196     var $alt_base64 = 0;
00197     var $alt_8bit = 0;
00198     var $jumperURL_prefix = ''; // This is a prefix that will be added to all links in the mail. Example: 'http://www.mydomain.com/jump?userid=###FIELD_uid###&url='. if used, anything after url= is urlencoded.
00199     var $jumperURL_useId = 0; // If set, then the array-key of the urls are inserted instead of the url itself. Smart in order to reduce link-length
00200     var $mediaList = ''; // If set, this is a list of the media-files (index-keys to the array) that should be represented in the html-mail
00201     var $http_password = '';
00202     var $http_username = '';
00203     var $postfix_version1 = FALSE;
00204 
00205         // Internal
00206     /*
00207     This is how the $theParts-array is normally looking
00208     var $theParts = array(
00209         'plain' => array(
00210             'content' => ''
00211         ),
00212         'html' => array(
00213             'content' => '',
00214             'path' => '',
00215             'media' => array(),
00216             'hrefs' => array()
00217         ),
00218         'attach' => array()
00219     );
00220     */
00221     var $theParts = array();
00222 
00223     var $messageid = '';
00224     var $returnPath = '';
00225     var $Xid = '';
00226     var $dontEncodeHeader = FALSE; // If set, the header will not be encoded
00227 
00228     var $headers = '';
00229     var $message = '';
00230     var $part = 0;
00231     var $image_fullpath_list = '';
00232     var $href_fullpath_list = '';
00233 
00234     var $plain_text_header = '';
00235     var $html_text_header = '';
00236     var $charset = '';
00237     var $defaultCharset = 'iso-8859-1';
00238 
00239 
00240     /**
00241      * Constructor. If the configuration variable forceReturnPath is set,
00242      * calls to mail will be called with a 5th parameter.
00243      * See function sendTheMail for more info
00244      *
00245      * @return  void
00246      */
00247     public function t3lib_htmlmail() {
00248         t3lib_div::logDeprecatedFunction();
00249         $this->forceReturnPath = $GLOBALS['TYPO3_CONF_VARS']['SYS']['forceReturnPath'];
00250 
00251         $this->mailer = 'TYPO3';
00252     }
00253 
00254 
00255     /**
00256      * start action that sets the message ID and the charset
00257      *
00258      * @return  void
00259      */
00260     public function start() {
00261         global $TYPO3_CONF_VARS;
00262 
00263             // Sets the message id
00264         $host = t3lib_div::getHostname();
00265         if (!$host || $host == '127.0.0.1' || $host == 'localhost' || $host == 'localhost.localdomain') {
00266             $host = ($TYPO3_CONF_VARS['SYS']['sitename'] ? preg_replace('/[^A-Za-z0-9_\-]/', '_', $TYPO3_CONF_VARS['SYS']['sitename']) : 'localhost') . '.TYPO3';
00267         }
00268 
00269         $idLeft = time() . '.' . uniqid();
00270         $idRight = !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'swift.generated';
00271         $this->messageid = $idLeft . '@' . $idRight;
00272 
00273             // Default line break for Unix systems.
00274         $this->linebreak = LF;
00275             // Line break for Windows. This is needed because PHP on Windows systems
00276             // send mails via SMTP instead of using sendmail, and thus the linebreak needs to be \r\n.
00277         if (TYPO3_OS == 'WIN') {
00278             $this->linebreak = CRLF;
00279         }
00280 
00281             // Sets the Charset
00282         if (!$this->charset) {
00283             if (is_object($GLOBALS['TSFE']) && $GLOBALS['TSFE']->renderCharset) {
00284                 $this->charset = $GLOBALS['TSFE']->renderCharset;
00285             } elseif (is_object($GLOBALS['LANG']) && $GLOBALS['LANG']->charSet) {
00286                 $this->charset = $GLOBALS['LANG']->charSet;
00287             } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
00288                 $this->charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
00289             } else {
00290                 $this->charset = $this->defaultCharset;
00291             }
00292         }
00293 
00294             // Use quoted-printable headers by default
00295         $this->useQuotedPrintable();
00296     }
00297 
00298 
00299     /**
00300      * sets the header of both Plain Text and HTML mails to quoted printable
00301      *
00302      * @return  void
00303      */
00304     public function useQuotedPrintable() {
00305         $this->plain_text_header = 'Content-Type: text/plain; charset=' . $this->charset . $this->linebreak . 'Content-Transfer-Encoding: quoted-printable';
00306         $this->html_text_header = 'Content-Type: text/html; charset=' . $this->charset . $this->linebreak . 'Content-Transfer-Encoding: quoted-printable';
00307     }
00308 
00309     /**
00310      * sets the encoding headers to base64 for both the Plain Text and HTML mail
00311      *
00312      * @return  void
00313      */
00314     public function useBase64() {
00315         $this->plain_text_header = 'Content-Type: text/plain; charset=' . $this->charset . $this->linebreak . 'Content-Transfer-Encoding: base64';
00316         $this->html_text_header = 'Content-Type: text/html; charset=' . $this->charset . $this->linebreak . 'Content-Transfer-Encoding: base64';
00317         $this->alt_base64 = 1;
00318     }
00319 
00320 
00321     /**
00322      * sets the encoding to 8bit and the current charset of both the Plain Text and the HTML mail
00323      *
00324      * @return  void
00325      */
00326     public function use8Bit() {
00327         $this->plain_text_header = 'Content-Type: text/plain; charset=' . $this->charset . $this->linebreak . 'Content-Transfer-Encoding: 8bit';
00328         $this->html_text_header = 'Content-Type: text/html; charset=' . $this->charset . $this->linebreak . 'Content-Transfer-Encoding: 8bit';
00329         $this->alt_8bit = 1;
00330     }
00331 
00332 
00333     /**
00334      * Encodes the message content according to the options "alt_base64" and "alt_8bit" (no need to encode here)
00335      * or to "quoted_printable" if no option is set.
00336      *
00337      * @param   string      $content the content that will be encoded
00338      * @return  string      the encoded content
00339      */
00340     public function encodeMsg($content) {
00341         if ($this->alt_base64) {
00342             return $this->makeBase64($content);
00343         } elseif ($this->alt_8bit) {
00344             return $content;
00345         } else {
00346             return t3lib_div::quoted_printable($content);
00347         }
00348     }
00349 
00350 
00351     /**
00352      * Adds plain-text, replaces the HTTP urls in the plain text and then encodes it
00353      *
00354      * @param   string      $content that will be added
00355      * @return  void
00356      */
00357     public function addPlain($content) {
00358         $content = $this->substHTTPurlsInPlainText($content);
00359         $this->setPlain($this->encodeMsg($content));
00360     }
00361 
00362 
00363     /**
00364      * Adds an attachment to the mail
00365      *
00366      * @param   string      $file: the filename to add
00367      * @return  boolean     whether the attachment was added or not
00368      */
00369     public function addAttachment($file) {
00370             // Fetching the content and the mime-type
00371         $fileInfo = $this->getExtendedURL($file);
00372         if ($fileInfo) {
00373             if (!$fileInfo['content_type']) {
00374                 $fileInfo['content_type'] = 'application/octet-stream';
00375             }
00376             $temp = $this->split_fileref($file);
00377             if ($temp['file']) {
00378                 $fileInfo['filename'] = $temp['file'];
00379             } elseif (strpos(' ' . $fileInfo['content_type'], 'htm')) {
00380                 $fileInfo['filename'] = 'index.html';
00381             } else {
00382                 $fileInfo['filename'] = 'unknown';
00383             }
00384             $this->theParts['attach'][] = $fileInfo;
00385             return TRUE;
00386         }
00387         return FALSE;
00388     }
00389 
00390 
00391     /**
00392      * Adds HTML and media, encodes it from a URL or file
00393      *
00394      * @param   string      $file: the filename to add
00395      * @return  boolean     whether the attachment was added or not
00396      */
00397     public function addHTML($file) {
00398         $status = $this->fetchHTML($file);
00399         if (!$status) {
00400             return FALSE;
00401         }
00402         if ($this->extractFramesInfo()) {
00403             return 'Document was a frameset. Stopped';
00404         }
00405         $this->extractMediaLinks();
00406         $this->extractHyperLinks();
00407         $this->fetchHTMLMedia();
00408         $this->substMediaNamesInHTML(0); // 0 = relative
00409         $this->substHREFsInHTML();
00410         $this->setHtml($this->encodeMsg($this->theParts['html']['content']));
00411     }
00412 
00413 
00414     /**
00415      * Extract HTML-parts, used externally
00416      *
00417      * @param   string      $html: will be added to the html "content" part
00418      * @param   string      $url: will be added to the html "path" part
00419      * @return  void
00420      */
00421     public function extractHtmlInit($html, $url) {
00422         $this->theParts['html']['content'] = $html;
00423         $this->theParts['html']['path'] = $url;
00424     }
00425 
00426 
00427     /**
00428      * Assembles the message by headers and content and finally send it to the provided recipient.
00429      *
00430      * @param   string      $recipient: The recipient the message should be delivered to (if blank, $this->recipient will be used instead)
00431      * @return  boolean     Returns whether the mail was sent (successfully accepted for delivery)
00432      */
00433     public function send($recipient) {
00434         if ($recipient) {
00435             $this->recipient = $recipient;
00436         }
00437         $this->setHeaders();
00438         $this->setContent();
00439         $mailWasSent = $this->sendTheMail();
00440         return $mailWasSent;
00441     }
00442 
00443 
00444     /*****************************************
00445      *
00446      * Main functions
00447      *
00448      *****************************************/
00449 
00450     /**
00451      * Clears the header-string and sets the headers based on object-vars.
00452      *
00453      * @return  void
00454      */
00455     public function setHeaders() {
00456         $this->headers = '';
00457             // Message_id
00458         $this->add_header('Message-ID: <' . $this->messageid . '>');
00459             // Return path
00460         if ($this->returnPath) {
00461             $this->add_header('Return-Path: ' . $this->returnPath);
00462             $this->add_header('Errors-To: ' . $this->returnPath);
00463         }
00464             // X-id
00465         if ($this->Xid) {
00466             $this->add_header('X-Typo3MID: ' . $this->Xid);
00467         }
00468 
00469             // From
00470         if ($this->from_email) {
00471             if ($this->from_name && !t3lib_div::isBrokenEmailEnvironment()) {
00472                 $this->add_header('From: ' . $this->from_name . ' <' . $this->from_email . '>');
00473             } else {
00474                 $this->add_header('From: ' . $this->from_email);
00475             }
00476         }
00477 
00478             // Cc
00479         if ($this->recipient_copy) {
00480             $this->add_header('Cc: ' . $this->recipient_copy);
00481         }
00482 
00483             // Bcc
00484         if ($this->recipient_blindcopy) {
00485             $this->add_header('Bcc: ' . $this->recipient_blindcopy);
00486         }
00487 
00488             // Reply
00489         if ($this->replyto_email) {
00490             if ($this->replyto_name) {
00491                 $this->add_header('Reply-To: ' . $this->replyto_name . ' <' . $this->replyto_email . '>');
00492             } else {
00493                 $this->add_header('Reply-To: ' . $this->replyto_email);
00494             }
00495         }
00496             // Organization, using american english spelling (organization / organisation) as defined in RFC 1036 / 2076
00497         if ($this->organisation) {
00498             $this->add_header('Organization: ' . $this->organisation);
00499         }
00500             // mailer
00501         if ($this->mailer) {
00502             $this->add_header('X-Mailer: ' . $this->mailer);
00503         }
00504             // priority
00505         if ($this->priority) {
00506             $this->add_header('X-Priority: ' . $this->priority);
00507         }
00508         $this->add_header('Mime-Version: 1.0');
00509 
00510         if (!$this->dontEncodeHeader) {
00511             $enc = $this->alt_base64 ? 'base64' : 'quoted_printable'; // Header must be ASCII, therefore only base64 or quoted_printable are allowed!
00512                 // Quote recipient and subject
00513             $this->recipient = t3lib_div::encodeHeader($this->recipient, $enc, $this->charset);
00514             $this->subject = t3lib_div::encodeHeader($this->subject, $enc, $this->charset);
00515         }
00516     }
00517 
00518 
00519     /**
00520      * Sets the recipient(s). If you supply a string, you set one recipient.
00521      * If you supply an array, every value is added as a recipient.
00522      *
00523      * @param   mixed       $recipient: the recipient(s) to set
00524      * @return  void
00525      */
00526     public function setRecipient($recipient) {
00527         $this->recipient = (is_array($recipient) ? implode(',', $recipient) : $recipient);
00528     }
00529 
00530 
00531     /**
00532      * Returns the content type based on whether the mail has media / attachments or no
00533      *
00534      * @return  string      the content type
00535      */
00536     public function getHTMLContentType() {
00537         return (count($this->theParts['html']['media']) ? 'multipart/related' : 'multipart/alternative');
00538     }
00539 
00540 
00541     /**
00542      * Begins building the message-body
00543      *
00544      * @return  void
00545      */
00546     public function setContent() {
00547         $this->message = '';
00548         $boundary = $this->getBoundary();
00549 
00550             // Setting up headers
00551         if (count($this->theParts['attach'])) {
00552                 // Generate (plain/HTML) / attachments
00553             $this->add_header('Content-Type: multipart/mixed;');
00554             $this->add_header(' boundary="' . $boundary . '"');
00555             $this->add_message('This is a multi-part message in MIME format.' . LF);
00556             $this->constructMixed($boundary);
00557         } elseif ($this->theParts['html']['content']) {
00558                 // Generate plain/HTML mail
00559             $this->add_header('Content-Type: ' . $this->getHTMLContentType() . ';');
00560             $this->add_header(' boundary="' . $boundary . '"');
00561             $this->add_message('This is a multi-part message in MIME format.' . LF);
00562             $this->constructHTML($boundary);
00563         } else {
00564                 // Generate plain only
00565             $this->add_header($this->plain_text_header);
00566             $this->add_message($this->getContent('plain'));
00567         }
00568     }
00569 
00570 
00571     /**
00572      * This functions combines the plain / HTML content with the attachments
00573      *
00574      * @param   string      $boundary: the mail boundary
00575      * @return  void
00576      */
00577     public function constructMixed($boundary) {
00578         $this->add_message('--' . $boundary);
00579 
00580         if ($this->theParts['html']['content']) {
00581                 // HTML and plain is added
00582             $newBoundary = $this->getBoundary();
00583             $this->add_message('Content-Type: ' . $this->getHTMLContentType() . ';');
00584             $this->add_message(' boundary="' . $newBoundary . '"');
00585             $this->add_message('');
00586             $this->constructHTML($newBoundary);
00587         } else {
00588                 // Purely plain
00589             $this->add_message($this->plain_text_header);
00590             $this->add_message('');
00591             $this->add_message($this->getContent('plain'));
00592         }
00593             // attachments are added
00594         if (is_array($this->theParts['attach'])) {
00595             foreach ($this->theParts['attach'] as $media) {
00596                 $this->add_message('--' . $boundary);
00597                 $this->add_message('Content-Type: ' . $media['content_type'] . ';');
00598                 $this->add_message(' name="' . $media['filename'] . '"');
00599                 $this->add_message('Content-Transfer-Encoding: base64');
00600                 $this->add_message('Content-Disposition: attachment;');
00601                 $this->add_message(' filename="' . $media['filename'] . '"');
00602                 $this->add_message('');
00603                 $this->add_message($this->makeBase64($media['content']));
00604             }
00605         }
00606         $this->add_message('--' . $boundary . '--' . LF);
00607     }
00608 
00609 
00610     /**
00611      * this function creates the HTML part of the mail
00612      *
00613      * @param   string      $boundary: the boundary to use
00614      * @return  void
00615      */
00616     public function constructHTML($boundary) {
00617             // If media, then we know, the multipart/related content-type has been set before this function call
00618         if (count($this->theParts['html']['media'])) {
00619             $this->add_message('--' . $boundary);
00620                 // HTML has media
00621             $newBoundary = $this->getBoundary();
00622             $this->add_message('Content-Type: multipart/alternative;');
00623             $this->add_message(' boundary="' . $newBoundary . '"');
00624             $this->add_message('Content-Transfer-Encoding: 7bit');
00625             $this->add_message('');
00626 
00627                 // Adding the plaintext/html mix, and use $newBoundary
00628             $this->constructAlternative($newBoundary);
00629             $this->constructHTML_media($boundary);
00630         } else {
00631                 // if no media, just use the $boundary for adding plaintext/html mix
00632             $this->constructAlternative($boundary);
00633         }
00634     }
00635 
00636 
00637     /**
00638      * Here plain is combined with HTML
00639      *
00640      * @param   string      $boundary: the boundary to use
00641      * @return  void
00642      */
00643     public function constructAlternative($boundary) {
00644         $this->add_message('--' . $boundary);
00645 
00646             // plain is added
00647         $this->add_message($this->plain_text_header);
00648         $this->add_message('');
00649         $this->add_message($this->getContent('plain'));
00650         $this->add_message('--' . $boundary);
00651 
00652             // html is added
00653         $this->add_message($this->html_text_header);
00654         $this->add_message('');
00655         $this->add_message($this->getContent('html'));
00656         $this->add_message('--' . $boundary . '--' . LF);
00657     }
00658 
00659 
00660     /**
00661      * Constructs the HTML-part of message if the HTML contains media
00662      *
00663      * @param   string      $boundary: the boundary to use
00664      * @return  void
00665      */
00666     public function constructHTML_media($boundary) {
00667             // media is added
00668         if (is_array($this->theParts['html']['media'])) {
00669             foreach ($this->theParts['html']['media'] as $key => $media) {
00670                 if (!$this->mediaList || t3lib_div::inList($this->mediaList, $key)) {
00671                     $this->add_message('--' . $boundary);
00672                     $this->add_message('Content-Type: ' . $media['ctype']);
00673                     $this->add_message('Content-ID: <part' . $key . '.' . $this->messageid . '>');
00674                     $this->add_message('Content-Transfer-Encoding: base64');
00675                     $this->add_message('');
00676                     $this->add_message($this->makeBase64($media['content']));
00677                 }
00678             }
00679         }
00680         $this->add_message('--' . $boundary . '--' . LF);
00681     }
00682 
00683 
00684     /**
00685      * Sends the mail by calling the mail() function in php. On Linux systems this will invoke the MTA
00686      * defined in php.ini (sendmail -t -i by default), on Windows a SMTP must be specified in the sys.ini.
00687      * Most common MTA's on Linux has a Sendmail interface, including Postfix and Exim.
00688      * For setting the return-path correctly, the parameter -f has to be added to the system call to sendmail.
00689      * This obviously does not have any effect on Windows, but on Sendmail compliant systems this works. If safe mode
00690      * is enabled, then extra parameters is not allowed, so a safe mode check is made before the mail() command is
00691      * invoked. When using the -f parameter, some MTA's will put an X-AUTHENTICATION-WARNING saying that
00692      * the return path was modified manually with the -f flag. To disable this warning make sure that the user running
00693      * Apache is in the /etc/mail/trusted-users table.
00694      *
00695      * POSTFIX: With postfix version below 2.0 there is a problem that the -f parameter can not be used in conjunction
00696      * with -t. Postfix will give an error in the maillog:
00697      *
00698      *  cannot handle command-line recipients with -t
00699      *
00700      * The -f parameter is only enabled if the parameter forceReturnPath is enabled in the install tool.
00701      *
00702      * This whole problem of return-path turns out to be quite tricky. If you have a solution that works better, on all
00703      * standard MTA's then we are very open for suggestions.
00704      *
00705      * With time this function should be made such that several ways of sending the mail is possible (local MTA, smtp other).
00706      *
00707      * @return  boolean     Returns whether the mail was sent (successfully accepted for delivery)
00708      */
00709     public function sendTheMail() {
00710         $mailWasSent = FALSE;
00711 
00712             // Sending the mail requires the recipient and message to be set.
00713         if (!trim($this->recipient) || !trim($this->message)) {
00714             return FALSE;
00715         }
00716 
00717             // On windows the -f flag is not used (specific for Sendmail and Postfix),
00718             // but instead the php.ini parameter sendmail_from is used.
00719         $returnPath = ($this->forceReturnPath && strlen($this->returnPath) > 0) ? '-f ' . escapeshellarg($this->returnPath) : '';
00720         if (TYPO3_OS == 'WIN' && $this->returnPath) {
00721             @ini_set('sendmail_from', t3lib_div::normalizeMailAddress($this->returnPath));
00722         }
00723         $recipient = t3lib_div::normalizeMailAddress($this->recipient);
00724 
00725             // If safe mode is on, the fifth parameter to mail is not allowed, so the fix wont work on unix with safe_mode=On
00726         $returnPathPossible = (!t3lib_utility_PhpOptions::isSafeModeEnabled() && $this->forceReturnPath);
00727         if ($returnPathPossible) {
00728             $mailWasSent = t3lib_utility_Mail::mail(
00729                 $recipient,
00730                 $this->subject,
00731                 $this->message,
00732                 $this->headers,
00733                 $returnPath
00734             );
00735         } else {
00736             $mailWasSent = t3lib_utility_Mail::mail(
00737                 $recipient,
00738                 $this->subject,
00739                 $this->message,
00740                 $this->headers
00741             );
00742         }
00743 
00744             // Auto response
00745         if ($this->auto_respond_msg) {
00746             $theParts = explode('/', $this->auto_respond_msg, 2);
00747             $theParts[0] = str_replace('###SUBJECT###', $this->subject, $theParts[0]);
00748             $theParts[1] = str_replace("/", LF, $theParts[1]);
00749             $theParts[1] = str_replace("###MESSAGE###", $this->getContent('plain'), $theParts[1]);
00750             if ($returnPathPossible) {
00751                 $mailWasSent = t3lib_utility_Mail::mail(
00752                     $this->from_email,
00753                     $theParts[0],
00754                     $theParts[1],
00755                     'From: ' . $recipient . $this->linebreak . $this->plain_text_header,
00756                     $returnPath
00757                 );
00758             } else {
00759                 $mailWasSent = t3lib_utility_Mail::mail(
00760                     $this->from_email,
00761                     $theParts[0],
00762                     $theParts[1],
00763                     'From: ' . $recipient . $this->linebreak . $this->plain_text_header
00764                 );
00765             }
00766         }
00767         if ($this->returnPath) {
00768             ini_restore('sendmail_from');
00769         }
00770         return $mailWasSent;
00771     }
00772 
00773 
00774     /**
00775      * Returns boundaries
00776      *
00777      * @return  string  the boundary
00778      */
00779     public function getBoundary() {
00780         $this->part++;
00781         return "----------" . uniqid("part_" . $this->part . "_");
00782     }
00783 
00784 
00785     /**
00786      * Sets the plain-text part. No processing done.
00787      *
00788      * @param   string      $content: the plain content
00789      * @return  void
00790      */
00791     public function setPlain($content) {
00792         $this->theParts['plain']['content'] = $content;
00793     }
00794 
00795 
00796     /**
00797      * Sets the HTML-part. No processing done.
00798      *
00799      * @param   string      $content: the HTML content
00800      * @return  void
00801      */
00802     public function setHtml($content) {
00803         $this->theParts['html']['content'] = $content;
00804     }
00805 
00806 
00807     /**
00808      * Adds a header to the mail. Use this AFTER the setHeaders()-function
00809      *
00810      * @param   string      $header: the header in form of "key: value"
00811      * @return  void
00812      */
00813     public function add_header($header) {
00814             // Mail headers must be ASCII, therefore we convert the whole header to either base64 or quoted_printable
00815         if (!$this->dontEncodeHeader && !stristr($header, 'Content-Type') && !stristr($header, 'Content-Transfer-Encoding')) {
00816                 // Field tags must not be encoded
00817             $parts = explode(': ', $header, 2);
00818             if (count($parts) == 2) {
00819                 $enc = $this->alt_base64 ? 'base64' : 'quoted_printable';
00820                 $parts[1] = t3lib_div::encodeHeader($parts[1], $enc, $this->charset);
00821                 $header = implode(': ', $parts);
00822             }
00823         }
00824 
00825         $this->headers .= $header . LF;
00826     }
00827 
00828 
00829     /**
00830      * Adds a line of text to the mail-body. Is normally used internally
00831      *
00832      * @param   string      $msg: the message to add
00833      * @return  void
00834      */
00835     public function add_message($msg) {
00836         $this->message .= $msg . LF;
00837     }
00838 
00839 
00840     /**
00841      * returns the content specified by the type (plain, html etc.)
00842      *
00843      * @param   string      $type: the content type, can either plain or html
00844      * @return  void
00845      */
00846     public function getContent($type) {
00847         return $this->theParts[$type]['content'];
00848     }
00849 
00850 
00851     /**
00852      * shows a preview of the email of the headers and the message
00853      *
00854      * @return  void
00855      */
00856     public function preview() {
00857         echo nl2br(htmlspecialchars($this->headers));
00858         echo "<BR>";
00859         echo nl2br(htmlspecialchars($this->message));
00860     }
00861 
00862 
00863     /****************************************************
00864      *
00865      * Functions for acquiring attachments, HTML, analyzing and so on  **
00866      *
00867      ***************************************************/
00868 
00869     /**
00870      * Fetches the HTML-content from either url og local serverfile
00871      *
00872      * @param   string      $file: the file to load
00873      * @return  boolean     whether the data was fetched or not
00874      */
00875     public function fetchHTML($file) {
00876             // Fetches the content of the page
00877         $this->theParts['html']['content'] = $this->getURL($file);
00878         if ($this->theParts['html']['content']) {
00879             $addr = $this->extParseUrl($file);
00880             $path = ($addr['scheme']) ? $addr['scheme'] . '://' . $addr['host'] . (($addr['port']) ? ':' . $addr['port'] : '') . (($addr['filepath']) ? $addr['filepath'] : '/') : $addr['filepath'];
00881             $this->theParts['html']['path'] = $path;
00882             return TRUE;
00883         } else {
00884             return FALSE;
00885         }
00886     }
00887 
00888 
00889     /**
00890      * Fetches the mediafiles which are found by extractMediaLinks()
00891      *
00892      * @return  void
00893      */
00894     public function fetchHTMLMedia() {
00895         if (!is_array($this->theParts['html']['media']) || !count($this->theParts['html']['media'])) {
00896             return;
00897         }
00898         foreach ($this->theParts['html']['media'] as $key => $media) {
00899                 // fetching the content and the mime-type
00900             $picdata = $this->getExtendedURL($this->theParts['html']['media'][$key]['absRef']);
00901             if (is_array($picdata)) {
00902                 $this->theParts['html']['media'][$key]['content'] = $picdata['content'];
00903                 $this->theParts['html']['media'][$key]['ctype'] = $picdata['content_type'];
00904             }
00905         }
00906     }
00907 
00908 
00909     /**
00910      * extracts all media-links from $this->theParts['html']['content']
00911      *
00912      * @return  void
00913      */
00914     public function extractMediaLinks() {
00915         $html_code = $this->theParts['html']['content'];
00916         $attribRegex = $this->tag_regex(array('img', 'table', 'td', 'tr', 'body', 'iframe', 'script', 'input', 'embed'));
00917 
00918             // split the document by the beginning of the above tags
00919         $codepieces = preg_split($attribRegex, $html_code);
00920         $len = strlen($codepieces[0]);
00921         $pieces = count($codepieces);
00922         $reg = array();
00923         for ($i = 1; $i < $pieces; $i++) {
00924             $tag = strtolower(strtok(substr($html_code, $len + 1, 10), ' '));
00925             $len += strlen($tag) + strlen($codepieces[$i]) + 2;
00926             $dummy = preg_match('/[^>]*/', $codepieces[$i], $reg);
00927             $attributes = $this->get_tag_attributes($reg[0]); // Fetches the attributes for the tag
00928             $imageData = array();
00929 
00930                 // Finds the src or background attribute
00931             $imageData['ref'] = ($attributes['src'] ? $attributes['src'] : $attributes['background']);
00932             if ($imageData['ref']) {
00933                     // find out if the value had quotes around it
00934                 $imageData['quotes'] = (substr($codepieces[$i], strpos($codepieces[$i], $imageData['ref']) - 1, 1) == '"') ? '"' : '';
00935                     // subst_str is the string to look for, when substituting lateron
00936                 $imageData['subst_str'] = $imageData['quotes'] . $imageData['ref'] . $imageData['quotes'];
00937                 if ($imageData['ref'] && !strstr($this->image_fullpath_list, "|" . $imageData["subst_str"] . "|")) {
00938                     $this->image_fullpath_list .= "|" . $imageData['subst_str'] . "|";
00939                     $imageData['absRef'] = $this->absRef($imageData['ref']);
00940                     $imageData['tag'] = $tag;
00941                     $imageData['use_jumpurl'] = $attributes['dmailerping'] ? 1 : 0;
00942                     $this->theParts['html']['media'][] = $imageData;
00943                 }
00944             }
00945         }
00946 
00947             // Extracting stylesheets
00948         $attribRegex = $this->tag_regex(array('link'));
00949             // Split the document by the beginning of the above tags
00950         $codepieces = preg_split($attribRegex, $html_code);
00951         $pieces = count($codepieces);
00952         for ($i = 1; $i < $pieces; $i++) {
00953             $dummy = preg_match('/[^>]*/', $codepieces[$i], $reg);
00954                 // fetches the attributes for the tag
00955             $attributes = $this->get_tag_attributes($reg[0]);
00956             $imageData = array();
00957             if (strtolower($attributes['rel']) == 'stylesheet' && $attributes['href']) {
00958                     // Finds the src or background attribute
00959                 $imageData['ref'] = $attributes['href'];
00960                     // Finds out if the value had quotes around it
00961                 $imageData['quotes'] = (substr($codepieces[$i], strpos($codepieces[$i], $imageData['ref']) - 1, 1) == '"') ? '"' : '';
00962                     // subst_str is the string to look for, when substituting lateron
00963                 $imageData['subst_str'] = $imageData['quotes'] . $imageData['ref'] . $imageData['quotes'];
00964                 if ($imageData['ref'] && !strstr($this->image_fullpath_list, "|" . $imageData["subst_str"] . "|")) {
00965                     $this->image_fullpath_list .= "|" . $imageData["subst_str"] . "|";
00966                     $imageData['absRef'] = $this->absRef($imageData["ref"]);
00967                     $this->theParts['html']['media'][] = $imageData;
00968                 }
00969             }
00970         }
00971 
00972             // fixes javascript rollovers
00973         $codepieces = explode('.src', $html_code);
00974         $pieces = count($codepieces);
00975         $expr = '/^[^' . quotemeta('"') . quotemeta("'") . ']*/';
00976         for ($i = 1; $i < $pieces; $i++) {
00977             $temp = $codepieces[$i];
00978             $temp = trim(str_replace('=', '', trim($temp)));
00979             preg_match($expr, substr($temp, 1, strlen($temp)), $reg);
00980             $imageData['ref'] = $reg[0];
00981             $imageData['quotes'] = substr($temp, 0, 1);
00982                 // subst_str is the string to look for, when substituting lateron
00983             $imageData['subst_str'] = $imageData['quotes'] . $imageData['ref'] . $imageData['quotes'];
00984             $theInfo = $this->split_fileref($imageData['ref']);
00985 
00986             switch ($theInfo['fileext']) {
00987                 case 'gif':
00988                 case 'jpeg':
00989                 case 'jpg':
00990                     if ($imageData['ref'] && !strstr($this->image_fullpath_list, "|" . $imageData["subst_str"] . "|")) {
00991                         $this->image_fullpath_list .= "|" . $imageData['subst_str'] . "|";
00992                         $imageData['absRef'] = $this->absRef($imageData['ref']);
00993                         $this->theParts['html']['media'][] = $imageData;
00994                     }
00995                     break;
00996             }
00997         }
00998     }
00999 
01000 
01001     /**
01002      * extracts all hyper-links from $this->theParts["html"]["content"]
01003      *
01004      * @return  void
01005      */
01006     public function extractHyperLinks() {
01007         $html_code = $this->theParts['html']['content'];
01008         $attribRegex = $this->tag_regex(array('a', 'form', 'area'));
01009         $codepieces = preg_split($attribRegex, $html_code); // Splits the document by the beginning of the above tags
01010         $len = strlen($codepieces[0]);
01011         $pieces = count($codepieces);
01012         for ($i = 1; $i < $pieces; $i++) {
01013             $tag = strtolower(strtok(substr($html_code, $len + 1, 10), " "));
01014             $len += strlen($tag) + strlen($codepieces[$i]) + 2;
01015 
01016             $dummy = preg_match('/[^>]*/', $codepieces[$i], $reg);
01017                 // Fetches the attributes for the tag
01018             $attributes = $this->get_tag_attributes($reg[0]);
01019             $hrefData = array();
01020             $hrefData['ref'] = ($attributes['href'] ? $attributes['href'] : $hrefData['ref'] = $attributes['action']);
01021             if ($hrefData['ref']) {
01022                     // Finds out if the value had quotes around it
01023                 $hrefData['quotes'] = (substr($codepieces[$i], strpos($codepieces[$i], $hrefData["ref"]) - 1, 1) == '"') ? '"' : '';
01024                     // subst_str is the string to look for, when substituting lateron
01025                 $hrefData['subst_str'] = $hrefData['quotes'] . $hrefData['ref'] . $hrefData['quotes'];
01026                 if ($hrefData['ref'] && substr(trim($hrefData['ref']), 0, 1) != "#" && !strstr($this->href_fullpath_list, "|" . $hrefData['subst_str'] . "|")) {
01027                     $this->href_fullpath_list .= "|" . $hrefData['subst_str'] . "|";
01028                     $hrefData['absRef'] = $this->absRef($hrefData['ref']);
01029                     $hrefData['tag'] = $tag;
01030                     $this->theParts['html']['hrefs'][] = $hrefData;
01031                 }
01032             }
01033         }
01034             // Extracts TYPO3 specific links made by the openPic() JS function
01035         $codepieces = explode("onClick=\"openPic('", $html_code);
01036         $pieces = count($codepieces);
01037         for ($i = 1; $i < $pieces; $i++) {
01038             $showpic_linkArr = explode("'", $codepieces[$i]);
01039             $hrefData['ref'] = $showpic_linkArr[0];
01040             if ($hrefData['ref']) {
01041                 $hrefData['quotes'] = "'";
01042                     // subst_str is the string to look for, when substituting lateron
01043                 $hrefData['subst_str'] = $hrefData['quotes'] . $hrefData['ref'] . $hrefData['quotes'];
01044                 if ($hrefData['ref'] && !strstr($this->href_fullpath_list, "|" . $hrefData['subst_str'] . "|")) {
01045                     $this->href_fullpath_list .= "|" . $hrefData['subst_str'] . "|";
01046                     $hrefData['absRef'] = $this->absRef($hrefData['ref']);
01047                     $this->theParts['html']['hrefs'][] = $hrefData;
01048                 }
01049             }
01050         }
01051     }
01052 
01053 
01054     /**
01055      * extracts all media-links from $this->theParts["html"]["content"]
01056      *
01057      * @return  array   two-dimensional array with information about each frame
01058      */
01059     public function extractFramesInfo() {
01060         $htmlCode = $this->theParts['html']['content'];
01061         $info = array();
01062         if (strpos(' ' . $htmlCode, '<frame ')) {
01063             $attribRegex = $this->tag_regex('frame');
01064                 // Splits the document by the beginning of the above tags
01065             $codepieces = preg_split($attribRegex, $htmlCode, 1000000);
01066             $pieces = count($codepieces);
01067             for ($i = 1; $i < $pieces; $i++) {
01068                 $dummy = preg_match('/[^>]*/', $codepieces[$i], $reg);
01069                     // Fetches the attributes for the tag
01070                 $attributes = $this->get_tag_attributes($reg[0]);
01071                 $frame = array();
01072                 $frame['src'] = $attributes['src'];
01073                 $frame['name'] = $attributes['name'];
01074                 $frame['absRef'] = $this->absRef($frame['src']);
01075                 $info[] = $frame;
01076             }
01077             return $info;
01078         }
01079     }
01080 
01081 
01082     /**
01083      * This function substitutes the media-references in $this->theParts["html"]["content"]
01084      *
01085      * @param   boolean     $absolute: If true, then the refs are substituted with http:// ref's indstead of Content-ID's (cid).
01086      * @return  void
01087      */
01088     public function substMediaNamesInHTML($absolute) {
01089         if (is_array($this->theParts['html']['media'])) {
01090             foreach ($this->theParts['html']['media'] as $key => $val) {
01091                 if ($val['use_jumpurl'] && $this->jumperURL_prefix) {
01092                     $subst = $this->jumperURL_prefix . t3lib_div::rawUrlEncodeFP($val['absRef']);
01093                 } else {
01094                     $subst = ($absolute) ? $val['absRef'] : 'cid:part' . $key . '.' . $this->messageid;
01095                 }
01096                 $this->theParts['html']['content'] = str_replace(
01097                     $val['subst_str'],
01098                     $val['quotes'] . $subst . $val['quotes'],
01099                     $this->theParts['html']['content']);
01100             }
01101         }
01102         if (!$absolute) {
01103             $this->fixRollOvers();
01104         }
01105     }
01106 
01107 
01108     /**
01109      * This function substitutes the hrefs in $this->theParts["html"]["content"]
01110      *
01111      * @return  void
01112      */
01113     public function substHREFsInHTML() {
01114         if (!is_array($this->theParts['html']['hrefs'])) {
01115             return;
01116         }
01117         foreach ($this->theParts['html']['hrefs'] as $key => $val) {
01118                 // Form elements cannot use jumpurl!
01119             if ($this->jumperURL_prefix && $val['tag'] != 'form') {
01120                 if ($this->jumperURL_useId) {
01121                     $substVal = $this->jumperURL_prefix . $key;
01122                 } else {
01123                     $substVal = $this->jumperURL_prefix . t3lib_div::rawUrlEncodeFP($val['absRef']);
01124                 }
01125             } else {
01126                 $substVal = $val['absRef'];
01127             }
01128             $this->theParts['html']['content'] = str_replace(
01129                 $val['subst_str'],
01130                 $val['quotes'] . $substVal . $val['quotes'],
01131                 $this->theParts['html']['content']);
01132         }
01133     }
01134 
01135 
01136     /**
01137      *  This substitutes the http:// urls in plain text with links
01138      *
01139      * @param   string      $content: the content to use to substitute
01140      * @return  string      the changed content
01141      */
01142     public function substHTTPurlsInPlainText($content) {
01143         if (!$this->jumperURL_prefix) {
01144             return $content;
01145         }
01146 
01147         $textpieces = explode("http://", $content);
01148         $pieces = count($textpieces);
01149         $textstr = $textpieces[0];
01150         for ($i = 1; $i < $pieces; $i++) {
01151             $len = strcspn($textpieces[$i], chr(32) . TAB . CRLF);
01152             if (trim(substr($textstr, -1)) == '' && $len) {
01153                 $lastChar = substr($textpieces[$i], $len - 1, 1);
01154                 if (!preg_match('/[A-Za-z0-9\/#]/', $lastChar)) {
01155                     $len--;
01156                 }
01157 
01158                 $parts = array();
01159                 $parts[0] = "http://" . substr($textpieces[$i], 0, $len);
01160                 $parts[1] = substr($textpieces[$i], $len);
01161 
01162                 if ($this->jumperURL_useId) {
01163                     $this->theParts['plain']['link_ids'][$i] = $parts[0];
01164                     $parts[0] = $this->jumperURL_prefix . '-' . $i;
01165                 } else {
01166                     $parts[0] = $this->jumperURL_prefix . t3lib_div::rawUrlEncodeFP($parts[0]);
01167                 }
01168                 $textstr .= $parts[0] . $parts[1];
01169             } else {
01170                 $textstr .= 'http://' . $textpieces[$i];
01171             }
01172         }
01173         return $textstr;
01174     }
01175 
01176 
01177     /**
01178      * JavaScript rollOvers cannot support graphics inside of mail.
01179      * If these exists we must let them refer to the absolute url. By the way:
01180      * Roll-overs seems to work only on some mail-readers and so far I've seen it
01181      * work on Netscape 4 message-center (but not 4.5!!)
01182      *
01183      * @return  void
01184      */
01185     public function fixRollOvers() {
01186         $newContent = '';
01187         $items = explode('.src', $this->theParts['html']['content']);
01188         if (count($items) <= 1) {
01189             return;
01190         }
01191 
01192         foreach ($items as $key => $part) {
01193             $sub = substr($part, 0, 200);
01194             if (preg_match('/cid:part[^ "\']*/', $sub, $reg)) {
01195                     // The position of the string
01196                 $thePos = strpos($part, $reg[0]);
01197                     // Finds the id of the media...
01198                 preg_match('/cid:part([^\.]*).*/', $sub, $reg2);
01199                 $theSubStr = $this->theParts['html']['media'][intval($reg2[1])]['absRef'];
01200                 if ($thePos && $theSubStr) {
01201                         // ... and substitutes the javaScript rollover image with this instead
01202                         // If the path is NOT and url, the reference is set to nothing
01203                     if (!strpos(' ' . $theSubStr, 'http://')) {
01204                         $theSubStr = 'http://';
01205                     }
01206                     $part = substr($part, 0, $thePos) . $theSubStr . substr($part, $thePos + strlen($reg[0]), strlen($part));
01207                 }
01208             }
01209             $newContent .= $part . ((($key + 1) != count($items)) ? '.src' : '');
01210         }
01211         $this->theParts['html']['content'] = $newContent;
01212     }
01213 
01214 
01215     /*******************************************
01216      *
01217      * File and URL-functions
01218      *
01219      *******************************************/
01220 
01221     /**
01222      * Returns base64-encoded content, which is broken every 76 character
01223      *
01224      * @param   string      $inputstr: the string to encode
01225      * @return  string      the encoded string
01226      */
01227     public function makeBase64($inputstr) {
01228         return chunk_split(base64_encode($inputstr));
01229     }
01230 
01231 
01232     /**
01233      * reads the URL or file and determines the Content-type by either guessing or opening a connection to the host
01234      *
01235      * @param   string      $url: the URL to get information of
01236      * @return  mixed       either false or the array with information
01237      */
01238     public function getExtendedURL($url) {
01239         $res = array();
01240         $res['content'] = $this->getURL($url);
01241         if (!$res['content']) {
01242             return FALSE;
01243         }
01244         $pathInfo = parse_url($url);
01245         $fileInfo = $this->split_fileref($pathInfo['path']);
01246         switch ($fileInfo['fileext']) {
01247             case 'gif':
01248             case 'png':
01249                 $res['content_type'] = 'image/' . $fileInfo['fileext'];
01250                 break;
01251             case 'jpg':
01252             case 'jpeg':
01253                 $res['content_type'] = 'image/jpeg';
01254                 break;
01255             case 'html':
01256             case 'htm':
01257                 $res['content_type'] = 'text/html';
01258                 break;
01259             case 'css':
01260                 $res['content_type'] = 'text/css';
01261                 break;
01262             case 'swf':
01263                 $res['content_type'] = 'application/x-shockwave-flash';
01264                 break;
01265             default:
01266                 $res['content_type'] = $this->getMimeType($url);
01267         }
01268         return $res;
01269     }
01270 
01271 
01272     /**
01273      * Adds HTTP user and password (from $this->http_username) to a URL
01274      *
01275      * @param   string      $url: the URL
01276      * @return  string      the URL with the added values
01277      */
01278     public function addUserPass($url) {
01279         $user = $this->http_username;
01280         $pass = $this->http_password;
01281         $matches = array();
01282         if ($user && $pass && preg_match('/^(https?:\/\/)/', $url, $matches)) {
01283             return $matches[1] . $user . ':' . $pass . '@' . substr($url, strlen($matches[1]));
01284         }
01285         return $url;
01286     }
01287 
01288 
01289     /**
01290      * reads a url or file
01291      *
01292      * @param   string      $url: the URL to fetch
01293      * @return  string      the content of the URL
01294      */
01295     public function getURL($url) {
01296         $url = $this->addUserPass($url);
01297         return t3lib_div::getURL($url);
01298     }
01299 
01300 
01301     /**
01302      * reads a url or file and strips the HTML-tags AND removes all
01303      * empty lines. This is used to read plain-text out of a HTML-page
01304      *
01305      * @param   string      $url: the URL to load
01306      * @return  the content
01307      */
01308     public function getStrippedURL($url) {
01309         $content = '';
01310         if ($fd = fopen($url, "rb")) {
01311             while (!feof($fd)) {
01312                 $line = fgetss($fd, 5000);
01313                 if (trim($line)) {
01314                     $content .= trim($line) . LF;
01315                 }
01316             }
01317             fclose($fd);
01318         }
01319         return $content;
01320     }
01321 
01322 
01323     /**
01324      * This function returns the mime type of the file specified by the url
01325      *
01326      * @param   string      $url: the url
01327      * @return  string      $mimeType: the mime type found in the header
01328      */
01329     public function getMimeType($url) {
01330         $mimeType = '';
01331         $headers = trim(t3lib_div::getURL($url, 2));
01332         if ($headers) {
01333             $matches = array();
01334             if (preg_match('/(Content-Type:[\s]*)([a-zA-Z_0-9\/\-\.\+]*)([\s]|$)/', $headers, $matches)) {
01335                 $mimeType = trim($matches[2]);
01336             }
01337         }
01338         return $mimeType;
01339     }
01340 
01341 
01342     /**
01343      * Returns the absolute address of a link. This is based on
01344      * $this->theParts["html"]["path"] being the root-address
01345      *
01346      * @param   string      $ref: address to use
01347      * @return  string      the absolute address
01348      */
01349     public function absRef($ref) {
01350         $ref = trim($ref);
01351         $info = parse_url($ref);
01352         if ($info['scheme']) {
01353             return $ref;
01354         } elseif (preg_match('/^\//', $ref)) {
01355             $addr = parse_url($this->theParts['html']['path']);
01356             return $addr['scheme'] . '://' . $addr['host'] . ($addr['port'] ? ':' . $addr['port'] : '') . $ref;
01357         } else {
01358                 // If the reference is relative, the path is added, in order for us to fetch the content
01359             return $this->theParts['html']['path'] . $ref;
01360         }
01361     }
01362 
01363 
01364     /**
01365      * Returns information about a file reference
01366      *
01367      * @param   string      $fileref: the file to use
01368      * @return  array       path, filename, filebody, fileext
01369      */
01370     public function split_fileref($fileref) {
01371         $info = array();
01372         if (preg_match('/(.*\/)(.*)$/', $fileref, $reg)) {
01373             $info['path'] = $reg[1];
01374             $info['file'] = $reg[2];
01375         } else {
01376             $info['path'] = '';
01377             $info['file'] = $fileref;
01378         }
01379         $reg = '';
01380         if (preg_match('/(.*)\.([^\.]*$)/', $info['file'], $reg)) {
01381             $info['filebody'] = $reg[1];
01382             $info['fileext'] = strtolower($reg[2]);
01383             $info['realFileext'] = $reg[2];
01384         } else {
01385             $info['filebody'] = $info['file'];
01386             $info['fileext'] = '';
01387         }
01388         return $info;
01389     }
01390 
01391 
01392     /**
01393      * Returns an array with file or url-information
01394      *
01395      * @param   string      $path: url to check
01396      * @return  array       information about the path / URL
01397      */
01398     public function extParseUrl($path) {
01399         $res = parse_url($path);
01400         preg_match('/(.*\/)([^\/]*)$/', $res['path'], $reg);
01401         $res['filepath'] = $reg[1];
01402         $res['filename'] = $reg[2];
01403         return $res;
01404     }
01405 
01406 
01407     /**
01408      * Creates a regular expression out of a list of tags
01409      *
01410      * @param   mixed       $tagArray: the list of tags (either as array or string if it is one tag)
01411      * @return  string      the regular expression
01412      */
01413     public function tag_regex($tags) {
01414         $tags = (!is_array($tags) ? array($tags) : $tags);
01415         $regexp = '/';
01416         $c = count($tags);
01417         foreach ($tags as $tag) {
01418             $c--;
01419             $regexp .= '<' . $tag . '[[:space:]]' . (($c) ? '|' : '');
01420         }
01421         return $regexp . '/i';
01422     }
01423 
01424 
01425     /**
01426      * This function analyzes a HTML tag
01427      * If an attribute is empty (like OPTION) the value of that key is just empty. Check it with is_set();
01428      *
01429      * @param   string      $tag: is either like this "<TAG OPTION ATTRIB=VALUE>" or
01430      *               this " OPTION ATTRIB=VALUE>" which means you can omit the tag-name
01431      * @return  array       array with attributes as keys in lower-case
01432      */
01433     public function get_tag_attributes($tag) {
01434         $attributes = array();
01435         $tag = ltrim(preg_replace('/^<[^ ]*/', '', trim($tag)));
01436         $tagLen = strlen($tag);
01437         $safetyCounter = 100;
01438             // Find attribute
01439         while ($tag) {
01440             $value = '';
01441             $reg = preg_split('/[[:space:]=>]/', $tag, 2);
01442             $attrib = $reg[0];
01443 
01444             $tag = ltrim(substr($tag, strlen($attrib), $tagLen));
01445             if (substr($tag, 0, 1) == '=') {
01446                 $tag = ltrim(substr($tag, 1, $tagLen));
01447                 if (substr($tag, 0, 1) == '"') {
01448                         // Quotes around the value
01449                     $reg = explode('"', substr($tag, 1, $tagLen), 2);
01450                     $tag = ltrim($reg[1]);
01451                     $value = $reg[0];
01452                 } else {
01453                         // No quotes around value
01454                     preg_match('/^([^[:space:]>]*)(.*)/', $tag, $reg);
01455                     $value = trim($reg[1]);
01456                     $tag = ltrim($reg[2]);
01457                     if (substr($tag, 0, 1) == '>') {
01458                         $tag = '';
01459                     }
01460                 }
01461             }
01462             $attributes[strtolower($attrib)] = $value;
01463             $safetyCounter--;
01464             if ($safetyCounter < 0) {
01465                 break;
01466             }
01467         }
01468         return $attributes;
01469     }
01470 }
01471 
01472 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_htmlmail.php'])) {
01473     include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_htmlmail.php']);
01474 }
01475 
01476 ?>