init.php 17 KB

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