]> git.wh0rd.org - tt-rss.git/blob - plugins/af_redditimgur/init.php
af_redditimgur updates:
[tt-rss.git] / plugins / af_redditimgur / init.php
1 <?php
2 class Af_RedditImgur extends Plugin {
3
4 /* @var PluginHost $host */
5 private $host;
6
7 function about() {
8 return array(1.0,
9 "Inline images (and other content) in Reddit RSS feeds",
10 "fox");
11 }
12
13 function flags() {
14 return array("needs_curl" => true);
15 }
16
17 function init($host) {
18 $this->host = $host;
19
20 $host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
21 $host->add_hook($host::HOOK_PREFS_TAB, $this);
22 }
23
24 function hook_prefs_tab($args) {
25 if ($args != "prefFeeds") return;
26
27 print "<div dojoType=\"dijit.layout.AccordionPane\" title=\"".__('Reddit content settings (af_redditimgur)')."\">";
28
29 $enable_readability = $this->host->get($this, "enable_readability");
30 $enable_content_dupcheck = $this->host->get($this, "enable_content_dupcheck");
31
32 print "<form dojoType=\"dijit.form.Form\">";
33
34 print "<script type=\"dojo/method\" event=\"onSubmit\" args=\"evt\">
35 evt.preventDefault();
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);
42 }
43 });
44 //this.reset();
45 }
46 </script>";
47
48 print_hidden("op", "pluginhandler");
49 print_hidden("method", "save");
50 print_hidden("plugin", "af_redditimgur");
51
52 print "<p>" . __("Uses Readability (full-text-rss) implementation by <a target='_blank' href='https://bitbucket.org/fivefilters/'>FiveFilters.org</a>");
53 print "<p/>";
54
55 print_checkbox("enable_readability", $enable_readability);
56 print "&nbsp;<label for=\"enable_readability\">" . __("Extract missing content using Readability") . "</label>";
57
58 print "<br/>";
59
60 print_checkbox("enable_content_dupcheck", $enable_content_dupcheck);
61 print "&nbsp;<label for=\"enable_content_dupcheck\">" . __("Enable additional duplicate checking") . "</label>";
62 print "<p>"; print_button("submit", __("Save"));
63 print "</form>";
64
65 print "</div>";
66 }
67
68 function save() {
69 $enable_readability = checkbox_to_sql_bool($_POST["enable_readability"]);
70 $enable_content_dupcheck = checkbox_to_sql_bool($_POST["enable_content_dupcheck"]);
71
72 $this->host->set($this, "enable_readability", $enable_readability, false);
73 $this->host->set($this, "enable_content_dupcheck", $enable_content_dupcheck);
74
75 echo __("Configuration saved");
76 }
77
78 /**
79 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
80 */
81 private function inline_stuff($article, &$doc, $xpath, $debug = false) {
82
83 $entries = $xpath->query('(//a[@href]|//img[@src])');
84 $img_entries = $xpath->query("(//img[@src])");
85
86 $found = false;
87 //$debug = 1;
88
89 foreach ($entries as $entry) {
90 if ($entry->hasAttribute("href") && strpos($entry->getAttribute("href"), "reddit.com") === FALSE) {
91
92 _debug("processing href: " . $entry->getAttribute("href"), $debug);
93
94 $matches = array();
95
96 if (!$found && preg_match("/^https?:\/\/twitter.com\/(.*?)\/status\/(.*)/", $entry->getAttribute("href"), $matches)) {
97 _debug("handling as twitter: " . $matches[1] . " " . $matches[2], $debug);
98
99 $oembed_result = fetch_file_contents("https://publish.twitter.com/oembed?url=" . urlencode($entry->getAttribute("href")));
100
101 if ($oembed_result) {
102 $oembed_result = json_decode($oembed_result, true);
103
104 if ($oembed_result && isset($oembed_result["html"])) {
105
106 $tmp = new DOMDocument();
107 if ($tmp->loadHTML('<?xml encoding="utf-8" ?>' . $oembed_result["html"])) {
108 $p = $doc->createElement("p");
109
110 $p->appendChild($doc->importNode(
111 $tmp->getElementsByTagName("blockquote")->item(0), TRUE));
112
113 $br = $doc->createElement('br');
114 $entry->parentNode->insertBefore($p, $entry);
115 $entry->parentNode->insertBefore($br, $entry);
116
117 $found = 1;
118 }
119 }
120 }
121 }
122
123 if (!$found && preg_match("/\.gfycat.com\/([a-z]+)?(\.[a-z]+)$/i", $entry->getAttribute("href"), $matches)) {
124 $entry->setAttribute("href", "http://www.gfycat.com/".$matches[1]);
125 }
126
127 if (!$found && preg_match("/https?:\/\/(www\.)?gfycat.com\/([a-z]+)$/i", $entry->getAttribute("href"), $matches)) {
128
129 _debug("Handling as Gfycat", $debug);
130
131 $tmp = fetch_file_contents($entry->getAttribute("href"));
132
133 if ($tmp) {
134 $tmpdoc = new DOMDocument();
135
136 if (@$tmpdoc->loadHTML($tmp)) {
137 $tmpxpath = new DOMXPath($tmpdoc);
138
139 $source_node = $tmpxpath->query("//video[contains(@class,'share-video')]//source[contains(@src, '.mp4')]")->item(0);
140 $poster_node = $tmpxpath->query("//video[contains(@class,'share-video') and @poster]")->item(0);
141
142 if ($source_node && $poster_node) {
143 $source_stream = $source_node->getAttribute("src");
144 $poster_url = $poster_node->getAttribute("poster");
145
146 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
147 $found = 1;
148 }
149 }
150 }
151 }
152
153 if (!$found && preg_match("/https?:\/\/v\.redd\.it\/(.*)$/i", $entry->getAttribute("href"), $matches)) {
154
155 _debug("Handling as reddit inline video", $debug);
156
157 $img = $img_entries->item(0);
158
159 if ($img) {
160 $poster_url = $img->getAttribute("src");
161 } else {
162 $poster_url = false;
163 }
164
165 // Get original article URL from v.redd.it redirects
166 $source_article_url = $this->get_location($matches[0]);
167 _debug("Resolved ".$matches[0]." to ".$source_article_url, $debug);
168
169 $source_stream = false;
170
171 if ($source_article_url) {
172 $j = json_decode(fetch_file_contents($source_article_url.".json"), true);
173
174 if ($j) {
175 foreach ($j as $listing) {
176 foreach ($listing["data"]["children"] as $child) {
177 if ($child["data"]["url"] == $matches[0]) {
178 try {
179 $source_stream = $child["data"]["media"]["reddit_video"]["fallback_url"];
180 }
181 catch (Exception $e) {
182 }
183 break 2;
184 }
185 }
186 }
187 }
188 }
189
190 if (!$source_stream) {
191 $source_stream = "https://v.redd.it/" . $matches[1] . "/DASH_600_K";
192 }
193
194 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
195 $found = 1;
196 }
197
198 if (!$found && preg_match("/https?:\/\/(www\.)?streamable.com\//i", $entry->getAttribute("href"))) {
199
200 _debug("Handling as Streamable", $debug);
201
202 $tmp = fetch_file_contents($entry->getAttribute("href"));
203
204 if ($tmp) {
205 $tmpdoc = new DOMDocument();
206
207 if (@$tmpdoc->loadHTML($tmp)) {
208 $tmpxpath = new DOMXPath($tmpdoc);
209
210 $source_node = $tmpxpath->query("//video[contains(@class,'video-player-tag')]//source[contains(@src, '.mp4')]")->item(0);
211 $poster_node = $tmpxpath->query("//video[contains(@class,'video-player-tag') and @poster]")->item(0);
212
213 if ($source_node && $poster_node) {
214 $source_stream = $source_node->getAttribute("src");
215 $poster_url = $poster_node->getAttribute("poster");
216
217 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
218 $found = 1;
219 }
220 }
221 }
222 }
223
224 // imgur .gif -> .gifv
225 if (!$found && preg_match("/i\.imgur\.com\/(.*?)\.gif$/i", $entry->getAttribute("href"))) {
226 _debug("Handling as imgur gif (->gifv)", $debug);
227
228 $entry->setAttribute("href",
229 str_replace(".gif", ".gifv", $entry->getAttribute("href")));
230 }
231
232 if (!$found && preg_match("/\.(gifv|mp4)$/i", $entry->getAttribute("href"))) {
233 _debug("Handling as imgur gifv", $debug);
234
235 $source_stream = str_replace(".gifv", ".mp4", $entry->getAttribute("href"));
236
237 if (strpos($source_stream, "imgur.com") !== FALSE)
238 $poster_url = str_replace(".mp4", "h.jpg", $source_stream);
239
240 $this->handle_as_video($doc, $entry, $source_stream, $poster_url, $debug);
241
242 $found = true;
243 }
244
245 $matches = array();
246 if (!$found && preg_match("/youtube\.com\/v\/([\w-]+)/", $entry->getAttribute("href"), $matches) ||
247 preg_match("/youtube\.com\/.*?[\&\?]v=([\w-]+)/", $entry->getAttribute("href"), $matches) ||
248 preg_match("/youtube\.com\/watch\?v=([\w-]+)/", $entry->getAttribute("href"), $matches) ||
249 preg_match("/\/\/youtu.be\/([\w-]+)/", $entry->getAttribute("href"), $matches)) {
250
251 $vid_id = $matches[1];
252
253 _debug("Handling as youtube: $vid_id", $debug);
254
255 $iframe = $doc->createElement("iframe");
256 $iframe->setAttribute("class", "youtube-player");
257 $iframe->setAttribute("type", "text/html");
258 $iframe->setAttribute("width", "640");
259 $iframe->setAttribute("height", "385");
260 $iframe->setAttribute("src", "https://www.youtube.com/embed/$vid_id");
261 $iframe->setAttribute("allowfullscreen", "1");
262 $iframe->setAttribute("frameborder", "0");
263
264 $br = $doc->createElement('br');
265 $entry->parentNode->insertBefore($iframe, $entry);
266 $entry->parentNode->insertBefore($br, $entry);
267
268 $found = true;
269 }
270
271 if (!$found && preg_match("/\.(jpg|jpeg|gif|png)(\?[0-9][0-9]*)?$/i", $entry->getAttribute("href")) ||
272 mb_strpos($entry->getAttribute("href"), "i.reddituploads.com") !== FALSE ||
273 mb_strpos($this->get_content_type($entry->getAttribute("href")), "image/") !== FALSE) {
274
275 _debug("Handling as a picture", $debug);
276
277 $img = $doc->createElement('img');
278 $img->setAttribute("src", $entry->getAttribute("href"));
279
280 $br = $doc->createElement('br');
281 $entry->parentNode->insertBefore($img, $entry);
282 $entry->parentNode->insertBefore($br, $entry);
283
284 $found = true;
285 }
286
287 // linked albums & pages
288
289 /*if (!$found && preg_match("/^https?:\/\/(m\.)?imgur.com\/([^\.\/]+$)/", $entry->getAttribute("href"), $matches) ||
290 preg_match("/^https?:\/\/(m\.)?imgur.com\/(a|album|gallery)\/[^\.]+$/", $entry->getAttribute("href"), $matches)) {
291
292 _debug("Handling as an imgur page/album/gallery", $debug);
293
294 $album_content = fetch_file_contents($entry->getAttribute("href"),
295 false, false, false, false, 10);
296
297 if ($album_content) {
298 $adoc = new DOMDocument();
299
300 if (@$adoc->loadHTML($album_content)) {
301 $axpath = new DOMXPath($adoc);
302
303 $aentries = $axpath->query("(//div[@class='post-image']/img[@src] | //a[@class='zoom']/img[@src] | //div[@class='video-elements']/source)");
304 $urls = [];
305
306 foreach ($aentries as $aentry) {
307
308 $url = $aentry->getAttribute("src");
309
310 if (!in_array($url, $urls)) {
311
312 if ($aentry->tagName == "img") {
313
314 $img = $doc->createElement('img');
315 $img->setAttribute("src", $url);
316 $entry->parentNode->insertBefore($doc->createElement('br'), $entry);
317
318 $br = $doc->createElement('br');
319
320 $entry->parentNode->insertBefore($img, $entry);
321 $entry->parentNode->insertBefore($br, $entry);
322 } else if ($aentry->tagName == "source") {
323
324 if (strpos($url, "imgur.com") !== FALSE)
325 $poster_url = str_replace(".mp4", "h.jpg", $url);
326 else
327 $poster_url = "";
328
329 $this->handle_as_video($doc, $entry, $url, $poster_url);
330
331 }
332
333 array_push($urls, $url);
334
335 $found = true;
336 }
337
338 }
339
340 if ($debug) print_r($urls);
341 }
342 }
343 } */
344
345 // wtf is this even
346 if (!$found && preg_match("/^https?:\/\/gyazo\.com\/([^\.\/]+$)/", $entry->getAttribute("href"), $matches)) {
347 $img_id = $matches[1];
348
349 _debug("handling as gyazo: $img_id", $debug);
350
351 $img = $doc->createElement('img');
352 $img->setAttribute("src", "https://i.gyazo.com/$img_id.jpg");
353
354 $br = $doc->createElement('br');
355 $entry->parentNode->insertBefore($img, $entry);
356 $entry->parentNode->insertBefore($br, $entry);
357
358 $found = true;
359 }
360
361 // let's try meta properties
362 if (!$found) {
363 _debug("looking for meta og:image", $debug);
364
365 $content = fetch_file_contents(["url" => $entry->getAttribute("href"),
366 "http_accept" => "text/*"]);
367
368 if ($content) {
369 $cdoc = new DOMDocument();
370
371 if (@$cdoc->loadHTML($content)) {
372 $cxpath = new DOMXPath($cdoc);
373
374 $og_image = $cxpath->query("//meta[@property='og:image']")->item(0);
375
376 if ($og_image) {
377
378 $og_src = $og_image->getAttribute("content");
379
380 if ($og_src) {
381 $img = $doc->createElement('img');
382 $img->setAttribute("src", $og_src);
383
384 $br = $doc->createElement('br');
385 $entry->parentNode->insertBefore($img, $entry);
386 $entry->parentNode->insertBefore($br, $entry);
387
388 $found = true;
389 }
390 }
391 }
392 }
393 }
394
395 }
396
397 // remove tiny thumbnails
398 if ($entry->hasAttribute("src")) {
399 if ($entry->parentNode && $entry->parentNode->parentNode) {
400 $entry->parentNode->parentNode->removeChild($entry->parentNode);
401 }
402 }
403 }
404
405 return $found;
406 }
407
408 function hook_article_filter($article) {
409
410 if (strpos($article["link"], "reddit.com/r/") !== FALSE) {
411 $doc = new DOMDocument();
412 @$doc->loadHTML($article["content"]);
413 $xpath = new DOMXPath($doc);
414
415 $content_link = $xpath->query("(//a[contains(., '[link]')])")->item(0);
416
417 if ($this->host->get($this, "enable_content_dupcheck")) {
418
419 if ($content_link) {
420 $content_href = $content_link->getAttribute("href");
421 $entry_guid = $article["guid_hashed"];
422 $owner_uid = $article["owner_uid"];
423
424 if (DB_TYPE == "pgsql") {
425 $interval_qpart = "date_entered < NOW() - INTERVAL '1 day'";
426 } else {
427 $interval_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY)";
428 }
429
430 $sth = $this->pdo->prepare("SELECT COUNT(id) AS cid
431 FROM ttrss_entries, ttrss_user_entries WHERE
432 ref_id = id AND
433 $interval_qpart AND
434 guid != ? AND
435 owner_uid = ? AND
436 content LIKE ?");
437
438 $sth->execute([$entry_guid, $owner_uid, "%href=\"$content_href\">[link]%"]);
439
440 if ($row = $sth->fetch()) {
441 $num_found = $row['cid'];
442
443 if ($num_found > 0) $article["force_catchup"] = true;
444 }
445 }
446 }
447
448 $found = $this->inline_stuff($article, $doc, $xpath);
449
450 $node = $doc->getElementsByTagName('body')->item(0);
451
452 if ($node && $found) {
453 $article["content"] = $doc->saveHTML($node);
454 } else if ($content_link) {
455 $article = $this->readability($article, $content_link->getAttribute("href"), $doc, $xpath);
456 }
457 }
458
459 return $article;
460 }
461
462 function api_version() {
463 return 2;
464 }
465
466 private function handle_as_video($doc, $entry, $source_stream, $poster_url = false, $debug = false) {
467
468 _debug("handle_as_video: $source_stream", $debug);
469
470 $video = $doc->createElement('video');
471 $video->setAttribute("autoplay", "1");
472 $video->setAttribute("controls", "1");
473 $video->setAttribute("loop", "1");
474
475 if ($poster_url) $video->setAttribute("poster", $poster_url);
476
477 $source = $doc->createElement('source');
478 $source->setAttribute("src", $source_stream);
479 $source->setAttribute("type", "video/mp4");
480
481 $video->appendChild($source);
482
483 $br = $doc->createElement('br');
484 $entry->parentNode->insertBefore($video, $entry);
485 $entry->parentNode->insertBefore($br, $entry);
486
487 $img = $doc->createElement('img');
488 $img->setAttribute("src",
489 "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D");
490
491 $entry->parentNode->insertBefore($img, $entry);
492 }
493
494 function testurl() {
495 $url = htmlspecialchars($_REQUEST["url"]);
496
497 header("Content-type: text/plain");
498
499 print "URL: $url\n";
500
501 $doc = new DOMDocument();
502 @$doc->loadHTML("<html><body><a href=\"$url\">[link]</a></body>");
503 $xpath = new DOMXPath($doc);
504
505 $found = $this->inline_stuff([], $doc, $xpath, true);
506
507 print "Inline result: $found\n";
508
509 if (!$found) {
510 print "\nReadability result:\n";
511
512 $article = $this->readability([], $url, $doc, $xpath, true);
513
514 print_r($article);
515 } else {
516 print "\nResulting HTML:\n";
517
518 print $doc->saveHTML();
519 }
520 }
521
522 private function get_header($url, $useragent = SELF_USER_AGENT, $header) {
523 $ret = false;
524
525 if (function_exists("curl_init") && !defined("NO_CURL")) {
526 $ch = curl_init($url);
527 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
528 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
529 curl_setopt($ch, CURLOPT_HEADER, true);
530 curl_setopt($ch, CURLOPT_NOBODY, true);
531 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("open_basedir"));
532 curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
533
534 @curl_exec($ch);
535 $ret = curl_getinfo($ch, $header);
536 }
537
538 return $ret;
539 }
540
541 private function get_content_type($url, $useragent = SELF_USER_AGENT) {
542 return $this->get_header($url, $useragent, CURLINFO_CONTENT_TYPE);
543 }
544
545 private function get_location($url, $useragent = SELF_USER_AGENT) {
546 return $this->get_header($url, $useragent, CURLINFO_EFFECTIVE_URL);
547 }
548
549 /**
550 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
551 */
552 private function readability($article, $url, $doc, $xpath, $debug = false) {
553
554 if (!defined('NO_CURL') && function_exists("curl_init") && $this->host->get($this, "enable_readability") &&
555 mb_strlen(strip_tags($article["content"])) <= 150) {
556
557 if (!class_exists("Readability")) require_once(dirname(dirname(__DIR__)). "/lib/readability/Readability.php");
558
559 if ($url &&
560 strpos($url, "twitter.com") === FALSE &&
561 strpos($url, "youtube.com") === FALSE &&
562 strpos($url, "reddit.com") === FALSE) {
563
564 /* link may lead to a huge video file or whatever, we need to check content type before trying to
565 parse it which p much requires curl */
566
567 $useragent_compat = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
568
569 $content_type = $this->get_content_type($url, $useragent_compat);
570
571 if ($content_type && strpos($content_type, "text/html") !== FALSE) {
572
573 $tmp = fetch_file_contents(["url" => $url,
574 "useragent" => $useragent_compat,
575 "http_accept" => "text/html"]);
576
577 if ($debug) _debug("tmplen: " . mb_strlen($tmp));
578
579 if ($tmp && mb_strlen($tmp) < 1024 * 500) {
580
581 $r = new Readability($tmp, $url);
582
583 if ($r->init()) {
584
585 $tmpxpath = new DOMXPath($r->dom);
586
587 $entries = $tmpxpath->query('(//a[@href]|//img[@src])');
588
589 foreach ($entries as $entry) {
590 if ($entry->hasAttribute("href")) {
591 $entry->setAttribute("href",
592 rewrite_relative_url($url, $entry->getAttribute("href")));
593
594 }
595
596 if ($entry->hasAttribute("src")) {
597 $entry->setAttribute("src",
598 rewrite_relative_url($url, $entry->getAttribute("src")));
599
600 }
601
602 }
603
604 $article["content"] = $r->articleContent->innerHTML . "<hr/>" . $article["content"];
605 }
606 }
607 }
608 }
609 }
610
611 return $article;
612 }
613 }