]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/Readability.php
typo in readme
[github/wallabag/wallabag.git] / inc / Readability.php
1 <?php
2 /**
3 * Arc90's Readability ported to PHP for FiveFilters.org
4 * Based on readability.js version 1.7.1 (without multi-page support)
5 * ------------------------------------------------------
6 * Original URL: http://lab.arc90.com/experiments/readability/js/readability.js
7 * Arc90's project URL: http://lab.arc90.com/experiments/readability/
8 * JS Source: http://code.google.com/p/arc90labs-readability
9 * Ported by: Keyvan Minoukadeh, http://www.keyvan.net
10 * More information: http://fivefilters.org/content-only/
11 * License: Apache License, Version 2.0
12 * Requires: PHP5
13 * Date: 2011-07-22
14 *
15 * Differences between the PHP port and the original
16 * ------------------------------------------------------
17 * Arc90's Readability is designed to run in the browser. It works on the DOM
18 * tree (the parsed HTML) after the page's CSS styles have been applied and
19 * Javascript code executed. This PHP port does not run inside a browser.
20 * We use PHP's ability to parse HTML to build our DOM tree, but we cannot
21 * rely on CSS or Javascript support. As such, the results will not always
22 * match Arc90's Readability. (For example, if a web page contains CSS style
23 * rules or Javascript code which hide certain HTML elements from display,
24 * Arc90's Readability will dismiss those from consideration but our PHP port,
25 * unable to understand CSS or Javascript, will not know any better.)
26 *
27 * Another significant difference is that the aim of Arc90's Readability is
28 * to re-present the main content block of a given web page so users can
29 * read it more easily in their browsers. Correct identification, clean up,
30 * and separation of the content block is only a part of this process.
31 * This PHP port is only concerned with this part, it does not include code
32 * that relates to presentation in the browser - Arc90 already do
33 * that extremely well, and for PDF output there's FiveFilters.org's
34 * PDF Newspaper: http://fivefilters.org/pdf-newspaper/.
35 *
36 * Finally, this class contains methods that might be useful for developers
37 * working on HTML document fragments. So without deviating too much from
38 * the original code (which I don't want to do because it makes debugging
39 * and updating more difficult), I've tried to make it a little more
40 * developer friendly. You should be able to use the methods here on
41 * existing DOMElement objects without passing an entire HTML document to
42 * be parsed.
43 */
44
45 // This class allows us to do JavaScript like assignements to innerHTML
46 require_once(dirname(__FILE__).'/JSLikeHTMLElement.php');
47
48 // Alternative usage (for testing only!)
49 // uncomment the lines below and call Readability.php in your browser
50 // passing it the URL of the page you'd like content from, e.g.:
51 // Readability.php?url=http://medialens.org/alerts/09/090615_the_guardian_climate.php
52
53 /*
54 if (!isset($_GET['url']) || $_GET['url'] == '') {
55 die('Please pass a URL to the script. E.g. Readability.php?url=bla.com/story.html');
56 }
57 $url = $_GET['url'];
58 if (!preg_match('!^https?://!i', $url)) $url = 'http://'.$url;
59 $html = file_get_contents($url);
60 $r = new Readability($html, $url);
61 $r->init();
62 echo $r->articleContent->innerHTML;
63 */
64
65
66 class Readability
67 {
68 /* constants */
69 const FLAG_STRIP_UNLIKELYS = 1;
70 const FLAG_WEIGHT_CLASSES = 2;
71 const FLAG_CLEAN_CONDITIONALLY = 4;
72
73 public $version = '1.7.1-without-multi-page';
74 public $convertLinksToFootnotes = false;
75 public $revertForcedParagraphElements = true;
76 public $articleTitle;
77 public $articleContent;
78 public $dom;
79 public $url = null; // optional - URL where HTML was retrieved
80 public $debug = false;
81 protected $body = null; //
82 protected $bodyCache = null; // Cache the body HTML in case we need to re-use it later
83 protected $flags = self::FLAG_CLEAN_CONDITIONALLY; // 1 | 2 | 4; // Start with all flags set.
84 protected $success = false; // indicates whether we were able to extract or not
85
86 /**
87 * All of the regular expressions in use within readability.
88 * Defined up here so we don't instantiate them repeatedly in loops.
89 **/
90 public $regexps = array(
91 'unlikelyCandidates' => '/combx|comment|comments|community|disqus|extra|foot|header|menu|remark|rss|shoutbox|sidebar|sponsor|ad-break|agegate|pagination|pager|popup|tweet|twitter/i',
92 'okMaybeItsACandidate' => '/and|article|body|column|main|shadow/i',
93 'positive' => '/article|body|content|entry|hentry|main|page|pagination|post|text|blog|story/i',
94 'negative' => '/combx|comment|comments|com-|contact|foot|footer|footnote|masthead|media|meta|outbrain|promo|related|scroll|shoutbox|sidebar|sponsor|shopping|tags|tool|widget/i',
95 'divToPElements' => '/<(a|blockquote|dl|div|ol|p|pre|table|ul)/i',
96 'replaceBrs' => '/(<br[^>]*>[ \n\r\t]*){2,}/i',
97 'replaceFonts' => '/<(\/?)font[^>]*>/i',
98 // 'trimRe' => '/^\s+|\s+$/g', // PHP has trim()
99 'normalize' => '/\s{2,}/',
100 'killBreaks' => '/(<br\s*\/?>(\s|&nbsp;?)*){1,}/',
101 'video' => '/http:\/\/(www\.)?(youtube|vimeo|dailymotion)\.com/i',
102 'skipFootnoteLink' => '/^\s*(\[?[a-z0-9]{1,2}\]?|^|edit|citation needed)\s*$/i'
103 );
104
105 /**
106 * Create instance of Readability
107 * @param string UTF-8 encoded string
108 * @param string (optional) URL associated with HTML (used for footnotes)
109 */
110 function __construct($html, $url=null)
111 {
112 /* Turn all double br's into p's */
113 $html = preg_replace($this->regexps['replaceBrs'], '</p><p>', $html);
114 $html = preg_replace($this->regexps['replaceFonts'], '<$1span>', $html);
115 $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");
116 $this->dom = new DOMDocument();
117 $this->dom->preserveWhiteSpace = false;
118 $this->dom->registerNodeClass('DOMElement', 'JSLikeHTMLElement');
119 if (trim($html) == '') $html = '<html></html>';
120 @$this->dom->loadHTML($html);
121 $this->url = $url;
122 }
123
124 /**
125 * Get article title element
126 * @return DOMElement
127 */
128 public function getTitle() {
129 return $this->articleTitle;
130 }
131
132 /**
133 * Get article content element
134 * @return DOMElement
135 */
136 public function getContent() {
137 return $this->articleContent;
138 }
139
140 /**
141 * Runs readability.
142 *
143 * Workflow:
144 * 1. Prep the document by removing script tags, css, etc.
145 * 2. Build readability's DOM tree.
146 * 3. Grab the article content from the current dom tree.
147 * 4. Replace the current DOM tree with the new one.
148 * 5. Read peacefully.
149 *
150 * @return boolean true if we found content, false otherwise
151 **/
152 public function init()
153 {
154 if (!isset($this->dom->documentElement)) return false;
155 $this->removeScripts($this->dom);
156 //die($this->getInnerHTML($this->dom->documentElement));
157
158 // Assume successful outcome
159 $this->success = true;
160
161 $bodyElems = $this->dom->getElementsByTagName('body');
162 if ($bodyElems->length > 0) {
163 if ($this->bodyCache == null) {
164 $this->bodyCache = $bodyElems->item(0)->innerHTML;
165 }
166 if ($this->body == null) {
167 $this->body = $bodyElems->item(0);
168 }
169 }
170
171 $this->prepDocument();
172
173 //die($this->dom->documentElement->parentNode->nodeType);
174 //$this->setInnerHTML($this->dom->documentElement, $this->getInnerHTML($this->dom->documentElement));
175 //die($this->getInnerHTML($this->dom->documentElement));
176
177 /* Build readability's DOM tree */
178 $overlay = $this->dom->createElement('div');
179 $innerDiv = $this->dom->createElement('div');
180 $articleTitle = $this->getArticleTitle();
181 $articleContent = $this->grabArticle();
182
183 if (!$articleContent) {
184 $this->success = false;
185 $articleContent = $this->dom->createElement('div');
186 $articleContent->setAttribute('id', 'readability-content');
187 $articleContent->innerHTML = '<p>Sorry, Readability was unable to parse this page for content.</p>';
188 }
189
190 $overlay->setAttribute('id', 'readOverlay');
191 $innerDiv->setAttribute('id', 'readInner');
192
193 /* Glue the structure of our document together. */
194 $innerDiv->appendChild($articleTitle);
195 $innerDiv->appendChild($articleContent);
196 $overlay->appendChild($innerDiv);
197
198 /* Clear the old HTML, insert the new content. */
199 $this->body->innerHTML = '';
200 $this->body->appendChild($overlay);
201 //document.body.insertBefore(overlay, document.body.firstChild);
202 $this->body->removeAttribute('style');
203
204 $this->postProcessContent($articleContent);
205
206 // Set title and content instance variables
207 $this->articleTitle = $articleTitle;
208 $this->articleContent = $articleContent;
209
210 return $this->success;
211 }
212
213 /**
214 * Debug
215 */
216 protected function dbg($msg) {
217 if ($this->debug) echo '* ',$msg, '<br />', "\n";
218 }
219
220 /**
221 * Run any post-process modifications to article content as necessary.
222 *
223 * @param DOMElement
224 * @return void
225 */
226 public function postProcessContent($articleContent) {
227 if ($this->convertLinksToFootnotes && !preg_match('/wikipedia\.org/', @$this->url)) {
228 $this->addFootnotes($articleContent);
229 }
230 }
231
232 /**
233 * Get the article title as an H1.
234 *
235 * @return DOMElement
236 */
237 protected function getArticleTitle() {
238 $curTitle = '';
239 $origTitle = '';
240
241 try {
242 $curTitle = $origTitle = $this->getInnerText($this->dom->getElementsByTagName('title')->item(0));
243 } catch(Exception $e) {}
244
245 if (preg_match('/ [\|\-] /', $curTitle))
246 {
247 $curTitle = preg_replace('/(.*)[\|\-] .*/i', '$1', $origTitle);
248
249 if (count(explode(' ', $curTitle)) < 3) {
250 $curTitle = preg_replace('/[^\|\-]*[\|\-](.*)/i', '$1', $origTitle);
251 }
252 }
253 else if (strpos($curTitle, ': ') !== false)
254 {
255 $curTitle = preg_replace('/.*:(.*)/i', '$1', $origTitle);
256
257 if (count(explode(' ', $curTitle)) < 3) {
258 $curTitle = preg_replace('/[^:]*[:](.*)/i','$1', $origTitle);
259 }
260 }
261 else if(strlen($curTitle) > 150 || strlen($curTitle) < 15)
262 {
263 $hOnes = $this->dom->getElementsByTagName('h1');
264 if($hOnes->length == 1)
265 {
266 $curTitle = $this->getInnerText($hOnes->item(0));
267 }
268 }
269
270 $curTitle = trim($curTitle);
271
272 if (count(explode(' ', $curTitle)) <= 4) {
273 $curTitle = $origTitle;
274 }
275
276 $articleTitle = $this->dom->createElement('h1');
277 $articleTitle->innerHTML = $curTitle;
278
279 return $articleTitle;
280 }
281
282 /**
283 * Prepare the HTML document for readability to scrape it.
284 * This includes things like stripping javascript, CSS, and handling terrible markup.
285 *
286 * @return void
287 **/
288 protected function prepDocument() {
289 /**
290 * In some cases a body element can't be found (if the HTML is totally hosed for example)
291 * so we create a new body node and append it to the document.
292 */
293 if ($this->body == null)
294 {
295 $this->body = $this->dom->createElement('body');
296 $this->dom->documentElement->appendChild($this->body);
297 }
298 $this->body->setAttribute('id', 'readabilityBody');
299
300 /* Remove all style tags in head */
301 $styleTags = $this->dom->getElementsByTagName('style');
302 for ($i = $styleTags->length-1; $i >= 0; $i--)
303 {
304 $styleTags->item($i)->parentNode->removeChild($styleTags->item($i));
305 }
306
307 /* Turn all double br's into p's */
308 /* Note, this is pretty costly as far as processing goes. Maybe optimize later. */
309 //document.body.innerHTML = document.body.innerHTML.replace(readability.regexps.replaceBrs, '</p><p>').replace(readability.regexps.replaceFonts, '<$1span>');
310 // We do this in the constructor for PHP as that's when we have raw HTML - before parsing it into a DOM tree.
311 // Manipulating innerHTML as it's done in JS is not possible in PHP.
312 }
313
314 /**
315 * For easier reading, convert this document to have footnotes at the bottom rather than inline links.
316 * @see http://www.roughtype.com/archives/2010/05/experiments_in.php
317 *
318 * @return void
319 **/
320 public function addFootnotes($articleContent) {
321 $footnotesWrapper = $this->dom->createElement('div');
322 $footnotesWrapper->setAttribute('id', 'readability-footnotes');
323 $footnotesWrapper->innerHTML = '<h3>References</h3>';
324
325 $articleFootnotes = $this->dom->createElement('ol');
326 $articleFootnotes->setAttribute('id', 'readability-footnotes-list');
327 $footnotesWrapper->appendChild($articleFootnotes);
328
329 $articleLinks = $articleContent->getElementsByTagName('a');
330
331 $linkCount = 0;
332 for ($i = 0; $i < $articleLinks->length; $i++)
333 {
334 $articleLink = $articleLinks->item($i);
335 $footnoteLink = $articleLink->cloneNode(true);
336 $refLink = $this->dom->createElement('a');
337 $footnote = $this->dom->createElement('li');
338 $linkDomain = @parse_url($footnoteLink->getAttribute('href'), PHP_URL_HOST);
339 if (!$linkDomain && isset($this->url)) $linkDomain = @parse_url($this->url, PHP_URL_HOST);
340 //linkDomain = footnoteLink.host ? footnoteLink.host : document.location.host,
341 $linkText = $this->getInnerText($articleLink);
342
343 if ((strpos($articleLink->getAttribute('class'), 'readability-DoNotFootnote') !== false) || preg_match($this->regexps['skipFootnoteLink'], $linkText)) {
344 continue;
345 }
346
347 $linkCount++;
348
349 /** Add a superscript reference after the article link */
350 $refLink->setAttribute('href', '#readabilityFootnoteLink-' . $linkCount);
351 $refLink->innerHTML = '<small><sup>[' . $linkCount . ']</sup></small>';
352 $refLink->setAttribute('class', 'readability-DoNotFootnote');
353 $refLink->setAttribute('style', 'color: inherit;');
354
355 //TODO: does this work or should we use DOMNode.isSameNode()?
356 if ($articleLink->parentNode->lastChild == $articleLink) {
357 $articleLink->parentNode->appendChild($refLink);
358 } else {
359 $articleLink->parentNode->insertBefore($refLink, $articleLink->nextSibling);
360 }
361
362 $articleLink->setAttribute('style', 'color: inherit; text-decoration: none;');
363 $articleLink->setAttribute('name', 'readabilityLink-' . $linkCount);
364
365 $footnote->innerHTML = '<small><sup><a href="#readabilityLink-' . $linkCount . '" title="Jump to Link in Article">^</a></sup></small> ';
366
367 $footnoteLink->innerHTML = ($footnoteLink->getAttribute('title') != '' ? $footnoteLink->getAttribute('title') : $linkText);
368 $footnoteLink->setAttribute('name', 'readabilityFootnoteLink-' . $linkCount);
369
370 $footnote->appendChild($footnoteLink);
371 if ($linkDomain) $footnote->innerHTML = $footnote->innerHTML . '<small> (' . $linkDomain . ')</small>';
372
373 $articleFootnotes->appendChild($footnote);
374 }
375
376 if ($linkCount > 0) {
377 $articleContent->appendChild($footnotesWrapper);
378 }
379 }
380
381 /**
382 * Reverts P elements with class 'readability-styled'
383 * to text nodes - which is what they were before.
384 *
385 * @param DOMElement
386 * @return void
387 */
388 function revertReadabilityStyledElements($articleContent) {
389 $xpath = new DOMXPath($articleContent->ownerDocument);
390 $elems = $xpath->query('.//p[@class="readability-styled"]', $articleContent);
391 //$elems = $articleContent->getElementsByTagName('p');
392 for ($i = $elems->length-1; $i >= 0; $i--) {
393 $e = $elems->item($i);
394 $e->parentNode->replaceChild($articleContent->ownerDocument->createTextNode($e->textContent), $e);
395 //if ($e->hasAttribute('class') && $e->getAttribute('class') == 'readability-styled') {
396 // $e->parentNode->replaceChild($this->dom->createTextNode($e->textContent), $e);
397 //}
398 }
399 }
400
401 /**
402 * Prepare the article node for display. Clean out any inline styles,
403 * iframes, forms, strip extraneous <p> tags, etc.
404 *
405 * @param DOMElement
406 * @return void
407 */
408 function prepArticle($articleContent) {
409 $this->cleanStyles($articleContent);
410 $this->killBreaks($articleContent);
411 if ($this->revertForcedParagraphElements) {
412 $this->revertReadabilityStyledElements($articleContent);
413 }
414
415 /* Clean out junk from the article content */
416 $this->cleanConditionally($articleContent, 'form');
417 $this->clean($articleContent, 'object');
418 $this->clean($articleContent, 'h1');
419
420 /**
421 * If there is only one h2, they are probably using it
422 * as a header and not a subheader, so remove it since we already have a header.
423 ***/
424 if ($articleContent->getElementsByTagName('h2')->length == 1) {
425 $this->clean($articleContent, 'h2');
426 }
427 $this->clean($articleContent, 'iframe');
428
429 $this->cleanHeaders($articleContent);
430
431 /* Do these last as the previous stuff may have removed junk that will affect these */
432 $this->cleanConditionally($articleContent, 'table');
433 $this->cleanConditionally($articleContent, 'ul');
434 $this->cleanConditionally($articleContent, 'div');
435
436 /* Remove extra paragraphs */
437 $articleParagraphs = $articleContent->getElementsByTagName('p');
438 for ($i = $articleParagraphs->length-1; $i >= 0; $i--)
439 {
440 $imgCount = $articleParagraphs->item($i)->getElementsByTagName('img')->length;
441 $embedCount = $articleParagraphs->item($i)->getElementsByTagName('embed')->length;
442 $objectCount = $articleParagraphs->item($i)->getElementsByTagName('object')->length;
443
444 if ($imgCount === 0 && $embedCount === 0 && $objectCount === 0 && $this->getInnerText($articleParagraphs->item($i), false) == '')
445 {
446 $articleParagraphs->item($i)->parentNode->removeChild($articleParagraphs->item($i));
447 }
448 }
449
450 try {
451 $articleContent->innerHTML = preg_replace('/<br[^>]*>\s*<p/i', '<p', $articleContent->innerHTML);
452 //articleContent.innerHTML = articleContent.innerHTML.replace(/<br[^>]*>\s*<p/gi, '<p');
453 }
454 catch (Exception $e) {
455 $this->dbg("Cleaning innerHTML of breaks failed. This is an IE strict-block-elements bug. Ignoring.: " . $e);
456 }
457 }
458
459 /**
460 * Initialize a node with the readability object. Also checks the
461 * className/id for special names to add to its score.
462 *
463 * @param Element
464 * @return void
465 **/
466 protected function initializeNode($node) {
467 $readability = $this->dom->createAttribute('readability');
468 $readability->value = 0; // this is our contentScore
469 $node->setAttributeNode($readability);
470
471 switch (strtoupper($node->tagName)) { // unsure if strtoupper is needed, but using it just in case
472 case 'DIV':
473 $readability->value += 5;
474 break;
475
476 case 'PRE':
477 case 'TD':
478 case 'BLOCKQUOTE':
479 $readability->value += 3;
480 break;
481
482 case 'ADDRESS':
483 case 'OL':
484 case 'UL':
485 case 'DL':
486 case 'DD':
487 case 'DT':
488 case 'LI':
489 case 'FORM':
490 $readability->value -= 3;
491 break;
492
493 case 'H1':
494 case 'H2':
495 case 'H3':
496 case 'H4':
497 case 'H5':
498 case 'H6':
499 case 'TH':
500 $readability->value -= 5;
501 break;
502 }
503 $readability->value += $this->getClassWeight($node);
504 }
505
506 /***
507 * grabArticle - Using a variety of metrics (content score, classname, element types), find the content that is
508 * most likely to be the stuff a user wants to read. Then return it wrapped up in a div.
509 *
510 * @return DOMElement
511 **/
512 protected function grabArticle($page=null) {
513 $stripUnlikelyCandidates = $this->flagIsActive(self::FLAG_STRIP_UNLIKELYS);
514 if (!$page) $page = $this->dom;
515 $allElements = $page->getElementsByTagName('*');
516 /**
517 * First, node prepping. Trash nodes that look cruddy (like ones with the class name "comment", etc), and turn divs
518 * into P tags where they have been used inappropriately (as in, where they contain no other block level elements.)
519 *
520 * Note: Assignment from index for performance. See http://www.peachpit.com/articles/article.aspx?p=31567&seqNum=5
521 * TODO: Shouldn't this be a reverse traversal?
522 **/
523 $node = null;
524 $nodesToScore = array();
525 for ($nodeIndex = 0; ($node = $allElements->item($nodeIndex)); $nodeIndex++) {
526 //for ($nodeIndex=$targetList->length-1; $nodeIndex >= 0; $nodeIndex--) {
527 //$node = $targetList->item($nodeIndex);
528 $tagName = strtoupper($node->tagName);
529 /* Remove unlikely candidates */
530 if ($stripUnlikelyCandidates) {
531 $unlikelyMatchString = $node->getAttribute('class') . $node->getAttribute('id');
532 if (
533 preg_match($this->regexps['unlikelyCandidates'], $unlikelyMatchString) &&
534 !preg_match($this->regexps['okMaybeItsACandidate'], $unlikelyMatchString) &&
535 $tagName != 'BODY'
536 )
537 {
538 $this->dbg('Removing unlikely candidate - ' . $unlikelyMatchString);
539 //$nodesToRemove[] = $node;
540 $node->parentNode->removeChild($node);
541 $nodeIndex--;
542 continue;
543 }
544 }
545
546 if ($tagName == 'P' || $tagName == 'TD' || $tagName == 'PRE') {
547 $nodesToScore[] = $node;
548 }
549
550 /* Turn all divs that don't have children block level elements into p's */
551 if ($tagName == 'DIV') {
552 if (!preg_match($this->regexps['divToPElements'], $node->innerHTML)) {
553 //$this->dbg('Altering div to p');
554 $newNode = $this->dom->createElement('p');
555 try {
556 $newNode->innerHTML = $node->innerHTML;
557 //$nodesToReplace[] = array('new'=>$newNode, 'old'=>$node);
558 $node->parentNode->replaceChild($newNode, $node);
559 $nodeIndex--;
560 $nodesToScore[] = $node; // or $newNode?
561 }
562 catch(Exception $e) {
563 $this->dbg('Could not alter div to p, reverting back to div.: ' . $e);
564 }
565 }
566 else
567 {
568 // EXPERIMENTAL
569 // TODO: change these p elements back to text nodes after processing
570 for ($i = 0, $il = $node->childNodes->length; $i < $il; $i++) {
571 $childNode = $node->childNodes->item($i);
572 if ($childNode->nodeType == 3) { // XML_TEXT_NODE
573 //$this->dbg('replacing text node with a p tag with the same content.');
574 $p = $this->dom->createElement('p');
575 $p->innerHTML = $childNode->nodeValue;
576 $p->setAttribute('style', 'display: inline;');
577 $p->setAttribute('class', 'readability-styled');
578 $childNode->parentNode->replaceChild($p, $childNode);
579 }
580 }
581 }
582 }
583 }
584
585 /**
586 * Loop through all paragraphs, and assign a score to them based on how content-y they look.
587 * Then add their score to their parent node.
588 *
589 * A score is determined by things like number of commas, class names, etc. Maybe eventually link density.
590 **/
591 $candidates = array();
592 for ($pt=0; $pt < count($nodesToScore); $pt++) {
593 $parentNode = $nodesToScore[$pt]->parentNode;
594 // $grandParentNode = $parentNode ? $parentNode->parentNode : null;
595 $grandParentNode = !$parentNode ? null : (($parentNode->parentNode instanceof DOMElement) ? $parentNode->parentNode : null);
596 $innerText = $this->getInnerText($nodesToScore[$pt]);
597
598 if (!$parentNode || !isset($parentNode->tagName)) {
599 continue;
600 }
601
602 /* If this paragraph is less than 25 characters, don't even count it. */
603 if(strlen($innerText) < 25) {
604 continue;
605 }
606
607 /* Initialize readability data for the parent. */
608 if (!$parentNode->hasAttribute('readability'))
609 {
610 $this->initializeNode($parentNode);
611 $candidates[] = $parentNode;
612 }
613
614 /* Initialize readability data for the grandparent. */
615 if ($grandParentNode && !$grandParentNode->hasAttribute('readability') && isset($grandParentNode->tagName))
616 {
617 $this->initializeNode($grandParentNode);
618 $candidates[] = $grandParentNode;
619 }
620
621 $contentScore = 0;
622
623 /* Add a point for the paragraph itself as a base. */
624 $contentScore++;
625
626 /* Add points for any commas within this paragraph */
627 $contentScore += count(explode(',', $innerText));
628
629 /* For every 100 characters in this paragraph, add another point. Up to 3 points. */
630 $contentScore += min(floor(strlen($innerText) / 100), 3);
631
632 /* Add the score to the parent. The grandparent gets half. */
633 $parentNode->getAttributeNode('readability')->value += $contentScore;
634
635 if ($grandParentNode) {
636 $grandParentNode->getAttributeNode('readability')->value += $contentScore/2;
637 }
638 }
639
640 /**
641 * After we've calculated scores, loop through all of the possible candidate nodes we found
642 * and find the one with the highest score.
643 **/
644 $topCandidate = null;
645 for ($c=0, $cl=count($candidates); $c < $cl; $c++)
646 {
647 /**
648 * Scale the final candidates score based on link density. Good content should have a
649 * relatively small link density (5% or less) and be mostly unaffected by this operation.
650 **/
651 $readability = $candidates[$c]->getAttributeNode('readability');
652 $readability->value = $readability->value * (1-$this->getLinkDensity($candidates[$c]));
653
654 $this->dbg('Candidate: ' . $candidates[$c]->tagName . ' (' . $candidates[$c]->getAttribute('class') . ':' . $candidates[$c]->getAttribute('id') . ') with score ' . $readability->value);
655
656 if (!$topCandidate || $readability->value > (int)$topCandidate->getAttribute('readability')) {
657 $topCandidate = $candidates[$c];
658 }
659 }
660
661 /**
662 * If we still have no top candidate, just use the body as a last resort.
663 * We also have to copy the body node so it is something we can modify.
664 **/
665 if ($topCandidate === null || strtoupper($topCandidate->tagName) == 'BODY')
666 {
667 $topCandidate = $this->dom->createElement('div');
668 if ($page instanceof DOMDocument) {
669 if (!isset($page->documentElement)) {
670 // we don't have a body either? what a mess! :)
671 } else {
672 $topCandidate->innerHTML = $page->documentElement->innerHTML;
673 $page->documentElement->innerHTML = '';
674 $page->documentElement->appendChild($topCandidate);
675 }
676 } else {
677 $topCandidate->innerHTML = $page->innerHTML;
678 $page->innerHTML = '';
679 $page->appendChild($topCandidate);
680 }
681 $this->initializeNode($topCandidate);
682 }
683
684 /**
685 * Now that we have the top candidate, look through its siblings for content that might also be related.
686 * Things like preambles, content split by ads that we removed, etc.
687 **/
688 $articleContent = $this->dom->createElement('div');
689 $articleContent->setAttribute('id', 'readability-content');
690 $siblingScoreThreshold = max(10, ((int)$topCandidate->getAttribute('readability')) * 0.2);
691 $siblingNodes = $topCandidate->parentNode->childNodes;
692 if (!isset($siblingNodes)) {
693 $siblingNodes = new stdClass;
694 $siblingNodes->length = 0;
695 }
696
697 for ($s=0, $sl=$siblingNodes->length; $s < $sl; $s++)
698 {
699 $siblingNode = $siblingNodes->item($s);
700 $append = false;
701
702 $this->dbg('Looking at sibling node: ' . $siblingNode->nodeName . (($siblingNode->nodeType === XML_ELEMENT_NODE && $siblingNode->hasAttribute('readability')) ? (' with score ' . $siblingNode->getAttribute('readability')) : ''));
703
704 //dbg('Sibling has score ' . ($siblingNode->readability ? siblingNode.readability.contentScore : 'Unknown'));
705
706 if ($siblingNode === $topCandidate)
707 // or if ($siblingNode->isSameNode($topCandidate))
708 {
709 $append = true;
710 }
711
712 $contentBonus = 0;
713 /* Give a bonus if sibling nodes and top candidates have the example same classname */
714 if ($siblingNode->nodeType === XML_ELEMENT_NODE && $siblingNode->getAttribute('class') == $topCandidate->getAttribute('class') && $topCandidate->getAttribute('class') != '') {
715 $contentBonus += ((int)$topCandidate->getAttribute('readability')) * 0.2;
716 }
717
718 if ($siblingNode->nodeType === XML_ELEMENT_NODE && $siblingNode->hasAttribute('readability') && (((int)$siblingNode->getAttribute('readability')) + $contentBonus) >= $siblingScoreThreshold)
719 {
720 $append = true;
721 }
722
723 if (strtoupper($siblingNode->nodeName) == 'P') {
724 $linkDensity = $this->getLinkDensity($siblingNode);
725 $nodeContent = $this->getInnerText($siblingNode);
726 $nodeLength = strlen($nodeContent);
727
728 if ($nodeLength > 80 && $linkDensity < 0.25)
729 {
730 $append = true;
731 }
732 else if ($nodeLength < 80 && $linkDensity === 0 && preg_match('/\.( |$)/', $nodeContent))
733 {
734 $append = true;
735 }
736 }
737
738 /* Look for a special classname */
739 if ($siblingNode->nodeType === XML_ELEMENT_NODE && $siblingNode->hasAttribute('class') && $siblingNode->getAttribute('class') != '')
740 {
741 if (preg_match($this->regexps['okMaybeItsACandidate'], $siblingNode->getAttribute('class'))) {
742 $append = true;
743 }
744 }
745
746 /* Look for a special classname */
747 if ($siblingNode->nodeType === XML_ELEMENT_NODE && $siblingNode->hasAttribute('id') && $siblingNode->getAttribute('id') != '')
748 {
749 if (preg_match($this->regexps['okMaybeItsACandidate'], $siblingNode->getAttribute('id'))) {
750 $append = true;
751 }
752 }
753
754
755 if ($append)
756 {
757 $this->dbg('Appending node: ' . $siblingNode->nodeName);
758
759 $nodeToAppend = null;
760 $sibNodeName = strtoupper($siblingNode->nodeName);
761 if ($sibNodeName != 'DIV' && $sibNodeName != 'P') {
762 /* We have a node that isn't a common block level element, like a form or td tag. Turn it into a div so it doesn't get filtered out later by accident. */
763
764 $this->dbg('Altering siblingNode of ' . $sibNodeName . ' to div.');
765 $nodeToAppend = $this->dom->createElement('div');
766 try {
767 $nodeToAppend->setAttribute('id', $siblingNode->getAttribute('id'));
768 $nodeToAppend->innerHTML = $siblingNode->innerHTML;
769 }
770 catch(Exception $e)
771 {
772 $this->dbg('Could not alter siblingNode to div, reverting back to original.');
773 $nodeToAppend = $siblingNode;
774 $s--;
775 $sl--;
776 }
777 } else {
778 $nodeToAppend = $siblingNode;
779 $s--;
780 $sl--;
781 }
782
783 /* To ensure a node does not interfere with readability styles, remove its classnames */
784 $nodeToAppend->removeAttribute('class');
785
786 /* Append sibling and subtract from our list because it removes the node when you append to another node */
787 $articleContent->appendChild($nodeToAppend);
788 }
789 }
790
791 /**
792 * So we have all of the content that we need. Now we clean it up for presentation.
793 **/
794 $this->prepArticle($articleContent);
795
796 /**
797 * Now that we've gone through the full algorithm, check to see if we got any meaningful content.
798 * If we didn't, we may need to re-run grabArticle with different flags set. This gives us a higher
799 * likelihood of finding the content, and the sieve approach gives us a higher likelihood of
800 * finding the -right- content.
801 **/
802 if (strlen($this->getInnerText($articleContent, false)) < 250)
803 {
804 // TODO: find out why element disappears sometimes, e.g. for this URL http://www.businessinsider.com/6-hedge-fund-etfs-for-average-investors-2011-7
805 // in the meantime, we check and create an empty element if it's not there.
806 if (!isset($this->body->childNodes)) $this->body = $this->dom->createElement('body');
807 $this->body->innerHTML = $this->bodyCache;
808
809 if ($this->flagIsActive(self::FLAG_STRIP_UNLIKELYS)) {
810 $this->removeFlag(self::FLAG_STRIP_UNLIKELYS);
811 return $this->grabArticle($this->body);
812 }
813 else if ($this->flagIsActive(self::FLAG_WEIGHT_CLASSES)) {
814 $this->removeFlag(self::FLAG_WEIGHT_CLASSES);
815 return $this->grabArticle($this->body);
816 }
817 else if ($this->flagIsActive(self::FLAG_CLEAN_CONDITIONALLY)) {
818 $this->removeFlag(self::FLAG_CLEAN_CONDITIONALLY);
819 return $this->grabArticle($this->body);
820 }
821 else {
822 return false;
823 }
824 }
825 return $articleContent;
826 }
827
828 /**
829 * Remove script tags from document
830 *
831 * @param DOMElement
832 * @return void
833 */
834 public function removeScripts($doc) {
835 $scripts = $doc->getElementsByTagName('script');
836 for($i = $scripts->length-1; $i >= 0; $i--)
837 {
838 $scripts->item($i)->parentNode->removeChild($scripts->item($i));
839 }
840 }
841
842 /**
843 * Get the inner text of a node.
844 * This also strips out any excess whitespace to be found.
845 *
846 * @param DOMElement $
847 * @param boolean $normalizeSpaces (default: true)
848 * @return string
849 **/
850 public function getInnerText($e, $normalizeSpaces=true) {
851 $textContent = '';
852
853 if (!isset($e->textContent) || $e->textContent == '') {
854 return '';
855 }
856
857 $textContent = trim($e->textContent);
858
859 if ($normalizeSpaces) {
860 return preg_replace($this->regexps['normalize'], ' ', $textContent);
861 } else {
862 return $textContent;
863 }
864 }
865
866 /**
867 * Get the number of times a string $s appears in the node $e.
868 *
869 * @param DOMElement $e
870 * @param string - what to count. Default is ","
871 * @return number (integer)
872 **/
873 public function getCharCount($e, $s=',') {
874 return substr_count($this->getInnerText($e), $s);
875 }
876
877 /**
878 * Remove the style attribute on every $e and under.
879 *
880 * @param DOMElement $e
881 * @return void
882 */
883 public function cleanStyles($e) {
884 if (!is_object($e)) return;
885 $elems = $e->getElementsByTagName('*');
886 foreach ($elems as $elem) {
887 $elem->removeAttribute('style');
888 }
889 }
890
891 /**
892 * Get the density of links as a percentage of the content
893 * This is the amount of text that is inside a link divided by the total text in the node.
894 *
895 * @param DOMElement $e
896 * @return number (float)
897 */
898 public function getLinkDensity($e) {
899 $links = $e->getElementsByTagName('a');
900 $textLength = strlen($this->getInnerText($e));
901 $linkLength = 0;
902 for ($i=0, $il=$links->length; $i < $il; $i++)
903 {
904 $linkLength += strlen($this->getInnerText($links->item($i)));
905 }
906 if ($textLength > 0) {
907 return $linkLength / $textLength;
908 } else {
909 return 0;
910 }
911 }
912
913 /**
914 * Get an elements class/id weight. Uses regular expressions to tell if this
915 * element looks good or bad.
916 *
917 * @param DOMElement $e
918 * @return number (Integer)
919 */
920 public function getClassWeight($e) {
921 if(!$this->flagIsActive(self::FLAG_WEIGHT_CLASSES)) {
922 return 0;
923 }
924
925 $weight = 0;
926
927 /* Look for a special classname */
928 if ($e->hasAttribute('class') && $e->getAttribute('class') != '')
929 {
930 if (preg_match($this->regexps['negative'], $e->getAttribute('class'))) {
931 $weight -= 25;
932 }
933 if (preg_match($this->regexps['positive'], $e->getAttribute('class'))) {
934 $weight += 25;
935 }
936 }
937
938 /* Look for a special ID */
939 if ($e->hasAttribute('id') && $e->getAttribute('id') != '')
940 {
941 if (preg_match($this->regexps['negative'], $e->getAttribute('id'))) {
942 $weight -= 25;
943 }
944 if (preg_match($this->regexps['positive'], $e->getAttribute('id'))) {
945 $weight += 25;
946 }
947 }
948 return $weight;
949 }
950
951 /**
952 * Remove extraneous break tags from a node.
953 *
954 * @param DOMElement $node
955 * @return void
956 */
957 public function killBreaks($node) {
958 $html = $node->innerHTML;
959 $html = preg_replace($this->regexps['killBreaks'], '<br />', $html);
960 $node->innerHTML = $html;
961 }
962
963 /**
964 * Clean a node of all elements of type "tag".
965 * (Unless it's a youtube/vimeo video. People love movies.)
966 *
967 * @param DOMElement $e
968 * @param string $tag
969 * @return void
970 */
971 public function clean($e, $tag) {
972 $targetList = $e->getElementsByTagName($tag);
973 $isEmbed = ($tag == 'object' || $tag == 'embed');
974
975 for ($y=$targetList->length-1; $y >= 0; $y--) {
976 /* Allow youtube and vimeo videos through as people usually want to see those. */
977 if ($isEmbed) {
978 $attributeValues = '';
979 for ($i=0, $il=$targetList->item($y)->attributes->length; $i < $il; $i++) {
980 $attributeValues .= $targetList->item($y)->attributes->item($i)->value . '|'; // DOMAttr? (TODO: test)
981 }
982
983 /* First, check the elements attributes to see if any of them contain youtube or vimeo */
984 if (preg_match($this->regexps['video'], $attributeValues)) {
985 continue;
986 }
987
988 /* Then check the elements inside this element for the same. */
989 if (preg_match($this->regexps['video'], $targetList->item($y)->innerHTML)) {
990 continue;
991 }
992 }
993 $targetList->item($y)->parentNode->removeChild($targetList->item($y));
994 }
995 }
996
997 /**
998 * Clean an element of all tags of type "tag" if they look fishy.
999 * "Fishy" is an algorithm based on content length, classnames,
1000 * link density, number of images & embeds, etc.
1001 *
1002 * @param DOMElement $e
1003 * @param string $tag
1004 * @return void
1005 */
1006 public function cleanConditionally($e, $tag) {
1007 if (!$this->flagIsActive(self::FLAG_CLEAN_CONDITIONALLY)) {
1008 return;
1009 }
1010
1011 $tagsList = $e->getElementsByTagName($tag);
1012 $curTagsLength = $tagsList->length;
1013
1014 /**
1015 * Gather counts for other typical elements embedded within.
1016 * Traverse backwards so we can remove nodes at the same time without effecting the traversal.
1017 *
1018 * TODO: Consider taking into account original contentScore here.
1019 */
1020 for ($i=$curTagsLength-1; $i >= 0; $i--) {
1021 $weight = $this->getClassWeight($tagsList->item($i));
1022 $contentScore = ($tagsList->item($i)->hasAttribute('readability')) ? (int)$tagsList->item($i)->getAttribute('readability') : 0;
1023
1024 $this->dbg('Cleaning Conditionally ' . $tagsList->item($i)->tagName . ' (' . $tagsList->item($i)->getAttribute('class') . ':' . $tagsList->item($i)->getAttribute('id') . ')' . (($tagsList->item($i)->hasAttribute('readability')) ? (' with score ' . $tagsList->item($i)->getAttribute('readability')) : ''));
1025
1026 if ($weight + $contentScore < 0) {
1027 $tagsList->item($i)->parentNode->removeChild($tagsList->item($i));
1028 }
1029 else if ( $this->getCharCount($tagsList->item($i), ',') < 10) {
1030 /**
1031 * If there are not very many commas, and the number of
1032 * non-paragraph elements is more than paragraphs or other ominous signs, remove the element.
1033 **/
1034 $p = $tagsList->item($i)->getElementsByTagName('p')->length;
1035 $img = $tagsList->item($i)->getElementsByTagName('img')->length;
1036 $li = $tagsList->item($i)->getElementsByTagName('li')->length-100;
1037 $input = $tagsList->item($i)->getElementsByTagName('input')->length;
1038
1039 $embedCount = 0;
1040 $embeds = $tagsList->item($i)->getElementsByTagName('embed');
1041 for ($ei=0, $il=$embeds->length; $ei < $il; $ei++) {
1042 if (preg_match($this->regexps['video'], $embeds->item($ei)->getAttribute('src'))) {
1043 $embedCount++;
1044 }
1045 }
1046
1047 $linkDensity = $this->getLinkDensity($tagsList->item($i));
1048 $contentLength = strlen($this->getInnerText($tagsList->item($i)));
1049 $toRemove = false;
1050
1051 if ( $img > $p ) {
1052 $toRemove = true;
1053 } else if ($li > $p && $tag != 'ul' && $tag != 'ol') {
1054 $toRemove = true;
1055 } else if ( $input > floor($p/3) ) {
1056 $toRemove = true;
1057 } else if ($contentLength < 25 && ($img === 0 || $img > 2) ) {
1058 $toRemove = true;
1059 } else if($weight < 25 && $linkDensity > 0.2) {
1060 $toRemove = true;
1061 } else if($weight >= 25 && $linkDensity > 0.5) {
1062 $toRemove = true;
1063 } else if(($embedCount == 1 && $contentLength < 75) || $embedCount > 1) {
1064 $toRemove = true;
1065 }
1066
1067 if ($toRemove) {
1068 $tagsList->item($i)->parentNode->removeChild($tagsList->item($i));
1069 }
1070 }
1071 }
1072 }
1073
1074 /**
1075 * Clean out spurious headers from an Element. Checks things like classnames and link density.
1076 *
1077 * @param DOMElement $e
1078 * @return void
1079 */
1080 public function cleanHeaders($e) {
1081 for ($headerIndex = 1; $headerIndex < 3; $headerIndex++) {
1082 $headers = $e->getElementsByTagName('h' . $headerIndex);
1083 for ($i=$headers->length-1; $i >=0; $i--) {
1084 if ($this->getClassWeight($headers->item($i)) < 0 || $this->getLinkDensity($headers->item($i)) > 0.33) {
1085 $headers->item($i)->parentNode->removeChild($headers->item($i));
1086 }
1087 }
1088 }
1089 }
1090
1091 public function flagIsActive($flag) {
1092 return ($this->flags & $flag) > 0;
1093 }
1094
1095 public function addFlag($flag) {
1096 $this->flags = $this->flags | $flag;
1097 }
1098
1099 public function removeFlag($flag) {
1100 $this->flags = $this->flags & ~$flag;
1101 }
1102 }
1103 ?>