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