-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathemailParser.class.php
More file actions
407 lines (339 loc) · 10.4 KB
/
Copy pathemailParser.class.php
File metadata and controls
407 lines (339 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
<?php
/**
* @author CaTz
* @link https://github.com/CaTzil/emailParser
*/
class emailParser
{
/**
*
* @var Boolean
*/
private $isImapExtensionAvailable = false;
/**
*
* @var String
*/
private $emailRawContent;
/**
*
* @var Associative Array
*/
protected $headers;
/**
*
* @var String of the whole headers part
*/
protected $rawHeaders;
/**
*
* @var String of all the mail without the headers
*/
protected $rawBodyParts;
/**
*
* @var String of the email initial boundry
*/
protected $boundry;
/**
*
* @var String charset of the email from the headers
*/
protected $charset;
/**
*
* @var Associative Array with text and html part of the email
*/
protected $bodies;
/**
*
* @var Associative Array with attachments of the email
*/
protected $files;
public function __construct($emailRawContent)
{
$this->emailRawContent = $emailRawContent;
$this->extractHeadersAndRawBody();
$this->parseHeaders();
$this->parseContent();
if (function_exists('imap_open'))
{
$this->isImapExtensionAvailable = true;
}
}
protected function extractHeadersAndRawBody()
{
$splitted_content = preg_split("/(\r?\n\r?\n)/", $this->emailRawContent);
$this->rawHeaders = $splitted_content[0];
$this->rawBodyParts = implode("\n\n", array_slice($splitted_content, 1));
}
protected function parseHeaders()
{
$this->boundry = null;
$this->charset = 'utf-8';
$lines = preg_split("/\r?\n|\r/", $this->rawHeaders);
$currentHeader = '';
foreach ($lines as $line)
{
if (preg_match('/([^:]+): ?(.*)$/', $line, $matches))
{
$newHeader = strtolower(trim($matches[1]));
$value = trim(stripslashes($matches[2]));
if(!isset($this->headers[$newHeader]))
$this->headers[$newHeader] = ($currentHeader == $newHeader) ? $this->headers[$newHeader] . $value : $value;
else
$this->headers[$newHeader] .= ' '.(($currentHeader == $newHeader) ? $this->headers[$newHeader] . $value : $value);
$currentHeader = $newHeader;
}
else
if ($currentHeader)
{ //concate to the current
$this->headers[$currentHeader] .= ' ' . trim($line);
}
}
//check and extract the boundry if exists
if (isset($this->headers["content-type"]))
{
$this->boundry = $this->getBoundry($this->headers["content-type"]);
}
//check and extract the charset if exists
if (isset($this->headers["content-type"]) && preg_match("/charset=(.*)/i", $this->headers["content-type"], $matches))
{
$this->charset = strtolower(trim($matches[1], '"\' '));
}
}
protected function parseContent()
{
// Not modern mail
if ($this->boundry == null)
{
$body = $this->rawBodyParts;
$body = $this->decodeContent($body, $this->headers['content-transfer-encoding'], $this->charset);
$this->bodies['plain'] = strip_tags($body);
$this->bodies['html'] = $body;
}
else
{
$this->parseByBoundry($this->rawBodyParts, $this->boundry);
}
}
protected function parseByBoundry($body, $boundry)
{
$count = substr_count($body, $boundry);
//seperate the body by the boundry
$parts = array();
for ($i = 0, $start = 0; $i < $count - 1; $i++)
{
$start = strpos($body, $boundry, $start) + strlen($boundry);
$end = strpos($body, $boundry, $start);
$parts[] = substr($body, $start, $end - $start);
}
if (is_array($parts) && count($parts))
{
foreach ($parts as $part)
{
if ($innerBoundry = $this->getBoundry($part))
{
$this->parseByBoundry(substr($part, strpos($part, $innerBoundry)), $innerBoundry);
}
else
{
//this part dosnet have boundry, so it pure data!
$this->parseBody($part);
$this->parseAttachment($part);
}
}
}
}
protected function parseBody($data)
{
if ((preg_match("/content-type:\s*text/(html|plain);\s*charset=(.*)/i", $data, $matches))
{
$type = strtolower($matches[1]);
$charset = trim(strtolower(stripslashes($matches[2])), "\"'\r\n ");
$encoding = $this->getEncoding($data);
if (!isset($this->bodies[$type]))
{
$this->bodies[$type] = $this->decodeContent(substr($data, strpos($data, "\n\n")), $encoding, $charset);
}
}
}
protected function parseAttachment($data)
{
if (preg_match("/Content\-Disposition: ?attachment;/i", $data, $matches))
{
$filename = null;
if (preg_match("/filename= ?(.*)/i", $data, $matches))
{
$filename = trim(stripslashes(strtolower($matches[1])), "'\" \r\n");
$filename = iconv_mime_decode($filename, 0, 'utf-8');
}
$content_type = null;
if (preg_match("%Content\-Type: ?([a-z]+/[a-z]+)%i", $data, $matches))
{
$content_type = strtolower($matches[1]);
}
$file["filename"] = $filename;
$file["content_type"] = $content_type;
$encoding = $this->getEncoding($data);
$file["data"] = $this->decodeContent(substr($data, strpos($data, "\n\n")), $encoding, 'utf-8', true);
$this->files[] = $file;
}
}
protected function getBoundry($content)
{
$boundry = '';
if (preg_match("/boundary=(.*)/i", $content, $matches))
{
$boundry = '--' . trim(stripslashes($matches[1]), '"\' ');
}
return $boundry;
}
protected function getEncoding($content)
{
if (preg_match("/Content\-Transfer\-Encoding: ?(.*)/i", $content, $matches))
{
$encoding = trim(strtolower($matches[1]), "'\"\r\n ");
}
else
if (isset($this->headers['content-transfer-encoding']))
{
$encoding = $this->headers['content-transfer-encoding'];
}
else
$encoding = 'base64';
return $encoding;
}
protected function decodeContent($content, $encodedWith, $charset, $isBinary = false)
{
$content = preg_replace('/((\r?\n)*)$/', '', $content);
if ($encodedWith == 'base64')
{
$content = base64_decode($content);
}
elseif ($encodedWith == 'quoted-printable')
{
$content = quoted_printable_decode($content);
}
if ($charset !== 'utf-8')
{
// FORMAT=FLOWED, despite being popular in emails, it is not
// supported by iconv
$charset = str_replace("FORMAT=FLOWED", "", $charset);
$content = iconv($charset, 'utf-8//TRANSLIT', $content);
if ($content === false)
{ // iconv returns FALSE on failure
$content = utf8_encode($content);
}
}
if (!$isBinary)
$content = stripslashes($content);
return $content;
}
/**
*
* @return string (in UTF-8 format)
* @throws Exception if a subject header is not found
*/
public function getSubject()
{
if (!isset($this->headers['subject']))
{
throw new Exception("Couldn't find the subject of the email");
}
$ret = '';
if ($this->isImapExtensionAvailable)
{
foreach (imap_mime_header_decode($this->headers['subject']) as $h)
{ // subject can span into several lines
$charset = ($h->charset == 'default') ? 'US-ASCII' : $h->charset;
$ret .= iconv($charset, "UTF-8//TRANSLIT", $h->text);
}
}
else
{
$ret = iconv_mime_decode($this->headers['subject'], 0, 'UTF-8');
}
return $ret;
}
/**
*
* @return array
*/
public function getCc()
{
if (!isset($this->headers['cc']))
{
return array();
}
return explode(',', $this->headers['cc']);
}
/**
*
* @return array
* @throws Exception if a to header is not found or if there are no recipient
*/
public function getTo()
{
if ((!isset($this->headers['to'])) || (!count($this->headers['to'])))
{
throw new Exception("Couldn't find the recipients of the email");
}
return explode(',', $this->headers['to']);
}
/**
* return string - UTF8 encoded
*/
public function getBody($returnType = 'plain')
{
return (isset($this->bodies[$returnType])) ? $this->bodies[$returnType] : "";
}
/**
* @return string - UTF8 encoded
*
*/
public function getPlainBody()
{
return $this->getBody();
}
/**
* return string - UTF8 encoded
*/
public function getHTMLBody()
{
return $this->getBody('html');
}
/**
* N.B.: if the header doesn't exist an empty string is returned
*
* @param string $headerName - the header we want to retrieve
* @return string - the value of the header
*/
public function getHeader($headerName)
{
$headerName = strtolower($headerName);
if (isset($this->headers[$headerName]))
{
return $this->headers[$headerName];
}
return '';
}
/**
*
* @return Associative Array - array of all the attachments, each entry is assoc array with file info.
*/
public function getAttachments($type='')
{
if($type)
{
foreach($this->files as $file)
{
//check the file type
if(strpos($file["content_type"], $type)!==false || strpos($file["file_name"], '.'.$type))
return $file;
}
}
return $this->files;
}
}
?>