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