[BUGFIX] Use t3lib_cache_frontend_VariableFrontend as fallback frontend
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_htmlmail.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * HTML mail class
29 *
30 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
31 */
32 /**
33 * [CLASS/FUNCTION INDEX of SCRIPT]
34 *
35 *
36 *
37 * 193: class t3lib_htmlmail
38 * 261: function t3lib_htmlmail ()
39 * 268: function start ()
40 * 305: function useQuotedPrintable()
41 * 315: function useBase64()
42 * 326: function use8Bit()
43 * 338: function encodeMsg($content)
44 * 348: function addPlain ($content)
45 * 360: function addAttachment($file)
46 * 378: function addHTML ($file)
47 * 401: function extractHtmlInit($html,$url)
48 * 412: function send($recipient)
49 *
50 * SECTION: Main functions
51 * 441: function setHeaders()
52 * 500: function setRecipient ($recip)
53 * 518: function getHTMLContentType()
54 * 527: function setContent()
55 * 554: function constructMixed ($boundary)
56 * 593: function constructHTML ($boundary)
57 * 617: function constructAlternative($boundary)
58 * 638: function constructHTML_media ($boundary)
59 * 691: function sendTheMail ()
60 * 757: function getBoundary()
61 * 769: function setPlain ($content)
62 * 780: function setHtml ($content)
63 * 791: function add_header($header)
64 * 812: function add_message($string)
65 * 823: function getContent($type)
66 * 832: function preview()
67 *
68 * SECTION: Functions for acquiring attachments, HTML, analyzing and so on **
69 * 860: function fetchHTML($file)
70 * 878: function fetchHTMLMedia()
71 * 899: function extractMediaLinks()
72 * 976: function extractHyperLinks()
73 * 1025: function extractFramesInfo()
74 * 1051: function substMediaNamesInHTML($absolute)
75 * 1078: function substHREFsInHTML()
76 * 1106: function substHTTPurlsInPlainText($content)
77 * 1142: function fixRollOvers()
78 *
79 * SECTION: File and URL-functions
80 * 1189: function makeBase64($inputstr)
81 * 1200: function getExtendedURL($url)
82 * 1222: function addUserPass($url)
83 * 1238: function getURL($url)
84 * 1250: function getStrippedURL($url)
85 * 1271: function getMimeType($url)
86 * 1300: function absRef($ref)
87 * 1320: function split_fileref($fileref)
88 * 1347: function extParseUrl($path)
89 * 1362: function tag_regex($tagArray)
90 * 1384: function get_tag_attributes($tag)
91 * 1426: function quoted_printable($string)
92 * 1437: function convertName($name)
93 *
94 * TOTAL FUNCTIONS: 49
95 * (This index is automatically created/updated by the extension "extdeveval")
96 *
97 */
98 /**
99 * NOTES on MIME mail structures:
100 *
101 * Plain + HTML
102 * multipart/alternative (text, html)
103 * multipart/alternative (text, html)
104 *
105 * Plain + HTML + image
106 * multipart/related (m/a, cids)
107 * multipart/alternative (text, html)
108 *
109 * multipart/related (m/a, cids)
110 * multipart/alternative (text, html)
111 *
112 * plain + attachment
113 * multipart/mixed
114 *
115 * HTML + Attachment:
116 * multipart/mixed (text/html , attachments)
117 *
118 * Plain + HTML + Attachments:
119 * multipart/mixed (m/a, attachments)
120 * multipart/alternative (text, html)
121 *
122 * Plain + HTML + image + attachment
123 *
124 * Outlook expr.
125 * multipart/mixed (m/r, attachments)
126 * multipart/related (m/a, cids)
127 * multipart/alternative (text, html)
128 *
129 *
130 *
131 * FROM RFC 1521:
132 *
133 * 5.1 Quoted-Printable Content-Transfer-Encoding
134 * 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.
135 *
136 * In this encoding, octets are to be represented as determined by the following rules:
137 * 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.
138 * 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).
139 * 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
140 * "=" 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.
141 * 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.
142 * 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.
143 * 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:
144 * Now's the time for all folk to come to the aid of their country.
145 *
146 * This can be represented, in the Quoted-Printable encoding, as
147 *
148 * Now's the time =
149 * for all folk to come=
150 * to the aid of their country.
151 *
152 * 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.
153 * 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.)
154 * 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
155 * !"#$@[\]^`{|}~
156 * according to rule #1. See Appendix B for more information.
157 * 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.
158 * 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
159 * platforms with different line break conventions.
160 * For formalists, the syntax of quoted-printable data is described by the following grammar:
161 *
162 * quoted-printable := ([*(ptext / SPACE / TAB) ptext] ["="] CRLF)
163 * ; Maximum line length of 76 characters excluding CRLF
164 *
165 * ptext := octet /<any ASCII character except "=", SPACE, or TAB>
166 * ; characters not listed as "mail-safe" in Appendix B
167 * ; are also not recommended.
168 *
169 * octet := "=" 2(DIGIT / "A" / "B" / "C" / "D" / "E" / "F")
170 * ; octet must be used for characters > 127, =, SPACE, or TAB,
171 * ; and is recommended for any characters not listed in
172 * ; Appendix B as "mail-safe".
173 */
174 /**
175 * HTML mail class
176 *
177 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
178 * @package TYPO3
179 * @subpackage t3lib
180 */
181 class t3lib_htmlmail {
182 // Headerinfo:
183 var $recipient = '';
184 var $recipient_copy = ''; // This recipient (or list of...) will also receive the mail. Regard it as a copy.
185 var $recipient_blindcopy = ''; // This recipient (or list of...) will also receive the mail as a blind copy. Regard it as a copy.
186 var $subject = '';
187 var $from_email = '';
188 var $from_name = '';
189 var $replyto_email = '';
190 var $replyto_name = '';
191 var $organisation = '';
192 var $priority = 3; // 1 = highest, 5 = lowest, 3 = normal
193 var $mailer = ''; // X-mailer, set to TYPO3 Major.Minor in constructor
194 var $alt_base64 = 0;
195 var $alt_8bit = 0;
196 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.
197 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
198 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
199 var $http_password = '';
200 var $http_username = '';
201 var $postfix_version1 = FALSE;
202
203 // Internal
204 /*
205 This is how the $theParts-array is normally looking
206 var $theParts = array(
207 'plain' => array(
208 'content' => ''
209 ),
210 'html' => array(
211 'content' => '',
212 'path' => '',
213 'media' => array(),
214 'hrefs' => array()
215 ),
216 'attach' => array()
217 );
218 */
219 var $theParts = array();
220
221 var $messageid = '';
222 var $returnPath = '';
223 var $Xid = '';
224 var $dontEncodeHeader = FALSE; // If set, the header will not be encoded
225
226 var $headers = '';
227 var $message = '';
228 var $part = 0;
229 var $image_fullpath_list = '';
230 var $href_fullpath_list = '';
231
232 var $plain_text_header = '';
233 var $html_text_header = '';
234 var $charset = '';
235 var $defaultCharset = 'iso-8859-1';
236
237
238 /**
239 * Constructor. If the configuration variable forceReturnPath is set,
240 * calls to mail will be called with a 5th parameter.
241 * See function sendTheMail for more info
242 *
243 * @return void
244 */
245 public function __construct() {
246 t3lib_div::logDeprecatedFunction();
247 $this->forceReturnPath = $GLOBALS['TYPO3_CONF_VARS']['SYS']['forceReturnPath'];
248
249 $this->mailer = 'TYPO3';
250 }
251
252
253 /**
254 * start action that sets the message ID and the charset
255 *
256 * @return void
257 */
258 public function start() {
259 global $TYPO3_CONF_VARS;
260
261 // Sets the message id
262 $host = t3lib_div::getHostname();
263 if (!$host || $host == '127.0.0.1' || $host == 'localhost' || $host == 'localhost.localdomain') {
264 $host = ($TYPO3_CONF_VARS['SYS']['sitename'] ? preg_replace('/[^A-Za-z0-9_\-]/', '_', $TYPO3_CONF_VARS['SYS']['sitename']) : 'localhost') . '.TYPO3';
265 }
266
267 $idLeft = time() . '.' . uniqid();
268 $idRight = !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'swift.generated';
269 $this->messageid = $idLeft . '@' . $idRight;
270
271 // Default line break for Unix systems.
272 $this->linebreak = LF;
273 // Line break for Windows. This is needed because PHP on Windows systems
274 // send mails via SMTP instead of using sendmail, and thus the linebreak needs to be \r\n.
275 if (TYPO3_OS == 'WIN') {
276 $this->linebreak = CRLF;
277 }
278
279 // Sets the Charset
280 if (!$this->charset) {
281 if (is_object($GLOBALS['TSFE']) && $GLOBALS['TSFE']->renderCharset) {
282 $this->charset = $GLOBALS['TSFE']->renderCharset;
283 } elseif (is_object($GLOBALS['LANG']) && $GLOBALS['LANG']->charSet) {
284 $this->charset = $GLOBALS['LANG']->charSet;
285 } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
286 $this->charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
287 } else {
288 $this->charset = $this->defaultCharset;
289 }
290 }
291
292 // Use quoted-printable headers by default
293 $this->useQuotedPrintable();
294 }
295
296
297 /**
298 * sets the header of both Plain Text and HTML mails to quoted printable
299 *
300 * @return void
301 */
302 public function useQuotedPrintable() {
303 $this->plain_text_header = 'Content-Type: text/plain; charset=' . $this->charset . $this->linebreak . 'Content-Transfer-Encoding: quoted-printable';
304 $this->html_text_header = 'Content-Type: text/html; charset=' . $this->charset . $this->linebreak . 'Content-Transfer-Encoding: quoted-printable';
305 }
306
307 /**
308 * sets the encoding headers to base64 for both the Plain Text and HTML mail
309 *
310 * @return void
311 */
312 public function useBase64() {
313 $this->plain_text_header = 'Content-Type: text/plain; charset=' . $this->charset . $this->linebreak . 'Content-Transfer-Encoding: base64';
314 $this->html_text_header = 'Content-Type: text/html; charset=' . $this->charset . $this->linebreak . 'Content-Transfer-Encoding: base64';
315 $this->alt_base64 = 1;
316 }
317
318
319 /**
320 * sets the encoding to 8bit and the current charset of both the Plain Text and the HTML mail
321 *
322 * @return void
323 */
324 public function use8Bit() {
325 $this->plain_text_header = 'Content-Type: text/plain; charset=' . $this->charset . $this->linebreak . 'Content-Transfer-Encoding: 8bit';
326 $this->html_text_header = 'Content-Type: text/html; charset=' . $this->charset . $this->linebreak . 'Content-Transfer-Encoding: 8bit';
327 $this->alt_8bit = 1;
328 }
329
330
331 /**
332 * Encodes the message content according to the options "alt_base64" and "alt_8bit" (no need to encode here)
333 * or to "quoted_printable" if no option is set.
334 *
335 * @param string $content the content that will be encoded
336 * @return string the encoded content
337 */
338 public function encodeMsg($content) {
339 if ($this->alt_base64) {
340 return $this->makeBase64($content);
341 } elseif ($this->alt_8bit) {
342 return $content;
343 } else {
344 return t3lib_div::quoted_printable($content);
345 }
346 }
347
348
349 /**
350 * Adds plain-text, replaces the HTTP urls in the plain text and then encodes it
351 *
352 * @param string $content that will be added
353 * @return void
354 */
355 public function addPlain($content) {
356 $content = $this->substHTTPurlsInPlainText($content);
357 $this->setPlain($this->encodeMsg($content));
358 }
359
360
361 /**
362 * Adds an attachment to the mail
363 *
364 * @param string $file: the filename to add
365 * @return boolean whether the attachment was added or not
366 */
367 public function addAttachment($file) {
368 // Fetching the content and the mime-type
369 $fileInfo = $this->getExtendedURL($file);
370 if ($fileInfo) {
371 if (!$fileInfo['content_type']) {
372 $fileInfo['content_type'] = 'application/octet-stream';
373 }
374 $temp = $this->split_fileref($file);
375 if ($temp['file']) {
376 $fileInfo['filename'] = $temp['file'];
377 } elseif (strpos(' ' . $fileInfo['content_type'], 'htm')) {
378 $fileInfo['filename'] = 'index.html';
379 } else {
380 $fileInfo['filename'] = 'unknown';
381 }
382 $this->theParts['attach'][] = $fileInfo;
383 return TRUE;
384 }
385 return FALSE;
386 }
387
388
389 /**
390 * Adds HTML and media, encodes it from a URL or file
391 *
392 * @param string $file: the filename to add
393 * @return boolean whether the attachment was added or not
394 */
395 public function addHTML($file) {
396 $status = $this->fetchHTML($file);
397 if (!$status) {
398 return FALSE;
399 }
400 if ($this->extractFramesInfo()) {
401 return 'Document was a frameset. Stopped';
402 }
403 $this->extractMediaLinks();
404 $this->extractHyperLinks();
405 $this->fetchHTMLMedia();
406 $this->substMediaNamesInHTML(0); // 0 = relative
407 $this->substHREFsInHTML();
408 $this->setHtml($this->encodeMsg($this->theParts['html']['content']));
409 }
410
411
412 /**
413 * Extract HTML-parts, used externally
414 *
415 * @param string $html: will be added to the html "content" part
416 * @param string $url: will be added to the html "path" part
417 * @return void
418 */
419 public function extractHtmlInit($html, $url) {
420 $this->theParts['html']['content'] = $html;
421 $this->theParts['html']['path'] = $url;
422 }
423
424
425 /**
426 * Assembles the message by headers and content and finally send it to the provided recipient.
427 *
428 * @param string $recipient: The recipient the message should be delivered to (if blank, $this->recipient will be used instead)
429 * @return boolean Returns whether the mail was sent (successfully accepted for delivery)
430 */
431 public function send($recipient) {
432 if ($recipient) {
433 $this->recipient = $recipient;
434 }
435 $this->setHeaders();
436 $this->setContent();
437 $mailWasSent = $this->sendTheMail();
438 return $mailWasSent;
439 }
440
441
442 /*****************************************
443 *
444 * Main functions
445 *
446 *****************************************/
447
448 /**
449 * Clears the header-string and sets the headers based on object-vars.
450 *
451 * @return void
452 */
453 public function setHeaders() {
454 $this->headers = '';
455 // Message_id
456 $this->add_header('Message-ID: <' . $this->messageid . '>');
457 // Return path
458 if ($this->returnPath) {
459 $this->add_header('Return-Path: ' . $this->returnPath);
460 $this->add_header('Errors-To: ' . $this->returnPath);
461 }
462 // X-id
463 if ($this->Xid) {
464 $this->add_header('X-Typo3MID: ' . $this->Xid);
465 }
466
467 // From
468 if ($this->from_email) {
469 if ($this->from_name && !t3lib_div::isBrokenEmailEnvironment()) {
470 $this->add_header('From: ' . $this->from_name . ' <' . $this->from_email . '>');
471 } else {
472 $this->add_header('From: ' . $this->from_email);
473 }
474 }
475
476 // Cc
477 if ($this->recipient_copy) {
478 $this->add_header('Cc: ' . $this->recipient_copy);
479 }
480
481 // Bcc
482 if ($this->recipient_blindcopy) {
483 $this->add_header('Bcc: ' . $this->recipient_blindcopy);
484 }
485
486 // Reply
487 if ($this->replyto_email) {
488 if ($this->replyto_name) {
489 $this->add_header('Reply-To: ' . $this->replyto_name . ' <' . $this->replyto_email . '>');
490 } else {
491 $this->add_header('Reply-To: ' . $this->replyto_email);
492 }
493 }
494 // Organization, using american english spelling (organization / organisation) as defined in RFC 1036 / 2076
495 if ($this->organisation) {
496 $this->add_header('Organization: ' . $this->organisation);
497 }
498 // mailer
499 if ($this->mailer) {
500 $this->add_header('X-Mailer: ' . $this->mailer);
501 }
502 // priority
503 if ($this->priority) {
504 $this->add_header('X-Priority: ' . $this->priority);
505 }
506 $this->add_header('Mime-Version: 1.0');
507
508 if (!$this->dontEncodeHeader) {
509 $enc = $this->alt_base64 ? 'base64' : 'quoted_printable'; // Header must be ASCII, therefore only base64 or quoted_printable are allowed!
510 // Quote recipient and subject
511 $this->recipient = t3lib_div::encodeHeader($this->recipient, $enc, $this->charset);
512 $this->subject = t3lib_div::encodeHeader($this->subject, $enc, $this->charset);
513 }
514 }
515
516
517 /**
518 * Sets the recipient(s). If you supply a string, you set one recipient.
519 * If you supply an array, every value is added as a recipient.
520 *
521 * @param mixed $recipient: the recipient(s) to set
522 * @return void
523 */
524 public function setRecipient($recipient) {
525 $this->recipient = (is_array($recipient) ? implode(',', $recipient) : $recipient);
526 }
527
528
529 /**
530 * Returns the content type based on whether the mail has media / attachments or no
531 *
532 * @return string the content type
533 */
534 public function getHTMLContentType() {
535 return (count($this->theParts['html']['media']) ? 'multipart/related' : 'multipart/alternative');
536 }
537
538
539 /**
540 * Begins building the message-body
541 *
542 * @return void
543 */
544 public function setContent() {
545 $this->message = '';
546 $boundary = $this->getBoundary();
547
548 // Setting up headers
549 if (count($this->theParts['attach'])) {
550 // Generate (plain/HTML) / attachments
551 $this->add_header('Content-Type: multipart/mixed;');
552 $this->add_header(' boundary="' . $boundary . '"');
553 $this->add_message('This is a multi-part message in MIME format.' . LF);
554 $this->constructMixed($boundary);
555 } elseif ($this->theParts['html']['content']) {
556 // Generate plain/HTML mail
557 $this->add_header('Content-Type: ' . $this->getHTMLContentType() . ';');
558 $this->add_header(' boundary="' . $boundary . '"');
559 $this->add_message('This is a multi-part message in MIME format.' . LF);
560 $this->constructHTML($boundary);
561 } else {
562 // Generate plain only
563 $this->add_header($this->plain_text_header);
564 $this->add_message($this->getContent('plain'));
565 }
566 }
567
568
569 /**
570 * This functions combines the plain / HTML content with the attachments
571 *
572 * @param string $boundary: the mail boundary
573 * @return void
574 */
575 public function constructMixed($boundary) {
576 $this->add_message('--' . $boundary);
577
578 if ($this->theParts['html']['content']) {
579 // HTML and plain is added
580 $newBoundary = $this->getBoundary();
581 $this->add_message('Content-Type: ' . $this->getHTMLContentType() . ';');
582 $this->add_message(' boundary="' . $newBoundary . '"');
583 $this->add_message('');
584 $this->constructHTML($newBoundary);
585 } else {
586 // Purely plain
587 $this->add_message($this->plain_text_header);
588 $this->add_message('');
589 $this->add_message($this->getContent('plain'));
590 }
591 // attachments are added
592 if (is_array($this->theParts['attach'])) {
593 foreach ($this->theParts['attach'] as $media) {
594 $this->add_message('--' . $boundary);
595 $this->add_message('Content-Type: ' . $media['content_type'] . ';');
596 $this->add_message(' name="' . $media['filename'] . '"');
597 $this->add_message('Content-Transfer-Encoding: base64');
598 $this->add_message('Content-Disposition: attachment;');
599 $this->add_message(' filename="' . $media['filename'] . '"');
600 $this->add_message('');
601 $this->add_message($this->makeBase64($media['content']));
602 }
603 }
604 $this->add_message('--' . $boundary . '--' . LF);
605 }
606
607
608 /**
609 * this function creates the HTML part of the mail
610 *
611 * @param string $boundary: the boundary to use
612 * @return void
613 */
614 public function constructHTML($boundary) {
615 // If media, then we know, the multipart/related content-type has been set before this function call
616 if (count($this->theParts['html']['media'])) {
617 $this->add_message('--' . $boundary);
618 // HTML has media
619 $newBoundary = $this->getBoundary();
620 $this->add_message('Content-Type: multipart/alternative;');
621 $this->add_message(' boundary="' . $newBoundary . '"');
622 $this->add_message('Content-Transfer-Encoding: 7bit');
623 $this->add_message('');
624
625 // Adding the plaintext/html mix, and use $newBoundary
626 $this->constructAlternative($newBoundary);
627 $this->constructHTML_media($boundary);
628 } else {
629 // if no media, just use the $boundary for adding plaintext/html mix
630 $this->constructAlternative($boundary);
631 }
632 }
633
634
635 /**
636 * Here plain is combined with HTML
637 *
638 * @param string $boundary: the boundary to use
639 * @return void
640 */
641 public function constructAlternative($boundary) {
642 $this->add_message('--' . $boundary);
643
644 // plain is added
645 $this->add_message($this->plain_text_header);
646 $this->add_message('');
647 $this->add_message($this->getContent('plain'));
648 $this->add_message('--' . $boundary);
649
650 // html is added
651 $this->add_message($this->html_text_header);
652 $this->add_message('');
653 $this->add_message($this->getContent('html'));
654 $this->add_message('--' . $boundary . '--' . LF);
655 }
656
657
658 /**
659 * Constructs the HTML-part of message if the HTML contains media
660 *
661 * @param string $boundary: the boundary to use
662 * @return void
663 */
664 public function constructHTML_media($boundary) {
665 // media is added
666 if (is_array($this->theParts['html']['media'])) {
667 foreach ($this->theParts['html']['media'] as $key => $media) {
668 if (!$this->mediaList || t3lib_div::inList($this->mediaList, $key)) {
669 $this->add_message('--' . $boundary);
670 $this->add_message('Content-Type: ' . $media['ctype']);
671 $this->add_message('Content-ID: <part' . $key . '.' . $this->messageid . '>');
672 $this->add_message('Content-Transfer-Encoding: base64');
673 $this->add_message('');
674 $this->add_message($this->makeBase64($media['content']));
675 }
676 }
677 }
678 $this->add_message('--' . $boundary . '--' . LF);
679 }
680
681
682 /**
683 * Sends the mail by calling the mail() function in php. On Linux systems this will invoke the MTA
684 * defined in php.ini (sendmail -t -i by default), on Windows a SMTP must be specified in the sys.ini.
685 * Most common MTA's on Linux has a Sendmail interface, including Postfix and Exim.
686 * For setting the return-path correctly, the parameter -f has to be added to the system call to sendmail.
687 * This obviously does not have any effect on Windows, but on Sendmail compliant systems this works. If safe mode
688 * is enabled, then extra parameters is not allowed, so a safe mode check is made before the mail() command is
689 * invoked. When using the -f parameter, some MTA's will put an X-AUTHENTICATION-WARNING saying that
690 * the return path was modified manually with the -f flag. To disable this warning make sure that the user running
691 * Apache is in the /etc/mail/trusted-users table.
692 *
693 * POSTFIX: With postfix version below 2.0 there is a problem that the -f parameter can not be used in conjunction
694 * with -t. Postfix will give an error in the maillog:
695 *
696 * cannot handle command-line recipients with -t
697 *
698 * The -f parameter is only enabled if the parameter forceReturnPath is enabled in the install tool.
699 *
700 * This whole problem of return-path turns out to be quite tricky. If you have a solution that works better, on all
701 * standard MTA's then we are very open for suggestions.
702 *
703 * With time this function should be made such that several ways of sending the mail is possible (local MTA, smtp other).
704 *
705 * @return boolean Returns whether the mail was sent (successfully accepted for delivery)
706 */
707 public function sendTheMail() {
708 $mailWasSent = FALSE;
709
710 // Sending the mail requires the recipient and message to be set.
711 if (!trim($this->recipient) || !trim($this->message)) {
712 return FALSE;
713 }
714
715 // On windows the -f flag is not used (specific for Sendmail and Postfix),
716 // but instead the php.ini parameter sendmail_from is used.
717 $returnPath = ($this->forceReturnPath && strlen($this->returnPath) > 0) ? '-f ' . escapeshellarg($this->returnPath) : '';
718 if (TYPO3_OS == 'WIN' && $this->returnPath) {
719 @ini_set('sendmail_from', t3lib_div::normalizeMailAddress($this->returnPath));
720 }
721 $recipient = t3lib_div::normalizeMailAddress($this->recipient);
722
723 if ($this->forceReturnPath) {
724 $mailWasSent = t3lib_utility_Mail::mail(
725 $recipient,
726 $this->subject,
727 $this->message,
728 $this->headers,
729 $returnPath
730 );
731 } else {
732 $mailWasSent = t3lib_utility_Mail::mail(
733 $recipient,
734 $this->subject,
735 $this->message,
736 $this->headers
737 );
738 }
739
740 // Auto response
741 if ($this->auto_respond_msg) {
742 $theParts = explode('/', $this->auto_respond_msg, 2);
743 $theParts[0] = str_replace('###SUBJECT###', $this->subject, $theParts[0]);
744 $theParts[1] = str_replace("/", LF, $theParts[1]);
745 $theParts[1] = str_replace("###MESSAGE###", $this->getContent('plain'), $theParts[1]);
746 if ($this->forceReturnPath) {
747 $mailWasSent = t3lib_utility_Mail::mail(
748 $this->from_email,
749 $theParts[0],
750 $theParts[1],
751 'From: ' . $recipient . $this->linebreak . $this->plain_text_header,
752 $returnPath
753 );
754 } else {
755 $mailWasSent = t3lib_utility_Mail::mail(
756 $this->from_email,
757 $theParts[0],
758 $theParts[1],
759 'From: ' . $recipient . $this->linebreak . $this->plain_text_header
760 );
761 }
762 }
763 if ($this->returnPath) {
764 ini_restore('sendmail_from');
765 }
766 return $mailWasSent;
767 }
768
769
770 /**
771 * Returns boundaries
772 *
773 * @return string the boundary
774 */
775 public function getBoundary() {
776 $this->part++;
777 return "----------" . uniqid("part_" . $this->part . "_");
778 }
779
780
781 /**
782 * Sets the plain-text part. No processing done.
783 *
784 * @param string $content: the plain content
785 * @return void
786 */
787 public function setPlain($content) {
788 $this->theParts['plain']['content'] = $content;
789 }
790
791
792 /**
793 * Sets the HTML-part. No processing done.
794 *
795 * @param string $content: the HTML content
796 * @return void
797 */
798 public function setHtml($content) {
799 $this->theParts['html']['content'] = $content;
800 }
801
802
803 /**
804 * Adds a header to the mail. Use this AFTER the setHeaders()-function
805 *
806 * @param string $header: the header in form of "key: value"
807 * @return void
808 */
809 public function add_header($header) {
810 // Mail headers must be ASCII, therefore we convert the whole header to either base64 or quoted_printable
811 if (!$this->dontEncodeHeader && !stristr($header, 'Content-Type') && !stristr($header, 'Content-Transfer-Encoding')) {
812 // Field tags must not be encoded
813 $parts = explode(': ', $header, 2);
814 if (count($parts) == 2) {
815 $enc = $this->alt_base64 ? 'base64' : 'quoted_printable';
816 $parts[1] = t3lib_div::encodeHeader($parts[1], $enc, $this->charset);
817 $header = implode(': ', $parts);
818 }
819 }
820
821 $this->headers .= $header . LF;
822 }
823
824
825 /**
826 * Adds a line of text to the mail-body. Is normally used internally
827 *
828 * @param string $msg: the message to add
829 * @return void
830 */
831 public function add_message($msg) {
832 $this->message .= $msg . LF;
833 }
834
835
836 /**
837 * returns the content specified by the type (plain, html etc.)
838 *
839 * @param string $type: the content type, can either plain or html
840 * @return void
841 */
842 public function getContent($type) {
843 return $this->theParts[$type]['content'];
844 }
845
846
847 /**
848 * shows a preview of the email of the headers and the message
849 *
850 * @return void
851 */
852 public function preview() {
853 echo nl2br(htmlspecialchars($this->headers));
854 echo "<BR>";
855 echo nl2br(htmlspecialchars($this->message));
856 }
857
858
859 /****************************************************
860 *
861 * Functions for acquiring attachments, HTML, analyzing and so on **
862 *
863 ***************************************************/
864
865 /**
866 * Fetches the HTML-content from either url og local serverfile
867 *
868 * @param string $file: the file to load
869 * @return boolean whether the data was fetched or not
870 */
871 public function fetchHTML($file) {
872 // Fetches the content of the page
873 $this->theParts['html']['content'] = $this->getURL($file);
874 if ($this->theParts['html']['content']) {
875 $addr = $this->extParseUrl($file);
876 $path = ($addr['scheme']) ? $addr['scheme'] . '://' . $addr['host'] . (($addr['port']) ? ':' . $addr['port'] : '') . (($addr['filepath']) ? $addr['filepath'] : '/') : $addr['filepath'];
877 $this->theParts['html']['path'] = $path;
878 return TRUE;
879 } else {
880 return FALSE;
881 }
882 }
883
884
885 /**
886 * Fetches the mediafiles which are found by extractMediaLinks()
887 *
888 * @return void
889 */
890 public function fetchHTMLMedia() {
891 if (!is_array($this->theParts['html']['media']) || !count($this->theParts['html']['media'])) {
892 return;
893 }
894 foreach ($this->theParts['html']['media'] as $key => $media) {
895 // fetching the content and the mime-type
896 $picdata = $this->getExtendedURL($this->theParts['html']['media'][$key]['absRef']);
897 if (is_array($picdata)) {
898 $this->theParts['html']['media'][$key]['content'] = $picdata['content'];
899 $this->theParts['html']['media'][$key]['ctype'] = $picdata['content_type'];
900 }
901 }
902 }
903
904
905 /**
906 * extracts all media-links from $this->theParts['html']['content']
907 *
908 * @return void
909 */
910 public function extractMediaLinks() {
911 $html_code = $this->theParts['html']['content'];
912 $attribRegex = $this->tag_regex(array('img', 'table', 'td', 'tr', 'body', 'iframe', 'script', 'input', 'embed'));
913
914 // split the document by the beginning of the above tags
915 $codepieces = preg_split($attribRegex, $html_code);
916 $len = strlen($codepieces[0]);
917 $pieces = count($codepieces);
918 $reg = array();
919 for ($i = 1; $i < $pieces; $i++) {
920 $tag = strtolower(strtok(substr($html_code, $len + 1, 10), ' '));
921 $len += strlen($tag) + strlen($codepieces[$i]) + 2;
922 $dummy = preg_match('/[^>]*/', $codepieces[$i], $reg);
923 $attributes = $this->get_tag_attributes($reg[0]); // Fetches the attributes for the tag
924 $imageData = array();
925
926 // Finds the src or background attribute
927 $imageData['ref'] = ($attributes['src'] ? $attributes['src'] : $attributes['background']);
928 if ($imageData['ref']) {
929 // find out if the value had quotes around it
930 $imageData['quotes'] = (substr($codepieces[$i], strpos($codepieces[$i], $imageData['ref']) - 1, 1) == '"') ? '"' : '';
931 // subst_str is the string to look for, when substituting lateron
932 $imageData['subst_str'] = $imageData['quotes'] . $imageData['ref'] . $imageData['quotes'];
933 if ($imageData['ref'] && !strstr($this->image_fullpath_list, "|" . $imageData["subst_str"] . "|")) {
934 $this->image_fullpath_list .= "|" . $imageData['subst_str'] . "|";
935 $imageData['absRef'] = $this->absRef($imageData['ref']);
936 $imageData['tag'] = $tag;
937 $imageData['use_jumpurl'] = $attributes['dmailerping'] ? 1 : 0;
938 $this->theParts['html']['media'][] = $imageData;
939 }
940 }
941 }
942
943 // Extracting stylesheets
944 $attribRegex = $this->tag_regex(array('link'));
945 // Split the document by the beginning of the above tags
946 $codepieces = preg_split($attribRegex, $html_code);
947 $pieces = count($codepieces);
948 for ($i = 1; $i < $pieces; $i++) {
949 $dummy = preg_match('/[^>]*/', $codepieces[$i], $reg);
950 // fetches the attributes for the tag
951 $attributes = $this->get_tag_attributes($reg[0]);
952 $imageData = array();
953 if (strtolower($attributes['rel']) == 'stylesheet' && $attributes['href']) {
954 // Finds the src or background attribute
955 $imageData['ref'] = $attributes['href'];
956 // Finds out if the value had quotes around it
957 $imageData['quotes'] = (substr($codepieces[$i], strpos($codepieces[$i], $imageData['ref']) - 1, 1) == '"') ? '"' : '';
958 // subst_str is the string to look for, when substituting lateron
959 $imageData['subst_str'] = $imageData['quotes'] . $imageData['ref'] . $imageData['quotes'];
960 if ($imageData['ref'] && !strstr($this->image_fullpath_list, "|" . $imageData["subst_str"] . "|")) {
961 $this->image_fullpath_list .= "|" . $imageData["subst_str"] . "|";
962 $imageData['absRef'] = $this->absRef($imageData["ref"]);
963 $this->theParts['html']['media'][] = $imageData;
964 }
965 }
966 }
967
968 // fixes javascript rollovers
969 $codepieces = explode('.src', $html_code);
970 $pieces = count($codepieces);
971 $expr = '/^[^' . quotemeta('"') . quotemeta("'") . ']*/';
972 for ($i = 1; $i < $pieces; $i++) {
973 $temp = $codepieces[$i];
974 $temp = trim(str_replace('=', '', trim($temp)));
975 preg_match($expr, substr($temp, 1, strlen($temp)), $reg);
976 $imageData['ref'] = $reg[0];
977 $imageData['quotes'] = substr($temp, 0, 1);
978 // subst_str is the string to look for, when substituting lateron
979 $imageData['subst_str'] = $imageData['quotes'] . $imageData['ref'] . $imageData['quotes'];
980 $theInfo = $this->split_fileref($imageData['ref']);
981
982 switch ($theInfo['fileext']) {
983 case 'gif':
984 case 'jpeg':
985 case 'jpg':
986 if ($imageData['ref'] && !strstr($this->image_fullpath_list, "|" . $imageData["subst_str"] . "|")) {
987 $this->image_fullpath_list .= "|" . $imageData['subst_str'] . "|";
988 $imageData['absRef'] = $this->absRef($imageData['ref']);
989 $this->theParts['html']['media'][] = $imageData;
990 }
991 break;
992 }
993 }
994 }
995
996
997 /**
998 * extracts all hyper-links from $this->theParts["html"]["content"]
999 *
1000 * @return void
1001 */
1002 public function extractHyperLinks() {
1003 $html_code = $this->theParts['html']['content'];
1004 $attribRegex = $this->tag_regex(array('a', 'form', 'area'));
1005 $codepieces = preg_split($attribRegex, $html_code); // Splits the document by the beginning of the above tags
1006 $len = strlen($codepieces[0]);
1007 $pieces = count($codepieces);
1008 for ($i = 1; $i < $pieces; $i++) {
1009 $tag = strtolower(strtok(substr($html_code, $len + 1, 10), " "));
1010 $len += strlen($tag) + strlen($codepieces[$i]) + 2;
1011
1012 $dummy = preg_match('/[^>]*/', $codepieces[$i], $reg);
1013 // Fetches the attributes for the tag
1014 $attributes = $this->get_tag_attributes($reg[0]);
1015 $hrefData = array();
1016 $hrefData['ref'] = ($attributes['href'] ? $attributes['href'] : $hrefData['ref'] = $attributes['action']);
1017 if ($hrefData['ref']) {
1018 // Finds out if the value had quotes around it
1019 $hrefData['quotes'] = (substr($codepieces[$i], strpos($codepieces[$i], $hrefData["ref"]) - 1, 1) == '"') ? '"' : '';
1020 // subst_str is the string to look for, when substituting lateron
1021 $hrefData['subst_str'] = $hrefData['quotes'] . $hrefData['ref'] . $hrefData['quotes'];
1022 if ($hrefData['ref'] && substr(trim($hrefData['ref']), 0, 1) != "#" && !strstr($this->href_fullpath_list, "|" . $hrefData['subst_str'] . "|")) {
1023 $this->href_fullpath_list .= "|" . $hrefData['subst_str'] . "|";
1024 $hrefData['absRef'] = $this->absRef($hrefData['ref']);
1025 $hrefData['tag'] = $tag;
1026 $this->theParts['html']['hrefs'][] = $hrefData;
1027 }
1028 }
1029 }
1030 // Extracts TYPO3 specific links made by the openPic() JS function
1031 $codepieces = explode("onClick=\"openPic('", $html_code);
1032 $pieces = count($codepieces);
1033 for ($i = 1; $i < $pieces; $i++) {
1034 $showpic_linkArr = explode("'", $codepieces[$i]);
1035 $hrefData['ref'] = $showpic_linkArr[0];
1036 if ($hrefData['ref']) {
1037 $hrefData['quotes'] = "'";
1038 // subst_str is the string to look for, when substituting lateron
1039 $hrefData['subst_str'] = $hrefData['quotes'] . $hrefData['ref'] . $hrefData['quotes'];
1040 if ($hrefData['ref'] && !strstr($this->href_fullpath_list, "|" . $hrefData['subst_str'] . "|")) {
1041 $this->href_fullpath_list .= "|" . $hrefData['subst_str'] . "|";
1042 $hrefData['absRef'] = $this->absRef($hrefData['ref']);
1043 $this->theParts['html']['hrefs'][] = $hrefData;
1044 }
1045 }
1046 }
1047 }
1048
1049
1050 /**
1051 * extracts all media-links from $this->theParts["html"]["content"]
1052 *
1053 * @return array two-dimensional array with information about each frame
1054 */
1055 public function extractFramesInfo() {
1056 $htmlCode = $this->theParts['html']['content'];
1057 $info = array();
1058 if (strpos(' ' . $htmlCode, '<frame ')) {
1059 $attribRegex = $this->tag_regex('frame');
1060 // Splits the document by the beginning of the above tags
1061 $codepieces = preg_split($attribRegex, $htmlCode, 1000000);
1062 $pieces = count($codepieces);
1063 for ($i = 1; $i < $pieces; $i++) {
1064 $dummy = preg_match('/[^>]*/', $codepieces[$i], $reg);
1065 // Fetches the attributes for the tag
1066 $attributes = $this->get_tag_attributes($reg[0]);
1067 $frame = array();
1068 $frame['src'] = $attributes['src'];
1069 $frame['name'] = $attributes['name'];
1070 $frame['absRef'] = $this->absRef($frame['src']);
1071 $info[] = $frame;
1072 }
1073 return $info;
1074 }
1075 }
1076
1077
1078 /**
1079 * This function substitutes the media-references in $this->theParts["html"]["content"]
1080 *
1081 * @param boolean $absolute: If TRUE, then the refs are substituted with http:// ref's indstead of Content-ID's (cid).
1082 * @return void
1083 */
1084 public function substMediaNamesInHTML($absolute) {
1085 if (is_array($this->theParts['html']['media'])) {
1086 foreach ($this->theParts['html']['media'] as $key => $val) {
1087 if ($val['use_jumpurl'] && $this->jumperURL_prefix) {
1088 $subst = $this->jumperURL_prefix . t3lib_div::rawUrlEncodeFP($val['absRef']);
1089 } else {
1090 $subst = ($absolute) ? $val['absRef'] : 'cid:part' . $key . '.' . $this->messageid;
1091 }
1092 $this->theParts['html']['content'] = str_replace(
1093 $val['subst_str'],
1094 $val['quotes'] . $subst . $val['quotes'],
1095 $this->theParts['html']['content']);
1096 }
1097 }
1098 if (!$absolute) {
1099 $this->fixRollOvers();
1100 }
1101 }
1102
1103
1104 /**
1105 * This function substitutes the hrefs in $this->theParts["html"]["content"]
1106 *
1107 * @return void
1108 */
1109 public function substHREFsInHTML() {
1110 if (!is_array($this->theParts['html']['hrefs'])) {
1111 return;
1112 }
1113 foreach ($this->theParts['html']['hrefs'] as $key => $val) {
1114 // Form elements cannot use jumpurl!
1115 if ($this->jumperURL_prefix && $val['tag'] != 'form') {
1116 if ($this->jumperURL_useId) {
1117 $substVal = $this->jumperURL_prefix . $key;
1118 } else {
1119 $substVal = $this->jumperURL_prefix . t3lib_div::rawUrlEncodeFP($val['absRef']);
1120 }
1121 } else {
1122 $substVal = $val['absRef'];
1123 }
1124 $this->theParts['html']['content'] = str_replace(
1125 $val['subst_str'],
1126 $val['quotes'] . $substVal . $val['quotes'],
1127 $this->theParts['html']['content']);
1128 }
1129 }
1130
1131
1132 /**
1133 * This substitutes the http:// urls in plain text with links
1134 *
1135 * @param string $content: the content to use to substitute
1136 * @return string the changed content
1137 */
1138 public function substHTTPurlsInPlainText($content) {
1139 if (!$this->jumperURL_prefix) {
1140 return $content;
1141 }
1142
1143 $textpieces = explode("http://", $content);
1144 $pieces = count($textpieces);
1145 $textstr = $textpieces[0];
1146 for ($i = 1; $i < $pieces; $i++) {
1147 $len = strcspn($textpieces[$i], chr(32) . TAB . CRLF);
1148 if (trim(substr($textstr, -1)) == '' && $len) {
1149 $lastChar = substr($textpieces[$i], $len - 1, 1);
1150 if (!preg_match('/[A-Za-z0-9\/#]/', $lastChar)) {
1151 $len--;
1152 }
1153
1154 $parts = array();
1155 $parts[0] = "http://" . substr($textpieces[$i], 0, $len);
1156 $parts[1] = substr($textpieces[$i], $len);
1157
1158 if ($this->jumperURL_useId) {
1159 $this->theParts['plain']['link_ids'][$i] = $parts[0];
1160 $parts[0] = $this->jumperURL_prefix . '-' . $i;
1161 } else {
1162 $parts[0] = $this->jumperURL_prefix . t3lib_div::rawUrlEncodeFP($parts[0]);
1163 }
1164 $textstr .= $parts[0] . $parts[1];
1165 } else {
1166 $textstr .= 'http://' . $textpieces[$i];
1167 }
1168 }
1169 return $textstr;
1170 }
1171
1172
1173 /**
1174 * JavaScript rollOvers cannot support graphics inside of mail.
1175 * If these exists we must let them refer to the absolute url. By the way:
1176 * Roll-overs seems to work only on some mail-readers and so far I've seen it
1177 * work on Netscape 4 message-center (but not 4.5!!)
1178 *
1179 * @return void
1180 */
1181 public function fixRollOvers() {
1182 $newContent = '';
1183 $items = explode('.src', $this->theParts['html']['content']);
1184 if (count($items) <= 1) {
1185 return;
1186 }
1187
1188 foreach ($items as $key => $part) {
1189 $sub = substr($part, 0, 200);
1190 if (preg_match('/cid:part[^ "\']*/', $sub, $reg)) {
1191 // The position of the string
1192 $thePos = strpos($part, $reg[0]);
1193 // Finds the id of the media...
1194 preg_match('/cid:part([^\.]*).*/', $sub, $reg2);
1195 $theSubStr = $this->theParts['html']['media'][intval($reg2[1])]['absRef'];
1196 if ($thePos && $theSubStr) {
1197 // ... and substitutes the javaScript rollover image with this instead
1198 // If the path is NOT and url, the reference is set to nothing
1199 if (!strpos(' ' . $theSubStr, 'http://')) {
1200 $theSubStr = 'http://';
1201 }
1202 $part = substr($part, 0, $thePos) . $theSubStr . substr($part, $thePos + strlen($reg[0]), strlen($part));
1203 }
1204 }
1205 $newContent .= $part . ((($key + 1) != count($items)) ? '.src' : '');
1206 }
1207 $this->theParts['html']['content'] = $newContent;
1208 }
1209
1210
1211 /*******************************************
1212 *
1213 * File and URL-functions
1214 *
1215 *******************************************/
1216
1217 /**
1218 * Returns base64-encoded content, which is broken every 76 character
1219 *
1220 * @param string $inputstr: the string to encode
1221 * @return string the encoded string
1222 */
1223 public function makeBase64($inputstr) {
1224 return chunk_split(base64_encode($inputstr));
1225 }
1226
1227
1228 /**
1229 * reads the URL or file and determines the Content-type by either guessing or opening a connection to the host
1230 *
1231 * @param string $url: the URL to get information of
1232 * @return mixed either FALSE or the array with information
1233 */
1234 public function getExtendedURL($url) {
1235 $res = array();
1236 $res['content'] = $this->getURL($url);
1237 if (!$res['content']) {
1238 return FALSE;
1239 }
1240 $pathInfo = parse_url($url);
1241 $fileInfo = $this->split_fileref($pathInfo['path']);
1242 switch ($fileInfo['fileext']) {
1243 case 'gif':
1244 case 'png':
1245 $res['content_type'] = 'image/' . $fileInfo['fileext'];
1246 break;
1247 case 'jpg':
1248 case 'jpeg':
1249 $res['content_type'] = 'image/jpeg';
1250 break;
1251 case 'html':
1252 case 'htm':
1253 $res['content_type'] = 'text/html';
1254 break;
1255 case 'css':
1256 $res['content_type'] = 'text/css';
1257 break;
1258 case 'swf':
1259 $res['content_type'] = 'application/x-shockwave-flash';
1260 break;
1261 default:
1262 $res['content_type'] = $this->getMimeType($url);
1263 }
1264 return $res;
1265 }
1266
1267
1268 /**
1269 * Adds HTTP user and password (from $this->http_username) to a URL
1270 *
1271 * @param string $url: the URL
1272 * @return string the URL with the added values
1273 */
1274 public function addUserPass($url) {
1275 $user = $this->http_username;
1276 $pass = $this->http_password;
1277 $matches = array();
1278 if ($user && $pass && preg_match('/^(https?:\/\/)/', $url, $matches)) {
1279 return $matches[1] . $user . ':' . $pass . '@' . substr($url, strlen($matches[1]));
1280 }
1281 return $url;
1282 }
1283
1284
1285 /**
1286 * reads a url or file
1287 *
1288 * @param string $url: the URL to fetch
1289 * @return string the content of the URL
1290 */
1291 public function getURL($url) {
1292 $url = $this->addUserPass($url);
1293 return t3lib_div::getURL($url);
1294 }
1295
1296
1297 /**
1298 * reads a url or file and strips the HTML-tags AND removes all
1299 * empty lines. This is used to read plain-text out of a HTML-page
1300 *
1301 * @param string $url: the URL to load
1302 * @return the content
1303 */
1304 public function getStrippedURL($url) {
1305 $content = '';
1306 if ($fd = fopen($url, "rb")) {
1307 while (!feof($fd)) {
1308 $line = fgetss($fd, 5000);
1309 if (trim($line)) {
1310 $content .= trim($line) . LF;
1311 }
1312 }
1313 fclose($fd);
1314 }
1315 return $content;
1316 }
1317
1318
1319 /**
1320 * This function returns the mime type of the file specified by the url
1321 *
1322 * @param string $url: the url
1323 * @return string $mimeType: the mime type found in the header
1324 */
1325 public function getMimeType($url) {
1326 $mimeType = '';
1327 $headers = trim(t3lib_div::getURL($url, 2));
1328 if ($headers) {
1329 $matches = array();
1330 if (preg_match('/(Content-Type:[\s]*)([a-zA-Z_0-9\/\-\.\+]*)([\s]|$)/', $headers, $matches)) {
1331 $mimeType = trim($matches[2]);
1332 }
1333 }
1334 return $mimeType;
1335 }
1336
1337
1338 /**
1339 * Returns the absolute address of a link. This is based on
1340 * $this->theParts["html"]["path"] being the root-address
1341 *
1342 * @param string $ref: address to use
1343 * @return string the absolute address
1344 */
1345 public function absRef($ref) {
1346 $ref = trim($ref);
1347 $info = parse_url($ref);
1348 if ($info['scheme']) {
1349 return $ref;
1350 } elseif (preg_match('/^\//', $ref)) {
1351 $addr = parse_url($this->theParts['html']['path']);
1352 return $addr['scheme'] . '://' . $addr['host'] . ($addr['port'] ? ':' . $addr['port'] : '') . $ref;
1353 } else {
1354 // If the reference is relative, the path is added, in order for us to fetch the content
1355 return $this->theParts['html']['path'] . $ref;
1356 }
1357 }
1358
1359
1360 /**
1361 * Returns information about a file reference
1362 *
1363 * @param string $fileref: the file to use
1364 * @return array path, filename, filebody, fileext
1365 */
1366 public function split_fileref($fileref) {
1367 $info = array();
1368 if (preg_match('/(.*\/)(.*)$/', $fileref, $reg)) {
1369 $info['path'] = $reg[1];
1370 $info['file'] = $reg[2];
1371 } else {
1372 $info['path'] = '';
1373 $info['file'] = $fileref;
1374 }
1375 $reg = '';
1376 if (preg_match('/(.*)\.([^\.]*$)/', $info['file'], $reg)) {
1377 $info['filebody'] = $reg[1];
1378 $info['fileext'] = strtolower($reg[2]);
1379 $info['realFileext'] = $reg[2];
1380 } else {
1381 $info['filebody'] = $info['file'];
1382 $info['fileext'] = '';
1383 }
1384 return $info;
1385 }
1386
1387
1388 /**
1389 * Returns an array with file or url-information
1390 *
1391 * @param string $path: url to check
1392 * @return array information about the path / URL
1393 */
1394 public function extParseUrl($path) {
1395 $res = parse_url($path);
1396 preg_match('/(.*\/)([^\/]*)$/', $res['path'], $reg);
1397 $res['filepath'] = $reg[1];
1398 $res['filename'] = $reg[2];
1399 return $res;
1400 }
1401
1402
1403 /**
1404 * Creates a regular expression out of a list of tags
1405 *
1406 * @param mixed $tagArray: the list of tags (either as array or string if it is one tag)
1407 * @return string the regular expression
1408 */
1409 public function tag_regex($tags) {
1410 $tags = (!is_array($tags) ? array($tags) : $tags);
1411 $regexp = '/';
1412 $c = count($tags);
1413 foreach ($tags as $tag) {
1414 $c--;
1415 $regexp .= '<' . $tag . '[[:space:]]' . (($c) ? '|' : '');
1416 }
1417 return $regexp . '/i';
1418 }
1419
1420
1421 /**
1422 * This function analyzes a HTML tag
1423 * If an attribute is empty (like OPTION) the value of that key is just empty. Check it with is_set();
1424 *
1425 * @param string $tag: is either like this "<TAG OPTION ATTRIB=VALUE>" or
1426 * this " OPTION ATTRIB=VALUE>" which means you can omit the tag-name
1427 * @return array array with attributes as keys in lower-case
1428 */
1429 public function get_tag_attributes($tag) {
1430 $attributes = array();
1431 $tag = ltrim(preg_replace('/^<[^ ]*/', '', trim($tag)));
1432 $tagLen = strlen($tag);
1433 $safetyCounter = 100;
1434 // Find attribute
1435 while ($tag) {
1436 $value = '';
1437 $reg = preg_split('/[[:space:]=>]/', $tag, 2);
1438 $attrib = $reg[0];
1439
1440 $tag = ltrim(substr($tag, strlen($attrib), $tagLen));
1441 if (substr($tag, 0, 1) == '=') {
1442 $tag = ltrim(substr($tag, 1, $tagLen));
1443 if (substr($tag, 0, 1) == '"') {
1444 // Quotes around the value
1445 $reg = explode('"', substr($tag, 1, $tagLen), 2);
1446 $tag = ltrim($reg[1]);
1447 $value = $reg[0];
1448 } else {
1449 // No quotes around value
1450 preg_match('/^([^[:space:]>]*)(.*)/', $tag, $reg);
1451 $value = trim($reg[1]);
1452 $tag = ltrim($reg[2]);
1453 if (substr($tag, 0, 1) == '>') {
1454 $tag = '';
1455 }
1456 }
1457 }
1458 $attributes[strtolower($attrib)] = $value;
1459 $safetyCounter--;
1460 if ($safetyCounter < 0) {
1461 break;
1462 }
1463 }
1464 return $attributes;
1465 }
1466 }
1467
1468 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_htmlmail.php'])) {
1469 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_htmlmail.php']);
1470 }
1471
1472 ?>