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