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