]>
git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/3rdparty/content-extractor/ContentExtractor.php
5 * Uses patterns specified in site config files and auto detection (hNews/PHP Readability)
6 * to extract content from HTML files.
10 * @author Keyvan Minoukadeh
11 * @copyright 2011 Keyvan Minoukadeh
12 * @license http://www.gnu.org/licenses/agpl-3.0.html AGPL v3
15 class ContentExtractor
17 protected static $tidy_config = array(
19 'output-xhtml' => true,
20 'logical-emphasis' => true,
21 'show-body-only' => false,
22 'new-blocklevel-tags' => 'article, aside, footer, header, hgroup, menu, nav, section, details, datagrid',
23 'new-inline-tags' => 'mark, time, meter, progress, data',
25 'drop-empty-paras' => true,
26 'drop-proprietary-attributes' => false,
27 'enclose-text' => true,
28 'enclose-block-text' => true,
30 'merge-spans' => true,
31 'char-encoding' => 'utf8',
32 'hide-comments' => true
37 protected $author = array();
41 protected $success = false;
42 public $fingerprints = array();
44 public $debug = false;
46 function __construct($path, $fallback=null) {
47 SiteConfig
::set_config_path($path, $fallback);
50 protected function debug($msg) {
52 $mem = round(memory_get_usage()/1024, 2);
53 $memPeak = round(memory_get_peak_usage()/1024, 2);
55 echo ' - mem used: ',$mem," (peak: $memPeak)\n";
61 public function reset() {
63 $this->readability
= null;
67 $this->author
= array();
68 $this->language
= null;
70 $this->success
= false;
73 public function findHostUsingFingerprints($html) {
74 $this->debug('Checking fingerprints...');
75 $head = substr($html, 0, 8000);
76 foreach ($this->fingerprints
as $_fp => $_fphost) {
78 if (is_array($_fphost)) {
79 if (isset($_fphost['head']) && $_fphost['head']) {
82 $_fphost = $_fphost['hostname'];
84 if (strpos($
$lookin, $_fp) !== false) {
85 $this->debug("Found match: $_fphost");
92 // returns true on success, false on failure
93 // $smart_tidy indicates that if tidy is used and no results are produced, we will
94 // try again without it. Tidy helps us deal with PHP's patchy HTML parsing most of the time
95 // but it has problems of its own which we try to avoid with this option.
96 public function process($html, $url, $smart_tidy=true) {
99 $host = @parse_url($url, PHP_URL_HOST);
100 if (!($this->config = SiteConfig::build($host))) {
101 // no match, check HTML for fingerprints
102 if (!empty($this->fingerprints) && ($_fphost = $this->findHostUsingFingerprints($html))) {
103 $this->config = SiteConfig::build($_fphost);
106 if (!$this->config) {
107 // no match, so use defaults
108 $this->config = new SiteConfig();
111 // store copy of config in our static cache array in case we need to process another URL
112 SiteConfig::add_to_cache($host, $this->config);
114 // do string replacements
115 foreach ($this->config->replace_string as $_repl) {
116 $html = str_replace($_repl[0], $_repl[1], $html);
120 // use tidy (if it exists)?
121 // This fixes problems with some sites which would otherwise
122 // trouble DOMDocument's HTML parsing. (Although sometimes it
123 // makes matters worse, which is why you can override it in site config files.)
125 if ($this->config->tidy && function_exists('tidy_parse_string') && $smart_tidy) {
126 $this->debug('Using Tidy');
127 $tidy = tidy_parse_string($html, self::$tidy_config, 'UTF8');
128 if (tidy_clean_repair($tidy)) {
129 $original_html = $html;
131 // $html = $tidy->value;
133 $body = $tidy->body();
134 if (preg_replace('/\s+/', '', $body->value) !== "<body
></body
>") {
135 $html = $tidy->value;
140 // load and parse html
141 $this->readability = new PocheReadability($html, $url);
143 // we use xpath to find elements in the given HTML document
144 // see http://en.wikipedia.org/wiki/XPath_1.0
145 $xpath = new DOMXPath($this->readability->dom);
148 foreach ($this->config->title as $pattern) {
149 $elems = @$xpath->evaluate($pattern, $this->readability->dom);
150 if (is_string($elems)) {
151 $this->debug('Title expression evaluated as string');
152 $this->title = trim($elems);
154 } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
155 $this->debug('Title matched');
156 $this->title = $elems->item(0)->textContent;
157 // remove title from document
159 $elems->item(0)->parentNode->removeChild($elems->item(0));
160 } catch (DOMException $e) {
167 // try to get author (if it hasn't already been set)
168 if (empty($this->author)) {
169 foreach ($this->config->author as $pattern) {
170 $elems = @$xpath->evaluate($pattern, $this->readability->dom);
171 if (is_string($elems)) {
172 $this->debug('Author expression evaluated as string');
173 if (trim($elems) != '') {
174 $this->author[] = trim($elems);
177 } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
178 foreach ($elems as $elem) {
179 if (!isset($elem->parentNode)) continue;
180 $this->author[] = trim($elem->textContent);
182 if (!empty($this->author)) break;
187 // try to get language
188 $_lang_xpath = array('//html[@lang]/@lang', '//meta[@name="DC
.language
"]/@content');
189 foreach ($_lang_xpath as $pattern) {
190 $elems = @$xpath->evaluate($pattern, $this->readability->dom);
191 if (is_string($elems)) {
192 if (trim($elems) != '') {
193 $this->language = trim($elems);
196 } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
197 foreach ($elems as $elem) {
198 if (!isset($elem->parentNode)) continue;
199 $this->language = trim($elem->textContent);
201 if ($this->language) break;
206 foreach ($this->config->date as $pattern) {
207 $elems = @$xpath->evaluate($pattern, $this->readability->dom);
208 if (is_string($elems)) {
209 $this->debug('Date expression evaluated as string');
210 $this->date = strtotime(trim($elems, "; \t\n\r\
0\x0B"));
211 } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
212 $this->debug('Date matched');
213 $this->date = $elems->item(0)->textContent;
214 $this->date = strtotime(trim($this->date, "; \t\n\r\
0\x0B"));
215 // remove date from document
216 // $elems->item(0)->parentNode->removeChild($elems->item(0));
225 // strip elements (using xpath expressions)
226 foreach ($this->config->strip as $pattern) {
227 $elems = @$xpath->query($pattern, $this->readability->dom);
229 if ($elems && $elems->length > 0) {
230 $this->debug('Stripping '.$elems->length.' elements (strip)');
231 for ($i=$elems->length-1; $i >= 0; $i--) {
232 $elems->item($i)->parentNode->removeChild($elems->item($i));
237 // strip elements (using id and class attribute values)
238 foreach ($this->config->strip_id_or_class as $string) {
239 $string = strtr($string, array("'"=>'', '"'=>''));
240 $elems = @$xpath->query("//*[contains(@class, '$string') or contains(@id, '$string')]", $this->readability->dom);
242 if ($elems && $elems->length
> 0) {
243 $this->debug('Stripping '.$elems->length
.' elements (strip_id_or_class)');
244 for ($i=$elems->length
-1; $i >= 0; $i--) {
245 $elems->item($i)->parentNode
->removeChild($elems->item($i));
250 // strip images (using src attribute values)
251 foreach ($this->config
->strip_image_src
as $string) {
252 $string = strtr($string, array("'"=>'', '"'=>''));
253 $elems = @$xpath->query("//img[contains(@src, '$string')]", $this->readability
->dom
);
255 if ($elems && $elems->length
> 0) {
256 $this->debug('Stripping '.$elems->length
.' image elements');
257 for ($i=$elems->length
-1; $i >= 0; $i--) {
258 $elems->item($i)->parentNode
->removeChild($elems->item($i));
262 // strip elements using Readability.com and Instapaper.com ignore class names
263 // .entry-unrelated and .instapaper_ignore
264 // See https://www.readability.com/publishers/guidelines/#view-plainGuidelines
265 // and http://blog.instapaper.com/post/730281947
266 $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' entry-unrelated ') or contains(concat(' ',normalize-space(@class),' '),' instapaper_ignore ')]", $this->readability
->dom
);
268 if ($elems && $elems->length
> 0) {
269 $this->debug('Stripping '.$elems->length
.' .entry-unrelated,.instapaper_ignore elements');
270 for ($i=$elems->length
-1; $i >= 0; $i--) {
271 $elems->item($i)->parentNode
->removeChild($elems->item($i));
275 // strip elements that contain style="display: none;"
276 $elems = @$xpath->query("//*[contains(@style,'display:none')]", $this->readability
->dom
);
278 if ($elems && $elems->length
> 0) {
279 $this->debug('Stripping '.$elems->length
.' elements with inline display:none style');
280 for ($i=$elems->length
-1; $i >= 0; $i--) {
281 $elems->item($i)->parentNode
->removeChild($elems->item($i));
286 foreach ($this->config
->body
as $pattern) {
287 $elems = @$xpath->query($pattern, $this->readability
->dom
);
289 if ($elems && $elems->length
> 0) {
290 $this->debug('Body matched');
291 if ($elems->length
== 1) {
292 $this->body
= $elems->item(0);
293 // prune (clean up elements that may not be content)
294 if ($this->config
->prune
) {
295 $this->debug('Pruning content');
296 $this->readability
->prepArticle($this->body
);
300 $this->body
= $this->readability
->dom
->createElement('div');
301 $this->debug($elems->length
.' body elems found');
302 foreach ($elems as $elem) {
303 if (!isset($elem->parentNode
)) continue;
304 $isDescendant = false;
305 foreach ($this->body
->childNodes
as $parent) {
306 if ($this->isDescendant($parent, $elem)) {
307 $isDescendant = true;
312 $this->debug('Element is child of another body element, skipping.');
314 // prune (clean up elements that may not be content)
315 if ($this->config
->prune
) {
316 $this->debug('Pruning content');
317 $this->readability
->prepArticle($elem);
319 $this->debug('Element added to body');
320 $this->body
->appendChild($elem);
328 $detect_title = $detect_body = $detect_author = $detect_date = false;
330 if (!isset($this->title
)) {
331 if (empty($this->config
->title
) || $this->config
->autodetect_on_failure
) {
332 $detect_title = true;
336 if (!isset($this->body
)) {
337 if (empty($this->config
->body
) || $this->config
->autodetect_on_failure
) {
342 if (empty($this->author
)) {
343 if (empty($this->config
->author
) || $this->config
->autodetect_on_failure
) {
344 $detect_author = true;
348 if (!isset($this->date
)) {
349 if (empty($this->config
->date
) || $this->config
->autodetect_on_failure
) {
355 if ($detect_title || $detect_body) {
357 $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' hentry ')]", $this->readability
->dom
);
358 if ($elems && $elems->length
> 0) {
359 $this->debug('hNews: found hentry');
360 $hentry = $elems->item(0);
363 // check for entry-title
364 $elems = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' entry-title ')]", $hentry);
365 if ($elems && $elems->length
> 0) {
366 $this->debug('hNews: found entry-title');
367 $this->title
= $elems->item(0)->textContent
;
368 // remove title from document
369 $elems->item(0)->parentNode
->removeChild($elems->item(0));
370 $detect_title = false;
375 // check for time element with pubdate attribute
376 $elems = @$xpath->query(".//time[@pubdate] | .//abbr[contains(concat(' ',normalize-space(@class),' '),' published ')]", $hentry);
377 if ($elems && $elems->length
> 0) {
378 $this->debug('hNews: found publication date');
379 $this->date
= strtotime(trim($elems->item(0)->textContent
));
380 // remove date from document
381 //$elems->item(0)->parentNode->removeChild($elems->item(0));
383 $detect_date = false;
390 if ($detect_author) {
391 // check for time element with pubdate attribute
392 $elems = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' vcard ') and (contains(concat(' ',normalize-space(@class),' '),' author ') or contains(concat(' ',normalize-space(@class),' '),' byline '))]", $hentry);
393 if ($elems && $elems->length
> 0) {
394 $this->debug('hNews: found author');
395 $author = $elems->item(0);
396 $fn = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' fn ')]", $author);
397 if ($fn && $fn->length
> 0) {
398 foreach ($fn as $_fn) {
399 if (trim($_fn->textContent
) != '') {
400 $this->author
[] = trim($_fn->textContent
);
404 if (trim($author->textContent
) != '') {
405 $this->author
[] = trim($author->textContent
);
408 $detect_author = empty($this->author
);
412 // check for entry-content.
413 // according to hAtom spec, if there are multiple elements marked entry-content,
414 // we include all of these in the order they appear - see http://microformats.org/wiki/hatom#Entry_Content
416 $elems = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' entry-content ')]", $hentry);
417 if ($elems && $elems->length
> 0) {
418 $this->debug('hNews: found entry-content');
419 if ($elems->length
== 1) {
420 // what if it's empty? (some sites misuse hNews - place their content outside an empty entry-content element)
421 $e = $elems->item(0);
422 if (($e->tagName
== 'img') || (trim($e->textContent
) != '')) {
423 $this->body
= $elems->item(0);
424 // prune (clean up elements that may not be content)
425 if ($this->config
->prune
) {
426 $this->debug('Pruning content');
427 $this->readability
->prepArticle($this->body
);
429 $detect_body = false;
431 $this->debug('hNews: skipping entry-content - appears not to contain content');
435 $this->body
= $this->readability
->dom
->createElement('div');
436 $this->debug($elems->length
.' entry-content elems found');
437 foreach ($elems as $elem) {
438 if (!isset($elem->parentNode
)) continue;
439 $isDescendant = false;
440 foreach ($this->body
->childNodes
as $parent) {
441 if ($this->isDescendant($parent, $elem)) {
442 $isDescendant = true;
447 $this->debug('Element is child of another body element, skipping.');
449 // prune (clean up elements that may not be content)
450 if ($this->config
->prune
) {
451 $this->debug('Pruning content');
452 $this->readability
->prepArticle($elem);
454 $this->debug('Element added to body');
455 $this->body
->appendChild($elem);
458 $detect_body = false;
465 // check for elements marked with instapaper_title
467 // check for instapaper_title
468 $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' instapaper_title ')]", $this->readability
->dom
);
469 if ($elems && $elems->length
> 0) {
470 $this->debug('title found (.instapaper_title)');
471 $this->title
= $elems->item(0)->textContent
;
472 // remove title from document
473 $elems->item(0)->parentNode
->removeChild($elems->item(0));
474 $detect_title = false;
477 // check for elements marked with instapaper_body
479 $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' instapaper_body ')]", $this->readability
->dom
);
480 if ($elems && $elems->length
> 0) {
481 $this->debug('body found (.instapaper_body)');
482 $this->body
= $elems->item(0);
483 // prune (clean up elements that may not be content)
484 if ($this->config
->prune
) {
485 $this->debug('Pruning content');
486 $this->readability
->prepArticle($this->body
);
488 $detect_body = false;
492 // Find author in rel="author" marked element
493 // We only use this if there's exactly one.
494 // If there's more than one, it could indicate more than
495 // one author, but it could also indicate that we're processing
496 // a page listing different articles with different authors.
497 if ($detect_author) {
498 $elems = @$xpath->query("//a[contains(concat(' ',normalize-space(@rel),' '),' author ')]", $this->readability
->dom
);
499 if ($elems && $elems->length
== 1) {
500 $this->debug('Author found (rel="author")');
501 $author = trim($elems->item(0)->textContent
);
503 $this->author
[] = $author;
504 $detect_author = false;
509 // Find date in pubdate marked time element
510 // For the same reason given above, we only use this
511 // if there's exactly one element.
513 $elems = @$xpath->query("//time[@pubdate]", $this->readability
->dom
);
514 if ($elems && $elems->length
== 1) {
515 $this->debug('Date found (pubdate marked time element)');
516 $this->date
= strtotime(trim($elems->item(0)->textContent
));
517 // remove date from document
518 //$elems->item(0)->parentNode->removeChild($elems->item(0));
520 $detect_date = false;
527 // still missing title or body, so we detect using Readability
528 if ($detect_title || $detect_body) {
529 $this->debug('Using Readability');
530 // clone body if we're only using Readability for title (otherwise it may interfere with body element)
531 if (isset($this->body
)) $this->body
= $this->body
->cloneNode(true);
532 $success = $this->readability
->init();
535 $this->debug('Detecting title');
536 $this->title
= $this->readability
->getTitle()->textContent
;
538 if ($detect_body && $success) {
539 $this->debug('Detecting body');
540 $this->body
= $this->readability
->getContent();
541 if ($this->body
->childNodes
->length
== 1 && $this->body
->firstChild
->nodeType
=== XML_ELEMENT_NODE
) {
542 $this->body
= $this->body
->firstChild
;
544 // prune (clean up elements that may not be content)
545 if ($this->config
->prune
) {
546 $this->debug('Pruning content');
547 $this->readability
->prepArticle($this->body
);
550 if (isset($this->body
)) {
552 $this->readability
->removeScripts($this->body
);
553 // remove any h1-h6 elements that appear as first thing in the body
554 // and which match our title
555 if (isset($this->title
) && ($this->title
!= '')) {
556 $firstChild = $this->body
->firstChild
;
557 while ($firstChild->nodeType
&& ($firstChild->nodeType
!== XML_ELEMENT_NODE
)) {
558 $firstChild = $firstChild->nextSibling
;
560 if (($firstChild->nodeType
=== XML_ELEMENT_NODE
)
561 && in_array(strtolower($firstChild->tagName
), array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'))
562 && (strtolower(trim($firstChild->textContent
)) == strtolower(trim($this->title
)))) {
563 $this->body
->removeChild($firstChild);
566 $this->success
= true;
569 // if we've had no success and we've used tidy, there's a chance
570 // that tidy has messed up. So let's try again without tidy...
571 if (!$this->success
&& $tidied && $smart_tidy) {
572 $this->debug('Trying again without tidy');
573 $this->process($original_html, $url, false);
576 return $this->success
;
579 private function isDescendant(DOMElement
$parent, DOMElement
$child) {
580 $node = $child->parentNode
;
581 while ($node != null) {
582 if ($node->isSameNode($parent)) return true;
583 $node = $node->parentNode
;
588 public function getContent() {
592 public function getTitle() {
596 public function getAuthors() {
597 return $this->author
;
600 public function getLanguage() {
601 return $this->language
;
604 public function getDate() {
608 public function getSiteConfig() {
609 return $this->config
;