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
|
|
|
|
8
|
|
|
namespace ZBateson\MailMimeParser\Parser; |
9
|
|
|
|
10
|
|
|
use Psr\Log\LogLevel; |
11
|
|
|
use ZBateson\MailMimeParser\Message\PartHeaderContainer; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Reads headers from an input stream, adding them to a PartHeaderContainer. |
15
|
|
|
* |
16
|
|
|
* @author Zaahid Bateson |
17
|
|
|
*/ |
18
|
|
|
class HeaderParserService |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* Ensures the header isn't empty and contains a colon separator character, |
22
|
|
|
* then splits it and adds it to the passed PartHeaderContainer. |
23
|
|
|
* |
24
|
|
|
* @param int $offset read offset for error reporting |
25
|
|
|
* @param string $header the header line |
26
|
|
|
* @param PartHeaderContainer $headerContainer the container |
27
|
|
|
*/ |
28
|
116 |
|
private function addRawHeaderToPart(int $offset, string $header, PartHeaderContainer $headerContainer) : static |
29
|
|
|
{ |
30
|
116 |
|
if ($header !== '') { |
31
|
115 |
|
if (\strpos($header, ':') !== false) { |
32
|
114 |
|
$a = \explode(':', $header, 2); |
33
|
114 |
|
$headerContainer->add($a[0], \trim($a[1])); |
34
|
|
|
} else { |
35
|
2 |
|
$headerContainer->addError( |
36
|
2 |
|
"Invalid header found at offset: $offset", |
37
|
2 |
|
LogLevel::ERROR |
38
|
2 |
|
); |
39
|
|
|
} |
40
|
|
|
} |
41
|
116 |
|
return $this; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Reads header lines up to an empty line, adding them to the passed |
46
|
|
|
* PartHeaderContainer. |
47
|
|
|
* |
48
|
|
|
* @param resource $handle The resource handle to read from. |
49
|
|
|
* @param PartHeaderContainer $container the container to add headers to. |
50
|
|
|
*/ |
51
|
116 |
|
public function parse($handle, PartHeaderContainer $container) : static |
52
|
|
|
{ |
53
|
116 |
|
$header = ''; |
54
|
|
|
do { |
55
|
116 |
|
$offset = \ftell($handle); |
56
|
116 |
|
$line = MessageParserService::readLine($handle); |
57
|
116 |
|
if ($line === false || $line === '' || $line[0] !== "\t" && $line[0] !== ' ') { |
58
|
116 |
|
$this->addRawHeaderToPart($offset, $header, $container); |
59
|
116 |
|
$header = ''; |
60
|
|
|
} else { |
61
|
97 |
|
$line = "\r\n" . $line; |
62
|
|
|
} |
63
|
116 |
|
$header .= \rtrim($line, "\r\n"); |
64
|
116 |
|
} while ($header !== ''); |
65
|
116 |
|
return $this; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|