]>
git.wh0rd.org - tt-rss.git/blob - plugins/af_redditimgur/init.php
2 class Af_RedditImgur
extends Plugin
{
4 /* @var PluginHost $host */
9 "Inline images (and other content) in Reddit RSS feeds",
14 return array("needs_curl" => true);
17 function init($host) {
20 $host->add_hook($host::HOOK_ARTICLE_FILTER
, $this);
21 $host->add_hook($host::HOOK_PREFS_TAB
, $this);
24 function hook_prefs_tab($args) {
25 if ($args != "prefFeeds") return;
27 print "<div dojoType=\"dijit.layout.AccordionPane\" title=\"".__('Reddit content settings (af_redditimgur)')."\">";
29 $enable_readability = $this->host
->get($this, "enable_readability");
30 $enable_content_dupcheck = $this->host
->get($this, "enable_content_dupcheck");
32 print "<form dojoType=\"dijit.form.Form\">";
34 print "<script type=\"dojo/method\" event=\"onSubmit\" args=\"evt\">
36 if (this.validate()) {
37 console.log(dojo.objectToQuery(this.getValues()));
38 new Ajax.Request('backend.php', {
39 parameters: dojo.objectToQuery(this.getValues()),
40 onComplete: function(transport) {
41 notify_info(transport.responseText);
48 print_hidden("op", "pluginhandler");
49 print_hidden("method", "save");
50 print_hidden("plugin", "af_redditimgur");
52 print "<p>" . __("Uses Readability (full-text-rss) implementation by <a target='_blank' href='https://bitbucket.org/fivefilters/'>FiveFilters.org</a>");
55 print_checkbox("enable_readability", $enable_readability);
56 print " <label for=\"enable_readability\">" . __("Extract missing content using Readability") . "</label>";
60 print_checkbox("enable_content_dupcheck", $enable_content_dupcheck);
61 print " <label for=\"enable_content_dupcheck\">" . __("Enable additional duplicate checking") . "</label>";
62 print "<p>"; print_button("submit", __("Save"));
69 $enable_readability = checkbox_to_sql_bool($_POST["enable_readability"]);
70 $enable_content_dupcheck = checkbox_to_sql_bool($_POST["enable_content_dupcheck"]);
72 $this->host
->set($this, "enable_readability", $enable_readability, false);
73 $this->host
->set($this, "enable_content_dupcheck", $enable_content_dupcheck);
75 echo __("Configuration saved");
79 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
81 private function inline_stuff($article, &$doc, $xpath, $debug = false) {
83 $entries = $xpath->query('(//a[@href]|//img[@src])');
84 $img_entries = $xpath->query("(//img[@src])");
88 foreach ($entries as $entry) {
89 if ($entry->hasAttribute("href")) {
91 _debug("processing href: " . $entry->getAttribute("href"), $debug);
95 if (preg_match("/^https?:\/\/twitter.com\/(.*?)\/status\/(.*)/", $entry->getAttribute("href"), $matches)) {
96 _debug("handling as twitter: " . $matches[1] . " " . $matches[2], $debug);
98 $oembed_result = fetch_file_contents("https://publish.twitter.com/oembed?url=" . urlencode($entry->getAttribute("href")));
100 if ($oembed_result) {
101 $oembed_result = json_decode($oembed_result, true);
103 if ($oembed_result && isset($oembed_result["html"])) {
105 $tmp = new DOMDocument();
106 if ($tmp->loadHTML('<?xml encoding="utf-8" ?>' . $oembed_result["html"])) {
107 $p = $doc->createElement("p");
109 $p->appendChild($doc->importNode(
110 $tmp->getElementsByTagName("blockquote")->item(0), TRUE));
112 $br = $doc->createElement('br');
113 $entry->parentNode
->insertBefore($p, $entry);
114 $entry->parentNode
->insertBefore($br, $entry);
122 if (!$found && preg_match("/\.gfycat.com\/([a-z]+)?(\.[a-z]+)$/i", $entry->getAttribute("href"), $matches)) {
123 $entry->setAttribute("href", "http://www.gfycat.com/".$matches[1]);
126 if (!$found && preg_match("/https?:\/\/(www\.)?gfycat.com\/([a-z]+)$/i", $entry->getAttribute("href"), $matches)) {
128 _debug("Handling as Gfycat", $debug);
130 $tmp = fetch_file_contents($entry->getAttribute("href"));
133 $tmpdoc = new DOMDocument();
135 if (@$tmpdoc->loadHTML($tmp)) {
136 $tmpxpath = new DOMXPath($tmpdoc);
138 $source_node = $tmpxpath->query("//video[contains(@class,'share-video')]//source[contains(@src, '.mp4')]")->item(0);
139 $poster_node = $tmpxpath->query("//video[contains(@class,'share-video') and @poster]")->item(0);
141 if ($source_node && $poster_node) {
142 $source_stream = $source_node->getAttribute("src");
143 $poster_url = $poster_node->getAttribute("poster");
145 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
152 if (!$found && preg_match("/https?:\/\/v\.redd\.it\/(.*)$/i", $entry->getAttribute("href"), $matches)) {
154 _debug("Handling as reddit inline video", $debug);
156 $img = $img_entries->item(0);
159 $poster_url = $img->getAttribute("src");
164 // Get original article URL from v.redd.it redirects
165 $source_article_url = $this->get_location($matches[0]);
166 _debug("Resolved ".$matches[0]." to ".$source_article_url, $debug);
168 $source_stream = false;
170 if ($source_article_url) {
171 $j = json_decode(fetch_file_contents($source_article_url.".json"), true);
174 foreach ($j as $listing) {
175 foreach ($listing["data"]["children"] as $child) {
176 if ($child["data"]["url"] == $matches[0]) {
178 $source_stream = $child["data"]["media"]["reddit_video"]["fallback_url"];
180 catch (Exception
$e) {
189 if (!$source_stream) {
190 $source_stream = "https://v.redd.it/" . $matches[1] . "/DASH_600_K";
193 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
197 if (!$found && preg_match("/https?:\/\/(www\.)?streamable.com\//i", $entry->getAttribute("href"))) {
199 _debug("Handling as Streamable", $debug);
201 $tmp = fetch_file_contents($entry->getAttribute("href"));
204 $tmpdoc = new DOMDocument();
206 if (@$tmpdoc->loadHTML($tmp)) {
207 $tmpxpath = new DOMXPath($tmpdoc);
209 $source_node = $tmpxpath->query("//video[contains(@class,'video-player-tag')]//source[contains(@src, '.mp4')]")->item(0);
210 $poster_node = $tmpxpath->query("//video[contains(@class,'video-player-tag') and @poster]")->item(0);
212 if ($source_node && $poster_node) {
213 $source_stream = $source_node->getAttribute("src");
214 $poster_url = $poster_node->getAttribute("poster");
216 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
223 // imgur .gif -> .gifv
224 if (!$found && preg_match("/i\.imgur\.com\/(.*?)\.gif$/i", $entry->getAttribute("href"))) {
225 _debug("Handling as imgur gif (->gifv)", $debug);
227 $entry->setAttribute("href",
228 str_replace(".gif", ".gifv", $entry->getAttribute("href")));
231 if (!$found && preg_match("/\.(gifv|mp4)$/i", $entry->getAttribute("href"))) {
232 _debug("Handling as imgur gifv", $debug);
234 $source_stream = str_replace(".gifv", ".mp4", $entry->getAttribute("href"));
236 if (strpos($source_stream, "imgur.com") !== FALSE)
237 $poster_url = str_replace(".mp4", "h.jpg", $source_stream);
239 $this->handle_as_video($doc, $entry, $source_stream, $poster_url, $debug);
245 if (!$found && preg_match("/youtube\.com\/v\/([\w-]+)/", $entry->getAttribute("href"), $matches) ||
246 preg_match("/youtube\.com\/.*?[\&\?]v=([\w-]+)/", $entry->getAttribute("href"), $matches) ||
247 preg_match("/youtube\.com\/watch\?v=([\w-]+)/", $entry->getAttribute("href"), $matches) ||
248 preg_match("/\/\/youtu.be\/([\w-]+)/", $entry->getAttribute("href"), $matches)) {
250 $vid_id = $matches[1];
252 _debug("Handling as youtube: $vid_id", $debug);
254 $iframe = $doc->createElement("iframe");
255 $iframe->setAttribute("class", "youtube-player");
256 $iframe->setAttribute("type", "text/html");
257 $iframe->setAttribute("width", "640");
258 $iframe->setAttribute("height", "385");
259 $iframe->setAttribute("src", "https://www.youtube.com/embed/$vid_id");
260 $iframe->setAttribute("allowfullscreen", "1");
261 $iframe->setAttribute("frameborder", "0");
263 $br = $doc->createElement('br');
264 $entry->parentNode
->insertBefore($iframe, $entry);
265 $entry->parentNode
->insertBefore($br, $entry);
270 if (!$found && preg_match("/\.(jpg|jpeg|gif|png)(\?[0-9][0-9]*)?$/i", $entry->getAttribute("href")) ||
271 mb_strpos($entry->getAttribute("href"), "i.reddituploads.com") !== FALSE ||
272 mb_strpos($this->get_content_type($entry->getAttribute("href")), "image/") !== FALSE) {
274 _debug("Handling as a picture", $debug);
276 $img = $doc->createElement('img');
277 $img->setAttribute("src", $entry->getAttribute("href"));
279 $br = $doc->createElement('br');
280 $entry->parentNode
->insertBefore($img, $entry);
281 $entry->parentNode
->insertBefore($br, $entry);
286 // linked albums & pages
288 if (!$found && preg_match("/^https?:\/\/(m\.)?imgur.com\/([^\.\/]+$)/", $entry->getAttribute("href"), $matches) ||
289 preg_match("/^https?:\/\/(m\.)?imgur.com\/(a|album|gallery)\/[^\.]+$/", $entry->getAttribute("href"), $matches)) {
291 _debug("Handling as an imgur page/album/gallery", $debug);
293 $album_content = fetch_file_contents($entry->getAttribute("href"),
294 false, false, false, false, 10);
296 if ($album_content) {
297 $adoc = new DOMDocument();
299 if (@$adoc->loadHTML($album_content)) {
300 $axpath = new DOMXPath($adoc);
302 $aentries = $axpath->query("(//div[@class='post-image']/img[@src] | //a[@class='zoom']/img[@src] | //div[@class='video-elements']/source)");
305 foreach ($aentries as $aentry) {
307 $url = $aentry->getAttribute("src");
309 if (!in_array($url, $urls)) {
311 if ($aentry->tagName
== "img") {
313 $img = $doc->createElement('img');
314 $img->setAttribute("src", $url);
315 $entry->parentNode
->insertBefore($doc->createElement('br'), $entry);
317 $br = $doc->createElement('br');
319 $entry->parentNode
->insertBefore($img, $entry);
320 $entry->parentNode
->insertBefore($br, $entry);
321 } else if ($aentry->tagName
== "source") {
323 if (strpos($url, "imgur.com") !== FALSE)
324 $poster_url = str_replace(".mp4", "h.jpg", $url);
328 $this->handle_as_video($doc, $entry, $url, $poster_url);
332 array_push($urls, $url);
339 if ($debug) print_r($urls);
345 if (!$found && preg_match("/^https?:\/\/gyazo\.com\/([^\.\/]+$)/", $entry->getAttribute("href"), $matches)) {
346 $img_id = $matches[1];
348 _debug("handling as gyazo: $img_id", $debug);
350 $img = $doc->createElement('img');
351 $img->setAttribute("src", "https://i.gyazo.com/$img_id.jpg");
353 $br = $doc->createElement('br');
354 $entry->parentNode
->insertBefore($img, $entry);
355 $entry->parentNode
->insertBefore($br, $entry);
361 // remove tiny thumbnails
362 if ($entry->hasAttribute("src")) {
363 if ($entry->parentNode
&& $entry->parentNode
->parentNode
) {
364 $entry->parentNode
->parentNode
->removeChild($entry->parentNode
);
372 function hook_article_filter($article) {
374 if (strpos($article["link"], "reddit.com/r/") !== FALSE) {
375 $doc = new DOMDocument();
376 @$doc->loadHTML($article["content"]);
377 $xpath = new DOMXPath($doc);
379 $content_link = $xpath->query("(//a[contains(., '[link]')])")->item(0);
381 if ($this->host
->get($this, "enable_content_dupcheck")) {
384 $content_href = $content_link->getAttribute("href");
385 $entry_guid = $article["guid_hashed"];
386 $owner_uid = $article["owner_uid"];
388 if (DB_TYPE
== "pgsql") {
389 $interval_qpart = "date_entered < NOW() - INTERVAL '1 day'";
391 $interval_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY)";
394 $sth = $this->pdo
->prepare("SELECT COUNT(id) AS cid
395 FROM ttrss_entries, ttrss_user_entries WHERE
402 $sth->execute([$entry_guid, $owner_uid, "%href=\"$content_href\">[link]%"]);
404 if ($row = $sth->fetch()) {
405 $num_found = $row['cid'];
407 if ($num_found > 0) $article["force_catchup"] = true;
412 $found = $this->inline_stuff($article, $doc, $xpath);
414 $node = $doc->getElementsByTagName('body')->item(0);
416 if ($node && $found) {
417 $article["content"] = $doc->saveHTML($node);
418 } else if ($content_link) {
419 $article = $this->readability($article, $content_link->getAttribute("href"), $doc, $xpath);
426 function api_version() {
430 private function handle_as_video($doc, $entry, $source_stream, $poster_url = false, $debug = false) {
432 _debug("handle_as_video: $source_stream", $debug);
434 $video = $doc->createElement('video');
435 $video->setAttribute("autoplay", "1");
436 $video->setAttribute("controls", "1");
437 $video->setAttribute("loop", "1");
439 if ($poster_url) $video->setAttribute("poster", $poster_url);
441 $source = $doc->createElement('source');
442 $source->setAttribute("src", $source_stream);
443 $source->setAttribute("type", "video/mp4");
445 $video->appendChild($source);
447 $br = $doc->createElement('br');
448 $entry->parentNode
->insertBefore($video, $entry);
449 $entry->parentNode
->insertBefore($br, $entry);
451 $img = $doc->createElement('img');
452 $img->setAttribute("src",
453 "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D");
455 $entry->parentNode
->insertBefore($img, $entry);
459 $url = htmlspecialchars($_REQUEST["url"]);
461 header("Content-type: text/plain");
465 $doc = new DOMDocument();
466 @$doc->loadHTML("<html><body><a href=\"$url\">[link]</a></body>");
467 $xpath = new DOMXPath($doc);
469 $found = $this->inline_stuff([], $doc, $xpath, true);
471 print "Inline result: $found\n";
474 print "\nReadability result:\n";
476 $article = $this->readability([], $url, $doc, $xpath, true);
480 print "\nResulting HTML:\n";
482 print $doc->saveHTML();
486 private function get_header($url, $useragent = SELF_USER_AGENT
, $header) {
489 if (function_exists("curl_init") && !defined("NO_CURL")) {
490 $ch = curl_init($url);
491 curl_setopt($ch, CURLOPT_TIMEOUT
, 5);
492 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
493 curl_setopt($ch, CURLOPT_HEADER
, true);
494 curl_setopt($ch, CURLOPT_NOBODY
, true);
495 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, !ini_get("open_basedir"));
496 curl_setopt($ch, CURLOPT_USERAGENT
, $useragent);
499 $ret = curl_getinfo($ch, $header);
505 private function get_content_type($url, $useragent = SELF_USER_AGENT
) {
506 return $this->get_header($url, $useragent, CURLINFO_CONTENT_TYPE
);
509 private function get_location($url, $useragent = SELF_USER_AGENT
) {
510 return $this->get_header($url, $useragent, CURLINFO_EFFECTIVE_URL
);
514 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
516 private function readability($article, $url, $doc, $xpath, $debug = false) {
518 if (!defined('NO_CURL') && function_exists("curl_init") && $this->host
->get($this, "enable_readability") &&
519 mb_strlen(strip_tags($article["content"])) <= 150) {
521 if (!class_exists("Readability")) require_once(dirname(dirname(__DIR__
)). "/lib/readability/Readability.php");
524 strpos($url, "twitter.com") === FALSE &&
525 strpos($url, "youtube.com") === FALSE &&
526 strpos($url, "reddit.com") === FALSE) {
528 /* link may lead to a huge video file or whatever, we need to check content type before trying to
529 parse it which p much requires curl */
531 $useragent_compat = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
533 $content_type = $this->get_content_type($url, $useragent_compat);
535 if ($content_type && strpos($content_type, "text/html") !== FALSE) {
537 $tmp = fetch_file_contents(array("url" => $url,
538 "useragent" => $useragent_compat));
540 if ($debug) _debug("tmplen: " . mb_strlen($tmp));
542 if ($tmp && mb_strlen($tmp) < 1024 * 500) {
544 $r = new Readability($tmp, $url);
548 $tmpxpath = new DOMXPath($r->dom
);
550 $entries = $tmpxpath->query('(//a[@href]|//img[@src])');
552 foreach ($entries as $entry) {
553 if ($entry->hasAttribute("href")) {
554 $entry->setAttribute("href",
555 rewrite_relative_url($url, $entry->getAttribute("href")));
559 if ($entry->hasAttribute("src")) {
560 $entry->setAttribute("src",
561 rewrite_relative_url($url, $entry->getAttribute("src")));
567 $article["content"] = $r->articleContent
->innerHTML
. "<hr/>" . $article["content"];