Readability.php 37 KB

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