init.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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. //$debug = 1;
  66. foreach ($entries as $entry) {
  67. if ($entry->hasAttribute("href") && strpos($entry->getAttribute("href"), "reddit.com") === FALSE) {
  68. _debug("processing href: " . $entry->getAttribute("href"), $debug);
  69. $matches = array();
  70. if (!$found && preg_match("/^https?:\/\/twitter.com\/(.*?)\/status\/(.*)/", $entry->getAttribute("href"), $matches)) {
  71. _debug("handling as twitter: " . $matches[1] . " " . $matches[2], $debug);
  72. $oembed_result = fetch_file_contents("https://publish.twitter.com/oembed?url=" . urlencode($entry->getAttribute("href")));
  73. if ($oembed_result) {
  74. $oembed_result = json_decode($oembed_result, true);
  75. if ($oembed_result && isset($oembed_result["html"])) {
  76. $tmp = new DOMDocument();
  77. if ($tmp->loadHTML('<?xml encoding="utf-8" ?>' . $oembed_result["html"])) {
  78. $p = $doc->createElement("p");
  79. $p->appendChild($doc->importNode(
  80. $tmp->getElementsByTagName("blockquote")->item(0), TRUE));
  81. $br = $doc->createElement('br');
  82. $entry->parentNode->insertBefore($p, $entry);
  83. $entry->parentNode->insertBefore($br, $entry);
  84. $found = 1;
  85. }
  86. }
  87. }
  88. }
  89. if (!$found && preg_match("/\.gfycat.com\/([a-z]+)?(\.[a-z]+)$/i", $entry->getAttribute("href"), $matches)) {
  90. $entry->setAttribute("href", "http://www.gfycat.com/".$matches[1]);
  91. }
  92. if (!$found && preg_match("/https?:\/\/(www\.)?gfycat.com\/([a-z]+)$/i", $entry->getAttribute("href"), $matches)) {
  93. _debug("Handling as Gfycat", $debug);
  94. $tmp = fetch_file_contents($entry->getAttribute("href"));
  95. if ($tmp) {
  96. $tmpdoc = new DOMDocument();
  97. if (@$tmpdoc->loadHTML($tmp)) {
  98. $tmpxpath = new DOMXPath($tmpdoc);
  99. $source_node = $tmpxpath->query("//video[contains(@class,'share-video')]//source[contains(@src, '.mp4')]")->item(0);
  100. $poster_node = $tmpxpath->query("//video[contains(@class,'share-video') and @poster]")->item(0);
  101. if ($source_node && $poster_node) {
  102. $source_stream = $source_node->getAttribute("src");
  103. $poster_url = $poster_node->getAttribute("poster");
  104. $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
  105. $found = 1;
  106. }
  107. }
  108. }
  109. }
  110. if (!$found && preg_match("/https?:\/\/v\.redd\.it\/(.*)$/i", $entry->getAttribute("href"), $matches)) {
  111. _debug("Handling as reddit inline video", $debug);
  112. $img = $img_entries->item(0);
  113. if ($img) {
  114. $poster_url = $img->getAttribute("src");
  115. } else {
  116. $poster_url = false;
  117. }
  118. // Get original article URL from v.redd.it redirects
  119. $source_article_url = $this->get_location($matches[0]);
  120. _debug("Resolved ".$matches[0]." to ".$source_article_url, $debug);
  121. $source_stream = false;
  122. if ($source_article_url) {
  123. $j = json_decode(fetch_file_contents($source_article_url.".json"), true);
  124. if ($j) {
  125. foreach ($j as $listing) {
  126. foreach ($listing["data"]["children"] as $child) {
  127. if ($child["data"]["url"] == $matches[0]) {
  128. try {
  129. $source_stream = $child["data"]["media"]["reddit_video"]["fallback_url"];
  130. }
  131. catch (Exception $e) {
  132. }
  133. break 2;
  134. }
  135. }
  136. }
  137. }
  138. }
  139. if (!$source_stream) {
  140. $source_stream = "https://v.redd.it/" . $matches[1] . "/DASH_600_K";
  141. }
  142. $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
  143. $found = 1;
  144. }
  145. if (!$found && preg_match("/https?:\/\/(www\.)?streamable.com\//i", $entry->getAttribute("href"))) {
  146. _debug("Handling as Streamable", $debug);
  147. $tmp = fetch_file_contents($entry->getAttribute("href"));
  148. if ($tmp) {
  149. $tmpdoc = new DOMDocument();
  150. if (@$tmpdoc->loadHTML($tmp)) {
  151. $tmpxpath = new DOMXPath($tmpdoc);
  152. $source_node = $tmpxpath->query("//video[contains(@class,'video-player-tag')]//source[contains(@src, '.mp4')]")->item(0);
  153. $poster_node = $tmpxpath->query("//video[contains(@class,'video-player-tag') and @poster]")->item(0);
  154. if ($source_node && $poster_node) {
  155. $source_stream = $source_node->getAttribute("src");
  156. $poster_url = $poster_node->getAttribute("poster");
  157. $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
  158. $found = 1;
  159. }
  160. }
  161. }
  162. }
  163. // imgur .gif -> .gifv
  164. if (!$found && preg_match("/i\.imgur\.com\/(.*?)\.gif$/i", $entry->getAttribute("href"))) {
  165. _debug("Handling as imgur gif (->gifv)", $debug);
  166. $entry->setAttribute("href",
  167. str_replace(".gif", ".gifv", $entry->getAttribute("href")));
  168. }
  169. if (!$found && preg_match("/\.(gifv|mp4)$/i", $entry->getAttribute("href"))) {
  170. _debug("Handling as imgur gifv", $debug);
  171. $source_stream = str_replace(".gifv", ".mp4", $entry->getAttribute("href"));
  172. if (strpos($source_stream, "imgur.com") !== FALSE)
  173. $poster_url = str_replace(".mp4", "h.jpg", $source_stream);
  174. $this->handle_as_video($doc, $entry, $source_stream, $poster_url, $debug);
  175. $found = true;
  176. }
  177. $matches = array();
  178. if (!$found && preg_match("/youtube\.com\/v\/([\w-]+)/", $entry->getAttribute("href"), $matches) ||
  179. preg_match("/youtube\.com\/.*?[\&\?]v=([\w-]+)/", $entry->getAttribute("href"), $matches) ||
  180. preg_match("/youtube\.com\/watch\?v=([\w-]+)/", $entry->getAttribute("href"), $matches) ||
  181. preg_match("/\/\/youtu.be\/([\w-]+)/", $entry->getAttribute("href"), $matches)) {
  182. $vid_id = $matches[1];
  183. _debug("Handling as youtube: $vid_id", $debug);
  184. $iframe = $doc->createElement("iframe");
  185. $iframe->setAttribute("class", "youtube-player");
  186. $iframe->setAttribute("type", "text/html");
  187. $iframe->setAttribute("width", "640");
  188. $iframe->setAttribute("height", "385");
  189. $iframe->setAttribute("src", "https://www.youtube.com/embed/$vid_id");
  190. $iframe->setAttribute("allowfullscreen", "1");
  191. $iframe->setAttribute("frameborder", "0");
  192. $br = $doc->createElement('br');
  193. $entry->parentNode->insertBefore($iframe, $entry);
  194. $entry->parentNode->insertBefore($br, $entry);
  195. $found = true;
  196. }
  197. if (!$found && preg_match("/\.(jpg|jpeg|gif|png)(\?[0-9][0-9]*)?$/i", $entry->getAttribute("href")) ||
  198. mb_strpos($entry->getAttribute("href"), "i.reddituploads.com") !== FALSE ||
  199. mb_strpos($this->get_content_type($entry->getAttribute("href")), "image/") !== FALSE) {
  200. _debug("Handling as a picture", $debug);
  201. $img = $doc->createElement('img');
  202. $img->setAttribute("src", $entry->getAttribute("href"));
  203. $br = $doc->createElement('br');
  204. $entry->parentNode->insertBefore($img, $entry);
  205. $entry->parentNode->insertBefore($br, $entry);
  206. $found = true;
  207. }
  208. // linked albums & pages
  209. /*if (!$found && preg_match("/^https?:\/\/(m\.)?imgur.com\/([^\.\/]+$)/", $entry->getAttribute("href"), $matches) ||
  210. preg_match("/^https?:\/\/(m\.)?imgur.com\/(a|album|gallery)\/[^\.]+$/", $entry->getAttribute("href"), $matches)) {
  211. _debug("Handling as an imgur page/album/gallery", $debug);
  212. $album_content = fetch_file_contents($entry->getAttribute("href"),
  213. false, false, false, false, 10);
  214. if ($album_content) {
  215. $adoc = new DOMDocument();
  216. if (@$adoc->loadHTML($album_content)) {
  217. $axpath = new DOMXPath($adoc);
  218. $aentries = $axpath->query("(//div[@class='post-image']/img[@src] | //a[@class='zoom']/img[@src] | //div[@class='video-elements']/source)");
  219. $urls = [];
  220. foreach ($aentries as $aentry) {
  221. $url = $aentry->getAttribute("src");
  222. if (!in_array($url, $urls)) {
  223. if ($aentry->tagName == "img") {
  224. $img = $doc->createElement('img');
  225. $img->setAttribute("src", $url);
  226. $entry->parentNode->insertBefore($doc->createElement('br'), $entry);
  227. $br = $doc->createElement('br');
  228. $entry->parentNode->insertBefore($img, $entry);
  229. $entry->parentNode->insertBefore($br, $entry);
  230. } else if ($aentry->tagName == "source") {
  231. if (strpos($url, "imgur.com") !== FALSE)
  232. $poster_url = str_replace(".mp4", "h.jpg", $url);
  233. else
  234. $poster_url = "";
  235. $this->handle_as_video($doc, $entry, $url, $poster_url);
  236. }
  237. array_push($urls, $url);
  238. $found = true;
  239. }
  240. }
  241. if ($debug) print_r($urls);
  242. }
  243. }
  244. } */
  245. // wtf is this even
  246. if (!$found && preg_match("/^https?:\/\/gyazo\.com\/([^\.\/]+$)/", $entry->getAttribute("href"), $matches)) {
  247. $img_id = $matches[1];
  248. _debug("handling as gyazo: $img_id", $debug);
  249. $img = $doc->createElement('img');
  250. $img->setAttribute("src", "https://i.gyazo.com/$img_id.jpg");
  251. $br = $doc->createElement('br');
  252. $entry->parentNode->insertBefore($img, $entry);
  253. $entry->parentNode->insertBefore($br, $entry);
  254. $found = true;
  255. }
  256. // let's try meta properties
  257. if (!$found) {
  258. _debug("looking for meta og:image", $debug);
  259. $content = fetch_file_contents(["url" => $entry->getAttribute("href"),
  260. "http_accept" => "text/*"]);
  261. if ($content) {
  262. $cdoc = new DOMDocument();
  263. if (@$cdoc->loadHTML($content)) {
  264. $cxpath = new DOMXPath($cdoc);
  265. $og_image = $cxpath->query("//meta[@property='og:image']")->item(0);
  266. if ($og_image) {
  267. $og_src = $og_image->getAttribute("content");
  268. if ($og_src) {
  269. $img = $doc->createElement('img');
  270. $img->setAttribute("src", $og_src);
  271. $br = $doc->createElement('br');
  272. $entry->parentNode->insertBefore($img, $entry);
  273. $entry->parentNode->insertBefore($br, $entry);
  274. $found = true;
  275. }
  276. }
  277. }
  278. }
  279. }
  280. }
  281. // remove tiny thumbnails
  282. if ($entry->hasAttribute("src")) {
  283. if ($entry->parentNode && $entry->parentNode->parentNode) {
  284. $entry->parentNode->parentNode->removeChild($entry->parentNode);
  285. }
  286. }
  287. }
  288. return $found;
  289. }
  290. function hook_article_filter($article) {
  291. if (strpos($article["link"], "reddit.com/r/") !== FALSE) {
  292. $doc = new DOMDocument();
  293. @$doc->loadHTML($article["content"]);
  294. $xpath = new DOMXPath($doc);
  295. $content_link = $xpath->query("(//a[contains(., '[link]')])")->item(0);
  296. if ($this->host->get($this, "enable_content_dupcheck")) {
  297. if ($content_link) {
  298. $content_href = $content_link->getAttribute("href");
  299. $entry_guid = $article["guid_hashed"];
  300. $owner_uid = $article["owner_uid"];
  301. if (DB_TYPE == "pgsql") {
  302. $interval_qpart = "date_entered < NOW() - INTERVAL '1 day'";
  303. } else {
  304. $interval_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY)";
  305. }
  306. $sth = $this->pdo->prepare("SELECT COUNT(id) AS cid
  307. FROM ttrss_entries, ttrss_user_entries WHERE
  308. ref_id = id AND
  309. $interval_qpart AND
  310. guid != ? AND
  311. owner_uid = ? AND
  312. content LIKE ?");
  313. $sth->execute([$entry_guid, $owner_uid, "%href=\"$content_href\">[link]%"]);
  314. if ($row = $sth->fetch()) {
  315. $num_found = $row['cid'];
  316. if ($num_found > 0) $article["force_catchup"] = true;
  317. }
  318. }
  319. }
  320. $found = $this->inline_stuff($article, $doc, $xpath);
  321. $node = $doc->getElementsByTagName('body')->item(0);
  322. if ($node && $found) {
  323. $article["content"] = $doc->saveHTML($node);
  324. } else if ($content_link) {
  325. $article = $this->readability($article, $content_link->getAttribute("href"), $doc, $xpath);
  326. }
  327. }
  328. return $article;
  329. }
  330. function api_version() {
  331. return 2;
  332. }
  333. private function handle_as_video($doc, $entry, $source_stream, $poster_url = false, $debug = false) {
  334. _debug("handle_as_video: $source_stream", $debug);
  335. $video = $doc->createElement('video');
  336. $video->setAttribute("autoplay", "1");
  337. $video->setAttribute("controls", "1");
  338. $video->setAttribute("loop", "1");
  339. if ($poster_url) $video->setAttribute("poster", $poster_url);
  340. $source = $doc->createElement('source');
  341. $source->setAttribute("src", $source_stream);
  342. $source->setAttribute("type", "video/mp4");
  343. $video->appendChild($source);
  344. $br = $doc->createElement('br');
  345. $entry->parentNode->insertBefore($video, $entry);
  346. $entry->parentNode->insertBefore($br, $entry);
  347. $img = $doc->createElement('img');
  348. $img->setAttribute("src",
  349. "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D");
  350. $entry->parentNode->insertBefore($img, $entry);
  351. }
  352. function testurl() {
  353. $url = htmlspecialchars($_REQUEST["url"]);
  354. header("Content-type: text/plain");
  355. print "URL: $url\n";
  356. $doc = new DOMDocument();
  357. @$doc->loadHTML("<html><body><a href=\"$url\">[link]</a></body>");
  358. $xpath = new DOMXPath($doc);
  359. $found = $this->inline_stuff([], $doc, $xpath, true);
  360. print "Inline result: $found\n";
  361. if (!$found) {
  362. print "\nReadability result:\n";
  363. $article = $this->readability([], $url, $doc, $xpath, true);
  364. print_r($article);
  365. } else {
  366. print "\nResulting HTML:\n";
  367. print $doc->saveHTML();
  368. }
  369. }
  370. private function get_header($url, $useragent = SELF_USER_AGENT, $header) {
  371. $ret = false;
  372. if (function_exists("curl_init") && !defined("NO_CURL")) {
  373. $ch = curl_init($url);
  374. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  375. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  376. curl_setopt($ch, CURLOPT_HEADER, true);
  377. curl_setopt($ch, CURLOPT_NOBODY, true);
  378. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("open_basedir"));
  379. curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
  380. @curl_exec($ch);
  381. $ret = curl_getinfo($ch, $header);
  382. }
  383. return $ret;
  384. }
  385. private function get_content_type($url, $useragent = SELF_USER_AGENT) {
  386. return $this->get_header($url, $useragent, CURLINFO_CONTENT_TYPE);
  387. }
  388. private function get_location($url, $useragent = SELF_USER_AGENT) {
  389. return $this->get_header($url, $useragent, CURLINFO_EFFECTIVE_URL);
  390. }
  391. /**
  392. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  393. */
  394. private function readability($article, $url, $doc, $xpath, $debug = false) {
  395. if (!defined('NO_CURL') && function_exists("curl_init") && $this->host->get($this, "enable_readability") &&
  396. mb_strlen(strip_tags($article["content"])) <= 150) {
  397. if (!class_exists("Readability")) require_once(dirname(dirname(__DIR__)). "/lib/readability/Readability.php");
  398. if ($url &&
  399. strpos($url, "twitter.com") === FALSE &&
  400. strpos($url, "youtube.com") === FALSE &&
  401. 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($tmp, $url);
  413. if ($r->init()) {
  414. $tmpxpath = new DOMXPath($r->dom);
  415. $entries = $tmpxpath->query('(//a[@href]|//img[@src])');
  416. foreach ($entries as $entry) {
  417. if ($entry->hasAttribute("href")) {
  418. $entry->setAttribute("href",
  419. rewrite_relative_url($url, $entry->getAttribute("href")));
  420. }
  421. if ($entry->hasAttribute("src")) {
  422. $entry->setAttribute("src",
  423. rewrite_relative_url($url, $entry->getAttribute("src")));
  424. }
  425. }
  426. $article["content"] = $r->articleContent->innerHTML . "<hr/>" . $article["content"];
  427. }
  428. }
  429. }
  430. }
  431. }
  432. return $article;
  433. }
  434. }