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