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