PageRenderTime 50ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/t3lib/class.t3lib_htmlmail.php

https://bitbucket.org/linxpinx/mercurial
PHP | 1504 lines | 760 code | 158 blank | 586 comment | 135 complexity | 38b0b7aac11a43672344306214b0a9e0 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, Unlicense, LGPL-2.1, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /***************************************************************
  3. * Copyright notice
  4. *
  5. * (c) 1999-2010 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: class.t3lib_htmlmail.php 8335 2010-07-28 08:55:04Z ohader $
  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 $recipient_blindcopy = ''; // This recipient (or list of...) will also receive the mail as a blind copy. Regard it as a copy.
  188. var $subject = '';
  189. var $from_email = '';
  190. var $from_name = '';
  191. var $replyto_email = '';
  192. var $replyto_name = '';
  193. var $organisation = '';
  194. var $priority = 3; // 1 = highest, 5 = lowest, 3 = normal
  195. var $mailer = ''; // X-mailer, set to TYPO3 Major.Minor in constructor
  196. var $alt_base64 = 0;
  197. var $alt_8bit = 0;
  198. var $jumperURL_prefix = ''; // This is a prefix that will be added to all links in the mail. Example: 'http://www.mydomain.com/jump?userid=###FIELD_uid###&url='. if used, anything after url= is urlencoded.
  199. var $jumperURL_useId = 0; // If set, then the array-key of the urls are inserted instead of the url itself. Smart in order to reduce link-length
  200. var $mediaList = ''; // If set, this is a list of the media-files (index-keys to the array) that should be represented in the html-mail
  201. var $http_password = '';
  202. var $http_username = '';
  203. var $postfix_version1 = false;
  204. // 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. var $messageid = '';
  222. var $returnPath = '';
  223. var $Xid = '';
  224. var $dontEncodeHeader = false; // If set, the header will not be encoded
  225. var $headers = '';
  226. var $message = '';
  227. var $part = 0;
  228. var $image_fullpath_list = '';
  229. var $href_fullpath_list = '';
  230. var $plain_text_header = '';
  231. var $html_text_header = '';
  232. var $charset = '';
  233. var $defaultCharset = 'iso-8859-1';
  234. /**
  235. * Constructor. If the configuration variable forceReturnPath is set,
  236. * calls to mail will be called with a 5th parameter.
  237. * See function sendTheMail for more info
  238. *
  239. * @return void
  240. */
  241. public function t3lib_htmlmail() {
  242. $this->forceReturnPath = $GLOBALS['TYPO3_CONF_VARS']['SYS']['forceReturnPath'];
  243. $this->mailer = 'TYPO3';
  244. }
  245. /**
  246. * start action that sets the message ID and the charset
  247. *
  248. * @return void
  249. */
  250. public function start() {
  251. global $TYPO3_CONF_VARS;
  252. // Sets the message id
  253. $host = t3lib_div::getHostname();
  254. if (!$host || $host == '127.0.0.1' || $host == 'localhost' || $host == 'localhost.localdomain') {
  255. $host = ($TYPO3_CONF_VARS['SYS']['sitename'] ? preg_replace('/[^A-Za-z0-9_\-]/', '_', $TYPO3_CONF_VARS['SYS']['sitename']) : 'localhost') . '.TYPO3';
  256. }
  257. $this->messageid = md5(microtime()) . '@' . $host;
  258. // Default line break for Unix systems.
  259. $this->linebreak = LF;
  260. // Line break for Windows. This is needed because PHP on Windows systems
  261. // send mails via SMTP instead of using sendmail, and thus the linebreak needs to be \r\n.
  262. if (TYPO3_OS == 'WIN') {
  263. $this->linebreak = CRLF;
  264. }
  265. // Sets the Charset
  266. if (!$this->charset) {
  267. if (is_object($GLOBALS['TSFE']) && $GLOBALS['TSFE']->renderCharset) {
  268. $this->charset = $GLOBALS['TSFE']->renderCharset;
  269. } elseif (is_object($GLOBALS['LANG']) && $GLOBALS['LANG']->charSet) {
  270. $this->charset = $GLOBALS['LANG']->charSet;
  271. } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
  272. $this->charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
  273. } else {
  274. $this->charset = $this->defaultCharset;
  275. }
  276. }
  277. // Use quoted-printable headers by default
  278. $this->useQuotedPrintable();
  279. }
  280. /**
  281. * sets the header of both Plain Text and HTML mails to quoted printable
  282. *
  283. * @return void
  284. */
  285. public function useQuotedPrintable() {
  286. $this->plain_text_header = 'Content-Type: text/plain; charset='.$this->charset.$this->linebreak.'Content-Transfer-Encoding: quoted-printable';
  287. $this->html_text_header = 'Content-Type: text/html; charset='.$this->charset.$this->linebreak.'Content-Transfer-Encoding: quoted-printable';
  288. }
  289. /**
  290. * sets the encoding headers to base64 for both the Plain Text and HTML mail
  291. *
  292. * @return void
  293. */
  294. public function useBase64() {
  295. $this->plain_text_header = 'Content-Type: text/plain; charset='.$this->charset.$this->linebreak.'Content-Transfer-Encoding: base64';
  296. $this->html_text_header = 'Content-Type: text/html; charset='.$this->charset.$this->linebreak.'Content-Transfer-Encoding: base64';
  297. $this->alt_base64 = 1;
  298. }
  299. /**
  300. * sets the encoding to 8bit and the current charset of both the Plain Text and the HTML mail
  301. *
  302. * @return void
  303. */
  304. public function use8Bit() {
  305. $this->plain_text_header = 'Content-Type: text/plain; charset='.$this->charset.$this->linebreak.'Content-Transfer-Encoding: 8bit';
  306. $this->html_text_header = 'Content-Type: text/html; charset='.$this->charset.$this->linebreak.'Content-Transfer-Encoding: 8bit';
  307. $this->alt_8bit = 1;
  308. }
  309. /**
  310. * Encodes the message content according to the options "alt_base64" and "alt_8bit" (no need to encode here)
  311. * or to "quoted_printable" if no option is set.
  312. *
  313. * @param string $content the content that will be encoded
  314. * @return string the encoded content
  315. */
  316. public function encodeMsg($content) {
  317. if ($this->alt_base64) {
  318. return $this->makeBase64($content);
  319. } elseif ($this->alt_8bit) {
  320. return $content;
  321. } else {
  322. return t3lib_div::quoted_printable($content);
  323. }
  324. }
  325. /**
  326. * Adds plain-text, replaces the HTTP urls in the plain text and then encodes it
  327. *
  328. * @param string $content that will be added
  329. * @return void
  330. */
  331. public function addPlain($content) {
  332. $content = $this->substHTTPurlsInPlainText($content);
  333. $this->setPlain($this->encodeMsg($content));
  334. }
  335. /**
  336. * Adds an attachment to the mail
  337. *
  338. * @param string $file: the filename to add
  339. * @return boolean whether the attachment was added or not
  340. */
  341. public function addAttachment($file) {
  342. // Fetching the content and the mime-type
  343. $fileInfo = $this->getExtendedURL($file);
  344. if ($fileInfo) {
  345. if (!$fileInfo['content_type']) {
  346. $fileInfo['content_type'] = 'application/octet-stream';
  347. }
  348. $temp = $this->split_fileref($file);
  349. if ($temp['file']) {
  350. $fileInfo['filename'] = $temp['file'];
  351. } elseif (strpos(' '.$fileInfo['content_type'], 'htm')) {
  352. $fileInfo['filename'] = 'index.html';
  353. } else {
  354. $fileInfo['filename'] = 'unknown';
  355. }
  356. $this->theParts['attach'][] = $fileInfo;
  357. return true;
  358. }
  359. return false;
  360. }
  361. /**
  362. * Adds HTML and media, encodes it from a URL or file
  363. *
  364. * @param string $file: the filename to add
  365. * @return boolean whether the attachment was added or not
  366. */
  367. public function addHTML($file) {
  368. $status = $this->fetchHTML($file);
  369. if (!$status) {
  370. return false;
  371. }
  372. if ($this->extractFramesInfo()) {
  373. return 'Document was a frameset. Stopped';
  374. }
  375. $this->extractMediaLinks();
  376. $this->extractHyperLinks();
  377. $this->fetchHTMLMedia();
  378. $this->substMediaNamesInHTML(0); // 0 = relative
  379. $this->substHREFsInHTML();
  380. $this->setHtml($this->encodeMsg($this->theParts['html']['content']));
  381. }
  382. /**
  383. * Extract HTML-parts, used externally
  384. *
  385. * @param string $html: will be added to the html "content" part
  386. * @param string $url: will be added to the html "path" part
  387. * @return void
  388. */
  389. public function extractHtmlInit($html,$url) {
  390. $this->theParts['html']['content'] = $html;
  391. $this->theParts['html']['path'] = $url;
  392. }
  393. /**
  394. * Assembles the message by headers and content and finally send it to the provided recipient.
  395. *
  396. * @param string $recipient: The recipient the message should be delivered to (if blank, $this->recipient will be used instead)
  397. * @return boolean Returns whether the mail was sent (successfully accepted for delivery)
  398. */
  399. public function send($recipient) {
  400. if ($recipient) {
  401. $this->recipient = $recipient;
  402. }
  403. $this->setHeaders();
  404. $this->setContent();
  405. $mailWasSent = $this->sendTheMail();
  406. return $mailWasSent;
  407. }
  408. /*****************************************
  409. *
  410. * Main functions
  411. *
  412. *****************************************/
  413. /**
  414. * Clears the header-string and sets the headers based on object-vars.
  415. *
  416. * @return void
  417. */
  418. public function setHeaders() {
  419. $this->headers = '';
  420. // Message_id
  421. $this->add_header('Message-ID: <'.$this->messageid.'>');
  422. // Return path
  423. if ($this->returnPath) {
  424. $this->add_header('Return-Path: '.$this->returnPath);
  425. $this->add_header('Errors-To: '.$this->returnPath);
  426. }
  427. // X-id
  428. if ($this->Xid) {
  429. $this->add_header('X-Typo3MID: '.$this->Xid);
  430. }
  431. // From
  432. if ($this->from_email) {
  433. if ($this->from_name && !t3lib_div::isBrokenEmailEnvironment()) {
  434. $this->add_header('From: '.$this->from_name.' <'.$this->from_email.'>');
  435. } else {
  436. $this->add_header('From: '.$this->from_email);
  437. }
  438. }
  439. // Cc
  440. if ($this->recipient_copy) {
  441. $this->add_header('Cc: ' . $this->recipient_copy);
  442. }
  443. // Bcc
  444. if ($this->recipient_blindcopy) {
  445. $this->add_header('Bcc: ' . $this->recipient_blindcopy);
  446. }
  447. // Reply
  448. if ($this->replyto_email) {
  449. if ($this->replyto_name) {
  450. $this->add_header('Reply-To: '.$this->replyto_name.' <'.$this->replyto_email.'>');
  451. } else {
  452. $this->add_header('Reply-To: '.$this->replyto_email);
  453. }
  454. }
  455. // Organization, using american english spelling (organization / organisation) as defined in RFC 1036 / 2076
  456. if ($this->organisation) {
  457. $this->add_header('Organization: ' . $this->organisation);
  458. }
  459. // mailer
  460. if ($this->mailer) {
  461. $this->add_header('X-Mailer: '.$this->mailer);
  462. }
  463. // priority
  464. if ($this->priority) {
  465. $this->add_header('X-Priority: '.$this->priority);
  466. }
  467. $this->add_header('Mime-Version: 1.0');
  468. if (!$this->dontEncodeHeader) {
  469. $enc = $this->alt_base64 ? 'base64' : 'quoted_printable'; // Header must be ASCII, therefore only base64 or quoted_printable are allowed!
  470. // Quote recipient and subject
  471. $this->recipient = t3lib_div::encodeHeader($this->recipient,$enc,$this->charset);
  472. $this->subject = t3lib_div::encodeHeader($this->subject,$enc,$this->charset);
  473. }
  474. }
  475. /**
  476. * Sets the recipient(s). If you supply a string, you set one recipient.
  477. * If you supply an array, every value is added as a recipient.
  478. *
  479. * @param mixed $recipient: the recipient(s) to set
  480. * @return void
  481. */
  482. public function setRecipient($recipient) {
  483. $this->recipient = (is_array($recipient) ? implode(',', $recipient) : $recipient);
  484. }
  485. /**
  486. * Returns the content type based on whether the mail has media / attachments or no
  487. *
  488. * @return string the content type
  489. */
  490. public function getHTMLContentType() {
  491. return (count($this->theParts['html']['media']) ? 'multipart/related' : 'multipart/alternative');
  492. }
  493. /**
  494. * Begins building the message-body
  495. *
  496. * @return void
  497. */
  498. public function setContent() {
  499. $this->message = '';
  500. $boundary = $this->getBoundary();
  501. // Setting up headers
  502. if (count($this->theParts['attach'])) {
  503. // Generate (plain/HTML) / attachments
  504. $this->add_header('Content-Type: multipart/mixed;');
  505. $this->add_header(' boundary="' . $boundary . '"');
  506. $this->add_message('This is a multi-part message in MIME format.' . LF);
  507. $this->constructMixed($boundary);
  508. } elseif ($this->theParts['html']['content']) {
  509. // Generate plain/HTML mail
  510. $this->add_header('Content-Type: ' . $this->getHTMLContentType() . ';');
  511. $this->add_header(' boundary="' . $boundary . '"');
  512. $this->add_message('This is a multi-part message in MIME format.' . LF);
  513. $this->constructHTML($boundary);
  514. } else {
  515. // Generate plain only
  516. $this->add_header($this->plain_text_header);
  517. $this->add_message($this->getContent('plain'));
  518. }
  519. }
  520. /**
  521. * This functions combines the plain / HTML content with the attachments
  522. *
  523. * @param string $boundary: the mail boundary
  524. * @return void
  525. */
  526. public function constructMixed($boundary) {
  527. $this->add_message('--' . $boundary);
  528. if ($this->theParts['html']['content']) {
  529. // HTML and plain is added
  530. $newBoundary = $this->getBoundary();
  531. $this->add_message('Content-Type: '.$this->getHTMLContentType() . ';');
  532. $this->add_message(' boundary="' . $newBoundary . '"');
  533. $this->add_message('');
  534. $this->constructHTML($newBoundary);
  535. } else {
  536. // Purely plain
  537. $this->add_message($this->plain_text_header);
  538. $this->add_message('');
  539. $this->add_message($this->getContent('plain'));
  540. }
  541. // attachments are added
  542. if (is_array($this->theParts['attach'])) {
  543. foreach ($this->theParts['attach'] as $media) {
  544. $this->add_message('--' . $boundary);
  545. $this->add_message('Content-Type: ' . $media['content_type'] . ';');
  546. $this->add_message(' name="' . $media['filename'] . '"');
  547. $this->add_message('Content-Transfer-Encoding: base64');
  548. $this->add_message('Content-Disposition: attachment;');
  549. $this->add_message(' filename="' . $media['filename'] . '"');
  550. $this->add_message('');
  551. $this->add_message($this->makeBase64($media['content']));
  552. }
  553. }
  554. $this->add_message('--' . $boundary . '--' . LF);
  555. }
  556. /**
  557. * this function creates the HTML part of the mail
  558. *
  559. * @param string $boundary: the boundary to use
  560. * @return void
  561. */
  562. public function constructHTML($boundary) {
  563. // If media, then we know, the multipart/related content-type has been set before this function call
  564. if (count($this->theParts['html']['media'])) {
  565. $this->add_message('--' . $boundary);
  566. // HTML has media
  567. $newBoundary = $this->getBoundary();
  568. $this->add_message('Content-Type: multipart/alternative;');
  569. $this->add_message(' boundary="' . $newBoundary . '"');
  570. $this->add_message('Content-Transfer-Encoding: 7bit');
  571. $this->add_message('');
  572. // Adding the plaintext/html mix, and use $newBoundary
  573. $this->constructAlternative($newBoundary);
  574. $this->constructHTML_media($boundary);
  575. } else {
  576. // if no media, just use the $boundary for adding plaintext/html mix
  577. $this->constructAlternative($boundary);
  578. }
  579. }
  580. /**
  581. * Here plain is combined with HTML
  582. *
  583. * @param string $boundary: the boundary to use
  584. * @return void
  585. */
  586. public function constructAlternative($boundary) {
  587. $this->add_message('--'.$boundary);
  588. // plain is added
  589. $this->add_message($this->plain_text_header);
  590. $this->add_message('');
  591. $this->add_message($this->getContent('plain'));
  592. $this->add_message('--' . $boundary);
  593. // html is added
  594. $this->add_message($this->html_text_header);
  595. $this->add_message('');
  596. $this->add_message($this->getContent('html'));
  597. $this->add_message('--' . $boundary . '--' . LF);
  598. }
  599. /**
  600. * Constructs the HTML-part of message if the HTML contains media
  601. *
  602. * @param string $boundary: the boundary to use
  603. * @return void
  604. */
  605. public function constructHTML_media($boundary) {
  606. // media is added
  607. if (is_array($this->theParts['html']['media'])) {
  608. foreach($this->theParts['html']['media'] as $key => $media) {
  609. if (!$this->mediaList || t3lib_div::inList($this->mediaList, $key)) {
  610. $this->add_message('--' . $boundary);
  611. $this->add_message('Content-Type: ' . $media['ctype']);
  612. $this->add_message('Content-ID: <part' . $key . '.' . $this->messageid . '>');
  613. $this->add_message('Content-Transfer-Encoding: base64');
  614. $this->add_message('');
  615. $this->add_message($this->makeBase64($media['content']));
  616. }
  617. }
  618. }
  619. $this->add_message('--' . $boundary . '--' . LF);
  620. }
  621. /**
  622. * Sends the mail by calling the mail() function in php. On Linux systems this will invoke the MTA
  623. * defined in php.ini (sendmail -t -i by default), on Windows a SMTP must be specified in the sys.ini.
  624. * Most common MTA's on Linux has a Sendmail interface, including Postfix and Exim.
  625. * For setting the return-path correctly, the parameter -f has to be added to the system call to sendmail.
  626. * This obviously does not have any effect on Windows, but on Sendmail compliant systems this works. If safe mode
  627. * is enabled, then extra parameters is not allowed, so a safe mode check is made before the mail() command is
  628. * invoked. When using the -f parameter, some MTA's will put an X-AUTHENTICATION-WARNING saying that
  629. * the return path was modified manually with the -f flag. To disable this warning make sure that the user running
  630. * Apache is in the /etc/mail/trusted-users table.
  631. *
  632. * POSTFIX: With postfix version below 2.0 there is a problem that the -f parameter can not be used in conjunction
  633. * with -t. Postfix will give an error in the maillog:
  634. *
  635. * cannot handle command-line recipients with -t
  636. *
  637. * The -f parameter is only enabled if the parameter forceReturnPath is enabled in the install tool.
  638. *
  639. * This whole problem of return-path turns out to be quite tricky. If you have a solution that works better, on all
  640. * standard MTA's then we are very open for suggestions.
  641. *
  642. * With time this function should be made such that several ways of sending the mail is possible (local MTA, smtp other).
  643. *
  644. * @return boolean Returns whether the mail was sent (successfully accepted for delivery)
  645. */
  646. public function sendTheMail() {
  647. $mailWasSent = false;
  648. // Sending the mail requires the recipient and message to be set.
  649. if (!trim($this->recipient) || !trim($this->message)) {
  650. return false;
  651. }
  652. // On windows the -f flag is not used (specific for Sendmail and Postfix),
  653. // but instead the php.ini parameter sendmail_from is used.
  654. $returnPath = ($this->forceReturnPath && strlen($this->returnPath) > 0) ? '-f ' . escapeshellarg($this->returnPath) : '';
  655. if (TYPO3_OS == 'WIN' && $this->returnPath) {
  656. @ini_set('sendmail_from', t3lib_div::normalizeMailAddress($this->returnPath));
  657. }
  658. $recipient = t3lib_div::normalizeMailAddress($this->recipient);
  659. // If safe mode is on, the fifth parameter to mail is not allowed, so the fix wont work on unix with safe_mode=On
  660. $returnPathPossible = (!ini_get('safe_mode') && $this->forceReturnPath);
  661. if ($returnPathPossible) {
  662. $mailWasSent = t3lib_utility_Mail::mail($recipient,
  663. $this->subject,
  664. $this->message,
  665. $this->headers,
  666. $returnPath);
  667. } else {
  668. $mailWasSent = t3lib_utility_Mail::mail($recipient,
  669. $this->subject,
  670. $this->message,
  671. $this->headers);
  672. }
  673. // Auto response
  674. if ($this->auto_respond_msg) {
  675. $theParts = explode('/',$this->auto_respond_msg,2);
  676. $theParts[0] = str_replace('###SUBJECT###', $this->subject, $theParts[0]);
  677. $theParts[1] = str_replace("/",LF,$theParts[1]);
  678. $theParts[1] = str_replace("###MESSAGE###", $this->getContent('plain'), $theParts[1]);
  679. if ($returnPathPossible) {
  680. $mailWasSent = t3lib_utility_Mail::mail($this->from_email,
  681. $theParts[0],
  682. $theParts[1],
  683. 'From: ' . $recipient,
  684. $returnPath);
  685. } else {
  686. $mailWasSent = t3lib_utility_Mail::mail($this->from_email,
  687. $theParts[0],
  688. $theParts[1],
  689. 'From: ' . $recipient);
  690. }
  691. }
  692. if ($this->returnPath) {
  693. ini_restore('sendmail_from');
  694. }
  695. return $mailWasSent;
  696. }
  697. /**
  698. * Returns boundaries
  699. *
  700. * @return string the boundary
  701. */
  702. public function getBoundary() {
  703. $this->part++;
  704. return "----------".uniqid("part_".$this->part."_");
  705. }
  706. /**
  707. * Sets the plain-text part. No processing done.
  708. *
  709. * @param string $content: the plain content
  710. * @return void
  711. */
  712. public function setPlain($content) {
  713. $this->theParts['plain']['content'] = $content;
  714. }
  715. /**
  716. * Sets the HTML-part. No processing done.
  717. *
  718. * @param string $content: the HTML content
  719. * @return void
  720. */
  721. public function setHtml($content) {
  722. $this->theParts['html']['content'] = $content;
  723. }
  724. /**
  725. * Adds a header to the mail. Use this AFTER the setHeaders()-function
  726. *
  727. * @param string $header: the header in form of "key: value"
  728. * @return void
  729. */
  730. public function add_header($header) {
  731. // Mail headers must be ASCII, therefore we convert the whole header to either base64 or quoted_printable
  732. if (!$this->dontEncodeHeader && !stristr($header,'Content-Type') && !stristr($header,'Content-Transfer-Encoding')) {
  733. // Field tags must not be encoded
  734. $parts = explode(': ',$header,2);
  735. if (count($parts) == 2) {
  736. $enc = $this->alt_base64 ? 'base64' : 'quoted_printable';
  737. $parts[1] = t3lib_div::encodeHeader($parts[1], $enc, $this->charset);
  738. $header = implode(': ', $parts);
  739. }
  740. }
  741. $this->headers .= $header.LF;
  742. }
  743. /**
  744. * Adds a line of text to the mail-body. Is normally used internally
  745. *
  746. * @param string $msg: the message to add
  747. * @return void
  748. */
  749. public function add_message($msg) {
  750. $this->message .= $msg.LF;
  751. }
  752. /**
  753. * returns the content specified by the type (plain, html etc.)
  754. *
  755. * @param string $type: the content type, can either plain or html
  756. * @return void
  757. */
  758. public function getContent($type) {
  759. return $this->theParts[$type]['content'];
  760. }
  761. /**
  762. * shows a preview of the email of the headers and the message
  763. *
  764. * @return void
  765. */
  766. public function preview() {
  767. echo nl2br(htmlspecialchars($this->headers));
  768. echo "<BR>";
  769. echo nl2br(htmlspecialchars($this->message));
  770. }
  771. /****************************************************
  772. *
  773. * Functions for acquiring attachments, HTML, analyzing and so on **
  774. *
  775. ***************************************************/
  776. /**
  777. * Fetches the HTML-content from either url og local serverfile
  778. *
  779. * @param string $file: the file to load
  780. * @return boolean whether the data was fetched or not
  781. */
  782. public function fetchHTML($file) {
  783. // Fetches the content of the page
  784. $this->theParts['html']['content'] = $this->getURL($file);
  785. if ($this->theParts['html']['content']) {
  786. $addr = $this->extParseUrl($file);
  787. $path = ($addr['scheme']) ? $addr['scheme'].'://'.$addr['host'].(($addr['port'])?':'.$addr['port']:'').(($addr['filepath'])?$addr['filepath']:'/') : $addr['filepath'];
  788. $this->theParts['html']['path'] = $path;
  789. return true;
  790. } else {
  791. return false;
  792. }
  793. }
  794. /**
  795. * Fetches the mediafiles which are found by extractMediaLinks()
  796. *
  797. * @return void
  798. */
  799. public function fetchHTMLMedia() {
  800. if (!is_array($this->theParts['html']['media']) || !count($this->theParts['html']['media'])) return;
  801. foreach ($this->theParts['html']['media'] as $key => $media) {
  802. // fetching the content and the mime-type
  803. $picdata = $this->getExtendedURL($this->theParts['html']['media'][$key]['absRef']);
  804. if (is_array($picdata)) {
  805. $this->theParts['html']['media'][$key]['content'] = $picdata['content'];
  806. $this->theParts['html']['media'][$key]['ctype'] = $picdata['content_type'];
  807. }
  808. }
  809. }
  810. /**
  811. * extracts all media-links from $this->theParts['html']['content']
  812. *
  813. * @return void
  814. */
  815. public function extractMediaLinks() {
  816. $html_code = $this->theParts['html']['content'];
  817. $attribRegex = $this->tag_regex(array('img','table','td','tr','body','iframe','script','input','embed'));
  818. // split the document by the beginning of the above tags
  819. $codepieces = preg_split($attribRegex, $html_code);
  820. $len = strlen($codepieces[0]);
  821. $pieces = count($codepieces);
  822. $reg = array();
  823. for ($i = 1; $i < $pieces; $i++) {
  824. $tag = strtolower(strtok(substr($html_code,$len+1,10),' '));
  825. $len += strlen($tag)+strlen($codepieces[$i])+2;
  826. $dummy = preg_match('/[^>]*/', $codepieces[$i], $reg);
  827. $attributes = $this->get_tag_attributes($reg[0]); // Fetches the attributes for the tag
  828. $imageData = array();
  829. // Finds the src or background attribute
  830. $imageData['ref'] = ($attributes['src'] ? $attributes['src'] : $attributes['background']);
  831. if ($imageData['ref']) {
  832. // find out if the value had quotes around it
  833. $imageData['quotes'] = (substr($codepieces[$i], strpos($codepieces[$i], $imageData['ref'])-1,1) == '"') ? '"' : '';
  834. // subst_str is the string to look for, when substituting lateron
  835. $imageData['subst_str'] = $imageData['quotes'].$imageData['ref'].$imageData['quotes'];
  836. if ($imageData['ref'] && !strstr($this->image_fullpath_list,"|".$imageData["subst_str"]."|")) {
  837. $this->image_fullpath_list .= "|".$imageData['subst_str']."|";
  838. $imageData['absRef'] = $this->absRef($imageData['ref']);
  839. $imageData['tag'] = $tag;
  840. $imageData['use_jumpurl'] = $attributes['dmailerping']?1:0;
  841. $this->theParts['html']['media'][] = $imageData;
  842. }
  843. }
  844. }
  845. // Extracting stylesheets
  846. $attribRegex = $this->tag_regex(array('link'));
  847. // Split the document by the beginning of the above tags
  848. $codepieces = preg_split($attribRegex, $html_code);
  849. $pieces = count($codepieces);
  850. for ($i = 1; $i < $pieces; $i++) {
  851. $dummy = preg_match('/[^>]*/', $codepieces[$i], $reg);
  852. // fetches the attributes for the tag
  853. $attributes = $this->get_tag_attributes($reg[0]);
  854. $imageData = array();
  855. if (strtolower($attributes['rel']) == 'stylesheet' && $attributes['href']) {
  856. // Finds the src or background attribute
  857. $imageData['ref'] = $attributes['href'];
  858. // Finds out if the value had quotes around it
  859. $imageData['quotes'] = (substr($codepieces[$i],strpos($codepieces[$i], $imageData['ref'])-1,1) == '"') ? '"' : '';
  860. // subst_str is the string to look for, when substituting lateron
  861. $imageData['subst_str'] = $imageData['quotes'].$imageData['ref'].$imageData['quotes'];
  862. if ($imageData['ref'] && !strstr($this->image_fullpath_list,"|".$imageData["subst_str"]."|")) {
  863. $this->image_fullpath_list .= "|".$imageData["subst_str"]."|";
  864. $imageData['absRef'] = $this->absRef($imageData["ref"]);
  865. $this->theParts['html']['media'][] = $imageData;
  866. }
  867. }
  868. }
  869. // fixes javascript rollovers
  870. $codepieces = explode('.src', $html_code);
  871. $pieces = count($codepieces);
  872. $expr = '/^[^'.quotemeta('"').quotemeta("'").']*/';
  873. for($i = 1; $i < $pieces; $i++) {
  874. $temp = $codepieces[$i];
  875. $temp = trim(str_replace('=','',trim($temp)));
  876. preg_match($expr,substr($temp,1,strlen($temp)),$reg);
  877. $imageData['ref'] = $reg[0];
  878. $imageData['quotes'] = substr($temp,0,1);
  879. // subst_str is the string to look for, when substituting lateron
  880. $imageData['subst_str'] = $imageData['quotes'].$imageData['ref'].$imageData['quotes'];
  881. $theInfo = $this->split_fileref($imageData['ref']);
  882. switch ($theInfo['fileext']) {
  883. case 'gif':
  884. case 'jpeg':
  885. case 'jpg':
  886. if ($imageData['ref'] && !strstr($this->image_fullpath_list,"|".$imageData["subst_str"]."|")) {
  887. $this->image_fullpath_list .= "|".$imageData['subst_str']."|";
  888. $imageData['absRef'] = $this->absRef($imageData['ref']);
  889. $this->theParts['html']['media'][] = $imageData;
  890. }
  891. break;
  892. }
  893. }
  894. }
  895. /**
  896. * extracts all hyper-links from $this->theParts["html"]["content"]
  897. *
  898. * @return void
  899. */
  900. public function extractHyperLinks() {
  901. $html_code = $this->theParts['html']['content'];
  902. $attribRegex = $this->tag_regex(array('a','form','area'));
  903. $codepieces = preg_split($attribRegex, $html_code); // Splits the document by the beginning of the above tags
  904. $len = strlen($codepieces[0]);
  905. $pieces = count($codepieces);
  906. for($i = 1; $i < $pieces; $i++) {
  907. $tag = strtolower(strtok(substr($html_code,$len+1,10)," "));
  908. $len += strlen($tag) + strlen($codepieces[$i]) + 2;
  909. $dummy = preg_match('/[^>]*/', $codepieces[$i], $reg);
  910. // Fetches the attributes for the tag
  911. $attributes = $this->get_tag_attributes($reg[0]);
  912. $hrefData = array();
  913. $hrefData['ref'] = ($attributes['href'] ? $attributes['href'] : $hrefData['ref'] = $attributes['action']);
  914. if ($hrefData['ref']) {
  915. // Finds out if the value had quotes around it
  916. $hrefData['quotes'] = (substr($codepieces[$i],strpos($codepieces[$i], $hrefData["ref"])-1,1) == '"') ? '"' : '';
  917. // subst_str is the string to look for, when substituting lateron
  918. $hrefData['subst_str'] = $hrefData['quotes'].$hrefData['ref'].$hrefData['quotes'];
  919. if ($hrefData['ref'] && substr(trim($hrefData['ref']),0,1) != "#" && !strstr($this->href_fullpath_list,"|".$hrefData['subst_str']."|")) {
  920. $this->href_fullpath_list .= "|".$hrefData['subst_str']."|";
  921. $hrefData['absRef'] = $this->absRef($hrefData['ref']);
  922. $hrefData['tag'] = $tag;
  923. $this->theParts['html']['hrefs'][] = $hrefData;
  924. }
  925. }
  926. }
  927. // Extracts TYPO3 specific links made by the openPic() JS function
  928. $codepieces = explode("onClick=\"openPic('", $html_code);
  929. $pieces = count($codepieces);
  930. for($i = 1; $i < $pieces; $i++) {
  931. $showpic_linkArr = explode("'",$codepieces[$i]);
  932. $hrefData['ref'] = $showpic_linkArr[0];
  933. if ($hrefData['ref']) {
  934. $hrefData['quotes'] = "'";
  935. // subst_str is the string to look for, when substituting lateron
  936. $hrefData['subst_str'] = $hrefData['quotes'].$hrefData['ref'].$hrefData['quotes'];
  937. if ($hrefData['ref'] && !strstr($this->href_fullpath_list,"|".$hrefData['subst_str']."|")) {
  938. $this->href_fullpath_list .= "|".$hrefData['subst_str']."|";
  939. $hrefData['absRef'] = $this->absRef($hrefData['ref']);
  940. $this->theParts['html']['hrefs'][] = $hrefData;
  941. }
  942. }
  943. }
  944. }
  945. /**
  946. * extracts all media-links from $this->theParts["html"]["content"]
  947. *
  948. * @return array two-dimensional array with information about each frame
  949. */
  950. public function extractFramesInfo() {
  951. $htmlCode = $this->theParts['html']['content'];
  952. $info = array();
  953. if (strpos(' '.$htmlCode,'<frame ')) {
  954. $attribRegex = $this->tag_regex('frame');
  955. // Splits the document by the beginning of the above tags
  956. $codepieces = preg_split($attribRegex, $htmlCode, 1000000);
  957. $pieces = count($codepieces);
  958. for($i = 1; $i < $pieces; $i++) {
  959. $dummy = preg_match('/[^>]*/', $codepieces[$i], $reg);
  960. // Fetches the attributes for the tag
  961. $attributes = $this->get_tag_attributes($reg[0]);
  962. $frame = array();
  963. $frame['src'] = $attributes['src'];
  964. $frame['name'] = $attributes['name'];
  965. $frame['absRef'] = $this->absRef($frame['src']);
  966. $info[] = $frame;
  967. }
  968. return $info;
  969. }
  970. }
  971. /**
  972. * This function substitutes the media-references in $this->theParts["html"]["content"]
  973. *
  974. * @param boolean $absolute: If true, then the refs are substituted with http:// ref's indstead of Content-ID's (cid).
  975. * @return void
  976. */
  977. public function substMediaNamesInHTML($absolute) {
  978. if (is_array($this->theParts['html']['media'])) {
  979. foreach ($this->theParts['html']['media'] as $key => $val) {
  980. if ($val['use_jumpurl'] && $this->jumperURL_prefix) {
  981. $subst = $this->jumperURL_prefix.t3lib_div::rawUrlEncodeFP($val['absRef']);
  982. } else {
  983. $subst = ($absolute) ? $val['absRef'] : 'cid:part'.$key.'.'.$this->messageid;
  984. }
  985. $this->theParts['html']['content'] = str_replace(
  986. $val['subst_str'],
  987. $val['quotes'] . $subst . $val['quotes'],
  988. $this->theParts['html']['content']);
  989. }
  990. }
  991. if (!$absolute) {
  992. $this->fixRollOvers();
  993. }
  994. }
  995. /**
  996. * This function substitutes the hrefs in $this->theParts["html"]["content"]
  997. *
  998. * @return void
  999. */
  1000. public function substHREFsInHTML() {
  1001. if (!is_array($this->theParts['html']['hrefs'])) return;
  1002. foreach ($this->theParts['html']['hrefs'] as $key => $val) {
  1003. // Form elements cannot use jumpurl!
  1004. if ($this->jumperURL_prefix && $val['tag'] != 'form') {
  1005. if ($this->jumperURL_useId) {
  1006. $substVal = $this->jumperURL_prefix.$key;
  1007. } else {
  1008. $substVal = $this->jumperURL_prefix.t3lib_div::rawUrlEncodeFP($val['absRef']);
  1009. }
  1010. } else {
  1011. $substVal = $val['absRef'];
  1012. }
  1013. $this->theParts['html']['content'] = str_replace(
  1014. $val['subst_str'],
  1015. $val['quotes'] . $substVal . $val['quotes'],
  1016. $this->theParts['html']['content']);
  1017. }
  1018. }
  1019. /**
  1020. * This substitutes the http:// urls in plain text with links
  1021. *
  1022. * @param string $content: the content to use to substitute
  1023. * @return string the changed content
  1024. */
  1025. public function substHTTPurlsInPlainText($content) {
  1026. if (!$this->jumperURL_prefix) return $content;
  1027. $textpieces = explode("http://", $content);
  1028. $pieces = count($textpieces);
  1029. $textstr = $textpieces[0];
  1030. for($i = 1; $i<$pieces; $i++) {
  1031. $len = strcspn($textpieces[$i],chr(32).TAB.CRLF);
  1032. if (trim(substr($textstr,-1)) == '' && $len) {
  1033. $lastChar = substr($textpieces[$i],$len-1,1);
  1034. if (!preg_match('/[A-Za-z0-9\/#]/',$lastChar)) {
  1035. $len--;
  1036. }
  1037. $parts = array();
  1038. $parts[0] = "http://".substr($textpieces[$i],0,$len);
  1039. $parts[1] = substr($textpieces[$i],$len);
  1040. if ($this->jumperURL_useId) {
  1041. $this->theParts['plain']['link_ids'][$i] = $parts[0];
  1042. $parts[0] = $this->jumperURL_prefix.'-'.$i;
  1043. } else {
  1044. $parts[0] = $this->jumperURL_prefix.t3lib_div::rawUrlEncodeFP($parts[0]);
  1045. }
  1046. $textstr .= $parts[0].$parts[1];
  1047. } else {
  1048. $textstr .= 'http://'.$textpieces[$i];
  1049. }
  1050. }
  1051. return $textstr;
  1052. }
  1053. /**
  1054. * JavaScript rollOvers cannot support graphics inside of mail.
  1055. * If these exists we must let them refer to the absolute url. By the way:
  1056. * Roll-overs seems to work only on some mail-readers and so far I've seen it
  1057. * work on Netscape 4 message-center (but not 4.5!!)
  1058. *
  1059. * @return void
  1060. */
  1061. public function fixRollOvers() {
  1062. $newContent = '';
  1063. $items = explode('.src',$this->theParts['html']['content']);
  1064. if (count($items) <= 1) return;
  1065. foreach($items as $key => $part) {
  1066. $sub = substr($part, 0, 200);
  1067. if (preg_match('/cid:part[^ "\']*/',$sub,$reg)) {
  1068. // The position of the string
  1069. $thePos = strpos($part,$reg[0]);
  1070. // Finds the id of the media...
  1071. preg_match('/cid:part([^\.]*).*/',$sub,$reg2);
  1072. $theSubStr = $this->theParts['html']['media'][intval($reg2[1])]['absRef'];
  1073. if ($thePos && $theSubStr) {
  1074. // ... and substitutes the javaScript rollover image with this instead
  1075. // If the path is NOT and url, the reference is set to nothing
  1076. if (!strpos(' '.$theSubStr, 'http://')) {
  1077. $theSubStr = 'http://';
  1078. }
  1079. $part = substr($part, 0, $thePos) . $theSubStr . substr($part,$thePos+strlen($reg[0]),strlen($part));
  1080. }
  1081. }
  1082. $newContent .= $part . ((($key+1) != count($items)) ? '.src' : '');
  1083. }
  1084. $this->theParts['html']['content'] = $newContent;
  1085. }
  1086. /*******************************************
  1087. *
  1088. * File and URL-functions
  1089. *
  1090. *******************************************/
  1091. /**
  1092. * Returns base64-encoded content, which is broken every 76 character
  1093. *
  1094. * @param string $inputstr: the string to encode
  1095. * @return string the encoded string
  1096. */
  1097. public function makeBase64($inputstr) {
  1098. return chunk_split(base64_encode($inputstr));
  1099. }
  1100. /**
  1101. * reads the URL or file and determines the Content-type by either guessing or opening a connection to the host
  1102. *
  1103. * @param string $url: the URL to get information of
  1104. * @return mixed either false or the array with information
  1105. */
  1106. public function getExtendedURL($url) {
  1107. $res = array();
  1108. $res['content'] = $this->getURL($url);
  1109. if (!$res['content']) return false;
  1110. $pathInfo = parse_url($url);
  1111. $fileInfo = $this->split_fileref($pathInfo['path']);
  1112. switch ($fileInfo['fileext']) {
  1113. case 'gif':
  1114. case 'png':
  1115. $res['content_type'] = 'image/'.$fileInfo['fileext'];
  1116. break;
  1117. case 'jpg':
  1118. case 'jpeg':
  1119. $res['content_type'] = 'image/jpeg';
  1120. break;
  1121. case 'html':
  1122. case 'htm':
  1123. $res['content_type'] = 'text/html';
  1124. break;
  1125. case 'css':
  1126. $res['content_type'] = 'text/css';
  1127. break;
  1128. case 'swf':
  1129. $res['content_type'] = 'application/x-shockwave-flash';
  1130. break;
  1131. default:
  1132. $res['content_type'] = $this->getMimeType($url);
  1133. }
  1134. return $res;
  1135. }
  1136. /**
  1137. * Adds HTTP user and password (from $this->http_username) to a URL
  1138. *
  1139. * @param string $url: the URL
  1140. * @return string the URL with the added values
  1141. */
  1142. public function addUserPass($url) {
  1143. $user = $this->http_username;
  1144. $pass = $this->http_password;
  1145. $matches = array();
  1146. if ($user && $pass && preg_match('/^(https?:\/\/)/', $url, $matches)) {
  1147. return $matches[1].$user.':'.$pass.'@'.substr($url,strlen($matches[1]));
  1148. }
  1149. return $url;
  1150. }
  1151. /**
  1152. * reads a url or file
  1153. *
  1154. * @param string $url: the URL to fetch
  1155. * @return string the content of the URL
  1156. */
  1157. public function getURL($url) {
  1158. $url = $this->addUserPass($url);
  1159. return t3lib_div::getURL($url);
  1160. }
  1161. /**
  1162. * reads a url or file and strips the HTML-tags AND removes all
  1163. * empty lines. This is used to read plain-text out of a HTML-page
  1164. *
  1165. * @param string $url: the URL to load
  1166. * @return the content
  1167. */
  1168. public function getStrippedURL($url) {
  1169. $content = '';
  1170. if ($fd = fopen($url, "rb")) {
  1171. while (!feof($fd)) {
  1172. $line = fgetss($fd, 5000);
  1173. if (trim($line)) {
  1174. $content .= trim($line) . LF;
  1175. }
  1176. }
  1177. fclose($fd);
  1178. }
  1179. return $content;
  1180. }
  1181. /**
  1182. * This function returns the mime type of the file specified by the url
  1183. *
  1184. * @param string $url: the url
  1185. * @return string $mimeType: the mime type found in the header
  1186. */
  1187. public function getMimeType($url) {
  1188. $mimeType = '';
  1189. $headers = trim(t3lib_div::getURL($url, 2));
  1190. if ($headers) {
  1191. $matches = array();
  1192. if (preg_match('/(Content-Type:[\s]*)([a-zA-Z_0-9\/\-\.\+]*)([\s]|$)/', $headers, $matches)) {
  1193. $mimeType = trim($matches[2]);
  1194. }
  1195. }
  1196. return $mimeType;
  1197. }
  1198. /**
  1199. * Returns the absolute address of a link. This is based on
  1200. * $this->theParts["html"]["path"] being the root-address
  1201. *
  1202. * @param string $ref: address to use
  1203. * @return string the absolute address
  1204. */
  1205. public function absRef($ref) {
  1206. $ref = trim($ref);
  1207. $info = parse_url($ref);
  1208. if ($info['scheme']) {
  1209. return $ref;
  1210. } elseif (preg_match('/^\//',$ref)) {
  1211. $addr = parse_url($this->theParts['html']['path']);
  1212. return $addr['scheme'].'://'.$addr['host'].($addr['port']?':'.$addr['port']:'').$ref;
  1213. } else {
  1214. // If the reference is relative, the path is added, in order for us to fetch the content
  1215. return $this->theParts['html']['path'] . $ref;
  1216. }
  1217. }
  1218. /**
  1219. * Returns information about a file reference
  1220. *…

Large files files are truncated, but you can click here to view the full file