init.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. <?php
  2. use andreskrey\Readability\Readability;
  3. use andreskrey\Readability\Configuration;
  4. class Af_RedditImgur extends Plugin {
  5. /* @var PluginHost $host */
  6. private $host;
  7. function about() {
  8. return array(1.0,
  9. "Inline images (and other content) in Reddit RSS feeds",
  10. "fox");
  11. }
  12. function flags() {
  13. return array("needs_curl" => true);
  14. }
  15. function init($host) {
  16. $this->host = $host;
  17. $host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
  18. $host->add_hook($host::HOOK_PREFS_TAB, $this);
  19. }
  20. function hook_prefs_tab($args) {
  21. if ($args != "prefFeeds") return;
  22. print "<div dojoType=\"dijit.layout.AccordionPane\" title=\"".__('Reddit content settings (af_redditimgur)')."\">";
  23. $enable_readability = $this->host->get($this, "enable_readability");
  24. $enable_content_dupcheck = $this->host->get($this, "enable_content_dupcheck");
  25. print "<form dojoType=\"dijit.form.Form\">";
  26. print "<script type=\"dojo/method\" event=\"onSubmit\" args=\"evt\">
  27. evt.preventDefault();
  28. if (this.validate()) {
  29. console.log(dojo.objectToQuery(this.getValues()));
  30. new Ajax.Request('backend.php', {
  31. parameters: dojo.objectToQuery(this.getValues()),
  32. onComplete: function(transport) {
  33. notify_info(transport.responseText);
  34. }
  35. });
  36. //this.reset();
  37. }
  38. </script>";
  39. print_hidden("op", "pluginhandler");
  40. print_hidden("method", "save");
  41. print_hidden("plugin", "af_redditimgur");
  42. print "<p>" . __("Uses Readability (full-text-rss) implementation by <a target='_blank' href='https://bitbucket.org/fivefilters/'>FiveFilters.org</a>");
  43. print "<p/>";
  44. print_checkbox("enable_readability", $enable_readability);
  45. print "&nbsp;<label for=\"enable_readability\">" . __("Extract missing content using Readability") . "</label>";
  46. print "<br/>";
  47. print_checkbox("enable_content_dupcheck", $enable_content_dupcheck);
  48. print "&nbsp;<label for=\"enable_content_dupcheck\">" . __("Enable additional duplicate checking") . "</label>";
  49. print "<p>"; print_button("submit", __("Save"));
  50. print "</form>";
  51. print "</div>";
  52. }
  53. function save() {
  54. $enable_readability = checkbox_to_sql_bool($_POST["enable_readability"]);
  55. $enable_content_dupcheck = checkbox_to_sql_bool($_POST["enable_content_dupcheck"]);
  56. $this->host->set($this, "enable_readability", $enable_readability, false);
  57. $this->host->set($this, "enable_content_dupcheck", $enable_content_dupcheck);
  58. echo __("Configuration saved");
  59. }
  60. /**
  61. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  62. */
  63. private function inline_stuff($article, &$doc, $xpath, $debug = false) {
  64. $entries = $xpath->query('(//a[@href]|//img[@src])');
  65. $img_entries = $xpath->query("(//img[@src])");
  66. $found = false;
  67. //$debug = 1;
  68. foreach ($entries as $entry) {
  69. if ($entry->hasAttribute("href") && strpos($entry->getAttribute("href"), "reddit.com") === FALSE) {
  70. _debug("processing href: " . $entry->getAttribute("href"), $debug);
  71. $matches = array();
  72. if (!$found && preg_match("/^https?:\/\/twitter.com\/(.*?)\/status\/(.*)/", $entry->getAttribute("href"), $matches)) {
  73. _debug("handling as twitter: " . $matches[1] . " " . $matches[2], $debug);
  74. $oembed_result = fetch_file_contents("https://publish.twitter.com/oembed?url=" . urlencode($entry->getAttribute("href")));
  75. if ($oembed_result) {
  76. $oembed_result = json_decode($oembed_result, true);
  77. if ($oembed_result && isset($oembed_result["html"])) {
  78. $tmp = new DOMDocument();
  79. if ($tmp->loadHTML('<?xml encoding="utf-8" ?>' . $oembed_result["html"])) {
  80. $p = $doc->createElement("p");
  81. $p->appendChild($doc->importNode(
  82. $tmp->getElementsByTagName("blockquote")->item(0), TRUE));
  83. $br = $doc->createElement('br');
  84. $entry->parentNode->insertBefore($p, $entry);
  85. $entry->parentNode->insertBefore($br, $entry);
  86. $found = 1;
  87. }
  88. }
  89. }
  90. }
  91. if (!$found && preg_match("/\.gfycat.com\/([a-z]+)?(\.[a-z]+)$/i", $entry->getAttribute("href"), $matches)) {
  92. $entry->setAttribute("href", "http://www.gfycat.com/".$matches[1]);
  93. }
  94. if (!$found && preg_match("/https?:\/\/(www\.)?gfycat.com\/([a-z]+)$/i", $entry->getAttribute("href"), $matches)) {
  95. _debug("Handling as Gfycat", $debug);
  96. $tmp = fetch_file_contents($entry->getAttribute("href"));
  97. if ($tmp) {
  98. $tmpdoc = new DOMDocument();
  99. if (@$tmpdoc->loadHTML($tmp)) {
  100. $tmpxpath = new DOMXPath($tmpdoc);
  101. $source_node = $tmpxpath->query("//video[contains(@class,'share-video')]//source[contains(@src, '.mp4')]")->item(0);
  102. $poster_node = $tmpxpath->query("//video[contains(@class,'share-video') and @poster]")->item(0);
  103. if ($source_node && $poster_node) {
  104. $source_stream = $source_node->getAttribute("src");
  105. $poster_url = $poster_node->getAttribute("poster");
  106. $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
  107. $found = 1;
  108. }
  109. }
  110. }
  111. }
  112. if (!$found && preg_match("/https?:\/\/v\.redd\.it\/(.*)$/i", $entry->getAttribute("href"), $matches)) {
  113. _debug("Handling as reddit inline video", $debug);
  114. $img = $img_entries->item(0);
  115. if ($img) {
  116. $poster_url = $img->getAttribute("src");
  117. } else {
  118. $poster_url = false;
  119. }
  120. // Get original article URL from v.redd.it redirects
  121. $source_article_url = $this->get_location($matches[0]);
  122. _debug("Resolved ".$matches[0]." to ".$source_article_url, $debug);
  123. $source_stream = false;
  124. if ($source_article_url) {
  125. $j = json_decode(fetch_file_contents($source_article_url.".json"), true);
  126. if ($j) {
  127. foreach ($j as $listing) {
  128. foreach ($listing["data"]["children"] as $child) {
  129. if ($child["data"]["url"] == $matches[0]) {
  130. try {
  131. $source_stream = $child["data"]["media"]["reddit_video"]["fallback_url"];
  132. }
  133. catch (Exception $e) {
  134. }
  135. break 2;
  136. }
  137. }
  138. }
  139. }
  140. }
  141. if (!$source_stream) {
  142. $source_stream = "https://v.redd.it/" . $matches[1] . "/DASH_600_K";
  143. }
  144. $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
  145. $found = 1;
  146. }
  147. if (!$found && preg_match("/https?:\/\/(www\.)?streamable.com\//i", $entry->getAttribute("href"))) {
  148. _debug("Handling as Streamable", $debug);
  149. $tmp = fetch_file_contents($entry->getAttribute("href"));
  150. if ($tmp) {
  151. $tmpdoc = new DOMDocument();
  152. if (@$tmpdoc->loadHTML($tmp)) {
  153. $tmpxpath = new DOMXPath($tmpdoc);
  154. $source_node = $tmpxpath->query("//video[contains(@class,'video-player-tag')]//source[contains(@src, '.mp4')]")->item(0);
  155. $poster_node = $tmpxpath->query("//video[contains(@class,'video-player-tag') and @poster]")->item(0);
  156. if ($source_node && $poster_node) {
  157. $source_stream = $source_node->getAttribute("src");
  158. $poster_url = $poster_node->getAttribute("poster");
  159. $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
  160. $found = 1;
  161. }
  162. }
  163. }
  164. }
  165. // imgur .gif -> .gifv
  166. if (!$found && preg_match("/i\.imgur\.com\/(.*?)\.gif$/i", $entry->getAttribute("href"))) {
  167. _debug("Handling as imgur gif (->gifv)", $debug);
  168. $entry->setAttribute("href",
  169. str_replace(".gif", ".gifv", $entry->getAttribute("href")));
  170. }
  171. if (!$found && preg_match("/\.(gifv|mp4)$/i", $entry->getAttribute("href"))) {
  172. _debug("Handling as imgur gifv", $debug);
  173. $source_stream = str_replace(".gifv", ".mp4", $entry->getAttribute("href"));
  174. if (strpos($source_stream, "imgur.com") !== FALSE)
  175. $poster_url = str_replace(".mp4", "h.jpg", $source_stream);
  176. $this->handle_as_video($doc, $entry, $source_stream, $poster_url, $debug);
  177. $found = true;
  178. }
  179. $matches = array();
  180. if (!$found && preg_match("/youtube\.com\/v\/([\w-]+)/", $entry->getAttribute("href"), $matches) ||
  181. preg_match("/youtube\.com\/.*?[\&\?]v=([\w-]+)/", $entry->getAttribute("href"), $matches) ||
  182. preg_match("/youtube\.com\/watch\?v=([\w-]+)/", $entry->getAttribute("href"), $matches) ||
  183. preg_match("/\/\/youtu.be\/([\w-]+)/", $entry->getAttribute("href"), $matches)) {
  184. $vid_id = $matches[1];
  185. _debug("Handling as youtube: $vid_id", $debug);
  186. $iframe = $doc->createElement("iframe");
  187. $iframe->setAttribute("class", "youtube-player");
  188. $iframe->setAttribute("type", "text/html");
  189. $iframe->setAttribute("width", "640");
  190. $iframe->setAttribute("height", "385");
  191. $iframe->setAttribute("src", "https://www.youtube.com/embed/$vid_id");
  192. $iframe->setAttribute("allowfullscreen", "1");
  193. $iframe->setAttribute("frameborder", "0");
  194. $br = $doc->createElement('br');
  195. $entry->parentNode->insertBefore($iframe, $entry);
  196. $entry->parentNode->insertBefore($br, $entry);
  197. $found = true;
  198. }
  199. if (!$found && preg_match("/\.(jpg|jpeg|gif|png)(\?[0-9][0-9]*)?$/i", $entry->getAttribute("href")) ||
  200. mb_strpos($entry->getAttribute("href"), "i.reddituploads.com") !== FALSE ||
  201. mb_strpos($this->get_content_type($entry->getAttribute("href")), "image/") !== FALSE) {
  202. _debug("Handling as a picture", $debug);
  203. $img = $doc->createElement('img');
  204. $img->setAttribute("src", $entry->getAttribute("href"));
  205. $br = $doc->createElement('br');
  206. $entry->parentNode->insertBefore($img, $entry);
  207. $entry->parentNode->insertBefore($br, $entry);
  208. $found = true;
  209. }
  210. // linked albums & pages
  211. /*if (!$found && preg_match("/^https?:\/\/(m\.)?imgur.com\/([^\.\/]+$)/", $entry->getAttribute("href"), $matches) ||
  212. preg_match("/^https?:\/\/(m\.)?imgur.com\/(a|album|gallery)\/[^\.]+$/", $entry->getAttribute("href"), $matches)) {
  213. _debug("Handling as an imgur page/album/gallery", $debug);
  214. $album_content = fetch_file_contents($entry->getAttribute("href"),
  215. false, false, false, false, 10);
  216. if ($album_content) {
  217. $adoc = new DOMDocument();
  218. if (@$adoc->loadHTML($album_content)) {
  219. $axpath = new DOMXPath($adoc);
  220. $aentries = $axpath->query("(//div[@class='post-image']/img[@src] | //a[@class='zoom']/img[@src] | //div[@class='video-elements']/source)");
  221. $urls = [];
  222. foreach ($aentries as $aentry) {
  223. $url = $aentry->getAttribute("src");
  224. if (!in_array($url, $urls)) {
  225. if ($aentry->tagName == "img") {
  226. $img = $doc->createElement('img');
  227. $img->setAttribute("src", $url);
  228. $entry->parentNode->insertBefore($doc->createElement('br'), $entry);
  229. $br = $doc->createElement('br');
  230. $entry->parentNode->insertBefore($img, $entry);
  231. $entry->parentNode->insertBefore($br, $entry);
  232. } else if ($aentry->tagName == "source") {
  233. if (strpos($url, "imgur.com") !== FALSE)
  234. $poster_url = str_replace(".mp4", "h.jpg", $url);
  235. else
  236. $poster_url = "";
  237. $this->handle_as_video($doc, $entry, $url, $poster_url);
  238. }
  239. array_push($urls, $url);
  240. $found = true;
  241. }
  242. }
  243. if ($debug) print_r($urls);
  244. }
  245. }
  246. } */
  247. // wtf is this even
  248. if (!$found && preg_match("/^https?:\/\/gyazo\.com\/([^\.\/]+$)/", $entry->getAttribute("href"), $matches)) {
  249. $img_id = $matches[1];
  250. _debug("handling as gyazo: $img_id", $debug);
  251. $img = $doc->createElement('img');
  252. $img->setAttribute("src", "https://i.gyazo.com/$img_id.jpg");
  253. $br = $doc->createElement('br');
  254. $entry->parentNode->insertBefore($img, $entry);
  255. $entry->parentNode->insertBefore($br, $entry);
  256. $found = true;
  257. }
  258. // let's try meta properties
  259. if (!$found) {
  260. _debug("looking for meta og:image", $debug);
  261. $content = fetch_file_contents(["url" => $entry->getAttribute("href"),
  262. "http_accept" => "text/*"]);
  263. if ($content) {
  264. $cdoc = new DOMDocument();
  265. if (@$cdoc->loadHTML($content)) {
  266. $cxpath = new DOMXPath($cdoc);
  267. $og_image = $cxpath->query("//meta[@property='og:image']")->item(0);
  268. if ($og_image) {
  269. $og_src = $og_image->getAttribute("content");
  270. if ($og_src) {
  271. $img = $doc->createElement('img');
  272. $img->setAttribute("src", $og_src);
  273. $br = $doc->createElement('br');
  274. $entry->parentNode->insertBefore($img, $entry);
  275. $entry->parentNode->insertBefore($br, $entry);
  276. $found = true;
  277. }
  278. }
  279. }
  280. }
  281. }
  282. }
  283. // remove tiny thumbnails
  284. if ($entry->hasAttribute("src")) {
  285. if ($entry->parentNode && $entry->parentNode->parentNode) {
  286. $entry->parentNode->parentNode->removeChild($entry->parentNode);
  287. }
  288. }
  289. }
  290. return $found;
  291. }
  292. function hook_article_filter($article) {
  293. if (strpos($article["link"], "reddit.com/r/") !== FALSE) {
  294. $doc = new DOMDocument();
  295. @$doc->loadHTML($article["content"]);
  296. $xpath = new DOMXPath($doc);
  297. $content_link = $xpath->query("(//a[contains(., '[link]')])")->item(0);
  298. if ($this->host->get($this, "enable_content_dupcheck")) {
  299. if ($content_link) {
  300. $content_href = $content_link->getAttribute("href");
  301. $entry_guid = $article["guid_hashed"];
  302. $owner_uid = $article["owner_uid"];
  303. if (DB_TYPE == "pgsql") {
  304. $interval_qpart = "date_entered < NOW() - INTERVAL '1 day'";
  305. } else {
  306. $interval_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY)";
  307. }
  308. $sth = $this->pdo->prepare("SELECT COUNT(id) AS cid
  309. FROM ttrss_entries, ttrss_user_entries WHERE
  310. ref_id = id AND
  311. $interval_qpart AND
  312. guid != ? AND
  313. owner_uid = ? AND
  314. content LIKE ?");
  315. $sth->execute([$entry_guid, $owner_uid, "%href=\"$content_href\">[link]%"]);
  316. if ($row = $sth->fetch()) {
  317. $num_found = $row['cid'];
  318. if ($num_found > 0) $article["force_catchup"] = true;
  319. }
  320. }
  321. }
  322. $found = $this->inline_stuff($article, $doc, $xpath);
  323. $node = $doc->getElementsByTagName('body')->item(0);
  324. if ($node && $found) {
  325. $article["content"] = $doc->saveHTML($node);
  326. } else if ($content_link) {
  327. $article = $this->readability($article, $content_link->getAttribute("href"), $doc, $xpath);
  328. }
  329. }
  330. return $article;
  331. }
  332. function api_version() {
  333. return 2;
  334. }
  335. private function handle_as_video($doc, $entry, $source_stream, $poster_url = false, $debug = false) {
  336. _debug("handle_as_video: $source_stream", $debug);
  337. $video = $doc->createElement('video');
  338. $video->setAttribute("autoplay", "1");
  339. $video->setAttribute("controls", "1");
  340. $video->setAttribute("loop", "1");
  341. if ($poster_url) $video->setAttribute("poster", $poster_url);
  342. $source = $doc->createElement('source');
  343. $source->setAttribute("src", $source_stream);
  344. $source->setAttribute("type", "video/mp4");
  345. $video->appendChild($source);
  346. $br = $doc->createElement('br');
  347. $entry->parentNode->insertBefore($video, $entry);
  348. $entry->parentNode->insertBefore($br, $entry);
  349. $img = $doc->createElement('img');
  350. $img->setAttribute("src",
  351. "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D");
  352. $entry->parentNode->insertBefore($img, $entry);
  353. }
  354. function testurl() {
  355. $url = htmlspecialchars($_REQUEST["url"]);
  356. header("Content-type: text/plain");
  357. print "URL: $url\n";
  358. $doc = new DOMDocument();
  359. @$doc->loadHTML("<html><body><a href=\"$url\">[link]</a></body>");
  360. $xpath = new DOMXPath($doc);
  361. $found = $this->inline_stuff([], $doc, $xpath, true);
  362. print "Inline result: $found\n";
  363. if (!$found) {
  364. print "\nReadability result:\n";
  365. $article = $this->readability([], $url, $doc, $xpath, true);
  366. print_r($article);
  367. } else {
  368. print "\nResulting HTML:\n";
  369. print $doc->saveHTML();
  370. }
  371. }
  372. private function get_header($url, $useragent = SELF_USER_AGENT, $header) {
  373. $ret = false;
  374. if (function_exists("curl_init") && !defined("NO_CURL")) {
  375. $ch = curl_init($url);
  376. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  377. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  378. curl_setopt($ch, CURLOPT_HEADER, true);
  379. curl_setopt($ch, CURLOPT_NOBODY, true);
  380. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("open_basedir"));
  381. curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
  382. @curl_exec($ch);
  383. $ret = curl_getinfo($ch, $header);
  384. }
  385. return $ret;
  386. }
  387. private function get_content_type($url, $useragent = SELF_USER_AGENT) {
  388. return $this->get_header($url, $useragent, CURLINFO_CONTENT_TYPE);
  389. }
  390. private function get_location($url, $useragent = SELF_USER_AGENT) {
  391. return $this->get_header($url, $useragent, CURLINFO_EFFECTIVE_URL);
  392. }
  393. /**
  394. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  395. */
  396. private function readability($article, $url, $doc, $xpath, $debug = false) {
  397. if (!defined('NO_CURL') && function_exists("curl_init") && $this->host->get($this, "enable_readability") &&
  398. mb_strlen(strip_tags($article["content"])) <= 150) {
  399. if (!class_exists("Readability")) require_once(dirname(dirname(__DIR__)). "/lib/readability/Readability.php");
  400. // do not try to embed posts linking back to other reddit posts
  401. if ($url && strpos($url, "reddit.com") === FALSE) {
  402. /* link may lead to a huge video file or whatever, we need to check content type before trying to
  403. parse it which p much requires curl */
  404. $useragent_compat = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
  405. $content_type = $this->get_content_type($url, $useragent_compat);
  406. if ($content_type && strpos($content_type, "text/html") !== FALSE) {
  407. $tmp = fetch_file_contents(["url" => $url,
  408. "useragent" => $useragent_compat,
  409. "http_accept" => "text/html"]);
  410. if ($debug) _debug("tmplen: " . mb_strlen($tmp));
  411. if ($tmp && mb_strlen($tmp) < 1024 * 500) {
  412. $r = new Readability(new Configuration());
  413. try {
  414. if ($r->parse($tmp)) {
  415. $tmpxpath = new DOMXPath($r->getDOMDocument());
  416. $entries = $tmpxpath->query('(//a[@href]|//img[@src])');
  417. foreach ($entries as $entry) {
  418. if ($entry->hasAttribute("href")) {
  419. $entry->setAttribute("href",
  420. rewrite_relative_url($url, $entry->getAttribute("href")));
  421. }
  422. if ($entry->hasAttribute("src")) {
  423. $entry->setAttribute("src",
  424. rewrite_relative_url($url, $entry->getAttribute("src")));
  425. }
  426. }
  427. $article["content"] = $r->getContent() . "<hr/>" . $article["content"];
  428. }
  429. } catch (ParseException $e) {
  430. //
  431. }
  432. }
  433. }
  434. }
  435. }
  436. return $article;
  437. }
  438. }