|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of the ZBateson\MailMimeParser project. |
|
4
|
|
|
* |
|
5
|
|
|
* @license http://opensource.org/licenses/bsd-license.php BSD |
|
6
|
|
|
*/ |
|
7
|
|
|
namespace ZBateson\MailMimeParser; |
|
8
|
|
|
|
|
9
|
|
|
use GuzzleHttp\Psr7; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Parses a MIME message into a \ZBateson\MailMimeParser\Message object. |
|
13
|
|
|
* |
|
14
|
|
|
* To invoke, call parse on a MailMimeParser object. |
|
15
|
|
|
* |
|
16
|
|
|
* $handle = fopen('path/to/file.txt'); |
|
17
|
|
|
* $parser = new MailMimeParser(); |
|
18
|
|
|
* $parser->parse($handle); |
|
19
|
|
|
* fclose($handle); |
|
20
|
|
|
* |
|
21
|
|
|
* @author Zaahid Bateson |
|
22
|
|
|
*/ |
|
23
|
|
|
class MailMimeParser |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* @var string defines the default charset used by MessagePart. |
|
27
|
|
|
*/ |
|
28
|
|
|
const DEFAULT_CHARSET = 'UTF-8'; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @var \ZBateson\MailMimeParser\SimpleDi dependency injection container |
|
32
|
|
|
*/ |
|
33
|
|
|
protected $di; |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* Sets up the parser. |
|
37
|
|
|
*/ |
|
38
|
3 |
|
public function __construct() |
|
39
|
|
|
{ |
|
40
|
3 |
|
$this->di = SimpleDi::singleton(); |
|
41
|
3 |
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Parses the passed stream handle into a ZBateson\MailMimeParser\Message |
|
45
|
|
|
* object and returns it. |
|
46
|
|
|
* |
|
47
|
|
|
* Internally, the message is first copied to a temp stream (with php://temp |
|
48
|
|
|
* which may keep it in memory or write it to disk) and its stream is used. |
|
49
|
|
|
* That way if the message is too large to hold in memory it can be written |
|
50
|
|
|
* to a temporary file if need be. |
|
51
|
|
|
* |
|
52
|
|
|
* @param resource|string $handleOrString the resource handle to the input |
|
53
|
|
|
* stream of the mime message, or a string containing a mime message |
|
54
|
|
|
* @return \ZBateson\MailMimeParser\Message |
|
55
|
|
|
*/ |
|
56
|
2 |
|
public function parse($handleOrString) |
|
57
|
|
|
{ |
|
58
|
2 |
|
$stream = Psr7\stream_for($handleOrString); |
|
|
|
|
|
|
59
|
2 |
|
$copy = Psr7\stream_for(fopen('php://temp', 'r+')); |
|
60
|
|
|
|
|
61
|
2 |
|
Psr7\copy_to_stream($stream, $copy); |
|
|
|
|
|
|
62
|
2 |
|
$copy->rewind(); |
|
63
|
|
|
|
|
64
|
|
|
// don't close it when $stream gets destroyed |
|
65
|
2 |
|
$stream->detach(); |
|
66
|
2 |
|
$parser = $this->di->newMessageParser(); |
|
67
|
2 |
|
return $parser->parse($copy); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|