init.php 17 KB

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