init.php 18 KB

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