[TASK] Remove trailing newlines from EOF
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_formmail.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 * Contains a class for formmail
29 *
30 * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
31 *
32 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
33 */
34 /**
35 * [CLASS/FUNCTION INDEX of SCRIPT]
36 *
37 *
38 *
39 * 69: class t3lib_formmail
40 * 95: function start($V,$base64=false)
41 * 172: function addAttachment($file, $filename)
42 *
43 * TOTAL FUNCTIONS: 2
44 * (This index is automatically created/updated by the extension "extdeveval")
45 *
46 */
47
48
49 /**
50 * Formmail class, used by the TYPO3 "cms" extension (default frontend) to send email forms.
51 *
52 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
53 * @package TYPO3
54 * @subpackage t3lib
55 * @see tslib_fe::sendFormmail(), t3lib/formmail.php
56 */
57 class t3lib_formmail {
58 protected $reserved_names = 'recipient,recipient_copy,auto_respond_msg,auto_respond_checksum,redirect,subject,attachment,from_email,from_name,replyto_email,replyto_name,organisation,priority,html_enabled,quoted_printable,submit_x,submit_y';
59 protected $dirtyHeaders = array(); // collection of suspicious header data, used for logging
60
61 protected $characterSet;
62 protected $subject;
63 protected $fromName;
64 protected $replyToName;
65 protected $organisation;
66 protected $fromAddress;
67 protected $replyToAddress;
68 protected $priority;
69 protected $autoRespondMessage;
70 protected $encoding = 'quoted-printable';
71
72 /** @var t3lib_mail_Message */
73 protected $mailMessage;
74 protected $recipient;
75 protected $plainContent = '';
76
77 /** @var array Files to clean up at the end (attachments) */
78 protected $temporaryFiles = array();
79
80 /**
81 * Start function
82 * This class is able to generate a mail in formmail-style from the data in $V
83 * Fields:
84 *
85 * [recipient]: email-adress of the one to receive the mail. If array, then all values are expected to be recipients
86 * [attachment]: ....
87 *
88 * [subject]: The subject of the mail
89 * [from_email]: Sender email. If not set, [email] is used
90 * [from_name]: Sender name. If not set, [name] is used
91 * [replyto_email]: Reply-to email. If not set [from_email] is used
92 * [replyto_name]: Reply-to name. If not set [from_name] is used
93 * [organisation]: Organization (header)
94 * [priority]: Priority, 1-5, default 3
95 * [html_enabled]: If mail is sent as html
96 * [use_base64]: If set, base64 encoding will be used instead of quoted-printable
97 *
98 * @param array Contains values for the field names listed above (with slashes removed if from POST input)
99 * @param boolean Whether to base64 encode the mail content
100 * @return void
101 */
102 function start($valueList, $base64 = false) {
103
104 $this->mailMessage = t3lib_div::makeInstance('t3lib_mail_Message');
105
106 if ($GLOBALS['TSFE']->config['config']['formMailCharset']) {
107 // Respect formMailCharset if it was set
108 $this->characterSet = $GLOBALS['TSFE']->csConvObj->parse_charset($GLOBALS['TSFE']->config['config']['formMailCharset']);
109 } elseif ($GLOBALS['TSFE']->metaCharset != $GLOBALS['TSFE']->renderCharset) {
110 // Use metaCharset for mail if different from renderCharset
111 $this->characterSet = $GLOBALS['TSFE']->metaCharset;
112 }
113
114 if ($base64 || $valueList['use_base64']) {
115 $this->encoding = 'base64';
116 }
117
118 if (isset($valueList['recipient'])) {
119 // convert form data from renderCharset to mail charset
120 $this->subject = ($valueList['subject'])
121 ? $valueList['subject']
122 : 'Formmail on ' . t3lib_div::getIndpEnv('HTTP_HOST');
123 $this->subject = $this->sanitizeHeaderString($this->subject);
124
125 $this->fromName = ($valueList['from_name'])
126 ? $valueList['from_name']
127 : (($valueList['name']) ? $valueList['name'] : '');
128 $this->fromName = $this->sanitizeHeaderString($this->fromName);
129
130 $this->replyToName = ($valueList['replyto_name']) ? $valueList['replyto_name'] : $this->fromName;
131 $this->replyToName = $this->sanitizeHeaderString($this->replyToName);
132
133 $this->organisation = ($valueList['organisation']) ? $valueList['organisation'] : '';
134 $this->organisation = $this->sanitizeHeaderString($this->organisation);
135
136 $this->fromAddress = ($valueList['from_email']) ? $valueList['from_email'] : (
137 ($valueList['email']) ? $valueList['email'] : ''
138 );
139 if (!t3lib_div::validEmail($this->fromAddress)) {
140 $this->fromAddress = t3lib_utility_Mail::getSystemFromAddress();
141 $this->fromName = t3lib_utility_Mail::getSystemFromName();
142 }
143
144 $this->replyToAddress = ($valueList['replyto_email']) ? $valueList['replyto_email'] : $this->fromAddress;
145
146 $this->priority = ($valueList['priority']) ? t3lib_div::intInRange($valueList['priority'], 1, 5) : 3;
147
148 // auto responder
149 $this->autoRespondMessage = (trim($valueList['auto_respond_msg']) && $this->fromAddress)
150 ? trim($valueList['auto_respond_msg'])
151 : '';
152
153 if ($this->autoRespondMessage !== '') {
154 // Check if the value of the auto responder message has been modified with evil intentions
155 $autoRespondChecksum = $valueList['auto_respond_checksum'];
156 $correctHmacChecksum = t3lib_div::hmac($this->autoRespondMessage);
157 if ($autoRespondChecksum !== $correctHmacChecksum) {
158 t3lib_div::sysLog('Possible misuse of t3lib_formmail auto respond method. Subject: ' . $valueList['subject'],
159 'Core',
160 3);
161 return;
162 } else {
163 $this->autoRespondMessage = $this->sanitizeHeaderString($this->autoRespondMessage);
164 }
165 }
166
167 $plainTextContent = '';
168 $htmlContent = '<table border="0" cellpadding="2" cellspacing="2">';
169
170 // Runs through $V and generates the mail
171 if (is_array($valueList)) {
172 foreach ($valueList as $key => $val) {
173 if (!t3lib_div::inList($this->reserved_names, $key)) {
174 $space = (strlen($val) > 60) ? LF : '';
175 $val = (is_array($val) ? implode($val, LF) : $val);
176
177 // convert form data from renderCharset to mail charset (HTML may use entities)
178 $plainTextValue = $val;
179 $HtmlValue = htmlspecialchars($val);
180
181 $plainTextContent .= strtoupper($key) . ': ' . $space . $plainTextValue . LF . $space;
182 $htmlContent .= '<tr><td bgcolor="#eeeeee"><font face="Verdana" size="1"><strong>' . strtoupper($key)
183 . '</strong></font></td><td bgcolor="#eeeeee"><font face="Verdana" size="1">' . nl2br($HtmlValue)
184 . '&nbsp;</font></td></tr>';
185 }
186 }
187 }
188 $htmlContent .= '</table>';
189
190 $this->plainContent = $plainTextContent;
191
192 if ($valueList['html_enabled']) {
193 $this->mailMessage->setBody($htmlContent, 'text/html');
194 $this->mailMessage->addPart($plainTextContent, 'text/plain');
195 } else {
196 $this->mailMessage->setBody($plainTextContent, 'text/plain');
197 }
198
199 for ($a = 0; $a < 10; $a++) {
200 $variableName = 'attachment' . (($a) ? $a : '');
201 if (!isset($_FILES[$variableName])) {
202 continue;
203 }
204 if (!is_uploaded_file($_FILES[$variableName]['tmp_name'])) {
205 t3lib_div::sysLog('Possible abuse of t3lib_formmail: temporary file "' . $_FILES[$variableName]['tmp_name']
206 . '" ("' . $_FILES[$variableName]['name'] . '") was not an uploaded file.', 'Core', 3);
207 }
208 if ($_FILES[$variableName]['tmp_name']['error'] !== UPLOAD_ERR_OK) {
209 t3lib_div::sysLog('Error in uploaded file in t3lib_formmail: temporary file "'
210 . $_FILES[$variableName]['tmp_name'] . '" ("' . $_FILES[$variableName]['name'] . '") Error code: '
211 . $_FILES[$variableName]['tmp_name']['error'], 'Core', 3);
212 }
213 $theFile = t3lib_div::upload_to_tempfile($_FILES[$variableName]['tmp_name']);
214 $theName = $_FILES[$variableName]['name'];
215
216 if ($theFile && file_exists($theFile)) {
217 if (filesize($theFile) < $GLOBALS['TYPO3_CONF_VARS']['FE']['formmailMaxAttachmentSize']) {
218 $this->mailMessage->attach(Swift_Attachment::fromPath($theFile)->setFilename($theName));
219 }
220 }
221 $this->temporaryFiles[] = $theFile;
222 }
223
224 $from = $this->fromName ? array($this->fromAddress => $this->fromName) : array($this->fromAddress);
225 $this->recipient = $this->parseAddresses($valueList['recipient']);
226 $this->mailMessage->setSubject($this->subject)
227 ->setFrom($from)
228 ->setTo($this->recipient)
229 ->setPriority($this->priority);
230 $replyTo = $this->replyToName ? array($this->replyToAddress => $this->replyToName) : array($this->replyToAddress);
231 $this->mailMessage->addReplyTo($replyTo);
232 $this->mailMessage->getHeaders()->addTextHeader('Organization', $this->organisation);
233 if ($valueList['recipient_copy']) {
234 $this->mailMessage->addCc($this->parseAddresses($valueList['recipient_copy']));
235 }
236 if ($this->characterSet) {
237 $this->mailMessage->setCharset($this->characterSet);
238 }
239 // Ignore target encoding. This is handled automatically by Swift Mailer and overriding the defaults
240 // is not worth the trouble
241
242 // log dirty header lines
243 if ($this->dirtyHeaders) {
244 t3lib_div::sysLog('Possible misuse of t3lib_formmail: see TYPO3 devLog', 'Core', 3);
245 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_DLOG']) {
246 t3lib_div::devLog('t3lib_formmail: ' . t3lib_div::arrayToLogString($this->dirtyHeaders, '', 200), 'Core', 3);
247 }
248 }
249 }
250 }
251
252 /**
253 * Checks string for suspicious characters
254 *
255 * @param string String to check
256 * @return string Valid or empty string
257 */
258 protected function sanitizeHeaderString($string) {
259 $pattern = '/[\r\n\f\e]/';
260 if (preg_match($pattern, $string) > 0) {
261 $this->dirtyHeaders[] = $string;
262 $string = '';
263 }
264 return $string;
265 }
266
267 /**
268 * Parses mailbox headers and turns them into an array.
269 *
270 * Mailbox headers are a comma separated list of 'name <email@example.org' combinations or plain email addresses (or a mix
271 * of these).
272 * The resulting array has key-value pairs where the key is either a number (no display name in the mailbox header) and the
273 * value is the email address, or the key is the email address and the value is the display name.
274 *
275 * @param string $rawAddresses Comma separated list of email addresses (optionally with display name)
276 * @return array Parsed list of addresses.
277 */
278 protected function parseAddresses($rawAddresses = '') {
279 /** @var $addressParser t3lib_mail_Rfc822AddressesParser */
280 $addressParser = t3lib_div::makeInstance('t3lib_mail_Rfc822AddressesParser', $rawAddresses);
281 $addresses = $addressParser->parseAddressList();
282 $addressList = array();
283 foreach ($addresses as $address) {
284 if ($address->personal) {
285 // item with name found ( name <email@example.org> )
286 $addressList[$address->mailbox . '@' . $address->host] = $address->personal;
287 } else {
288 // item without name found ( email@example.org )
289 $addressList[] = $address->mailbox . '@' . $address->host;
290 }
291 }
292 return $addressList;
293 }
294
295 /**
296 * Sends the actual mail and handles autorespond message
297 *
298 * @return boolean
299 */
300 public function sendTheMail() {
301
302 // Sending the mail requires the recipient and message to be set.
303 if (!$this->mailMessage->getTo() || !trim($this->mailMessage->getBody())) {
304 return FALSE;
305 }
306
307 $this->mailMessage->send();
308
309 // Auto response
310 if ($this->autoRespondMessage) {
311 $theParts = explode('/', $this->autoRespondMessage, 2);
312 $theParts[0] = str_replace('###SUBJECT###', $this->subject, $theParts[0]);
313 $theParts[1] = str_replace("/", LF, $theParts[1]);
314 $theParts[1] = str_replace("###MESSAGE###", $this->plainContent, $theParts[1]);
315
316 /** @var $autoRespondMail t3lib_mail_Message */
317 $autoRespondMail = t3lib_div::makeInstance('t3lib_mail_Message');
318 $autoRespondMail->setTo($this->fromAddress)
319 ->setSubject($theParts[0])
320 ->setFrom($this->recipient)
321 ->setBody($theParts[1]);
322 $autoRespondMail->send();
323 }
324 return $this->mailMessage->isSent();
325 }
326
327 /**
328 * Do some cleanup at the end (deleting attachment files)
329 */
330 public function __destruct() {
331 foreach ($this->temporaryFiles as $file) {
332 t3lib_div::unlink_tempfile($file);
333 }
334 }
335 }
336
337
338 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_formmail.php'])) {
339 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_formmail.php']);
340 }
341
342 ?>