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