Readability.php 36 KB

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