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