]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/3rdparty/content-extractor/ContentExtractor.php
poche now uses Full Text RSS to fetch content
[github/wallabag/wallabag.git] / inc / 3rdparty / content-extractor / ContentExtractor.php
1 <?php
2 /**
3 * Content Extractor
4 *
5 * Uses patterns specified in site config files and auto detection (hNews/PHP Readability)
6 * to extract content from HTML files.
7 *
8 * @version 0.8
9 * @date 2012-02-21
10 * @author Keyvan Minoukadeh
11 * @copyright 2011 Keyvan Minoukadeh
12 * @license http://www.gnu.org/licenses/agpl-3.0.html AGPL v3
13 */
14
15 class ContentExtractor
16 {
17 protected static $tidy_config = array(
18 'clean' => true,
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',
24 'wrap' => 0,
25 'drop-empty-paras' => true,
26 'drop-proprietary-attributes' => false,
27 'enclose-text' => true,
28 'enclose-block-text' => true,
29 'merge-divs' => true,
30 'merge-spans' => true,
31 'char-encoding' => 'utf8',
32 'hide-comments' => true
33 );
34 protected $html;
35 protected $config;
36 protected $title;
37 protected $author = array();
38 protected $language;
39 protected $date;
40 protected $body;
41 protected $success = false;
42 public $fingerprints = array();
43 public $readability;
44 public $debug = false;
45
46 function __construct($path, $fallback=null) {
47 SiteConfig::set_config_path($path, $fallback);
48 }
49
50 protected function debug($msg) {
51 if ($this->debug) {
52 $mem = round(memory_get_usage()/1024, 2);
53 $memPeak = round(memory_get_peak_usage()/1024, 2);
54 echo '* ',$msg;
55 echo ' - mem used: ',$mem," (peak: $memPeak)\n";
56 ob_flush();
57 flush();
58 }
59 }
60
61 public function reset() {
62 $this->html = null;
63 $this->readability = null;
64 $this->config = null;
65 $this->title = null;
66 $this->body = null;
67 $this->author = array();
68 $this->language = null;
69 $this->date = null;
70 $this->success = false;
71 }
72
73 public function findHostUsingFingerprints($html) {
74 $this->debug('Checking fingerprints...');
75 $head = substr($html, 0, 8000);
76 foreach ($this->fingerprints as $_fp => $_fphost) {
77 $lookin = 'html';
78 if (is_array($_fphost)) {
79 if (isset($_fphost['head']) && $_fphost['head']) {
80 $lookin = 'head';
81 }
82 $_fphost = $_fphost['hostname'];
83 }
84 if (strpos($$lookin, $_fp) !== false) {
85 $this->debug("Found match: $_fphost");
86 return $_fphost;
87 }
88 }
89 return false;
90 }
91
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) {
97 $this->reset();
98 // extract host name
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);
104 }
105 unset($_fphost);
106 if (!$this->config) {
107 // no match, so use defaults
108 $this->config = new SiteConfig();
109 }
110 }
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);
113
114 // do string replacements
115 foreach ($this->config->replace_string as $_repl) {
116 $html = str_replace($_repl[0], $_repl[1], $html);
117 }
118 unset($_repl);
119
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.)
124 $tidied = false;
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;
130 $tidied = true;
131 // $html = $tidy->value;
132 }
133 $body = $tidy->body();
134 if (preg_replace('/\s+/', '', $body->value) !== "<body></body>") {
135 $html = $tidy->value;
136 }
137 unset($tidy);
138 }
139
140 // load and parse html
141 $this->readability = new Readability($html, $url);
142
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);
146
147 // try to get title
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);
153 break;
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
158 try {
159 $elems->item(0)->parentNode->removeChild($elems->item(0));
160 } catch (DOMException $e) {
161 // do nothing
162 }
163 break;
164 }
165 }
166
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);
175 break;
176 }
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);
181 }
182 if (!empty($this->author)) break;
183 }
184 }
185 }
186
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);
194 break;
195 }
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);
200 }
201 if ($this->language) break;
202 }
203 }
204
205 // try to get date
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));
217 }
218 if (!$this->date) {
219 $this->date = null;
220 } else {
221 break;
222 }
223 }
224
225 // strip elements (using xpath expressions)
226 foreach ($this->config->strip as $pattern) {
227 $elems = @$xpath->query($pattern, $this->readability->dom);
228 // check for matches
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));
233 }
234 }
235 }
236
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);
241 // check for matches
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));
246 }
247 }
248 }
249
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);
254 // check for matches
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));
259 }
260 }
261 }
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);
267 // check for matches
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));
272 }
273 }
274
275 // strip elements that contain style="display: none;"
276 $elems = @$xpath->query("//*[contains(@style,'display:none')]", $this->readability->dom);
277 // check for matches
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));
282 }
283 }
284
285 // try to get body
286 foreach ($this->config->body as $pattern) {
287 $elems = @$xpath->query($pattern, $this->readability->dom);
288 // check for matches
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);
297 }
298 break;
299 } else {
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;
308 break;
309 }
310 }
311 if ($isDescendant) {
312 $this->debug('Element is child of another body element, skipping.');
313 } else {
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);
318 }
319 $this->debug('Element added to body');
320 $this->body->appendChild($elem);
321 }
322 }
323 }
324 }
325 }
326
327 // auto detect?
328 $detect_title = $detect_body = $detect_author = $detect_date = false;
329 // detect title?
330 if (!isset($this->title)) {
331 if (empty($this->config->title) || $this->config->autodetect_on_failure) {
332 $detect_title = true;
333 }
334 }
335 // detect body?
336 if (!isset($this->body)) {
337 if (empty($this->config->body) || $this->config->autodetect_on_failure) {
338 $detect_body = true;
339 }
340 }
341 // detect author?
342 if (empty($this->author)) {
343 if (empty($this->config->author) || $this->config->autodetect_on_failure) {
344 $detect_author = true;
345 }
346 }
347 // detect date?
348 if (!isset($this->date)) {
349 if (empty($this->config->date) || $this->config->autodetect_on_failure) {
350 $detect_date = true;
351 }
352 }
353
354 // check for hNews
355 if ($detect_title || $detect_body) {
356 // check for hentry
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);
361
362 if ($detect_title) {
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;
371 }
372 }
373
374 if ($detect_date) {
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));
382 if ($this->date) {
383 $detect_date = false;
384 } else {
385 $this->date = null;
386 }
387 }
388 }
389
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);
401 }
402 }
403 } else {
404 if (trim($author->textContent) != '') {
405 $this->author[] = trim($author->textContent);
406 }
407 }
408 $detect_author = empty($this->author);
409 }
410 }
411
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
415 if ($detect_body) {
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);
428 }
429 $detect_body = false;
430 } else {
431 $this->debug('hNews: skipping entry-content - appears not to contain content');
432 }
433 unset($e);
434 } else {
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;
443 break;
444 }
445 }
446 if ($isDescendant) {
447 $this->debug('Element is child of another body element, skipping.');
448 } else {
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);
453 }
454 $this->debug('Element added to body');
455 $this->body->appendChild($elem);
456 }
457 }
458 $detect_body = false;
459 }
460 }
461 }
462 }
463 }
464
465 // check for elements marked with instapaper_title
466 if ($detect_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;
475 }
476 }
477 // check for elements marked with instapaper_body
478 if ($detect_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);
487 }
488 $detect_body = false;
489 }
490 }
491
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);
502 if ($author != '') {
503 $this->author[] = $author;
504 $detect_author = false;
505 }
506 }
507 }
508
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.
512 if ($detect_date) {
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));
519 if ($this->date) {
520 $detect_date = false;
521 } else {
522 $this->date = null;
523 }
524 }
525 }
526
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();
533 }
534 if ($detect_title) {
535 $this->debug('Detecting title');
536 $this->title = $this->readability->getTitle()->textContent;
537 }
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;
543 }
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);
548 }
549 }
550 if (isset($this->body)) {
551 // remove scripts
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;
559 }
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);
564 }
565 }
566 $this->success = true;
567 }
568
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);
574 }
575
576 return $this->success;
577 }
578
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;
584 }
585 return false;
586 }
587
588 public function getContent() {
589 return $this->body;
590 }
591
592 public function getTitle() {
593 return $this->title;
594 }
595
596 public function getAuthors() {
597 return $this->author;
598 }
599
600 public function getLanguage() {
601 return $this->language;
602 }
603
604 public function getDate() {
605 return $this->date;
606 }
607
608 public function getSiteConfig() {
609 return $this->config;
610 }
611 }
612 ?>