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