dd90b71bef728996a6bf43f4488ee5a2f69c2ccf
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_readmail.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2013 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 /**
29 * Functions used to read email content
30 * The class is still just a bunch of miscellaneous functions used to read content out of emails
31 *
32 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
33 * @deprecated since 6.0, will be removed with 6.2
34 */
35 class t3lib_readmail {
36
37 /**
38 * @todo Define visibility
39 */
40 public $dateAbbrevs = array(
41 'JAN' => 1,
42 'FEB' => 2,
43 'MAR' => 3,
44 'APR' => 4,
45 'MAY' => 5,
46 'JUN' => 6,
47 'JUL' => 7,
48 'AUG' => 8,
49 'SEP' => 9,
50 'OCT' => 10,
51 'NOV' => 11,
52 'DEC' => 12
53 );
54
55 // = +0100 (CET)
56 /**
57 * @todo Define visibility
58 */
59 public $serverGMToffsetMinutes = 60;
60
61 /**
62 * Deprecation constructor
63 */
64 public function __construct() {
65 \TYPO3\CMS\Core\Utility\GeneralUtility::deprecationLog('Class t3lib_readmail is deprecated and unused since TYPO3 6.0. It will be removed with version 6.2.');
66 }
67
68
69 /*******************************
70 *
71 * General
72 *
73 ********************************/
74 /**
75 * Returns the text content of a mail which has previously been parsed by eg. extractMailHeader()
76 * Probably obsolete since the function fullParse() is more advanced and safer to use.
77 *
78 * @param array $mailParts Output from extractMailHeader()
79 * @return string The content.
80 * @todo Define visibility
81 */
82 public function getMessage($mailParts) {
83 if ($mailParts['content-type']) {
84 $CType = $this->getCType($mailParts['content-type']);
85 if ($CType['boundary']) {
86 $parts = $this->getMailBoundaryParts($CType['boundary'], $mailParts['CONTENT']);
87 $c = $this->getTextContent($parts[0]);
88 } else {
89 $c = $this->getTextContent('Content-Type: ' . $mailParts['content-type'] . '
90 ' . $mailParts['CONTENT']);
91 }
92 } else {
93 $c = $mailParts['CONTENT'];
94 }
95 return $c;
96 }
97
98 /**
99 * Returns the body part of a raw mail message (including headers)
100 * Probably obsolete since the function fullParse() is more advanced and safer to use.
101 *
102 * @param string $content Raw mail content
103 * @return string Body of message
104 * @todo Define visibility
105 */
106 public function getTextContent($content) {
107 $p = $this->extractMailHeader($content);
108 // Here some decoding might be needed...
109 // However we just return what is believed to be the proper notification:
110 return $p['CONTENT'];
111 }
112
113 /**
114 * Splits the body of a mail into parts based on the boundary string given.
115 * Obsolete, use fullParse()
116 *
117 * @param string $boundary Boundary string used to split the content.
118 * @param string $content BODY section of a mail
119 * @return array Parts of the mail based on this
120 * @todo Define visibility
121 */
122 public function getMailBoundaryParts($boundary, $content) {
123 $mParts = explode('--' . $boundary, $content);
124 unset($mParts[0]);
125 $new = array();
126 foreach ($mParts as $val) {
127 if (trim($val) == '--') {
128 break;
129 }
130 $new[] = ltrim($val);
131 }
132 return $new;
133 }
134
135 /**
136 * Returns Content Type plus more.
137 * Obsolete, use fullParse()
138 *
139 * @param string $str "ContentType" string with more
140 * @return array Parts in key/value pairs
141 * @ignore
142 * @todo Define visibility
143 */
144 public function getCType($str) {
145 $parts = explode(';', $str);
146 $cTypes = array();
147 $cTypes['ContentType'] = $parts[0];
148 next($parts);
149 while (list(, $ppstr) = each($parts)) {
150 $mparts = explode('=', $ppstr, 2);
151 if (count($mparts) > 1) {
152 $cTypes[strtolower(trim($mparts[0]))] = preg_replace('/^"/', '', trim(preg_replace('/"$/', '', trim($mparts[1]))));
153 } else {
154 $cTypes[] = $ppstr;
155 }
156 }
157 return $cTypes;
158 }
159
160 /**
161 * Analyses the return-mail content for the Dmailer module - used to find what reason there was for rejecting the mail
162 * Used by the Dmailer, but not exclusively.
163 *
164 * @param string $c Message body/text
165 * @return array Key/value pairs with analysis result. Eg. "reason", "content", "reason_text", "mailserver" etc.
166 * @todo Define visibility
167 */
168 public function analyseReturnError($c) {
169 $cp = array();
170 // QMAIL
171 if (strstr($c, '--- Below this line is a copy of the message.')) {
172 // Splits by the QMAIL divider
173 list($c) = explode('--- Below this line is a copy of the message.', $c);
174 $cp['content'] = trim($c);
175 $parts = explode('>:', $c, 2);
176 $cp['reason_text'] = trim($parts[1]);
177 $cp['mailserver'] = 'Qmail';
178 if (preg_match('/550|no mailbox|account does not exist/i', $cp['reason_text'])) {
179 // 550 Invalid recipient
180 $cp['reason'] = 550;
181 } elseif (stristr($cp['reason_text'], 'couldn\'t find any host named')) {
182 // Bad host
183 $cp['reason'] = 2;
184 } elseif (preg_match('/Error in Header|invalid Message-ID header/i', $cp['reason_text'])) {
185 $cp['reason'] = 554;
186 } else {
187 $cp['reason'] = -1;
188 }
189 } elseif (strstr($c, 'The Postfix program')) {
190 // Postfix
191 $cp['content'] = trim($c);
192 $parts = explode('>:', $c, 2);
193 $cp['reason_text'] = trim($parts[1]);
194 $cp['mailserver'] = 'Postfix';
195 if (stristr($cp['reason_text'], '550')) {
196 // 550 Invalid recipient, User unknown
197 $cp['reason'] = 550;
198 } elseif (stristr($cp['reason_text'], '553')) {
199 // No such user
200 $cp['reason'] = 553;
201 } elseif (stristr($cp['reason_text'], '551')) {
202 // Mailbox full
203 $cp['reason'] = 551;
204 } else {
205 $cp['reason'] = -1;
206 }
207 } else {
208 // No-named:
209 $cp['content'] = trim($c);
210 $cp['reason_text'] = trim(substr($c, 0, 1000));
211 $cp['mailserver'] = 'unknown';
212 if (preg_match('/Unknown Recipient|Delivery failed 550|Receiver not found|User not listed|recipient problem|Delivery to the following recipients failed|User unknown|recipient name is not recognized/i', $cp['reason_text'])) {
213 // 550 Invalid recipient, User unknown
214 $cp['reason'] = 550;
215 } elseif (preg_match('/over quota|mailbox full/i', $cp['reason_text'])) {
216 $cp['reason'] = 551;
217 } elseif (preg_match('/Error in Header/i', $cp['reason_text'])) {
218 $cp['reason'] = 554;
219 } else {
220 $cp['reason'] = -1;
221 }
222 }
223 return $cp;
224 }
225
226 /**
227 * Decodes a header-string with the =?....?= syntax including base64/quoted-printable encoding.
228 *
229 * @param string $str A string (encoded or not) from a mail header, like sender name etc.
230 * @return string The input string, but with the parts in =?....?= decoded.
231 * @todo Define visibility
232 */
233 public function decodeHeaderString($str) {
234 $parts = explode('=?', $str, 2);
235 if (count($parts) == 2) {
236 list($charset, $encType, $encContent) = explode('?', $parts[1], 3);
237 $subparts = explode('?=', $encContent, 2);
238 $encContent = $subparts[0];
239 switch (strtolower($encType)) {
240 case 'q':
241 $encContent = quoted_printable_decode($encContent);
242 $encContent = str_replace('_', ' ', $encContent);
243 break;
244 case 'b':
245 $encContent = base64_decode($encContent);
246 break;
247 }
248 // Calls decodeHeaderString recursively for any subsequent encoded section.
249 $parts[1] = $encContent . $this->decodeHeaderString($subparts[1]);
250 }
251 return implode('', $parts);
252 }
253
254 /**
255 * Extracts name/email parts from a header field (like 'To:' or 'From:' with name/email mixed up.
256 *
257 * @param string $str Value from a header field containing name/email values.
258 * @return array Array with the name and email in. Email is validated, otherwise not set.
259 * @todo Define visibility
260 */
261 public function extractNameEmail($str) {
262 $outArr = array();
263 // Email:
264 $reg = '';
265 preg_match('/<([^>]*)>/', $str, $reg);
266 if (\TYPO3\CMS\Core\Utility\GeneralUtility::validEmail($str)) {
267 $outArr['email'] = $str;
268 } elseif ($reg[1] && \TYPO3\CMS\Core\Utility\GeneralUtility::validEmail($reg[1])) {
269 $outArr['email'] = $reg[1];
270 // Find name:
271 list($namePart) = explode($reg[0], $str);
272 if (trim($namePart)) {
273 $reg = '';
274 preg_match('/"([^"]*)"/', $str, $reg);
275 if (trim($reg[1])) {
276 $outArr['name'] = trim($reg[1]);
277 } else {
278 $outArr['name'] = trim($namePart);
279 }
280 }
281 }
282 return $outArr;
283 }
284
285 /**
286 * Returns the data from the 'content-type' field. That is the boundary, charset and mime-type
287 *
288 * @param string $contentTypeStr "Content-type-string
289 * @return array key/value pairs with the result.
290 * @todo Define visibility
291 */
292 public function getContentTypeData($contentTypeStr) {
293 $outValue = array();
294 $cTypeParts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(';', $contentTypeStr, 1);
295 // Content type, first value is supposed to be the mime-type, whatever after the first is something else.
296 $outValue['_MIME_TYPE'] = $cTypeParts[0];
297 reset($cTypeParts);
298 next($cTypeParts);
299 while (list(, $v) = Each($cTypeParts)) {
300 $reg = '';
301 preg_match('/([^=]*)="(.*)"/i', $v, $reg);
302 if (trim($reg[1]) && trim($reg[2])) {
303 $outValue[strtolower($reg[1])] = $reg[2];
304 }
305 }
306 return $outValue;
307 }
308
309 /**
310 * Makes a UNIX-date based on the timestamp in the 'Date' header field.
311 *
312 * @param string $dateStr String with a timestamp according to email standards.
313 * @return integer The timestamp converted to unix-time in seconds and compensated for GMT/CET ($this->serverGMToffsetMinutes);
314 * @todo Define visibility
315 */
316 public function makeUnixDate($dateStr) {
317 $dateParts = explode(',', $dateStr);
318 $dateStr = count($dateParts) > 1 ? $dateParts[1] : $dateParts[0];
319 $spaceParts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(' ', $dateStr, 1);
320 $spaceParts[1] = $this->dateAbbrevs[strtoupper($spaceParts[1])];
321 $timeParts = explode(':', $spaceParts[3]);
322 $timeStamp = mktime($timeParts[0], $timeParts[1], $timeParts[2], $spaceParts[1], $spaceParts[0], $spaceParts[2]);
323 $offset = $this->getGMToffset($spaceParts[4]);
324 // Compensates for GMT by subtracting the number of seconds which the date is offset from serverTime
325 $timeStamp -= $offset * 60;
326 return $timeStamp;
327 }
328
329 /**
330 * Parsing the GMT offset value from a mail timestamp.
331 *
332 * @param string $GMT A string like "+0100" or so.
333 * @return integer Minutes to offset the timestamp
334 * @access private
335 * @todo Define visibility
336 */
337 public function getGMToffset($GMT) {
338 $GMToffset = substr($GMT, 1, 2) * 60 + substr($GMT, 3, 2);
339 $GMToffset *= substr($GMT, 0, 1) == '+' ? 1 : -1;
340 $GMToffset -= $this->serverGMToffsetMinutes;
341 return $GMToffset;
342 }
343
344 /**
345 * This returns the mail header items in an array with associative keys and the mail body part in another CONTENT field
346 *
347 * @param string $content Raw mail content
348 * @param integer $limit A safety limit that will put a upper length to how many header chars will be processed. Set to zero means that there is no limit. (Uses a simple substr() to limit the amount of mail data to process to avoid run-away)
349 * @return array An array where each key/value pair is a header-key/value pair. The mail BODY is returned in the key 'CONTENT' if $limit is not set!
350 * @todo Define visibility
351 */
352 public function extractMailHeader($content, $limit = 0) {
353 if ($limit) {
354 $content = substr($content, 0, $limit);
355 }
356 $lines = explode(LF, ltrim($content));
357 $headers = array();
358 $p = '';
359 foreach ($lines as $k => $str) {
360 if (!trim($str)) {
361 break;
362 }
363 // Header finished
364 $parts = explode(' ', $str, 2);
365 if ($parts[0] && substr($parts[0], -1) == ':') {
366 $p = strtolower(substr($parts[0], 0, -1));
367 if (isset($headers[$p])) {
368 $headers[$p . '.'][] = $headers[$p];
369 $headers[$p] = '';
370 }
371 $headers[$p] = trim($parts[1]);
372 } else {
373 $headers[$p] .= ' ' . trim($str);
374 }
375 unset($lines[$k]);
376 }
377 if (!$limit) {
378 $headers['CONTENT'] = ltrim(implode(LF, $lines));
379 }
380 return $headers;
381 }
382
383 /**
384 * The extended version of the extractMailHeader() which will also parse all the content body into an array and further process the header fields and decode content etc. Returns every part of the mail ready to go.
385 *
386 * @param string $content Raw email input.
387 * @return array Multidimensional array with all parts of the message organized nicely. Use t3lib_utility_Debug::debug() to analyse it visually.
388 * @todo Define visibility
389 */
390 public function fullParse($content) {
391 // *************************
392 // PROCESSING the HEADER part of the mail
393 // *************************
394 // Splitting header and body of mail:
395 $mailParts = $this->extractMailHeader($content);
396 // Decoding header values which potentially can be encoded by =?...?=
397 $list = explode(',', 'subject,thread-topic,from,to');
398 foreach ($list as $headerType) {
399 if (isset($mailParts[$headerType])) {
400 $mailParts[$headerType] = $this->decodeHeaderString($mailParts[$headerType]);
401 }
402 }
403 // Separating email/names from header fields which can contain email addresses.
404 $list = explode(',', 'from,to,reply-to,sender,return-path');
405 foreach ($list as $headerType) {
406 if (isset($mailParts[$headerType])) {
407 $mailParts['_' . strtoupper($headerType)] = $this->extractNameEmail($mailParts[$headerType]);
408 }
409 }
410 // Decode date from human-readable format to unix-time (includes compensation for GMT CET)
411 $mailParts['_DATE'] = $this->makeUnixDate($mailParts['date']);
412 // Transfer encodings of body content
413 switch (strtolower($mailParts['content-transfer-encoding'])) {
414 case 'quoted-printable':
415 $mailParts['CONTENT'] = quoted_printable_decode($mailParts['CONTENT']);
416 break;
417 case 'base64':
418 $mailParts['CONTENT'] = base64_decode($mailParts['CONTENT']);
419 break;
420 }
421 // Content types
422 $mailParts['_CONTENT_TYPE_DAT'] = $this->getContentTypeData($mailParts['content-type']);
423 // *************************
424 // PROCESSING the CONTENT part of the mail (the body)
425 // *************************
426 $cType = strtolower($mailParts['_CONTENT_TYPE_DAT']['_MIME_TYPE']);
427 // Only looking for 'multipart' in string.
428 $cType = substr($cType, 0, 9);
429 switch ($cType) {
430 case 'multipart':
431 if ($mailParts['_CONTENT_TYPE_DAT']['boundary']) {
432 $contentSectionParts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode('--' . $mailParts['_CONTENT_TYPE_DAT']['boundary'], $mailParts['CONTENT'], 1);
433 $contentSectionParts_proc = array();
434 foreach ($contentSectionParts as $k => $v) {
435 if (substr($v, 0, 2) == '--') {
436 break;
437 }
438 $contentSectionParts_proc[$k] = $this->fullParse($v);
439 }
440 $mailParts['CONTENT'] = $contentSectionParts_proc;
441 } else {
442 $mailParts['CONTENT'] = 'ERROR: No boundary found.';
443 }
444 break;
445 default:
446 if (strtolower($mailParts['_CONTENT_TYPE_DAT']['charset']) == 'utf-8') {
447 $mailParts['CONTENT'] = utf8_decode($mailParts['CONTENT']);
448 }
449 break;
450 }
451 return $mailParts;
452 }
453
454 }
455
456 ?>