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