PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/t3lib/class.t3lib_readmail.php

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