forked from djmattyg007/official-library-php-email-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PlancakeEmailParser.php
554 lines (501 loc) · 18.2 KB
/
PlancakeEmailParser.php
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
<?php
/*************************************************************************************
* ===================================================================================*
* Software by: Danyuki Software Limited *
* This file is part of Plancake. *
* *
* Copyright 2009-2010-2011 by: Danyuki Software Limited *
* Support, News, Updates at: http://www.plancake.com *
* Licensed under the LGPL version 3 license. *
* Danyuki Software Limited is registered in England and Wales (Company No. 07554549) *
**************************************************************************************
* Plancake is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License v3.0 for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
**************************************************************************************
*
* Valuable contributions by:
* - Chris
*
* **************************************************************************************/
/**
* Extracts the headers and the body of an email
* Obviously it can't extract the bcc header because it doesn't appear in the content
* of the email.
*
* N.B.: if you deal with non-English languages, we recommend you install the IMAP PHP extension:
* the Plancake PHP Email Parser will detect it and used it automatically for better results.
*
* For more info, check:
* https://github.com/plancake/official-library-php-email-parser
*
* @author dan
*/
class PlancakeEmailParser
{
const PLAINTEXT = 1;
const HTML = 2;
/**
* @var bool
*/
protected $isImapExtensionAvailable = false;
/**
* @var string
*/
protected $emailRawContent;
/**
* @var bool
*/
protected $debug = false;
/**
* @var array
*/
protected $rawFields;
/**
* @var string[]
*/
protected $rawBodyLines;
/**
* Headers that should always replace a previous header of the same type,
* rather than be combined into an array.
*
* @var array
*/
protected $singleHeaders = array(
"orig-date",
"sender",
"reply-to",
"to",
"cc",
"bcc",
"message-id",
"in-reply-to",
"subject",
);
/**
* @param string $emailRawContent
* @param bool $debug
*/
public function __construct($emailRawContent, $debug = false)
{
$this->emailRawContent = $emailRawContent;
$this->debug = $debug;
$this->extractHeadersAndRawBody();
if (function_exists('imap_open')) {
$this->isImapExtensionAvailable = true;
}
}
/**
* @param string $message
*/
protected function debug($message)
{
if ($this->debug === true) {
var_dump($message);
}
}
protected function extractHeadersAndRawBody()
{
$lines = preg_split("/(\r?\n|\r)/", $this->emailRawContent);
$currentHeader = '';
$i = 0;
foreach ($lines as $line) {
if (self::isNewLine($line)) {
// end of headers
$this->rawBodyLines = array_slice($lines, $i);
break;
}
if ($this->isLineStartingWithPrintableChar($line)) {
// start of new header
$result = preg_match('/([^:]+): ?(.*)$/', $line, $matches);
if (!$result) {
$i++;
continue;
}
$newHeader = strtolower($matches[1]);
$value = $matches[2];
if (isset($this->rawFields[$newHeader]) && !is_array($newHeader)) {
if (is_array($this->rawFields[$newHeader])) {
$this->rawFields[$newHeader][] = $value;
} else {
$this->rawFields[$newHeader] = array($this->rawFields[$newHeader], $value);
}
} else {
$this->rawFields[$newHeader] = $value;
}
$currentHeader = $newHeader;
} else {
// more lines related to the current header
if ($currentHeader) { // to prevent notice from empty lines
$withoutIndent = preg_replace("/^\s+/", "", $line);
if (is_array($this->rawFields[$currentHeader])) {
$this->rawFields[$currentHeader][count($this->rawFields[$currentHeader]) - 1] .= $withoutIndent;
} else {
$this->rawFields[$currentHeader] .= $withoutIndent;
}
}
}
$i++;
}
}
/**
* @return array the parsed headers as associative array
*/
public function getHeaders()
{
return $this->rawFields;
}
/**
* @return string (in UTF-8 format)
*/
public function getSubject()
{
if (!isset($this->rawFields['subject'])) {
return null;
}
$ret = '';
if ($this->isImapExtensionAvailable) {
foreach (imap_mime_header_decode($this->rawFields['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 = utf8_encode(iconv_mime_decode($this->rawFields['subject']));
}
return $ret;
}
/**
* @param string $userField
* @return array
*/
public function tokeniseUserField($userField)
{
$userField = trim($userField);
$userFieldChars = self::strSplitUnicode($userField);
$charCount = count($userFieldChars);
$return = array();
$curName = "";
$curEmail = "";
$startChars = array('"' => '"', "<" => ">");
$startChar = null;
for ($x = 0; $x < $charCount; $x++) {
$this->debug("start iteration");
$this->debug(implode("", array_slice($userFieldChars, $x)));
if (strlen($curName) === 0 && isset($startChars[$userFieldChars[$x]])) {
// If we haven't started processing a name yet, and the name starts with one
// of the denoted "start characters", make a note of which character was used
// to start the name, then move onto the next character.
$this->debug("start mark {$userFieldChars[$x]}");
$startChar = $startChars[$userFieldChars[$x]];
} elseif (strlen($curName) === 0 || $startChar !== null) {
$this->debug("start name");
$y = $x;
while (true) {
$curName .= $userFieldChars[$y];
$y++;
if ($y >= $charCount) {
break;
}
if ($startChar !== null) {
// If $startChar is set, it means we need to keep going until
// we find the matching end character. The point of this is to
// not break on things like commas and spaces, because the name
// has probably been quoted so that we don't break on commas
// and spaces.
if ($userFieldChars[$y] === $startChar) {
$y++;
break;
}
} else {
if ($userFieldChars[$y] === " ") {
if (isset($userFieldChars[$y + 1]) && $userFieldChars[$y + 1] === "<") {
// If we hit a space, and it's followed immediately by left
// bracket, it means we're processing a name, and we're about
// to move onto the actual email address.
break;
}
} elseif ($userFieldChars[$y] === ",") {
// If we hit a comma, it means we're processing an email address,
// and we're about to move onto the next entry in the list.
break;
}
}
}
$x = $y;
$startChar = null;
} elseif (strlen($curName) &&
$userFieldChars[$x] === " " &&
$userFieldChars[$x + 1] === "<") {
// We just had a name delimieted by quotes, and now we're about to move
// onto the actual email address.
$this->debug("found opening bracket after a space");
$x++;
} elseif (strlen($curName) &&
$userFieldChars[$x] === "<") {
// We just had a name not delimieted by quotes, and now we're about to
// move onto the actual email address.
$this->debug("found opening bracket");
} else {
// We had a name before the actual email address. We're now grabbing the
// actual email address.
$this->debug("start email");
$y = $x;
while ($userFieldChars[$y] !== ">") {
$curEmail .= $userFieldChars[$y];
$y++;
}
$x = $y;
$return[] = array(
"name" => $curName,
"email" => $curEmail,
);
$curName = "";
$this->debug($return);
}
if (strlen($curName)) {
$this->debug(implode("", array_slice($userFieldChars, $x)));
if ($x >= $charCount || $userFieldChars[$x] === ",") {
// We had a "name" that was actually an email address with no name.
$this->debug("we have an email address with no name");
$return[] = array(
"name" => "",
"email" => $curName,
);
$curEmail = $curName;
$curName = "";
}
}
if (strlen($curEmail)) {
// We've found and saved an email address. This must signal the end
// of an item in the list. Reset, and move to the start of the next
// item (or the end of the list)
$this->debug("we have an email, reset");
$curEmail = "";
$this->debug(implode("", array_slice($userFieldChars, $x)));
while ($x < $charCount && $userFieldChars[$x] !== ",") {
$x++;
}
$this->debug(implode("", array_slice($userFieldChars, $x)));
while ($x < $charCount && $userFieldChars[$x] === " ") {
$x++;
}
$x++;
}
}
$this->debug(implode("", array_slice($userFieldChars, $x)));
return $return;
}
/**
* @return array
*/
public function getTo()
{
if (!isset($this->rawFields['to'])) {
return array();
}
return $this->tokeniseUserField($this->rawFields['to']);
}
/**
* @return array
*/
public function getCc()
{
if (!isset($this->rawFields['cc'])) {
return array();
}
return $this->tokeniseUserField($this->rawFields['cc']);
}
/**
* @return array
*/
public function getBcc()
{
if (!isset($this->rawFields['bcc'])) {
return array();
}
return $this->tokeniseUserField($this->rawFields['bcc']);
}
/**
* @return array
*/
public function getFrom()
{
if (!isset($this->rawFields['from'])) {
return array();
}
return $this->tokeniseUserField($this->rawFields['from']);
}
/**
* @return array
*/
public function getSender()
{
if (!isset($this->rawFields['sender'])) {
return array();
}
$sender = $this->tokeniseUserField($this->rawFields['sender']);
if (isset($sender[0])) {
return $sender[0];
} else {
return array();
}
}
/**
* return string - UTF8 encoded
*
* Example of an email body
*
* --0016e65b5ec22721580487cb20fd
* Content-Type: text/plain; charset=ISO-8859-1
*
* Hi all. I am new to Android development.
* Please help me.
*
* --
* My signature
*
* email: [email protected]
* web: http://www.example.com
*
* --0016e65b5ec22721580487cb20fd
* Content-Type: text/html; charset=ISO-8859-1
*/
public function getBody($returnType = self::PLAINTEXT)
{
$body = '';
$detectedContentType = false;
$contentTransferEncoding = null;
$charset = 'ASCII';
$waitingForContentStart = true;
if ($returnType == self::HTML) {
$contentTypeRegex = '/^Content-Type: ?text\/html/i';
} else {
$contentTypeRegex = '/^Content-Type: ?text\/plain/i';
}
// there could be more than one boundary
preg_match_all('!boundary=(.*?)[;$]!mi', $this->emailRawContent, $matches);
$boundariesRaw = $matches[1];
$boundaries = array();
foreach ($boundariesRaw as $i => $v) {
// sometimes boundaries are delimited by quotes - we want to remove them
$tempboundary = str_replace(array("'", '"'), '', $v);
// actual boundary lines start with --
$boundaries[] = '--' . $tempboundary;
// or start and end with --
$boundaries[] = '--' . $tempboundary . '--';
}
foreach ($this->rawBodyLines as $line) {
if (!$detectedContentType) {
if (preg_match($contentTypeRegex, $line, $matches)) {
$detectedContentType = true;
}
if (preg_match('/charset=(.*)/i', $line, $matches)) {
$charset = strtoupper(trim($matches[1], '"'));
}
} elseif ($detectedContentType && $waitingForContentStart) {
if (preg_match('/charset=(.*)/i', $line, $matches)) {
$charset = strtoupper(trim($matches[1], '"'));
}
if ($contentTransferEncoding == null && preg_match('/^Content-Transfer-Encoding: ?(.*)/i', $line, $matches)) {
$contentTransferEncoding = $matches[1];
}
if (self::isNewLine($line)) {
$waitingForContentStart = false;
}
} else { // ($detectedContentType && !$waitingForContentStart)
// collecting the actual content until we find the delimiter
if (is_array($boundaries)) {
if (in_array($line, $boundaries)) { // found the delimiter
break;
}
}
$body .= $line . "\n";
}
}
if (!$detectedContentType) {
// if here, we missed the text/plain content-type (probably it was
// in the header), thus we assume the whole body is what we are after
$body = implode("\n", $this->rawBodyLines);
}
// removing trailing new lines
$body = preg_replace('/((\r?\n)*)$/', '', $body);
if ($contentTransferEncoding == 'base64') {
$body = base64_decode($body);
} elseif ($contentTransferEncoding == 'quoted-printable') {
$body = quoted_printable_decode($body);
}
if ($charset != 'UTF-8') {
// FORMAT=FLOWED, despite being popular in emails, it is not
// supported by iconv
$charset = str_replace("FORMAT=FLOWED", "", $charset);
$bodyCopy = $body;
$body = iconv($charset, 'UTF-8//TRANSLIT', $body);
if ($body === false) { // iconv returns false on failure
$body = utf8_encode($bodyCopy);
}
}
return $body;
}
/**
* @return string - UTF8 encoded
*/
public function getPlainBody()
{
return $this->getBody(self::PLAINTEXT);
}
/**
* return string - UTF8 encoded
*/
public function getHTMLBody()
{
return $this->getBody(self::HTML);
}
/**
* @param string $headerName the header we want to retrieve
* @return array|string|null the value(s) of the header
*/
public function getHeader($headerName)
{
$headerName = strtolower($headerName);
if (isset($this->rawFields[$headerName])) {
return $this->rawFields[$headerName];
}
return null;
}
/**
* @param string $line
* @return bool
*/
public static function isNewLine($line)
{
$line = str_replace("\r", '', $line);
$line = str_replace("\n", '', $line);
return (strlen($line) === 0);
}
/**
* @param string $line
* @return bool
*/
private function isLineStartingWithPrintableChar($line)
{
return preg_match('/^[A-Za-z]/', $line);
}
/**
* @param string $string
* @return string[]
*/
protected static function strSplitUnicode($string)
{
$return = array();
$len = mb_strlen($string, "UTF-8");
for ($i = 0; $i < $len; $i++) {
$return[] = mb_substr($string, $i, 1, "UTF-8");
}
return $return;
}
}