]>
git.wh0rd.org - tt-rss.git/blob - plugins/af_redditimgur/init.php
9d10c09be039df3b5a62f6df919c21226daffe05
2 class Af_RedditImgur
extends Plugin
{
7 "Inline images (and other content) in Reddit RSS feeds",
12 return array("needs_curl" => true);
15 function init($host) {
18 $host->add_hook($host::HOOK_ARTICLE_FILTER
, $this);
19 $host->add_hook($host::HOOK_PREFS_TAB
, $this);
22 function hook_prefs_tab($args) {
23 if ($args != "prefFeeds") return;
25 print "<div dojoType=\"dijit.layout.AccordionPane\" title=\"".__('Reddit content settings (af_redditimgur)')."\">";
27 $enable_readability = $this->host
->get($this, "enable_readability");
28 $enable_content_dupcheck = $this->host
->get($this, "enable_content_dupcheck");
30 print "<form dojoType=\"dijit.form.Form\">";
32 print "<script type=\"dojo/method\" event=\"onSubmit\" args=\"evt\">
34 if (this.validate()) {
35 console.log(dojo.objectToQuery(this.getValues()));
36 new Ajax.Request('backend.php', {
37 parameters: dojo.objectToQuery(this.getValues()),
38 onComplete: function(transport) {
39 notify_info(transport.responseText);
46 print_hidden("op", "pluginhandler");
47 print_hidden("method", "save");
48 print_hidden("plugin", "af_redditimgur");
50 print "<p>" . __("Uses Readability (full-text-rss) implementation by <a target='_blank' href='https://bitbucket.org/fivefilters/'>FiveFilters.org</a>");
53 print_checkbox("enable_readability", $enable_readability);
54 print " <label for=\"enable_readability\">" . __("Extract missing content using Readability") . "</label>";
58 print_checkbox("enable_content_dupcheck", $enable_content_dupcheck);
59 print " <label for=\"enable_content_dupcheck\">" . __("Enable additional duplicate checking") . "</label>";
60 print "<p>"; print_button("submit", __("Save"));
67 $enable_readability = checkbox_to_sql_bool($_POST["enable_readability"]) == "true";
68 $enable_content_dupcheck = checkbox_to_sql_bool($_POST["enable_content_dupcheck"]) == "true";
70 $this->host
->set($this, "enable_readability", $enable_readability, false);
71 $this->host
->set($this, "enable_content_dupcheck", $enable_content_dupcheck);
73 echo __("Configuration saved");
77 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
79 private function inline_stuff($article, &$doc, $xpath, $debug = false) {
81 $entries = $xpath->query('(//a[@href]|//img[@src])');
82 $img_entries = $xpath->query("(//img[@src])");
86 foreach ($entries as $entry) {
87 if ($entry->hasAttribute("href")) {
89 _debug("processing href: " . $entry->getAttribute("href"), $debug);
93 if (preg_match("/^https?:\/\/twitter.com\/(.*?)\/status\/(.*)/", $entry->getAttribute("href"), $matches)) {
94 _debug("handling as twitter: " . $matches[1] . " " . $matches[2], $debug);
96 $oembed_result = fetch_file_contents("https://publish.twitter.com/oembed?url=" . urlencode($entry->getAttribute("href")));
99 $oembed_result = json_decode($oembed_result, true);
101 if ($oembed_result && isset($oembed_result["html"])) {
103 $tmp = new DOMDocument();
104 if ($tmp->loadHTML('<?xml encoding="utf-8" ?>' . $oembed_result["html"])) {
105 $p = $doc->createElement("p");
107 $p->appendChild($doc->importNode(
108 $tmp->getElementsByTagName("blockquote")->item(0), TRUE));
110 $br = $doc->createElement('br');
111 $entry->parentNode
->insertBefore($p, $entry);
112 $entry->parentNode
->insertBefore($br, $entry);
120 if (!$found && preg_match("/\.gfycat.com\/([a-z]+)?(\.[a-z]+)$/i", $entry->getAttribute("href"), $matches)) {
121 $entry->setAttribute("href", "http://www.gfycat.com/".$matches[1]);
124 if (!$found && preg_match("/https?:\/\/(www\.)?gfycat.com\/([a-z]+)$/i", $entry->getAttribute("href"), $matches)) {
126 _debug("Handling as Gfycat", $debug);
128 $tmp = fetch_file_contents($entry->getAttribute("href"));
131 $tmpdoc = new DOMDocument();
133 if (@$tmpdoc->loadHTML($tmp)) {
134 $tmpxpath = new DOMXPath($tmpdoc);
136 $source_node = $tmpxpath->query("//video[contains(@class,'share-video')]//source[contains(@src, '.mp4')]")->item(0);
137 $poster_node = $tmpxpath->query("//video[contains(@class,'share-video') and @poster]")->item(0);
139 if ($source_node && $poster_node) {
140 $source_stream = $source_node->getAttribute("src");
141 $poster_url = $poster_node->getAttribute("poster");
143 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
150 if (!$found && preg_match("/https?:\/\/v\.redd\.it\/(.*)$/i", $entry->getAttribute("href"), $matches)) {
152 _debug("Handling as reddit inline video", $debug);
154 $img = $img_entries->item(0);
157 $poster_url = $img->getAttribute("src");
162 // IMPORTANT: This assumes the article GUID is kept in "owner_uid,entry_guid" format, and
163 // Reddit feed entries will keep the <id> element (so get_id returns it).
164 $feeditem_id = explode(",", $article["guid"])[1];
165 $source_stream = false;
166 $j = json_decode(fetch_file_contents($article["link"].".json"), true);
169 foreach ($j as $listing) {
170 foreach ($listing["data"]["children"] as $child) {
171 // Found the child object corresponding to the article (e.g. same name+ID like "t3_70j63a").
172 if ($child["data"]["name"] == $feeditem_id) {
174 $source_stream = $child["data"]["media"]["reddit_video"]["fallback_url"];
176 catch (Exception
$e) {
184 if (!$source_stream) {
185 $source_stream = "https://v.redd.it/" . $matches[1] . "/DASH_600_K";
188 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
192 if (!$found && preg_match("/https?:\/\/(www\.)?streamable.com\//i", $entry->getAttribute("href"))) {
194 _debug("Handling as Streamable", $debug);
196 $tmp = fetch_file_contents($entry->getAttribute("href"));
199 $tmpdoc = new DOMDocument();
201 if (@$tmpdoc->loadHTML($tmp)) {
202 $tmpxpath = new DOMXPath($tmpdoc);
204 $source_node = $tmpxpath->query("//video[contains(@class,'video-player-tag')]//source[contains(@src, '.mp4')]")->item(0);
205 $poster_node = $tmpxpath->query("//video[contains(@class,'video-player-tag') and @poster]")->item(0);
207 if ($source_node && $poster_node) {
208 $source_stream = $source_node->getAttribute("src");
209 $poster_url = $poster_node->getAttribute("poster");
211 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
218 // imgur .gif -> .gifv
219 if (!$found && preg_match("/i\.imgur\.com\/(.*?)\.gif$/i", $entry->getAttribute("href"))) {
220 _debug("Handling as imgur gif (->gifv)", $debug);
222 $entry->setAttribute("href",
223 str_replace(".gif", ".gifv", $entry->getAttribute("href")));
226 if (!$found && preg_match("/\.(gifv|mp4)$/i", $entry->getAttribute("href"))) {
227 _debug("Handling as imgur gifv", $debug);
229 $source_stream = str_replace(".gifv", ".mp4", $entry->getAttribute("href"));
231 if (strpos($source_stream, "imgur.com") !== FALSE)
232 $poster_url = str_replace(".mp4", "h.jpg", $source_stream);
234 $this->handle_as_video($doc, $entry, $source_stream, $poster_url, $debug);
240 if (!$found && preg_match("/youtube\.com\/v\/([\w-]+)/", $entry->getAttribute("href"), $matches) ||
241 preg_match("/youtube\.com\/.*?[\&\?]v=([\w-]+)/", $entry->getAttribute("href"), $matches) ||
242 preg_match("/youtube\.com\/watch\?v=([\w-]+)/", $entry->getAttribute("href"), $matches) ||
243 preg_match("/\/\/youtu.be\/([\w-]+)/", $entry->getAttribute("href"), $matches)) {
245 $vid_id = $matches[1];
247 _debug("Handling as youtube: $vid_id", $debug);
249 $iframe = $doc->createElement("iframe");
250 $iframe->setAttribute("class", "youtube-player");
251 $iframe->setAttribute("type", "text/html");
252 $iframe->setAttribute("width", "640");
253 $iframe->setAttribute("height", "385");
254 $iframe->setAttribute("src", "https://www.youtube.com/embed/$vid_id");
255 $iframe->setAttribute("allowfullscreen", "1");
256 $iframe->setAttribute("frameborder", "0");
258 $br = $doc->createElement('br');
259 $entry->parentNode
->insertBefore($iframe, $entry);
260 $entry->parentNode
->insertBefore($br, $entry);
265 if (!$found && preg_match("/\.(jpg|jpeg|gif|png)(\?[0-9][0-9]*)?$/i", $entry->getAttribute("href")) ||
266 mb_strpos($entry->getAttribute("href"), "i.reddituploads.com") !== FALSE ||
267 mb_strpos($this->get_content_type($entry->getAttribute("href")), "image/") !== FALSE) {
269 _debug("Handling as a picture", $debug);
271 $img = $doc->createElement('img');
272 $img->setAttribute("src", $entry->getAttribute("href"));
274 $br = $doc->createElement('br');
275 $entry->parentNode
->insertBefore($img, $entry);
276 $entry->parentNode
->insertBefore($br, $entry);
281 // linked albums & pages
283 if (!$found && preg_match("/^https?:\/\/(m\.)?imgur.com\/([^\.\/]+$)/", $entry->getAttribute("href"), $matches) ||
284 preg_match("/^https?:\/\/(m\.)?imgur.com\/(a|album|gallery)\/[^\.]+$/", $entry->getAttribute("href"), $matches)) {
286 _debug("Handling as an imgur page/album/gallery", $debug);
288 $album_content = fetch_file_contents($entry->getAttribute("href"),
289 false, false, false, false, 10);
291 if ($album_content) {
292 $adoc = new DOMDocument();
294 if (@$adoc->loadHTML($album_content)) {
295 $axpath = new DOMXPath($adoc);
297 $aentries = $axpath->query("(//div[@class='post-image']/img[@src] | //a[@class='zoom']/img[@src] | //div[@class='video-elements']/source)");
300 foreach ($aentries as $aentry) {
302 $url = $aentry->getAttribute("src");
304 if (!in_array($url, $urls)) {
306 if ($aentry->tagName
== "img") {
308 $img = $doc->createElement('img');
309 $img->setAttribute("src", $url);
310 $entry->parentNode
->insertBefore($doc->createElement('br'), $entry);
312 $br = $doc->createElement('br');
314 $entry->parentNode
->insertBefore($img, $entry);
315 $entry->parentNode
->insertBefore($br, $entry);
316 } else if ($aentry->tagName
== "source") {
318 if (strpos($url, "imgur.com") !== FALSE)
319 $poster_url = str_replace(".mp4", "h.jpg", $url);
323 $this->handle_as_video($doc, $entry, $url, $poster_url);
327 array_push($urls, $url);
334 if ($debug) print_r($urls);
340 if (!$found && preg_match("/^https?:\/\/gyazo\.com\/([^\.\/]+$)/", $entry->getAttribute("href"), $matches)) {
341 $img_id = $matches[1];
343 _debug("handling as gyazo: $img_id", $debug);
345 $img = $doc->createElement('img');
346 $img->setAttribute("src", "https://i.gyazo.com/$img_id.jpg");
348 $br = $doc->createElement('br');
349 $entry->parentNode
->insertBefore($img, $entry);
350 $entry->parentNode
->insertBefore($br, $entry);
356 // remove tiny thumbnails
357 if ($entry->hasAttribute("src")) {
358 if ($entry->parentNode
&& $entry->parentNode
->parentNode
) {
359 $entry->parentNode
->parentNode
->removeChild($entry->parentNode
);
367 function hook_article_filter($article) {
369 if (strpos($article["link"], "reddit.com/r/") !== FALSE) {
370 $doc = new DOMDocument();
371 @$doc->loadHTML($article["content"]);
372 $xpath = new DOMXPath($doc);
374 $content_link = $xpath->query("(//a[contains(., '[link]')])")->item(0);
376 if ($this->host
->get($this, "enable_content_dupcheck")) {
379 $content_href = db_escape_string($content_link->getAttribute("href"));
380 $entry_guid = db_escape_string($article["guid_hashed"]);
381 $owner_uid = $article["owner_uid"];
383 if (DB_TYPE
== "pgsql") {
384 $interval_qpart = "date_entered < NOW() - INTERVAL '1 day'";
386 $interval_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY)";
389 $result = db_query("SELECT COUNT(id) AS cid
390 FROM ttrss_entries, ttrss_user_entries WHERE
393 guid != '$entry_guid' AND
394 owner_uid = '$owner_uid' AND
395 content LIKE '%href=\"$content_href\">[link]%'");
398 $num_found = db_fetch_result($result, 0, "cid");
400 if ($num_found > 0) $article["force_catchup"] = true;
405 $found = $this->inline_stuff($article, $doc, $xpath);
407 $node = $doc->getElementsByTagName('body')->item(0);
409 if ($node && $found) {
410 $article["content"] = $doc->saveHTML($node);
411 } else if ($content_link) {
412 $article = $this->readability($article, $content_link->getAttribute("href"), $doc, $xpath);
419 function api_version() {
423 private function handle_as_video($doc, $entry, $source_stream, $poster_url = false, $debug = false) {
425 _debug("handle_as_video: $source_stream", $debug);
427 $video = $doc->createElement('video');
428 $video->setAttribute("autoplay", "1");
429 $video->setAttribute("controls", "1");
430 $video->setAttribute("loop", "1");
432 if ($poster_url) $video->setAttribute("poster", $poster_url);
434 $source = $doc->createElement('source');
435 $source->setAttribute("src", $source_stream);
436 $source->setAttribute("type", "video/mp4");
438 $video->appendChild($source);
440 $br = $doc->createElement('br');
441 $entry->parentNode
->insertBefore($video, $entry);
442 $entry->parentNode
->insertBefore($br, $entry);
444 $img = $doc->createElement('img');
445 $img->setAttribute("src",
446 "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D");
448 $entry->parentNode
->insertBefore($img, $entry);
452 $url = htmlspecialchars($_REQUEST["url"]);
454 header("Content-type: text/plain");
458 $doc = new DOMDocument();
459 @$doc->loadHTML("<html><body><a href=\"$url\">[link]</a></body>");
460 $xpath = new DOMXPath($doc);
462 $found = $this->inline_stuff([], $doc, $xpath, true);
464 print "Inline result: $found\n";
467 print "\nReadability result:\n";
469 $article = $this->readability([], $url, $doc, $xpath, true);
473 print "\nResulting HTML:\n";
475 print $doc->saveHTML();
479 private function get_content_type($url, $useragent = SELF_USER_AGENT
) {
480 $content_type = false;
482 if (function_exists("curl_init") && !defined("NO_CURL")) {
483 $ch = curl_init($url);
484 curl_setopt($ch, CURLOPT_TIMEOUT
, 5);
485 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
486 curl_setopt($ch, CURLOPT_HEADER
, true);
487 curl_setopt($ch, CURLOPT_NOBODY
, true);
488 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, !ini_get("open_basedir"));
489 curl_setopt($ch, CURLOPT_USERAGENT
, $useragent);
492 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
495 return $content_type;
499 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
501 private function readability($article, $url, $doc, $xpath, $debug = false) {
503 if (!defined('NO_CURL') && function_exists("curl_init") && $this->host
->get($this, "enable_readability") &&
504 mb_strlen(strip_tags($article["content"])) <= 150) {
506 if (!class_exists("Readability")) require_once(dirname(dirname(__DIR__
)). "/lib/readability/Readability.php");
509 strpos($url, "twitter.com") === FALSE &&
510 strpos($url, "youtube.com") === FALSE &&
511 strpos($url, "reddit.com") === FALSE) {
513 /* link may lead to a huge video file or whatever, we need to check content type before trying to
514 parse it which p much requires curl */
516 $useragent_compat = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
518 $content_type = $this->get_content_type($url, $useragent_compat);
520 if ($content_type && strpos($content_type, "text/html") !== FALSE) {
522 $tmp = fetch_file_contents(array("url" => $url,
523 "useragent" => $useragent_compat));
525 if ($debug) _debug("tmplen: " . mb_strlen($tmp));
527 if ($tmp && mb_strlen($tmp) < 1024 * 500) {
529 $r = new Readability($tmp, $url);
533 $tmpxpath = new DOMXPath($r->dom
);
535 $entries = $tmpxpath->query('(//a[@href]|//img[@src])');
537 foreach ($entries as $entry) {
538 if ($entry->hasAttribute("href")) {
539 $entry->setAttribute("href",
540 rewrite_relative_url($url, $entry->getAttribute("href")));
544 if ($entry->hasAttribute("src")) {
545 $entry->setAttribute("src",
546 rewrite_relative_url($url, $entry->getAttribute("src")));
552 $article["content"] = $r->articleContent
->innerHTML
. "<hr/>" . $article["content"];