Readability.php 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719
  1. <?php
  2. namespace andreskrey\Readability;
  3. use andreskrey\Readability\Nodes\DOM\DOMDocument;
  4. use andreskrey\Readability\Nodes\DOM\DOMElement;
  5. use andreskrey\Readability\Nodes\DOM\DOMNode;
  6. use andreskrey\Readability\Nodes\DOM\DOMText;
  7. use andreskrey\Readability\Nodes\NodeUtility;
  8. use Psr\Log\LoggerInterface;
  9. /**
  10. * Class Readability.
  11. */
  12. class Readability
  13. {
  14. /**
  15. * Main DOMDocument where all the magic happens.
  16. *
  17. * @var DOMDocument
  18. */
  19. protected $dom;
  20. /**
  21. * Title of the article.
  22. *
  23. * @var string|null
  24. */
  25. protected $title = null;
  26. /**
  27. * Final DOMDocument with the fully parsed HTML.
  28. *
  29. * @var DOMDocument|null
  30. */
  31. protected $content = null;
  32. /**
  33. * Excerpt of the article.
  34. *
  35. * @var string|null
  36. */
  37. protected $excerpt = null;
  38. /**
  39. * Main image of the article.
  40. *
  41. * @var string|null
  42. */
  43. protected $image = null;
  44. /**
  45. * Author of the article. Extracted from the byline tags and other social media properties.
  46. *
  47. * @var string|null
  48. */
  49. protected $author = null;
  50. /**
  51. * Direction of the text.
  52. *
  53. * @var string|null
  54. */
  55. protected $direction = null;
  56. /**
  57. * Configuration object.
  58. *
  59. * @var Configuration
  60. */
  61. private $configuration;
  62. /**
  63. * Logger object.
  64. *
  65. * @var LoggerInterface
  66. */
  67. private $logger;
  68. /**
  69. * Collection of attempted text extractions.
  70. *
  71. * @var array
  72. */
  73. private $attempts = [];
  74. /**
  75. * @var array
  76. */
  77. private $defaultTagsToScore = [
  78. 'section',
  79. 'h2',
  80. 'h3',
  81. 'h4',
  82. 'h5',
  83. 'h6',
  84. 'p',
  85. 'td',
  86. 'pre',
  87. ];
  88. /**
  89. * @var array
  90. */
  91. private $alterToDIVExceptions = [
  92. 'div',
  93. 'article',
  94. 'section',
  95. 'p',
  96. ];
  97. /**
  98. * Readability constructor.
  99. *
  100. * @param Configuration $configuration
  101. */
  102. public function __construct(Configuration $configuration)
  103. {
  104. $this->configuration = $configuration;
  105. $this->logger = $this->configuration->getLogger();
  106. }
  107. /**
  108. * Main parse function.
  109. *
  110. * @param $html
  111. *
  112. * @throws ParseException
  113. *
  114. * @return array|bool
  115. */
  116. public function parse($html)
  117. {
  118. $this->logger->info('*** Starting parse process...');
  119. $this->dom = $this->loadHTML($html);
  120. // Checking for minimum HTML to work with.
  121. if (!($root = $this->dom->getElementsByTagName('body')->item(0)) || !$root->firstChild) {
  122. $this->logger->emergency('No body tag present or body tag empty');
  123. throw new ParseException('Invalid or incomplete HTML.');
  124. }
  125. $this->getMetadata();
  126. $this->getMainImage();
  127. while (true) {
  128. $root = $root->firstChild;
  129. $elementsToScore = $this->getNodes($root);
  130. $this->logger->debug(sprintf('Elements to score: \'%s\'', count($elementsToScore)));
  131. $result = $this->rateNodes($elementsToScore);
  132. /*
  133. * Now that we've gone through the full algorithm, check to see if
  134. * we got any meaningful content. If we didn't, we may need to re-run
  135. * grabArticle with different flags set. This gives us a higher likelihood of
  136. * finding the content, and the sieve approach gives us a higher likelihood of
  137. * finding the -right- content.
  138. */
  139. $length = mb_strlen(preg_replace(NodeUtility::$regexps['onlyWhitespace'], '', $result->textContent));
  140. $this->logger->info(sprintf('[Parsing] Article parsed. Amount of words: %s. Current threshold is: %s', $length, $this->configuration->getWordThreshold()));
  141. $parseSuccessful = true;
  142. if ($result && $length < $this->configuration->getWordThreshold()) {
  143. $this->dom = $this->loadHTML($html);
  144. $root = $this->dom->getElementsByTagName('body')->item(0);
  145. $parseSuccessful = false;
  146. if ($this->configuration->getStripUnlikelyCandidates()) {
  147. $this->logger->debug('[Parsing] Threshold not met, trying again setting StripUnlikelyCandidates as false');
  148. $this->configuration->setStripUnlikelyCandidates(false);
  149. $this->attempts[] = ['articleContent' => $result, 'textLength' => $length];
  150. } elseif ($this->configuration->getWeightClasses()) {
  151. $this->logger->debug('[Parsing] Threshold not met, trying again setting WeightClasses as false');
  152. $this->configuration->setWeightClasses(false);
  153. $this->attempts[] = ['articleContent' => $result, 'textLength' => $length];
  154. } elseif ($this->configuration->getCleanConditionally()) {
  155. $this->logger->debug('[Parsing] Threshold not met, trying again setting CleanConditionally as false');
  156. $this->configuration->setCleanConditionally(false);
  157. $this->attempts[] = ['articleContent' => $result, 'textLength' => $length];
  158. } else {
  159. $this->logger->debug('[Parsing] Threshold not met, searching across attempts for some content.');
  160. $this->attempts[] = ['articleContent' => $result, 'textLength' => $length];
  161. // No luck after removing flags, just return the longest text we found during the different loops
  162. usort($this->attempts, function ($a, $b) {
  163. return $a['textLength'] < $b['textLength'];
  164. });
  165. // But first check if we actually have something
  166. if (!$this->attempts[0]['textLength']) {
  167. $this->logger->emergency('[Parsing] Could not parse text, giving up :(');
  168. throw new ParseException('Could not parse text.');
  169. }
  170. $this->logger->debug('[Parsing] Threshold not met, but found some content in previous attempts.');
  171. $result = $this->attempts[0]['articleContent'];
  172. $parseSuccessful = true;
  173. break;
  174. }
  175. } else {
  176. break;
  177. }
  178. }
  179. if ($parseSuccessful) {
  180. $result = $this->postProcessContent($result);
  181. // If we haven't found an excerpt in the article's metadata, use the article's
  182. // first paragraph as the excerpt. This can be used for displaying a preview of
  183. // the article's content.
  184. if (!$this->getExcerpt()) {
  185. $this->logger->debug('[Parsing] No excerpt text found on metadata, extracting first p node and using it as excerpt.');
  186. $paragraphs = $result->getElementsByTagName('p');
  187. if ($paragraphs->length > 0) {
  188. $this->setExcerpt(trim($paragraphs->item(0)->textContent));
  189. }
  190. }
  191. $this->setContent($result);
  192. $this->logger->info('*** Parse successful :)');
  193. return true;
  194. }
  195. }
  196. /**
  197. * Creates a DOM Document object and loads the provided HTML on it.
  198. *
  199. * Used for the first load of Readability and subsequent reloads (when disabling flags and rescanning the text)
  200. * Previous versions of Readability used this method one time and cloned the DOM to keep a backup. This caused bugs
  201. * because cloning the DOM object keeps a relation between the clone and the original one, doing changes in both
  202. * objects and ruining the backup.
  203. *
  204. * @param string $html
  205. *
  206. * @return DOMDocument
  207. */
  208. private function loadHTML($html)
  209. {
  210. $this->logger->debug('[Loading] Loading HTML...');
  211. // To avoid throwing a gazillion of errors on malformed HTMLs
  212. libxml_use_internal_errors(true);
  213. $dom = new DOMDocument('1.0', 'utf-8');
  214. if (!$this->configuration->getSubstituteEntities()) {
  215. // Keep the original HTML entities
  216. $dom->substituteEntities = false;
  217. }
  218. if ($this->configuration->getNormalizeEntities()) {
  219. $this->logger->debug('[Loading] Normalized entities via mb_convert_encoding.');
  220. // Replace UTF-8 characters with the HTML Entity equivalent. Useful to fix html with mixed content
  221. $html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
  222. }
  223. if ($this->configuration->getSummonCthulhu()) {
  224. $this->logger->debug('[Loading] Removed script tags via regex H̶͈̩̟̬̱͠E̡̨̬͔̳̜͢͠ ̡̧̯͉̩͙̩̹̞̠͎͈̹̥̠͞ͅͅC̶͉̞̘̖̝̗͓̬̯͍͉̤̬͢͢͞Ò̟̘͉͖͎͉̱̭̣̕M̴̯͈̻̱̱̣̗͈̠̙̲̥͘͞E̷̛͙̼̲͍͕̹͍͇̗̻̬̮̭̱̥͢Ş̛̟͔̙̜̤͇̮͍̙̝̀͘');
  225. $html = preg_replace('/<script\b[^>]*>([\s\S]*?)<\/script>/', '', $html);
  226. }
  227. // Prepend the XML tag to avoid having issues with special characters. Should be harmless.
  228. $dom->loadHTML('<?xml encoding="UTF-8">' . $html);
  229. $dom->encoding = 'UTF-8';
  230. $this->removeScripts($dom);
  231. $this->prepDocument($dom);
  232. $this->logger->debug('[Loading] Loaded HTML successfully.');
  233. return $dom;
  234. }
  235. /**
  236. * Tries to guess relevant info from metadata of the html. Sets the results in the Readability properties.
  237. */
  238. private function getMetadata()
  239. {
  240. $this->logger->debug('[Metadata] Retrieving metadata...');
  241. $values = [];
  242. // Match "description", or Twitter's "twitter:description" (Cards)
  243. // in name attribute.
  244. $namePattern = '/^\s*((twitter)\s*:\s*)?(description|title|image)\s*$/i';
  245. // Match Facebook's Open Graph title & description properties.
  246. $propertyPattern = '/^\s*og\s*:\s*(description|title|image)\s*$/i';
  247. foreach ($this->dom->getElementsByTagName('meta') as $meta) {
  248. /* @var DOMNode $meta */
  249. $elementName = $meta->getAttribute('name');
  250. $elementProperty = $meta->getAttribute('property');
  251. if (in_array('author', [$elementName, $elementProperty])) {
  252. $this->logger->info(sprintf('[Metadata] Found author: \'%s\'', $meta->getAttribute('content')));
  253. $this->setAuthor($meta->getAttribute('content'));
  254. continue;
  255. }
  256. $name = null;
  257. if (preg_match($namePattern, $elementName)) {
  258. $name = $elementName;
  259. } elseif (preg_match($propertyPattern, $elementProperty)) {
  260. $name = $elementProperty;
  261. }
  262. if ($name) {
  263. $content = $meta->getAttribute('content');
  264. if ($content) {
  265. // Convert to lowercase and remove any whitespace
  266. // so we can match below.
  267. $name = preg_replace('/\s/', '', strtolower($name));
  268. $values[$name] = trim($content);
  269. }
  270. }
  271. }
  272. if (array_key_exists('description', $values)) {
  273. $this->logger->info(sprintf('[Metadata] Found excerpt in \'description\' tag: \'%s\'', $values['description']));
  274. $this->setExcerpt($values['description']);
  275. } elseif (array_key_exists('og:description', $values)) {
  276. // Use facebook open graph description.
  277. $this->logger->info(sprintf('[Metadata] Found excerpt in \'og:description\' tag: \'%s\'', $values['og:description']));
  278. $this->setExcerpt($values['og:description']);
  279. } elseif (array_key_exists('twitter:description', $values)) {
  280. // Use twitter cards description.
  281. $this->logger->info(sprintf('[Metadata] Found excerpt in \'twitter:description\' tag: \'%s\'', $values['twitter:description']));
  282. $this->setExcerpt($values['twitter:description']);
  283. }
  284. $this->setTitle($this->getArticleTitle());
  285. if (!$this->getTitle()) {
  286. if (array_key_exists('og:title', $values)) {
  287. // Use facebook open graph title.
  288. $this->logger->info(sprintf('[Metadata] Found title in \'og:title\' tag: \'%s\'', $values['og:title']));
  289. $this->setTitle($values['og:title']);
  290. } elseif (array_key_exists('twitter:title', $values)) {
  291. // Use twitter cards title.
  292. $this->logger->info(sprintf('[Metadata] Found title in \'twitter:title\' tag: \'%s\'', $values['twitter:title']));
  293. $this->setTitle($values['twitter:title']);
  294. }
  295. }
  296. if (array_key_exists('og:image', $values) || array_key_exists('twitter:image', $values)) {
  297. if (array_key_exists('og:image', $values)) {
  298. $this->logger->info(sprintf('[Metadata] Found main image in \'og:image\' tag: \'%s\'', $values['og:image']));
  299. $this->setImage($values['og:image']);
  300. } else {
  301. $this->logger->info(sprintf('[Metadata] Found main image in \'twitter:image\' tag: \'%s\'', $values['twitter:image']));
  302. $this->setImage($values['twitter:image']);
  303. }
  304. }
  305. }
  306. /**
  307. * Returns all the images of the parsed article.
  308. *
  309. * @return array
  310. */
  311. public function getImages()
  312. {
  313. $result = [];
  314. if ($this->getImage()) {
  315. $result[] = $this->getImage();
  316. }
  317. if (null == $this->getDOMDocument()) {
  318. return $result;
  319. }
  320. foreach ($this->getDOMDocument()->getElementsByTagName('img') as $img) {
  321. if ($src = $img->getAttribute('src')) {
  322. $result[] = $src;
  323. }
  324. }
  325. if ($this->configuration->getFixRelativeURLs()) {
  326. foreach ($result as &$imgSrc) {
  327. $imgSrc = $this->toAbsoluteURI($imgSrc);
  328. }
  329. }
  330. $result = array_unique(array_filter($result));
  331. return $result;
  332. }
  333. /**
  334. * Tries to get the main article image. Will only update the metadata if the getMetadata function couldn't
  335. * find a correct image.
  336. */
  337. public function getMainImage()
  338. {
  339. $imgUrl = false;
  340. if ($this->getImage() !== null) {
  341. $imgUrl = $this->getImage();
  342. }
  343. if (!$imgUrl) {
  344. foreach ($this->dom->getElementsByTagName('link') as $link) {
  345. /** @var \DOMElement $link */
  346. /*
  347. * Check for the rel attribute, then check if the rel attribute is either img_src or image_src, and
  348. * finally check for the existence of the href attribute, which should hold the image url.
  349. */
  350. if ($link->hasAttribute('rel') && ($link->getAttribute('rel') === 'img_src' || $link->getAttribute('rel') === 'image_src') && $link->hasAttribute('href')) {
  351. $imgUrl = $link->getAttribute('href');
  352. break;
  353. }
  354. }
  355. }
  356. if (!empty($imgUrl) && $this->configuration->getFixRelativeURLs()) {
  357. $this->setImage($this->toAbsoluteURI($imgUrl));
  358. }
  359. }
  360. /**
  361. * Returns the title of the html. Prioritizes the title from the metadata against the title tag.
  362. *
  363. * @return string|null
  364. */
  365. private function getArticleTitle()
  366. {
  367. $originalTitle = null;
  368. if ($this->getTitle()) {
  369. $originalTitle = $this->getTitle();
  370. } else {
  371. $this->logger->debug('[Metadata] Could not find title in metadata, searching for the title tag...');
  372. $titleTag = $this->dom->getElementsByTagName('title');
  373. if ($titleTag->length > 0) {
  374. $this->logger->info(sprintf('[Metadata] Using title tag as article title: \'%s\'', $titleTag->item(0)->nodeValue));
  375. $originalTitle = $titleTag->item(0)->nodeValue;
  376. }
  377. }
  378. if ($originalTitle === null) {
  379. return null;
  380. }
  381. $curTitle = $originalTitle;
  382. $titleHadHierarchicalSeparators = false;
  383. /*
  384. * If there's a separator in the title, first remove the final part
  385. *
  386. * Sanity warning: if you eval this match in PHPStorm's "Evaluate expression" box, it will return false
  387. * I can assure you it works properly if you let the code run.
  388. */
  389. if (preg_match('/ [\|\-\\\\\/>»] /i', $curTitle)) {
  390. $titleHadHierarchicalSeparators = (bool)preg_match('/ [\\\\\/>»] /', $curTitle);
  391. $curTitle = preg_replace('/(.*)[\|\-\\\\\/>»] .*/i', '$1', $originalTitle);
  392. $this->logger->info(sprintf('[Metadata] Found hierarchical separators in title, new title is: \'%s\'', $curTitle));
  393. // If the resulting title is too short (3 words or fewer), remove
  394. // the first part instead:
  395. if (count(preg_split('/\s+/', $curTitle)) < 3) {
  396. $curTitle = preg_replace('/[^\|\-\\\\\/>»]*[\|\-\\\\\/>»](.*)/i', '$1', $originalTitle);
  397. $this->logger->info(sprintf('[Metadata] Title too short, using the first part of the title instead: \'%s\'', $curTitle));
  398. }
  399. } elseif (strpos($curTitle, ': ') !== false) {
  400. // Check if we have an heading containing this exact string, so we
  401. // could assume it's the full title.
  402. $match = false;
  403. for ($i = 1; $i <= 2; $i++) {
  404. foreach ($this->dom->getElementsByTagName('h' . $i) as $hTag) {
  405. // Trim texts to avoid having false negatives when the title is surrounded by spaces or tabs
  406. if (trim($hTag->nodeValue) === trim($curTitle)) {
  407. $match = true;
  408. }
  409. }
  410. }
  411. // If we don't, let's extract the title out of the original title string.
  412. if (!$match) {
  413. $curTitle = substr($originalTitle, strrpos($originalTitle, ':') + 1);
  414. $this->logger->info(sprintf('[Metadata] Title has a colon in the middle, new title is: \'%s\'', $curTitle));
  415. // If the title is now too short, try the first colon instead:
  416. if (count(preg_split('/\s+/', $curTitle)) < 3) {
  417. $curTitle = substr($originalTitle, strpos($originalTitle, ':') + 1);
  418. $this->logger->info(sprintf('[Metadata] Title too short, using the first part of the title instead: \'%s\'', $curTitle));
  419. } elseif (count(preg_split('/\s+/', substr($curTitle, 0, strpos($curTitle, ':')))) > 5) {
  420. // But if we have too many words before the colon there's something weird
  421. // with the titles and the H tags so let's just use the original title instead
  422. $curTitle = $originalTitle;
  423. }
  424. }
  425. } elseif (mb_strlen($curTitle) > 150 || mb_strlen($curTitle) < 15) {
  426. $hOnes = $this->dom->getElementsByTagName('h1');
  427. if ($hOnes->length === 1) {
  428. $curTitle = $hOnes->item(0)->nodeValue;
  429. $this->logger->info(sprintf('[Metadata] Using title from an H1 node: \'%s\'', $curTitle));
  430. }
  431. }
  432. $curTitle = trim($curTitle);
  433. /*
  434. * If we now have 4 words or fewer as our title, and either no
  435. * 'hierarchical' separators (\, /, > or ») were found in the original
  436. * title or we decreased the number of words by more than 1 word, use
  437. * the original title.
  438. */
  439. $curTitleWordCount = count(preg_split('/\s+/', $curTitle));
  440. $originalTitleWordCount = count(preg_split('/\s+/', preg_replace('/[\|\-\\\\\/>»]+/', '', $originalTitle))) - 1;
  441. if ($curTitleWordCount <= 4 &&
  442. (!$titleHadHierarchicalSeparators || $curTitleWordCount !== $originalTitleWordCount)) {
  443. $curTitle = $originalTitle;
  444. $this->logger->info(sprintf('Using title from an H1 node: \'%s\'', $curTitle));
  445. }
  446. return $curTitle;
  447. }
  448. /**
  449. * Convert URI to an absolute URI.
  450. *
  451. * @param $uri string URI to convert
  452. *
  453. * @return string
  454. */
  455. private function toAbsoluteURI($uri)
  456. {
  457. list($pathBase, $scheme, $prePath) = $this->getPathInfo($this->configuration->getOriginalURL());
  458. // If this is already an absolute URI, return it.
  459. if (preg_match('/^[a-zA-Z][a-zA-Z0-9\+\-\.]*:/', $uri)) {
  460. return $uri;
  461. }
  462. // Scheme-rooted relative URI.
  463. if (substr($uri, 0, 2) === '//') {
  464. return $scheme . '://' . substr($uri, 2);
  465. }
  466. // Prepath-rooted relative URI.
  467. if (substr($uri, 0, 1) === '/') {
  468. return $prePath . $uri;
  469. }
  470. // Dotslash relative URI.
  471. if (strpos($uri, './') === 0) {
  472. return $pathBase . substr($uri, 2);
  473. }
  474. // Ignore hash URIs:
  475. if (substr($uri, 0, 1) === '#') {
  476. return $uri;
  477. }
  478. // Standard relative URI; add entire path. pathBase already includes a
  479. // trailing "/".
  480. return $pathBase . $uri;
  481. }
  482. /**
  483. * Returns full path info of an URL.
  484. *
  485. * @param string $url
  486. *
  487. * @return array [$pathBase, $scheme, $prePath]
  488. */
  489. public function getPathInfo($url)
  490. {
  491. // Check for base URLs
  492. if ($this->dom->baseURI !== null) {
  493. if (substr($this->dom->baseURI, 0, 1) === '/') {
  494. // URLs starting with '/' override completely the URL defined in the link
  495. $pathBase = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . $this->dom->baseURI;
  496. } else {
  497. // Otherwise just prepend the base to the actual path
  498. $pathBase = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . dirname(parse_url($url, PHP_URL_PATH)) . '/' . rtrim($this->dom->baseURI, '/') . '/';
  499. }
  500. } else {
  501. $pathBase = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . dirname(parse_url($url, PHP_URL_PATH)) . '/';
  502. }
  503. $scheme = parse_url($pathBase, PHP_URL_SCHEME);
  504. $prePath = $scheme . '://' . parse_url($pathBase, PHP_URL_HOST);
  505. return [$pathBase, $scheme, $prePath];
  506. }
  507. /**
  508. * Gets nodes from the root element.
  509. *
  510. * @param $node DOMNode|DOMText
  511. *
  512. * @return array
  513. */
  514. private function getNodes($node)
  515. {
  516. $this->logger->info('[Get Nodes] Retrieving nodes...');
  517. $stripUnlikelyCandidates = $this->configuration->getStripUnlikelyCandidates();
  518. $elementsToScore = [];
  519. /*
  520. * First, node prepping. Trash nodes that look cruddy (like ones with the
  521. * class name "comment", etc), and turn divs into P tags where they have been
  522. * used inappropriately (as in, where they contain no other block level elements.)
  523. */
  524. while ($node) {
  525. $matchString = $node->getAttribute('class') . ' ' . $node->getAttribute('id');
  526. // Remove DOMComments nodes as we don't need them and mess up children counting
  527. if ($node->nodeType === XML_COMMENT_NODE) {
  528. $this->logger->debug(sprintf('[Get Nodes] Found comment node, removing... Node content was: \'%s\'', substr($node->nodeValue, 0, 128)));
  529. $node = NodeUtility::removeAndGetNext($node);
  530. continue;
  531. }
  532. // Check to see if this node is a byline, and remove it if it is.
  533. if ($this->checkByline($node, $matchString)) {
  534. $this->logger->debug(sprintf('[Get Nodes] Found byline, removing... Node content was: \'%s\'', substr($node->nodeValue, 0, 128)));
  535. $node = NodeUtility::removeAndGetNext($node);
  536. continue;
  537. }
  538. // Remove unlikely candidates
  539. if ($stripUnlikelyCandidates) {
  540. if (
  541. preg_match(NodeUtility::$regexps['unlikelyCandidates'], $matchString) &&
  542. !preg_match(NodeUtility::$regexps['okMaybeItsACandidate'], $matchString) &&
  543. $node->nodeName !== 'body' &&
  544. $node->nodeName !== 'a'
  545. ) {
  546. $this->logger->debug(sprintf('[Get Nodes] Removing unlikely candidate. Node content was: \'%s\'', substr($node->nodeValue, 0, 128)));
  547. $node = NodeUtility::removeAndGetNext($node);
  548. continue;
  549. }
  550. }
  551. // Remove DIV, SECTION, and HEADER nodes without any content(e.g. text, image, video, or iframe).
  552. if (($node->nodeName === 'div' || $node->nodeName === 'section' || $node->nodeName === 'header' ||
  553. $node->nodeName === 'h1' || $node->nodeName === 'h2' || $node->nodeName === 'h3' ||
  554. $node->nodeName === 'h4' || $node->nodeName === 'h5' || $node->nodeName === 'h6' ||
  555. $node->nodeName === 'p') &&
  556. $node->isElementWithoutContent()) {
  557. $this->logger->debug(sprintf('[Get Nodes] Removing empty \'%s\' node.', $node->nodeName));
  558. $node = NodeUtility::removeAndGetNext($node);
  559. continue;
  560. }
  561. if (in_array(strtolower($node->nodeName), $this->defaultTagsToScore)) {
  562. $this->logger->debug(sprintf('[Get Nodes] Adding node to score list, node content is: \'%s\'', substr($node->nodeValue, 0, 128)));
  563. $elementsToScore[] = $node;
  564. }
  565. // Turn all divs that don't have children block level elements into p's
  566. if ($node->nodeName === 'div') {
  567. /*
  568. * Sites like http://mobile.slate.com encloses each paragraph with a DIV
  569. * element. DIVs with only a P element inside and no text content can be
  570. * safely converted into plain P elements to avoid confusing the scoring
  571. * algorithm with DIVs with are, in practice, paragraphs.
  572. */
  573. if ($node->hasSinglePNode()) {
  574. $this->logger->debug(sprintf('[Get Nodes] Found DIV with a single P node, removing DIV. Node content is: \'%s\'', substr($node->nodeValue, 0, 128)));
  575. $pNode = $node->getChildren(true)[0];
  576. $node->parentNode->replaceChild($pNode, $node);
  577. $node = $pNode;
  578. $elementsToScore[] = $node;
  579. } elseif (!$node->hasSingleChildBlockElement()) {
  580. $this->logger->debug(sprintf('[Get Nodes] Found DIV with a single child block element, converting to a P node. Node content is: \'%s\'', substr($node->nodeValue, 0, 128)));
  581. $node = NodeUtility::setNodeTag($node, 'p');
  582. $elementsToScore[] = $node;
  583. } else {
  584. // EXPERIMENTAL
  585. foreach ($node->getChildren() as $child) {
  586. /** @var $child DOMNode */
  587. if ($child->nodeType === XML_TEXT_NODE && mb_strlen(trim($child->getTextContent())) > 0) {
  588. $this->logger->debug(sprintf('[Get Nodes] Found DIV a text node inside, converting to a P node. Node content is: \'%s\'', substr($node->nodeValue, 0, 128)));
  589. $newNode = $node->createNode($child, 'p');
  590. $child->parentNode->replaceChild($newNode, $child);
  591. }
  592. }
  593. }
  594. }
  595. $node = NodeUtility::getNextNode($node);
  596. }
  597. return $elementsToScore;
  598. }
  599. /**
  600. * Checks if the node is a byline.
  601. *
  602. * @param DOMNode $node
  603. * @param string $matchString
  604. *
  605. * @return bool
  606. */
  607. private function checkByline($node, $matchString)
  608. {
  609. if (!$this->configuration->getArticleByLine()) {
  610. return false;
  611. }
  612. /*
  613. * Check if the byline is already set
  614. */
  615. if ($this->getAuthor()) {
  616. return false;
  617. }
  618. $rel = $node->getAttribute('rel');
  619. if ($rel === 'author' || preg_match(NodeUtility::$regexps['byline'], $matchString) && $this->isValidByline($node->getTextContent())) {
  620. $this->logger->info(sprintf('[Metadata] Found article author: \'%s\'', $node->getTextContent()));
  621. $this->setAuthor(trim($node->getTextContent()));
  622. return true;
  623. }
  624. return false;
  625. }
  626. /**
  627. * Checks the validity of a byLine. Based on string length.
  628. *
  629. * @param string $text
  630. *
  631. * @return bool
  632. */
  633. private function isValidByline($text)
  634. {
  635. if (gettype($text) == 'string') {
  636. $byline = trim($text);
  637. return (mb_strlen($byline) > 0) && (mb_strlen($text) < 100);
  638. }
  639. return false;
  640. }
  641. /**
  642. * Removes all the scripts of the html.
  643. *
  644. * @param DOMDocument $dom
  645. */
  646. private function removeScripts(DOMDocument $dom)
  647. {
  648. $toRemove = ['script', 'noscript'];
  649. foreach ($toRemove as $tag) {
  650. while ($script = $dom->getElementsByTagName($tag)) {
  651. if ($script->item(0)) {
  652. $script->item(0)->parentNode->removeChild($script->item(0));
  653. } else {
  654. break;
  655. }
  656. }
  657. }
  658. }
  659. /**
  660. * Prepares the document for parsing.
  661. *
  662. * @param DOMDocument $dom
  663. */
  664. private function prepDocument(DOMDocument $dom)
  665. {
  666. $this->logger->info('[PrepDocument] Preparing document for parsing...');
  667. /*
  668. * DOMNodeList must be converted to an array before looping over it.
  669. * This is done to avoid node shifting when removing nodes.
  670. *
  671. * Reverse traversing cannot be done here because we need to find brs that are right next to other brs.
  672. * (If we go the other way around we need to search for previous nodes forcing the creation of new functions
  673. * that will be used only here)
  674. */
  675. foreach (iterator_to_array($dom->getElementsByTagName('br')) as $br) {
  676. $next = $br->nextSibling;
  677. /*
  678. * Whether 2 or more <br> elements have been found and replaced with a
  679. * <p> block.
  680. */
  681. $replaced = false;
  682. /*
  683. * If we find a <br> chain, remove the <br>s until we hit another element
  684. * or non-whitespace. This leaves behind the first <br> in the chain
  685. * (which will be replaced with a <p> later).
  686. */
  687. while (($next = NodeUtility::nextElement($next)) && ($next->nodeName === 'br')) {
  688. $this->logger->debug('[PrepDocument] Removing chain of BR nodes...');
  689. $replaced = true;
  690. $brSibling = $next->nextSibling;
  691. $next->parentNode->removeChild($next);
  692. $next = $brSibling;
  693. }
  694. /*
  695. * If we removed a <br> chain, replace the remaining <br> with a <p>. Add
  696. * all sibling nodes as children of the <p> until we hit another <br>
  697. * chain.
  698. */
  699. if ($replaced) {
  700. $p = $dom->createElement('p');
  701. $br->parentNode->replaceChild($p, $br);
  702. $next = $p->nextSibling;
  703. while ($next) {
  704. // If we've hit another <br><br>, we're done adding children to this <p>.
  705. if ($next->nodeName === 'br') {
  706. $nextElem = NodeUtility::nextElement($next);
  707. if ($nextElem && $nextElem->nodeName === 'br') {
  708. break;
  709. }
  710. }
  711. $this->logger->debug('[PrepDocument] Replacing BR with a P node...');
  712. // Otherwise, make this node a child of the new <p>.
  713. $sibling = $next->nextSibling;
  714. $p->appendChild($next);
  715. $next = $sibling;
  716. }
  717. }
  718. }
  719. // Replace font tags with span
  720. $fonts = $dom->getElementsByTagName('font');
  721. $length = $fonts->length;
  722. for ($i = 0; $i < $length; $i++) {
  723. $this->logger->debug('[PrepDocument] Converting font tag into a span tag.');
  724. $font = $fonts->item($length - 1 - $i);
  725. NodeUtility::setNodeTag($font, 'span', true);
  726. }
  727. }
  728. /**
  729. * Assign scores to each node. Returns full article parsed or false on error.
  730. *
  731. * @param array $nodes
  732. *
  733. * @return DOMDocument|bool
  734. */
  735. private function rateNodes($nodes)
  736. {
  737. $this->logger->info('[Rating] Rating nodes...');
  738. $candidates = [];
  739. /** @var DOMElement $node */
  740. foreach ($nodes as $node) {
  741. if (is_null($node->parentNode)) {
  742. continue;
  743. }
  744. // Discard nodes with less than 25 characters, without blank space
  745. if (mb_strlen($node->getTextContent(true)) < 25) {
  746. continue;
  747. }
  748. $ancestors = $node->getNodeAncestors();
  749. // Exclude nodes with no ancestor
  750. if (count($ancestors) === 0) {
  751. continue;
  752. }
  753. // Start with a point for the paragraph itself as a base.
  754. $contentScore = 1;
  755. // Add points for any commas within this paragraph.
  756. $contentScore += count(explode(',', $node->getTextContent(true)));
  757. // For every 100 characters in this paragraph, add another point. Up to 3 points.
  758. $contentScore += min(floor(mb_strlen($node->getTextContent(true)) / 100), 3);
  759. $this->logger->debug(sprintf('[Rating] Node score %s, content: \'%s\'', $contentScore, substr($node->nodeValue, 0, 128)));
  760. /** @var $ancestor DOMElement */
  761. foreach ($ancestors as $level => $ancestor) {
  762. $this->logger->debug('[Rating] Found ancestor, initializing and adding it as a candidate...');
  763. if (!$ancestor->isInitialized()) {
  764. $ancestor->initializeNode($this->configuration->getWeightClasses());
  765. $candidates[] = $ancestor;
  766. }
  767. /*
  768. * Node score divider:
  769. * - parent: 1 (no division)
  770. * - grandparent: 2
  771. * - great grandparent+: ancestor level * 3
  772. */
  773. if ($level === 0) {
  774. $scoreDivider = 1;
  775. } elseif ($level === 1) {
  776. $scoreDivider = 2;
  777. } else {
  778. $scoreDivider = $level * 3;
  779. }
  780. $currentScore = $ancestor->contentScore;
  781. $ancestor->contentScore = $currentScore + ($contentScore / $scoreDivider);
  782. $this->logger->debug(sprintf('[Rating] Ancestor score %s, value: \'%s\'', $ancestor->contentScore, substr($ancestor->nodeValue, 0, 128)));
  783. }
  784. }
  785. /*
  786. * After we've calculated scores, loop through all of the possible
  787. * candidate nodes we found and find the one with the highest score.
  788. */
  789. $topCandidates = [];
  790. foreach ($candidates as $candidate) {
  791. /*
  792. * Scale the final candidates score based on link density. Good content
  793. * should have a relatively small link density (5% or less) and be mostly
  794. * unaffected by this operation.
  795. */
  796. $candidate->contentScore = $candidate->contentScore * (1 - $candidate->getLinkDensity());
  797. for ($i = 0; $i < $this->configuration->getMaxTopCandidates(); $i++) {
  798. $aTopCandidate = isset($topCandidates[$i]) ? $topCandidates[$i] : null;
  799. if (!$aTopCandidate || $candidate->contentScore > $aTopCandidate->contentScore) {
  800. array_splice($topCandidates, $i, 0, [$candidate]);
  801. if (count($topCandidates) > $this->configuration->getMaxTopCandidates()) {
  802. array_pop($topCandidates);
  803. }
  804. break;
  805. }
  806. }
  807. }
  808. $topCandidate = isset($topCandidates[0]) ? $topCandidates[0] : null;
  809. $parentOfTopCandidate = null;
  810. /*
  811. * If we still have no top candidate, just use the body as a last resort.
  812. * We also have to copy the body node so it is something we can modify.
  813. */
  814. if ($topCandidate === null || $topCandidate->nodeName === 'body') {
  815. $this->logger->info('[Rating] No top candidate found or top candidate is the body tag. Moving all child nodes to a new DIV node.');
  816. // Move all of the page's children into topCandidate
  817. $topCandidate = new DOMDocument('1.0', 'utf-8');
  818. $topCandidate->encoding = 'UTF-8';
  819. $topCandidate->appendChild($topCandidate->createElement('div', ''));
  820. $kids = $this->dom->getElementsByTagName('body')->item(0)->childNodes;
  821. // Cannot be foreached, don't ask me why.
  822. for ($i = 0; $i < $kids->length; $i++) {
  823. $import = $topCandidate->importNode($kids->item($i), true);
  824. $topCandidate->firstChild->appendChild($import);
  825. }
  826. // Candidate must be created using firstChild to grab the DOMElement instead of the DOMDocument.
  827. $topCandidate = $topCandidate->firstChild;
  828. } elseif ($topCandidate) {
  829. $this->logger->info(sprintf('[Rating] Found top candidate, score: %s', $topCandidate->contentScore));
  830. // Find a better top candidate node if it contains (at least three) nodes which belong to `topCandidates` array
  831. // and whose scores are quite closed with current `topCandidate` node.
  832. $alternativeCandidateAncestors = [];
  833. for ($i = 1; $i < count($topCandidates); $i++) {
  834. if ($topCandidates[$i]->contentScore / $topCandidate->contentScore >= 0.75) {
  835. array_push($alternativeCandidateAncestors, $topCandidates[$i]->getNodeAncestors(false));
  836. }
  837. }
  838. $MINIMUM_TOPCANDIDATES = 3;
  839. if (count($alternativeCandidateAncestors) >= $MINIMUM_TOPCANDIDATES) {
  840. $parentOfTopCandidate = $topCandidate->parentNode;
  841. while ($parentOfTopCandidate->nodeName !== 'body') {
  842. $listsContainingThisAncestor = 0;
  843. for ($ancestorIndex = 0; $ancestorIndex < count($alternativeCandidateAncestors) && $listsContainingThisAncestor < $MINIMUM_TOPCANDIDATES; $ancestorIndex++) {
  844. $listsContainingThisAncestor += (int)in_array($parentOfTopCandidate, $alternativeCandidateAncestors[$ancestorIndex]);
  845. }
  846. if ($listsContainingThisAncestor >= $MINIMUM_TOPCANDIDATES) {
  847. $topCandidate = $parentOfTopCandidate;
  848. break;
  849. }
  850. $parentOfTopCandidate = $parentOfTopCandidate->parentNode;
  851. }
  852. }
  853. /*
  854. * Because of our bonus system, parents of candidates might have scores
  855. * themselves. They get half of the node. There won't be nodes with higher
  856. * scores than our topCandidate, but if we see the score going *up* in the first
  857. * few steps up the tree, that's a decent sign that there might be more content
  858. * lurking in other places that we want to unify in. The sibling stuff
  859. * below does some of that - but only if we've looked high enough up the DOM
  860. * tree.
  861. */
  862. $parentOfTopCandidate = $topCandidate->parentNode;
  863. $lastScore = $topCandidate->contentScore;
  864. // The scores shouldn't get too low.
  865. $scoreThreshold = $lastScore / 3;
  866. /* @var DOMElement $parentOfTopCandidate */
  867. // Check if we are actually dealing with a DOMNode and not a DOMDocument node or higher
  868. while ($parentOfTopCandidate->nodeName !== 'body' && $parentOfTopCandidate->nodeType === XML_ELEMENT_NODE) {
  869. $parentScore = $parentOfTopCandidate->contentScore;
  870. if ($parentScore < $scoreThreshold) {
  871. break;
  872. }
  873. if ($parentScore > $lastScore) {
  874. // Alright! We found a better parent to use.
  875. $topCandidate = $parentOfTopCandidate;
  876. $this->logger->info('[Rating] Found a better top candidate.');
  877. break;
  878. }
  879. $lastScore = $parentOfTopCandidate->contentScore;
  880. $parentOfTopCandidate = $parentOfTopCandidate->parentNode;
  881. }
  882. // If the top candidate is the only child, use parent instead. This will help sibling
  883. // joining logic when adjacent content is actually located in parent's sibling node.
  884. $parentOfTopCandidate = $topCandidate->parentNode;
  885. while ($parentOfTopCandidate->nodeName !== 'body' && count($parentOfTopCandidate->getChildren(true)) === 1) {
  886. $topCandidate = $parentOfTopCandidate;
  887. $parentOfTopCandidate = $topCandidate->parentNode;
  888. }
  889. }
  890. /*
  891. * Now that we have the top candidate, look through its siblings for content
  892. * that might also be related. Things like preambles, content split by ads
  893. * that we removed, etc.
  894. */
  895. $this->logger->info('[Rating] Creating final article content document...');
  896. $articleContent = new DOMDocument('1.0', 'utf-8');
  897. $articleContent->createElement('div');
  898. $siblingScoreThreshold = max(10, $topCandidate->contentScore * 0.2);
  899. // Keep potential top candidate's parent node to try to get text direction of it later.
  900. $parentOfTopCandidate = $topCandidate->parentNode;
  901. $siblings = $parentOfTopCandidate->getChildren();
  902. $hasContent = false;
  903. $this->logger->info('[Rating] Adding top candidate siblings...');
  904. /** @var DOMElement $sibling */
  905. foreach ($siblings as $sibling) {
  906. $append = false;
  907. if ($sibling === $topCandidate) {
  908. $this->logger->debug('[Rating] Sibling is equal to the top candidate, adding to the final article...');
  909. $append = true;
  910. } else {
  911. $contentBonus = 0;
  912. // Give a bonus if sibling nodes and top candidates have the example same classname
  913. if ($sibling->getAttribute('class') === $topCandidate->getAttribute('class') && $topCandidate->getAttribute('class') !== '') {
  914. $contentBonus += $topCandidate->contentScore * 0.2;
  915. }
  916. if ($sibling->contentScore + $contentBonus >= $siblingScoreThreshold) {
  917. $append = true;
  918. } elseif ($sibling->nodeName === 'p') {
  919. $linkDensity = $sibling->getLinkDensity();
  920. $nodeContent = $sibling->getTextContent(true);
  921. if (mb_strlen($nodeContent) > 80 && $linkDensity < 0.25) {
  922. $append = true;
  923. } elseif ($nodeContent && mb_strlen($nodeContent) < 80 && $linkDensity === 0 && preg_match('/\.( |$)/', $nodeContent)) {
  924. $append = true;
  925. }
  926. }
  927. }
  928. if ($append) {
  929. $this->logger->debug(sprintf('[Rating] Appending sibling to final article, content is: \'%s\'', substr($sibling->nodeValue, 0, 128)));
  930. $hasContent = true;
  931. if (!in_array(strtolower($sibling->nodeName), $this->alterToDIVExceptions)) {
  932. /*
  933. * We have a node that isn't a common block level element, like a form or td tag.
  934. * Turn it into a div so it doesn't get filtered out later by accident.
  935. */
  936. $sibling = NodeUtility::setNodeTag($sibling, 'div');
  937. }
  938. $import = $articleContent->importNode($sibling, true);
  939. $articleContent->appendChild($import);
  940. /*
  941. * No node shifting needs to be check because when calling getChildren, an array is made with the
  942. * children of the parent node, instead of using the DOMElement childNodes function, which, when used
  943. * along with appendChild, would shift the nodes position and the current foreach will behave in
  944. * unpredictable ways.
  945. */
  946. }
  947. }
  948. $articleContent = $this->prepArticle($articleContent);
  949. if ($hasContent) {
  950. // Find out text direction from ancestors of final top candidate.
  951. $ancestors = array_merge([$parentOfTopCandidate, $topCandidate], $parentOfTopCandidate->getNodeAncestors());
  952. foreach ($ancestors as $ancestor) {
  953. $articleDir = $ancestor->getAttribute('dir');
  954. if ($articleDir) {
  955. $this->setDirection($articleDir);
  956. $this->logger->debug(sprintf('[Rating] Found article direction: %s', $articleDir));
  957. break;
  958. }
  959. }
  960. return $articleContent;
  961. } else {
  962. return false;
  963. }
  964. }
  965. /**
  966. * Cleans up the final article.
  967. *
  968. * @param DOMDocument $article
  969. *
  970. * @return DOMDocument
  971. */
  972. public function prepArticle(DOMDocument $article)
  973. {
  974. $this->logger->info('[PrepArticle] Preparing final article...');
  975. $this->_cleanStyles($article);
  976. $this->_clean($article, 'style');
  977. // Check for data tables before we continue, to avoid removing items in
  978. // those tables, which will often be isolated even though they're
  979. // visually linked to other content-ful elements (text, images, etc.).
  980. $this->_markDataTables($article);
  981. // Clean out junk from the article content
  982. $this->_cleanConditionally($article, 'form');
  983. $this->_cleanConditionally($article, 'fieldset');
  984. $this->_clean($article, 'object');
  985. $this->_clean($article, 'embed');
  986. $this->_clean($article, 'h1');
  987. $this->_clean($article, 'footer');
  988. $this->_clean($article, 'link');
  989. // Clean out elements have "share" in their id/class combinations from final top candidates,
  990. // which means we don't remove the top candidates even they have "share".
  991. foreach ($article->childNodes as $child) {
  992. $this->_cleanMatchedNodes($child, '/share/i');
  993. }
  994. /*
  995. * If there is only one h2 and its text content substantially equals article title,
  996. * they are probably using it as a header and not a subheader,
  997. * so remove it since we already extract the title separately.
  998. */
  999. $h2 = $article->getElementsByTagName('h2');
  1000. if ($h2->length === 1) {
  1001. $lengthSimilarRate = (mb_strlen($h2->item(0)->textContent) - mb_strlen($this->getTitle())) / max(mb_strlen($this->getTitle()), 1);
  1002. if (abs($lengthSimilarRate) < 0.5) {
  1003. if ($lengthSimilarRate > 0) {
  1004. $titlesMatch = strpos($h2->item(0)->textContent, $this->getTitle()) !== false;
  1005. } else {
  1006. $titlesMatch = strpos($this->getTitle(), $h2->item(0)->textContent) !== false;
  1007. }
  1008. if ($titlesMatch) {
  1009. $this->logger->info('[PrepArticle] Found title repeated in an H2 node, removing...');
  1010. $this->_clean($article, 'h2');
  1011. }
  1012. }
  1013. }
  1014. $this->_clean($article, 'iframe');
  1015. $this->_clean($article, 'input');
  1016. $this->_clean($article, 'textarea');
  1017. $this->_clean($article, 'select');
  1018. $this->_clean($article, 'button');
  1019. $this->_cleanHeaders($article);
  1020. // Do these last as the previous stuff may have removed junk
  1021. // that will affect these
  1022. $this->_cleanConditionally($article, 'table');
  1023. $this->_cleanConditionally($article, 'ul');
  1024. $this->_cleanConditionally($article, 'div');
  1025. $this->_cleanExtraParagraphs($article);
  1026. foreach (iterator_to_array($article->getElementsByTagName('br')) as $br) {
  1027. $next = $br->nextSibling;
  1028. if ($next && $next->nodeName === 'p') {
  1029. $this->logger->debug('[PrepArticle] Removing br node next to a p node.');
  1030. $br->parentNode->removeChild($br);
  1031. }
  1032. }
  1033. return $article;
  1034. }
  1035. /**
  1036. * Look for 'data' (as opposed to 'layout') tables, for which we use
  1037. * similar checks as
  1038. * https://dxr.mozilla.org/mozilla-central/rev/71224049c0b52ab190564d3ea0eab089a159a4cf/accessible/html/HTMLTableAccessible.cpp#920.
  1039. *
  1040. * @param DOMDocument $article
  1041. *
  1042. * @return void
  1043. */
  1044. public function _markDataTables(DOMDocument $article)
  1045. {
  1046. $tables = $article->getElementsByTagName('table');
  1047. foreach ($tables as $table) {
  1048. /** @var DOMElement $table */
  1049. $role = $table->getAttribute('role');
  1050. if ($role === 'presentation') {
  1051. $table->setReadabilityDataTable(false);
  1052. continue;
  1053. }
  1054. $datatable = $table->getAttribute('datatable');
  1055. if ($datatable == '0') {
  1056. $table->setReadabilityDataTable(false);
  1057. continue;
  1058. }
  1059. $summary = $table->getAttribute('summary');
  1060. if ($summary) {
  1061. $table->setReadabilityDataTable(true);
  1062. continue;
  1063. }
  1064. $caption = $table->getElementsByTagName('caption');
  1065. if ($caption->length > 0 && $caption->item(0)->childNodes->length > 0) {
  1066. $table->setReadabilityDataTable(true);
  1067. continue;
  1068. }
  1069. // If the table has a descendant with any of these tags, consider a data table:
  1070. foreach (['col', 'colgroup', 'tfoot', 'thead', 'th'] as $dataTableDescendants) {
  1071. if ($table->getElementsByTagName($dataTableDescendants)->length > 0) {
  1072. $table->setReadabilityDataTable(true);
  1073. continue 2;
  1074. }
  1075. }
  1076. // Nested tables indicate a layout table:
  1077. if ($table->getElementsByTagName('table')->length > 0) {
  1078. $table->setReadabilityDataTable(false);
  1079. continue;
  1080. }
  1081. $sizeInfo = $table->getRowAndColumnCount();
  1082. if ($sizeInfo['rows'] >= 10 || $sizeInfo['columns'] > 4) {
  1083. $table->setReadabilityDataTable(true);
  1084. continue;
  1085. }
  1086. // Now just go by size entirely:
  1087. $table->setReadabilityDataTable($sizeInfo['rows'] * $sizeInfo['columns'] > 10);
  1088. }
  1089. }
  1090. /**
  1091. * Remove the style attribute on every e and under.
  1092. *
  1093. * @param $node DOMDocument|DOMNode
  1094. **/
  1095. public function _cleanStyles($node)
  1096. {
  1097. if (property_exists($node, 'tagName') && $node->tagName === 'svg') {
  1098. return;
  1099. }
  1100. // Do not bother if there's no method to remove an attribute
  1101. if (method_exists($node, 'removeAttribute')) {
  1102. $presentational_attributes = ['align', 'background', 'bgcolor', 'border', 'cellpadding', 'cellspacing', 'frame', 'hspace', 'rules', 'style', 'valign', 'vspace'];
  1103. // Remove `style` and deprecated presentational attributes
  1104. foreach ($presentational_attributes as $presentational_attribute) {
  1105. $node->removeAttribute($presentational_attribute);
  1106. }
  1107. $deprecated_size_attribute_elems = ['table', 'th', 'td', 'hr', 'pre'];
  1108. if (property_exists($node, 'tagName') && in_array($node->tagName, $deprecated_size_attribute_elems)) {
  1109. $node->removeAttribute('width');
  1110. $node->removeAttribute('height');
  1111. }
  1112. }
  1113. $cur = $node->firstChild;
  1114. while ($cur !== null) {
  1115. $this->_cleanStyles($cur);
  1116. $cur = $cur->nextSibling;
  1117. }
  1118. }
  1119. /**
  1120. * Clean out elements whose id/class combinations match specific string.
  1121. *
  1122. * @param $node DOMElement Node to clean
  1123. * @param $regex string Match id/class combination.
  1124. *
  1125. * @return void
  1126. **/
  1127. public function _cleanMatchedNodes($node, $regex)
  1128. {
  1129. $endOfSearchMarkerNode = NodeUtility::getNextNode($node, true);
  1130. $next = NodeUtility::getNextNode($node);
  1131. while ($next && $next !== $endOfSearchMarkerNode) {
  1132. if (preg_match($regex, sprintf('%s %s', $next->getAttribute('class'), $next->getAttribute('id')))) {
  1133. $this->logger->debug(sprintf('Removing matched node with regex: \'%s\', node class was: \'%s\', id: \'%s\'', $regex, $next->getAttribute('class'), $next->getAttribute('id')));
  1134. $next = NodeUtility::removeAndGetNext($next);
  1135. } else {
  1136. $next = NodeUtility::getNextNode($next);
  1137. }
  1138. }
  1139. }
  1140. /**
  1141. * @param DOMDocument $article
  1142. *
  1143. * @return void
  1144. */
  1145. public function _cleanExtraParagraphs(DOMDocument $article)
  1146. {
  1147. $paragraphs = $article->getElementsByTagName('p');
  1148. $length = $paragraphs->length;
  1149. for ($i = 0; $i < $length; $i++) {
  1150. $paragraph = $paragraphs->item($length - 1 - $i);
  1151. $imgCount = $paragraph->getElementsByTagName('img')->length;
  1152. $embedCount = $paragraph->getElementsByTagName('embed')->length;
  1153. $objectCount = $paragraph->getElementsByTagName('object')->length;
  1154. // At this point, nasty iframes have been removed, only remain embedded video ones.
  1155. $iframeCount = $paragraph->getElementsByTagName('iframe')->length;
  1156. $totalCount = $imgCount + $embedCount + $objectCount + $iframeCount;
  1157. if ($totalCount === 0 && !preg_replace(NodeUtility::$regexps['onlyWhitespace'], '', $paragraph->textContent)) {
  1158. $this->logger->debug(sprintf('[PrepArticle] Removing extra paragraph. Text content was: \'%s\'', substr($paragraph->textContent, 0, 128)));
  1159. $paragraph->parentNode->removeChild($paragraph);
  1160. }
  1161. }
  1162. }
  1163. /**
  1164. * @param DOMDocument $article
  1165. *
  1166. * @return void
  1167. */
  1168. public function _cleanConditionally(DOMDocument $article, $tag)
  1169. {
  1170. if (!$this->configuration->getCleanConditionally()) {
  1171. return;
  1172. }
  1173. $isList = in_array($tag, ['ul', 'ol']);
  1174. /*
  1175. * Gather counts for other typical elements embedded within.
  1176. * Traverse backwards so we can remove nodes at the same time
  1177. * without effecting the traversal.
  1178. */
  1179. $DOMNodeList = $article->getElementsByTagName($tag);
  1180. $length = $DOMNodeList->length;
  1181. for ($i = 0; $i < $length; $i++) {
  1182. /** @var $node DOMElement */
  1183. $node = $DOMNodeList->item($length - 1 - $i);
  1184. // First check if we're in a data table, in which case don't remove us.
  1185. if ($node->hasAncestorTag($node, 'table', -1) && $node->isReadabilityDataTable()) {
  1186. continue;
  1187. }
  1188. $weight = 0;
  1189. if ($this->configuration->getWeightClasses()) {
  1190. $weight = $node->getClassWeight();
  1191. }
  1192. if ($weight < 0) {
  1193. $this->logger->debug(sprintf('[PrepArticle] Removing tag \'%s\' with 0 or less weight', $tag));
  1194. NodeUtility::removeNode($node);
  1195. continue;
  1196. }
  1197. if (substr_count($node->getTextContent(), ',') < 10) {
  1198. /*
  1199. * If there are not very many commas, and the number of
  1200. * non-paragraph elements is more than paragraphs or other
  1201. * ominous signs, remove the element.
  1202. */
  1203. $p = $node->getElementsByTagName('p')->length;
  1204. $img = $node->getElementsByTagName('img')->length;
  1205. $li = $node->getElementsByTagName('li')->length - 100;
  1206. $input = $node->getElementsByTagName('input')->length;
  1207. $embedCount = 0;
  1208. $embeds = $node->getElementsByTagName('embed');
  1209. foreach ($embeds as $embedNode) {
  1210. if (preg_match(NodeUtility::$regexps['videos'], $embedNode->C14N())) {
  1211. $embedCount++;
  1212. }
  1213. }
  1214. $linkDensity = $node->getLinkDensity();
  1215. $contentLength = mb_strlen($node->getTextContent(true));
  1216. $haveToRemove =
  1217. ($img > 1 && $p / $img < 0.5 && !$node->hasAncestorTag($node, 'figure')) ||
  1218. (!$isList && $li > $p) ||
  1219. ($input > floor($p / 3)) ||
  1220. (!$isList && $contentLength < 25 && ($img === 0 || $img > 2) && !$node->hasAncestorTag($node, 'figure')) ||
  1221. (!$isList && $weight < 25 && $linkDensity > 0.2) ||
  1222. ($weight >= 25 && $linkDensity > 0.5) ||
  1223. (($embedCount === 1 && $contentLength < 75) || $embedCount > 1);
  1224. if ($haveToRemove) {
  1225. $this->logger->debug(sprintf('[PrepArticle] Removing tag \'%s\'.', $tag));
  1226. NodeUtility::removeNode($node);
  1227. }
  1228. }
  1229. }
  1230. }
  1231. /**
  1232. * Clean a node of all elements of type "tag".
  1233. * (Unless it's a youtube/vimeo video. People love movies.).
  1234. *
  1235. * @param $article DOMDocument
  1236. * @param $tag string tag to clean
  1237. *
  1238. * @return void
  1239. **/
  1240. public function _clean(DOMDocument $article, $tag)
  1241. {
  1242. $isEmbed = in_array($tag, ['object', 'embed', 'iframe']);
  1243. $DOMNodeList = $article->getElementsByTagName($tag);
  1244. $length = $DOMNodeList->length;
  1245. for ($i = 0; $i < $length; $i++) {
  1246. $item = $DOMNodeList->item($length - 1 - $i);
  1247. // Allow youtube and vimeo videos through as people usually want to see those.
  1248. if ($isEmbed) {
  1249. $attributeValues = [];
  1250. foreach ($item->attributes as $name => $value) {
  1251. $attributeValues[] = $value->nodeValue;
  1252. }
  1253. $attributeValues = implode('|', $attributeValues);
  1254. // First, check the elements attributes to see if any of them contain youtube or vimeo
  1255. if (preg_match(NodeUtility::$regexps['videos'], $attributeValues)) {
  1256. continue;
  1257. }
  1258. // Then check the elements inside this element for the same.
  1259. if (preg_match(NodeUtility::$regexps['videos'], $item->C14N())) {
  1260. continue;
  1261. }
  1262. }
  1263. $this->logger->debug(sprintf('[PrepArticle] Removing node \'%s\'.', $item->tagName));
  1264. NodeUtility::removeNode($item);
  1265. }
  1266. }
  1267. /**
  1268. * Clean out spurious headers from an Element. Checks things like classnames and link density.
  1269. *
  1270. * @param DOMDocument $article
  1271. *
  1272. * @return void
  1273. **/
  1274. public function _cleanHeaders(DOMDocument $article)
  1275. {
  1276. for ($headerIndex = 1; $headerIndex < 3; $headerIndex++) {
  1277. $headers = $article->getElementsByTagName('h' . $headerIndex);
  1278. /** @var $header DOMElement */
  1279. foreach ($headers as $header) {
  1280. $weight = 0;
  1281. if ($this->configuration->getWeightClasses()) {
  1282. $weight = $header->getClassWeight();
  1283. }
  1284. if ($weight < 0) {
  1285. $this->logger->debug(sprintf('[PrepArticle] Removing H node with 0 or less weight. Content was: \'%s\'', substr($header->nodeValue, 0, 128)));
  1286. NodeUtility::removeNode($header);
  1287. }
  1288. }
  1289. }
  1290. }
  1291. /**
  1292. * Removes the class="" attribute from every element in the given
  1293. * subtree.
  1294. *
  1295. * Readability.js has a special filter to avoid cleaning the classes that the algorithm adds. We don't add classes
  1296. * here so no need to filter those.
  1297. *
  1298. * @param DOMDocument|DOMNode $node
  1299. *
  1300. * @return void
  1301. **/
  1302. public function _cleanClasses($node)
  1303. {
  1304. if ($node->getAttribute('class') !== '') {
  1305. $node->removeAttribute('class');
  1306. }
  1307. for ($node = $node->firstChild; $node !== null; $node = $node->nextSibling) {
  1308. $this->_cleanClasses($node);
  1309. }
  1310. }
  1311. /**
  1312. * @param DOMDocument $article
  1313. *
  1314. * @return DOMDocument
  1315. */
  1316. public function postProcessContent(DOMDocument $article)
  1317. {
  1318. $this->logger->info('[PostProcess] PostProcessing content...');
  1319. // Readability cannot open relative uris so we convert them to absolute uris.
  1320. if ($this->configuration->getFixRelativeURLs()) {
  1321. foreach (iterator_to_array($article->getElementsByTagName('a')) as $link) {
  1322. /** @var DOMElement $link */
  1323. $href = $link->getAttribute('href');
  1324. if ($href) {
  1325. // Replace links with javascript: URIs with text content, since
  1326. // they won't work after scripts have been removed from the page.
  1327. if (strpos($href, 'javascript:') === 0) {
  1328. $this->logger->debug(sprintf('[PostProcess] Removing \'javascript:\' link. Content is: \'%s\'', substr($link->textContent, 0, 128)));
  1329. $text = $article->createTextNode($link->textContent);
  1330. $link->parentNode->replaceChild($text, $link);
  1331. } else {
  1332. $this->logger->debug(sprintf('[PostProcess] Converting link to absolute URI: \'%s\'', substr($href, 0, 128)));
  1333. $link->setAttribute('href', $this->toAbsoluteURI($href));
  1334. }
  1335. }
  1336. }
  1337. foreach ($article->getElementsByTagName('img') as $img) {
  1338. /** @var DOMElement $img */
  1339. /*
  1340. * Extract all possible sources of img url and select the first one on the list.
  1341. */
  1342. $url = [
  1343. $img->getAttribute('src'),
  1344. $img->getAttribute('data-src'),
  1345. $img->getAttribute('data-original'),
  1346. $img->getAttribute('data-orig'),
  1347. $img->getAttribute('data-url')
  1348. ];
  1349. $src = array_filter($url);
  1350. $src = reset($src);
  1351. if ($src) {
  1352. $this->logger->debug(sprintf('[PostProcess] Converting image URL to absolute URI: \'%s\'', substr($src, 0, 128)));
  1353. $img->setAttribute('src', $this->toAbsoluteURI($src));
  1354. }
  1355. }
  1356. }
  1357. $this->_cleanClasses($article);
  1358. return $article;
  1359. }
  1360. /**
  1361. * @return null|string
  1362. */
  1363. public function __toString()
  1364. {
  1365. return sprintf('<h1>%s</h1>%s', $this->getTitle(), $this->getContent());
  1366. }
  1367. /**
  1368. * @return string|null
  1369. */
  1370. public function getTitle()
  1371. {
  1372. return $this->title;
  1373. }
  1374. /**
  1375. * @param string $title
  1376. */
  1377. protected function setTitle($title)
  1378. {
  1379. $this->title = $title;
  1380. }
  1381. /**
  1382. * @return string|null
  1383. */
  1384. public function getContent()
  1385. {
  1386. return ($this->content instanceof DOMDocument) ? $this->content->C14N() : null;
  1387. }
  1388. /**
  1389. * @return DOMDocument|null
  1390. */
  1391. public function getDOMDocument()
  1392. {
  1393. return $this->content;
  1394. }
  1395. /**
  1396. * @param DOMDocument $content
  1397. */
  1398. protected function setContent(DOMDocument $content)
  1399. {
  1400. $this->content = $content;
  1401. }
  1402. /**
  1403. * @return null|string
  1404. */
  1405. public function getExcerpt()
  1406. {
  1407. return $this->excerpt;
  1408. }
  1409. /**
  1410. * @param null|string $excerpt
  1411. */
  1412. public function setExcerpt($excerpt)
  1413. {
  1414. $this->excerpt = $excerpt;
  1415. }
  1416. /**
  1417. * @return string|null
  1418. */
  1419. public function getImage()
  1420. {
  1421. return $this->image;
  1422. }
  1423. /**
  1424. * @param string $image
  1425. */
  1426. protected function setImage($image)
  1427. {
  1428. $this->image = $image;
  1429. }
  1430. /**
  1431. * @return string|null
  1432. */
  1433. public function getAuthor()
  1434. {
  1435. return $this->author;
  1436. }
  1437. /**
  1438. * @param string $author
  1439. */
  1440. protected function setAuthor($author)
  1441. {
  1442. $this->author = $author;
  1443. }
  1444. /**
  1445. * @return null|string
  1446. */
  1447. public function getDirection()
  1448. {
  1449. return $this->direction;
  1450. }
  1451. /**
  1452. * @param null|string $direction
  1453. */
  1454. public function setDirection($direction)
  1455. {
  1456. $this->direction = $direction;
  1457. }
  1458. }