Newer
Older
<?php
/*********************************************************************
class.mailparse.php
Mail parsing helper class.
Mail parsing will change once we move to PHP5
Peter Rotich <peter@osticket.com>
Copyright (c) 2006-2012 osTicket
http://www.osticket.com
Released under the GNU General Public License WITHOUT ANY WARRANTY.
See LICENSE.TXT for details.
vim: expandtab sw=4 ts=4 sts=4:
**********************************************************************/
require_once(PEAR_DIR.'Mail/mimeDecode.php');
require_once(PEAR_DIR.'Mail/RFC822.php');
class Mail_Parse {
var $mime_message;
var $include_bodies;
var $decode_headers;
var $decode_bodies;
var $struct;
function Mail_parse($mimeMessage,$includeBodies=true,$decodeHeaders=TRUE,$decodeBodies=TRUE){
$this->mime_message=$mimeMessage;
$this->include_bodies=$includeBodies;
$this->decode_headers=$decodeHeaders;
$this->decode_bodies=$decodeBodies;
}
function decode() {
$params = array('crlf' => "\r\n",
'input' =>$this->mime_message,
'include_bodies'=> $this->include_bodies,
'decode_headers'=> $this->decode_headers,
'decode_bodies' => $this->decode_bodies);
$this->splitBodyHeader();
$this->struct=Mail_mimeDecode::decode($params);
return (PEAR::isError($this->struct) || !(count($this->struct->headers)>1))?FALSE:TRUE;
}
function splitBodyHeader() {
if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s",
$this->mime_message,
$match)) { # nolint
$this->header=$match[1]; # nolint
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
}
}
/**
* Takes the header section of an email message with the form of
* Header: Value
* and returns a hashtable of header-name => value pairs. Also, this
* function properly handles header values that span multiple lines
* (such as Content-Type).
*
* Specify $as_array to TRUE to keep all header values. If a header is
* specified more than once, all the values are placed in an array under
* the header key. If left as FALSE, only the value given in the last
* occurance of the header is retained.
*/
/* static */ function splitHeaders($headers_text, $as_array=false) {
$headers = preg_split("/\r?\n/", $headers_text);
for ($i=0, $k=count($headers); $i<$k; $i++) {
# XXX: Might tabs be used here?
if (substr($headers[$i], 0, 1) == " ") {
# Continuation from previous header (runon to next line)
$j=$i-1; while (!isset($headers[$j]) && $j>0) $j--;
$headers[$j] .= "\n".ltrim($headers[$i]);
unset($headers[$i]);
} elseif (strlen($headers[$i]) == 0) {
unset($headers[$i]);
}
}
$array = array();
foreach ($headers as $hdr) {
list($name, $val) = explode(": ", $hdr, 2);
# Create list of values if header is specified more than once
if ($array[$name] && $as_array) {
if (is_array($array[$name])) $array[$name][] = $val;
else $array[$name] = array($array[$name], $val);
} else {
$array[$name] = $val;
}
}
return $array;
}
function getStruct(){
return $this->struct;
}
function getHeader() {
if(!$this->header) $this->splitBodyHeader();
return $this->header;
}
function getError(){
return PEAR::isError($this->struct)?$this->struct->getMessage():'';
}
function getFromAddressList(){
return Mail_Parse::parseAddressList($this->struct->headers['from']);
}
function getToAddressList(){
//Delivered-to incase it was a BBC mail.
return Mail_Parse::parseAddressList($this->struct->headers['to']?$this->struct->headers['to']:$this->struct->headers['delivered-to']);
}
function getCcAddressList(){
return $this->struct->headers['cc']?Mail_Parse::parseAddressList($this->struct->headers['cc']):null;
}
function getMessageId(){
return $this->struct->headers['message-id'];
}
function getSubject(){
return $this->struct->headers['subject'];
}
function getBody(){
$body='';
if(!($body=$this->getPart($this->struct,'text/plain'))) {
if(($body=$this->getPart($this->struct,'text/html'))) {
//Cleanup the html.
$body=str_replace("</DIV><DIV>", "\n", $body);
$body=str_replace(array("<br>", "<br />", "<BR>", "<BR />"), "\n", $body);
$body=Format::striptags(Format::html($body));
}
}
return $body;
}
function getPart($struct,$ctypepart) {
if($struct && !$struct->parts) {
$ctype = @strtolower($struct->ctype_primary.'/'.$struct->ctype_secondary);
if($ctype && strcasecmp($ctype,$ctypepart)==0)
return $struct->body;
}
$data='';
if($struct && $struct->parts) {
foreach($struct->parts as $i=>$part) {
if($part && !$part->disposition && ($text=$this->getPart($part,$ctypepart)))
$data.=$text;
}
}
return $data;
}
function mime_encode($text, $charset=null, $encoding='utf-8') {
return Format::encode($text, $charset, $encoding);
}
function getAttachments($part=null){
if($part==null)
$part=$this->getStruct();
if($part && $part->disposition
&& (!strcasecmp($part->disposition,'attachment')
|| !strcasecmp($part->disposition,'inline')
|| !strcasecmp($part->ctype_primary,'image'))){
if(!($filename=$part->d_parameters['filename']) && $part->d_parameters['filename*'])
$filename=$part->d_parameters['filename*']; //Do we need to decode?
$file=array(
'name' => $filename,
'type' => strtolower($part->ctype_primary.'/'.$part->ctype_secondary),
'data' => $this->mime_encode($part->body, $part->ctype_parameters['charset'])
);
if(!$this->decode_bodies && $part->headers['content-transfer-encoding'])
$file['encoding'] = $part->headers['content-transfer-encoding'];
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
}
$files=array();
if($part->parts){
foreach($part->parts as $k=>$p){
if($p && ($result=$this->getAttachments($p))) {
$files=array_merge($files,$result);
}
}
}
return $files;
}
function getPriority(){
return Mail_Parse::parsePriority($this->getHeader());
}
function parsePriority($header=null){
$priority=0;
if($header && ($begin=strpos($header,'X-Priority:'))!==false){
$begin+=strlen('X-Priority:');
$xpriority=preg_replace("/[^0-9]/", "",substr($header, $begin, strpos($header,"\n",$begin) - $begin));
if(!is_numeric($xpriority))
$priority=0;
elseif($xpriority>4)
$priority=1;
elseif($xpriority>=3)
$priority=2;
elseif($xpriority>0)
$priority=3;
}
return $priority;
}
function parseAddressList($address){
return Mail_RFC822::parseAddressList($address, null, null,false);
}
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
function parse($rawemail) {
$parser= new Mail_Parse($rawemail);
return ($parser && $parser->decode())?$parser:null;
}
}
class EmailDataParser {
var $stream;
var $error;
function EmailDataParser($stream=null) {
$this->stream = $stream;
}
function parse($stream) {
$contents ='';
if(is_resource($stream)) {
while(!feof($stream))
$contents .= fread($stream, 8192);
} else {
$contents = $stream;
}
$parser= new Mail_Parse($contents);
if(!$parser->decode()) //Decode...returns false on decoding errors
return $this->err('Email parse failed ['.$parser->getError().']');
$data =array();
//FROM address: who sent the email.
if(($fromlist = $parser->getFromAddressList()) && !PEAR::isError($fromlist)) {
$from=$fromlist[0]; //Default.
foreach($fromlist as $fromobj) {
if(!Validator::is_email($fromobj->mailbox.'@'.$fromobj->host)) continue;
$from = $fromobj;
break;
}
$data['name'] = trim($from->personal,'"');
if($from->comment && $from->comment[0])
$data['name'].= ' ('.$from->comment[0].')';
$data['email'] = $from->mailbox.'@'.$from->host;
}
//TO Address:Try to figure out the email address... associated with the incoming email.
$emailId = 0;
if(($tolist = $parser->getToAddressList())) {
foreach ($tolist as $toaddr) {
if(($emailId=Email::getIdByEmail($toaddr->mailbox.'@'.$toaddr->host)))
break;
}
}
//maybe we got CC'ed??
if(!$emailId && ($cclist=$parser->getCcAddressList())) {
foreach ($cclist as $ccaddr) {
if(($emailId=Email::getIdByEmail($ccaddr->mailbox.'@'.$ccaddr->host)))
break;
}
}
$data['subject'] = Format::utf8encode($parser->getSubject());
$data['message'] = Format::utf8encode(Format::stripEmptyLines($parser->getBody()));
$data['header'] = $parser->getHeader();
$data['mid'] = $parser->getMessageId();
$data['priorityId'] = $parser->getPriority();
$data['emailId'] = $emailId;
//attachments XXX: worry about encoding??
$data['attachments'] = $parser->getAttachments();
return $data;
}
function err($error) {
$this->error = $error;
return false;
}
function getError() {
return $this->lastError();
}
function lastError() {
return $this->error;
}