-
Notifications
You must be signed in to change notification settings - Fork 6
/
Extractor.php
290 lines (250 loc) · 7.31 KB
/
Extractor.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
<?php
/*
* This file is part of the Yoozi Golem package.
*
* (c) Yoozi Inc. <hello@yoozi.cn>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yoozi\Miner;
use Buzz\Browser;
use Pdp\Parser as DomainParser;
use Pdp\PublicSuffixListManager;
use Yoozi\Miner\Exception\RuntimeException;
use Buzz\Client\ClientInterface as HttpClientInterface;
/**
* Extract metadata from HTML source content.
*
* @author Saturn HU <yangg.hu@yoozi.cn>
*/
class Extractor
{
/**
* Holds the parser.
*
* @var \Yoozi\Miner\Parsers\ParserInterface
*/
protected $parser;
/**
* Holds the configuration of extrator.
*
* @var \Yoozi\Miner\Config
*/
protected $config;
/**
* Holds the ultimate parsed metadata.
*
* @var array
*/
protected $metadata = array();
/**
* Holds the to-be parsed raw document.
*
* @var string
*/
protected $document;
/**
* Holds the charset of the HTML document.
*
* @var string
*/
protected $charset = null;
/**
* Set up the configuration for this extrator.
*
* @param array $config
*/
public function __construct(array $config = array())
{
$this->config = new Config($config);
}
/**
* Run the extraction on the HTML content, and apply $callback if necessary.
*
* @param string $source
* @param \Clousure $callback
* @throws \Yoozi\Miner\Exception\RuntimeException
* @return \Yoozi\Miner\Extractor
*/
public function run(\Closure $callback = null)
{
if (! $document = $this->document) {
throw new RuntimeException('Miner can not extract an empty document.');
}
$class = 'Yoozi\\Miner\\Parsers\\' . ucfirst($this->config->get('parser'));
$this->parser = new $class($this->config, $this->toDomDocument($document));
$metadata = array_merge($this->parser->parse(), $this->metadata);
return $this->metadata = $callback ? $callback($metadata) : $metadata;
}
/**
* Parse an url address, and fill up the basic metadata.
*
* @param string $url
* @param \Buzz\Client\ClientInterface $client
* @return \Yoozi\Miner\Extractor
*/
public function fromUrl($url, HttpClientInterface $client = null)
{
$browser = new Browser($client);
$response = $browser->get($url, $this->config->get('headers'));
$request = $browser->getLastRequest();
$this->metadata = array();
foreach (array('url', 'host', 'domain', 'favicon') as $key) {
$this->metadata[$key] = $this->{'get' . studly_case($key)}($request);
}
if ($response->isSuccessful()) {
$this->document = $response->getContent();
$this->charset = $response->getHeaderAttribute('Content-Type', 'charset');
}
return $this;
}
/**
* Set the document directly from HTML source.
*
* @param string $source
* @return \Yoozi\Miner\Extractor
*/
public function fromSource($source)
{
$this->metadata = array();
$this->document = $source;
return $this;
}
/**
* Get config of this extractor.
*
* @return \Yoozi\Miner\Config
*/
public function getConfig()
{
return $this->config ?: new Config;
}
/**
* Get the parser object we're currently using.
*
* @return mixed
*/
public function getParser()
{
return $this->parser;
}
/**
* Get charset of the document.
*
* @return string
*/
public function getCharset()
{
return $this->charset;
}
/**
* Array representation of the parsed result.
*
* @return array
*/
public function toArray()
{
return $this->metadata;
}
/**
* JSON representation of the parsed result.
*
* @return string
*/
public function toJson($options = 0)
{
return json_encode($this->metadata, $options);
}
/**
* Get the url we're currently parsing.
*
* @param Buzz\Message\Request $request
* @return string
*/
protected function getUrl($request)
{
return $request->getUrl();
}
/**
* Get the host.
*
* @param Buzz\Message\Request $request
* @return string
*/
protected function getHost($request)
{
return $request->getHost();
}
/**
* Get the fully qualified naked domain name.
*
* @param Buzz\Message\Request $request
* @return string
*/
protected function getDomain($request)
{
if ($host = filter_var($this->metadata['host'], FILTER_VALIDATE_IP)) {
return $host;
}
$manager = new PublicSuffixListManager;
$parser = new DomainParser($manager->getList());
return $parser->parseUrl($this->metadata['url'])->host->registerableDomain;
}
/**
* Returns the favicon image of the webpage.
*
* Here we use the free Google favicon web service.
*
* @param \Buzz\Message\Request $request
* @return string
*/
protected function getFavicon($request)
{
return 'http://www.google.com/s2/favicons?domain=' . $this->metadata['domain'];
}
/**
* Helper function to return the current HTML as a DOMDocument.
*
* @param string $html
* @return \DOMDocument
*/
protected function toDomDocument($html)
{
if (! $this->charset) {
preg_match("/charset=([\w|\-]+);?/", $html, $match);
$this->charset = isset($match[1]) ? $match[1] : 'utf-8';
}
$html = mb_convert_encoding($html, 'HTML-ENTITIES', $this->charset);
$html = $this->sanitize($html);
$revert = libxml_use_internal_errors(true);
$dom = new \DOMDocument('1.0', 'utf-8');
// DomDocument cannot recognize the HTML5 charset meta tag, which may
// cause potential problems for processing pages in CJK charset.
$fix = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>';
$dom->loadHTML($fix . $html);
libxml_use_internal_errors($revert);
return $dom;
}
/**
* Sanitize the HTML content to prevent the DOM transformation failure.
*
* @param string $string
* @return string
*/
protected function sanitize($string)
{
// 剔除多余的 HTML 编码标记,避免解析出错
preg_match("/charset=([\w|\-]+);?/", $string, $match);
if (isset($match[1])) {
$string = preg_replace("/charset=([\w|\-]+);?/", "", $string, 1);
}
// Replace all doubled-up <BR> tags with <P> tags, and remove fonts.
$string = preg_replace("/<br\/?>[ \r\n\s]*<br\/?>/i", "</p><p>", $string);
$string = preg_replace("/<\/?font[^>]*>/i", "", $string);
// @see https://github.com/feelinglucky/php-readability/issues/7
// - from http://stackoverflow.com/questions/7130867/remove-script-tag-from-html-content
$string = preg_replace("#<script(.*?)>(.*?)</script>#is", "", $string);
return trim($string);
}
}