2 use andreskrey\Readability\Readability
;
3 use andreskrey\Readability\Configuration
;
5 class Af_RedditImgur
extends Plugin
{
7 /* @var PluginHost $host */
12 "Inline images (and other content) in Reddit RSS feeds",
17 return array("needs_curl" => true);
20 function init($host) {
23 $host->add_hook($host::HOOK_ARTICLE_FILTER
, $this);
24 $host->add_hook($host::HOOK_PREFS_TAB
, $this);
27 function hook_prefs_tab($args) {
28 if ($args != "prefFeeds") return;
30 print "<div dojoType=\"dijit.layout.AccordionPane\" title=\"".__('Reddit content settings (af_redditimgur)')."\">";
32 $enable_readability = $this->host
->get($this, "enable_readability");
33 $enable_content_dupcheck = $this->host
->get($this, "enable_content_dupcheck");
35 print "<form dojoType=\"dijit.form.Form\">";
37 print "<script type=\"dojo/method\" event=\"onSubmit\" args=\"evt\">
39 if (this.validate()) {
40 console.log(dojo.objectToQuery(this.getValues()));
41 new Ajax.Request('backend.php', {
42 parameters: dojo.objectToQuery(this.getValues()),
43 onComplete: function(transport) {
44 notify_info(transport.responseText);
51 print_hidden("op", "pluginhandler");
52 print_hidden("method", "save");
53 print_hidden("plugin", "af_redditimgur");
55 print "<p>" . __("Uses Readability (full-text-rss) implementation by <a target='_blank' href='https://bitbucket.org/fivefilters/'>FiveFilters.org</a>");
58 print_checkbox("enable_readability", $enable_readability);
59 print " <label for=\"enable_readability\">" . __("Extract missing content using Readability") . "</label>";
63 print_checkbox("enable_content_dupcheck", $enable_content_dupcheck);
64 print " <label for=\"enable_content_dupcheck\">" . __("Enable additional duplicate checking") . "</label>";
65 print "<p>"; print_button("submit", __("Save"));
72 $enable_readability = checkbox_to_sql_bool($_POST["enable_readability"]);
73 $enable_content_dupcheck = checkbox_to_sql_bool($_POST["enable_content_dupcheck"]);
75 $this->host
->set($this, "enable_readability", $enable_readability, false);
76 $this->host
->set($this, "enable_content_dupcheck", $enable_content_dupcheck);
78 echo __("Configuration saved");
82 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
84 private function inline_stuff($article, &$doc, $xpath, $debug = false) {
86 $entries = $xpath->query('(//a[@href]|//img[@src])');
87 $img_entries = $xpath->query("(//img[@src])");
92 foreach ($entries as $entry) {
93 if ($entry->hasAttribute("href") && strpos($entry->getAttribute("href"), "reddit.com") === FALSE) {
95 _debug("processing href: " . $entry->getAttribute("href"), $debug);
99 if (!$found && preg_match("/^https?:\/\/twitter.com\/(.*?)\/status\/(.*)/", $entry->getAttribute("href"), $matches)) {
100 _debug("handling as twitter: " . $matches[1] . " " . $matches[2], $debug);
102 $oembed_result = fetch_file_contents("https://publish.twitter.com/oembed?url=" . urlencode($entry->getAttribute("href")));
104 if ($oembed_result) {
105 $oembed_result = json_decode($oembed_result, true);
107 if ($oembed_result && isset($oembed_result["html"])) {
109 $tmp = new DOMDocument();
110 if ($tmp->loadHTML('<?xml encoding="utf-8" ?>' . $oembed_result["html"])) {
111 $p = $doc->createElement("p");
113 $p->appendChild($doc->importNode(
114 $tmp->getElementsByTagName("blockquote")->item(0), TRUE));
116 $br = $doc->createElement('br');
117 $entry->parentNode
->insertBefore($p, $entry);
118 $entry->parentNode
->insertBefore($br, $entry);
126 if (!$found && preg_match("/\.gfycat.com\/([a-z]+)?(\.[a-z]+)$/i", $entry->getAttribute("href"), $matches)) {
127 $entry->setAttribute("href", "http://www.gfycat.com/".$matches[1]);
130 if (!$found && preg_match("/https?:\/\/(www\.)?gfycat.com\/([a-z]+)$/i", $entry->getAttribute("href"), $matches)) {
132 _debug("Handling as Gfycat", $debug);
134 $tmp = fetch_file_contents($entry->getAttribute("href"));
137 $tmpdoc = new DOMDocument();
139 if (@$tmpdoc->loadHTML($tmp)) {
140 $tmpxpath = new DOMXPath($tmpdoc);
142 $source_node = $tmpxpath->query("//video[contains(@class,'share-video')]//source[contains(@src, '.mp4')]")->item(0);
143 $poster_node = $tmpxpath->query("//video[contains(@class,'share-video') and @poster]")->item(0);
145 if ($source_node && $poster_node) {
146 $source_stream = $source_node->getAttribute("src");
147 $poster_url = $poster_node->getAttribute("poster");
149 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
156 if (!$found && preg_match("/https?:\/\/v\.redd\.it\/(.*)$/i", $entry->getAttribute("href"), $matches)) {
158 _debug("Handling as reddit inline video", $debug);
160 $img = $img_entries->item(0);
163 $poster_url = $img->getAttribute("src");
168 // Get original article URL from v.redd.it redirects
169 $source_article_url = $this->get_location($matches[0]);
170 _debug("Resolved ".$matches[0]." to ".$source_article_url, $debug);
172 $source_stream = false;
174 if ($source_article_url) {
175 $j = json_decode(fetch_file_contents($source_article_url.".json"), true);
178 foreach ($j as $listing) {
179 foreach ($listing["data"]["children"] as $child) {
180 if ($child["data"]["url"] == $matches[0]) {
182 $source_stream = $child["data"]["media"]["reddit_video"]["fallback_url"];
184 catch (Exception
$e) {
193 if (!$source_stream) {
194 $source_stream = "https://v.redd.it/" . $matches[1] . "/DASH_600_K";
197 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
201 if (!$found && preg_match("/https?:\/\/(www\.)?streamable.com\//i", $entry->getAttribute("href"))) {
203 _debug("Handling as Streamable", $debug);
205 $tmp = fetch_file_contents($entry->getAttribute("href"));
208 $tmpdoc = new DOMDocument();
210 if (@$tmpdoc->loadHTML($tmp)) {
211 $tmpxpath = new DOMXPath($tmpdoc);
213 $source_node = $tmpxpath->query("//video[contains(@class,'video-player-tag')]//source[contains(@src, '.mp4')]")->item(0);
214 $poster_node = $tmpxpath->query("//video[contains(@class,'video-player-tag') and @poster]")->item(0);
216 if ($source_node && $poster_node) {
217 $source_stream = $source_node->getAttribute("src");
218 $poster_url = $poster_node->getAttribute("poster");
220 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
227 // imgur .gif -> .gifv
228 if (!$found && preg_match("/i\.imgur\.com\/(.*?)\.gif$/i", $entry->getAttribute("href"))) {
229 _debug("Handling as imgur gif (->gifv)", $debug);
231 $entry->setAttribute("href",
232 str_replace(".gif", ".gifv", $entry->getAttribute("href")));
235 if (!$found && preg_match("/\.(gifv|mp4)$/i", $entry->getAttribute("href"))) {
236 _debug("Handling as imgur gifv", $debug);
238 $source_stream = str_replace(".gifv", ".mp4", $entry->getAttribute("href"));
240 if (strpos($source_stream, "imgur.com") !== FALSE)
241 $poster_url = str_replace(".mp4", "h.jpg", $source_stream);
243 $this->handle_as_video($doc, $entry, $source_stream, $poster_url, $debug);
249 if (!$found && preg_match("/youtube\.com\/v\/([\w-]+)/", $entry->getAttribute("href"), $matches) ||
250 preg_match("/youtube\.com\/.*?[\&\?]v=([\w-]+)/", $entry->getAttribute("href"), $matches) ||
251 preg_match("/youtube\.com\/watch\?v=([\w-]+)/", $entry->getAttribute("href"), $matches) ||
252 preg_match("/\/\/youtu.be\/([\w-]+)/", $entry->getAttribute("href"), $matches)) {
254 $vid_id = $matches[1];
256 _debug("Handling as youtube: $vid_id", $debug);
258 $iframe = $doc->createElement("iframe");
259 $iframe->setAttribute("class", "youtube-player");
260 $iframe->setAttribute("type", "text/html");
261 $iframe->setAttribute("width", "640");
262 $iframe->setAttribute("height", "385");
263 $iframe->setAttribute("src", "https://www.youtube.com/embed/$vid_id");
264 $iframe->setAttribute("allowfullscreen", "1");
265 $iframe->setAttribute("frameborder", "0");
267 $br = $doc->createElement('br');
268 $entry->parentNode
->insertBefore($iframe, $entry);
269 $entry->parentNode
->insertBefore($br, $entry);
274 if (!$found && preg_match("/\.(jpg|jpeg|gif|png)(\?[0-9][0-9]*)?$/i", $entry->getAttribute("href")) ||
275 mb_strpos($entry->getAttribute("href"), "i.reddituploads.com") !== FALSE ||
276 mb_strpos($this->get_content_type($entry->getAttribute("href")), "image/") !== FALSE) {
278 _debug("Handling as a picture", $debug);
280 $img = $doc->createElement('img');
281 $img->setAttribute("src", $entry->getAttribute("href"));
283 $br = $doc->createElement('br');
284 $entry->parentNode
->insertBefore($img, $entry);
285 $entry->parentNode
->insertBefore($br, $entry);
290 // linked albums & pages
292 /*if (!$found && preg_match("/^https?:\/\/(m\.)?imgur.com\/([^\.\/]+$)/", $entry->getAttribute("href"), $matches) ||
293 preg_match("/^https?:\/\/(m\.)?imgur.com\/(a|album|gallery)\/[^\.]+$/", $entry->getAttribute("href"), $matches)) {
295 _debug("Handling as an imgur page/album/gallery", $debug);
297 $album_content = fetch_file_contents($entry->getAttribute("href"),
298 false, false, false, false, 10);
300 if ($album_content) {
301 $adoc = new DOMDocument();
303 if (@$adoc->loadHTML($album_content)) {
304 $axpath = new DOMXPath($adoc);
306 $aentries = $axpath->query("(//div[@class='post-image']/img[@src] | //a[@class='zoom']/img[@src] | //div[@class='video-elements']/source)");
309 foreach ($aentries as $aentry) {
311 $url = $aentry->getAttribute("src");
313 if (!in_array($url, $urls)) {
315 if ($aentry->tagName == "img") {
317 $img = $doc->createElement('img');
318 $img->setAttribute("src", $url);
319 $entry->parentNode->insertBefore($doc->createElement('br'), $entry);
321 $br = $doc->createElement('br');
323 $entry->parentNode->insertBefore($img, $entry);
324 $entry->parentNode->insertBefore($br, $entry);
325 } else if ($aentry->tagName == "source") {
327 if (strpos($url, "imgur.com") !== FALSE)
328 $poster_url = str_replace(".mp4", "h.jpg", $url);
332 $this->handle_as_video($doc, $entry, $url, $poster_url);
336 array_push($urls, $url);
343 if ($debug) print_r($urls);
349 if (!$found && preg_match("/^https?:\/\/gyazo\.com\/([^\.\/]+$)/", $entry->getAttribute("href"), $matches)) {
350 $img_id = $matches[1];
352 _debug("handling as gyazo: $img_id", $debug);
354 $img = $doc->createElement('img');
355 $img->setAttribute("src", "https://i.gyazo.com/$img_id.jpg");
357 $br = $doc->createElement('br');
358 $entry->parentNode
->insertBefore($img, $entry);
359 $entry->parentNode
->insertBefore($br, $entry);
364 // let's try meta properties
366 _debug("looking for meta og:image", $debug);
368 $content = fetch_file_contents(["url" => $entry->getAttribute("href"),
369 "http_accept" => "text/*"]);
372 $cdoc = new DOMDocument();
374 if (@$cdoc->loadHTML($content)) {
375 $cxpath = new DOMXPath($cdoc);
377 $og_image = $cxpath->query("//meta[@property='og:image']")->item(0);
381 $og_src = $og_image->getAttribute("content");
384 $img = $doc->createElement('img');
385 $img->setAttribute("src", $og_src);
387 $br = $doc->createElement('br');
388 $entry->parentNode
->insertBefore($img, $entry);
389 $entry->parentNode
->insertBefore($br, $entry);
400 // remove tiny thumbnails
401 if ($entry->hasAttribute("src")) {
402 if ($entry->parentNode
&& $entry->parentNode
->parentNode
) {
403 $entry->parentNode
->parentNode
->removeChild($entry->parentNode
);
411 function hook_article_filter($article) {
413 if (strpos($article["link"], "reddit.com/r/") !== FALSE) {
414 $doc = new DOMDocument();
415 @$doc->loadHTML($article["content"]);
416 $xpath = new DOMXPath($doc);
418 $content_link = $xpath->query("(//a[contains(., '[link]')])")->item(0);
420 if ($this->host
->get($this, "enable_content_dupcheck")) {
423 $content_href = $content_link->getAttribute("href");
424 $entry_guid = $article["guid_hashed"];
425 $owner_uid = $article["owner_uid"];
427 if (DB_TYPE
== "pgsql") {
428 $interval_qpart = "date_entered < NOW() - INTERVAL '1 day'";
430 $interval_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY)";
433 $sth = $this->pdo
->prepare("SELECT COUNT(id) AS cid
434 FROM ttrss_entries, ttrss_user_entries WHERE
441 $sth->execute([$entry_guid, $owner_uid, "%href=\"$content_href\">[link]%"]);
443 if ($row = $sth->fetch()) {
444 $num_found = $row['cid'];
446 if ($num_found > 0) $article["force_catchup"] = true;
451 $found = $this->inline_stuff($article, $doc, $xpath);
453 $node = $doc->getElementsByTagName('body')->item(0);
455 if ($node && $found) {
456 $article["content"] = $doc->saveHTML($node);
457 } else if ($content_link) {
458 $article = $this->readability($article, $content_link->getAttribute("href"), $doc, $xpath);
465 function api_version() {
469 private function handle_as_video($doc, $entry, $source_stream, $poster_url = false, $debug = false) {
471 _debug("handle_as_video: $source_stream", $debug);
473 $video = $doc->createElement('video');
474 $video->setAttribute("autoplay", "1");
475 $video->setAttribute("controls", "1");
476 $video->setAttribute("loop", "1");
478 if ($poster_url) $video->setAttribute("poster", $poster_url);
480 $source = $doc->createElement('source');
481 $source->setAttribute("src", $source_stream);
482 $source->setAttribute("type", "video/mp4");
484 $video->appendChild($source);
486 $br = $doc->createElement('br');
487 $entry->parentNode
->insertBefore($video, $entry);
488 $entry->parentNode
->insertBefore($br, $entry);
490 $img = $doc->createElement('img');
491 $img->setAttribute("src",
492 "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D");
494 $entry->parentNode
->insertBefore($img, $entry);
498 $url = htmlspecialchars($_REQUEST["url"]);
500 header("Content-type: text/plain");
504 $doc = new DOMDocument();
505 @$doc->loadHTML("<html><body><a href=\"$url\">[link]</a></body>");
506 $xpath = new DOMXPath($doc);
508 $found = $this->inline_stuff([], $doc, $xpath, true);
510 print "Inline result: $found\n";
513 print "\nReadability result:\n";
515 $article = $this->readability([], $url, $doc, $xpath, true);
519 print "\nResulting HTML:\n";
521 print $doc->saveHTML();
525 private function get_header($url, $useragent = SELF_USER_AGENT
, $header) {
528 if (function_exists("curl_init") && !defined("NO_CURL")) {
529 $ch = curl_init($url);
530 curl_setopt($ch, CURLOPT_TIMEOUT
, 5);
531 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
532 curl_setopt($ch, CURLOPT_HEADER
, true);
533 curl_setopt($ch, CURLOPT_NOBODY
, true);
534 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, !ini_get("open_basedir"));
535 curl_setopt($ch, CURLOPT_USERAGENT
, $useragent);
538 $ret = curl_getinfo($ch, $header);
544 private function get_content_type($url, $useragent = SELF_USER_AGENT
) {
545 return $this->get_header($url, $useragent, CURLINFO_CONTENT_TYPE
);
548 private function get_location($url, $useragent = SELF_USER_AGENT
) {
549 return $this->get_header($url, $useragent, CURLINFO_EFFECTIVE_URL
);
553 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
555 private function readability($article, $url, $doc, $xpath, $debug = false) {
557 if (!defined('NO_CURL') && function_exists("curl_init") && $this->host
->get($this, "enable_readability") &&
558 mb_strlen(strip_tags($article["content"])) <= 150) {
560 if (!class_exists("Readability")) require_once(dirname(dirname(__DIR__
)). "/lib/readability/Readability.php");
562 // do not try to embed posts linking back to other reddit posts
563 if ($url && strpos($url, "reddit.com") === FALSE) {
565 /* link may lead to a huge video file or whatever, we need to check content type before trying to
566 parse it which p much requires curl */
568 $useragent_compat = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
570 $content_type = $this->get_content_type($url, $useragent_compat);
572 if ($content_type && strpos($content_type, "text/html") !== FALSE) {
574 $tmp = fetch_file_contents(["url" => $url,
575 "useragent" => $useragent_compat,
576 "http_accept" => "text/html"]);
578 if ($debug) _debug("tmplen: " . mb_strlen($tmp));
580 if ($tmp && mb_strlen($tmp) < 1024 * 500) {
582 $r = new Readability(new Configuration());
585 if ($r->parse($tmp)) {
587 $tmpxpath = new DOMXPath($r->getDOMDocument());
589 $entries = $tmpxpath->query('(//a[@href]|//img[@src])');
591 foreach ($entries as $entry) {
592 if ($entry->hasAttribute("href")) {
593 $entry->setAttribute("href",
594 rewrite_relative_url($url, $entry->getAttribute("href")));
598 if ($entry->hasAttribute("src")) {
599 $entry->setAttribute("src",
600 rewrite_relative_url($url, $entry->getAttribute("src")));
606 $article["content"] = $r->getContent() . "<hr/>" . $article["content"];
608 } catch (ParseException
$e) {