]> git.wh0rd.org - tt-rss.git/blame - plugins/af_redditimgur/init.php
use catchall exception handler for readability
[tt-rss.git] / plugins / af_redditimgur / init.php
CommitLineData
cc85704f 1<?php
b22766fc
AD
2use andreskrey\Readability\Readability;
3use andreskrey\Readability\Configuration;
4
0862a602 5class Af_RedditImgur extends Plugin {
11d1a8a6
AD
6
7 /* @var PluginHost $host */
19c73507
AD
8 private $host;
9
d2a421e3 10 function about() {
7a866114 11 return array(1.0,
a95fb169 12 "Inline images (and other content) in Reddit RSS feeds",
7a866114
AD
13 "fox");
14 }
15
41245888
AD
16 function flags() {
17 return array("needs_curl" => true);
18 }
19
d2a421e3 20 function init($host) {
19c73507
AD
21 $this->host = $host;
22
23 $host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
b90c4468
AD
24 $host->add_hook($host::HOOK_PREFS_TAB, $this);
25 }
26
27 function hook_prefs_tab($args) {
28 if ($args != "prefFeeds") return;
29
dc8bd8a6 30 print "<div dojoType=\"dijit.layout.AccordionPane\" title=\"".__('Reddit content settings (af_redditimgur)')."\">";
b90c4468
AD
31
32 $enable_readability = $this->host->get($this, "enable_readability");
891b77f9 33 $enable_content_dupcheck = $this->host->get($this, "enable_content_dupcheck");
8788698b 34
6d95e535
AD
35 if (version_compare(PHP_VERSION, '5.6.0', '<')) {
36 print_error("Readability requires PHP version 5.6.");
37 }
38
b90c4468
AD
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
328118d1
AD
55 print_hidden("op", "pluginhandler");
56 print_hidden("method", "save");
57 print_hidden("plugin", "af_redditimgur");
b90c4468 58
dc8bd8a6
AD
59 print_checkbox("enable_readability", $enable_readability);
60 print "&nbsp;<label for=\"enable_readability\">" . __("Extract missing content using Readability") . "</label>";
b90c4468 61
891b77f9 62 print "<br/>";
8788698b 63
dc8bd8a6
AD
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"));
b90c4468
AD
67 print "</form>";
68
69 print "</div>";
70 }
71
72 function save() {
da9ea57d
AD
73 $enable_readability = checkbox_to_sql_bool($_POST["enable_readability"]);
74 $enable_content_dupcheck = checkbox_to_sql_bool($_POST["enable_content_dupcheck"]);
4533b3ef 75
891b77f9
AD
76 $this->host->set($this, "enable_readability", $enable_readability, false);
77 $this->host->set($this, "enable_content_dupcheck", $enable_content_dupcheck);
b90c4468
AD
78
79 echo __("Configuration saved");
19c73507
AD
80 }
81
21ce7d9e
AD
82 /**
83 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
84 */
ec482d28 85 private function inline_stuff($article, &$doc, $xpath, $debug = false) {
cc85704f 86
6322fc68 87 $entries = $xpath->query('(//a[@href]|//img[@src])');
06a19166 88 $img_entries = $xpath->query("(//img[@src])");
cc85704f 89
6322fc68 90 $found = false;
b70c3daf 91 //$debug = 1;
ce7d5e87 92
6322fc68 93 foreach ($entries as $entry) {
b70c3daf 94 if ($entry->hasAttribute("href") && strpos($entry->getAttribute("href"), "reddit.com") === FALSE) {
299aeb30 95
ec482d28
AD
96 _debug("processing href: " . $entry->getAttribute("href"), $debug);
97
6322fc68 98 $matches = array();
5d429910 99
b70c3daf 100 if (!$found && preg_match("/^https?:\/\/twitter.com\/(.*?)\/status\/(.*)/", $entry->getAttribute("href"), $matches)) {
8788698b
AD
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();
48007463 111 if ($tmp->loadHTML('<?xml encoding="utf-8" ?>' . $oembed_result["html"])) {
8788698b
AD
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
43db5b99 127 if (!$found && preg_match("/\.gfycat.com\/([a-z]+)?(\.[a-z]+)$/i", $entry->getAttribute("href"), $matches)) {
5f297a5c
AD
128 $entry->setAttribute("href", "http://www.gfycat.com/".$matches[1]);
129 }
130
43db5b99 131 if (!$found && preg_match("/https?:\/\/(www\.)?gfycat.com\/([a-z]+)$/i", $entry->getAttribute("href"), $matches)) {
5d429910 132
ec482d28
AD
133 _debug("Handling as Gfycat", $debug);
134
6322fc68 135 $tmp = fetch_file_contents($entry->getAttribute("href"));
5d429910 136
6322fc68
AD
137 if ($tmp) {
138 $tmpdoc = new DOMDocument();
5d429910 139
58a44ecb 140 if (@$tmpdoc->loadHTML($tmp)) {
6322fc68 141 $tmpxpath = new DOMXPath($tmpdoc);
b8887ebb 142
46506d3f
AD
143 $source_node = $tmpxpath->query("//video[contains(@class,'share-video')]//source[contains(@src, '.mp4')]")->item(0);
144 $poster_node = $tmpxpath->query("//video[contains(@class,'share-video') and @poster]")->item(0);
5d429910 145
46506d3f
AD
146 if ($source_node && $poster_node) {
147 $source_stream = $source_node->getAttribute("src");
148 $poster_url = $poster_node->getAttribute("poster");
5d429910 149
46506d3f
AD
150 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
151 $found = 1;
5d429910 152 }
6322fc68
AD
153 }
154 }
6322fc68 155 }
98e20510 156
06a19166
AD
157 if (!$found && preg_match("/https?:\/\/v\.redd\.it\/(.*)$/i", $entry->getAttribute("href"), $matches)) {
158
159 _debug("Handling as reddit inline video", $debug);
160
161 $img = $img_entries->item(0);
162
163 if ($img) {
164 $poster_url = $img->getAttribute("src");
165 } else {
166 $poster_url = false;
167 }
168
8352d7c6 169 // Get original article URL from v.redd.it redirects
170 $source_article_url = $this->get_location($matches[0]);
171 _debug("Resolved ".$matches[0]." to ".$source_article_url, $debug);
172
81d83a68 173 $source_stream = false;
8352d7c6 174
175 if ($source_article_url) {
176 $j = json_decode(fetch_file_contents($source_article_url.".json"), true);
177
178 if ($j) {
179 foreach ($j as $listing) {
180 foreach ($listing["data"]["children"] as $child) {
181 if ($child["data"]["url"] == $matches[0]) {
182 try {
183 $source_stream = $child["data"]["media"]["reddit_video"]["fallback_url"];
184 }
185 catch (Exception $e) {
186 }
187 break 2;
81d83a68 188 }
81d83a68 189 }
190 }
191 }
192 }
193
194 if (!$source_stream) {
195 $source_stream = "https://v.redd.it/" . $matches[1] . "/DASH_600_K";
196 }
06a19166
AD
197
198 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
199 $found = 1;
200 }
201
60e97d9e
AD
202 if (!$found && preg_match("/https?:\/\/(www\.)?streamable.com\//i", $entry->getAttribute("href"))) {
203
204 _debug("Handling as Streamable", $debug);
205
206 $tmp = fetch_file_contents($entry->getAttribute("href"));
207
208 if ($tmp) {
209 $tmpdoc = new DOMDocument();
210
211 if (@$tmpdoc->loadHTML($tmp)) {
212 $tmpxpath = new DOMXPath($tmpdoc);
213
214 $source_node = $tmpxpath->query("//video[contains(@class,'video-player-tag')]//source[contains(@src, '.mp4')]")->item(0);
215 $poster_node = $tmpxpath->query("//video[contains(@class,'video-player-tag') and @poster]")->item(0);
216
217 if ($source_node && $poster_node) {
218 $source_stream = $source_node->getAttribute("src");
219 $poster_url = $poster_node->getAttribute("poster");
220
221 $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
222 $found = 1;
223 }
224 }
225 }
226 }
227
5f297a5c 228 // imgur .gif -> .gifv
43db5b99 229 if (!$found && preg_match("/i\.imgur\.com\/(.*?)\.gif$/i", $entry->getAttribute("href"))) {
ec482d28
AD
230 _debug("Handling as imgur gif (->gifv)", $debug);
231
5f297a5c
AD
232 $entry->setAttribute("href",
233 str_replace(".gif", ".gifv", $entry->getAttribute("href")));
234 }
235
8c395462 236 if (!$found && preg_match("/\.(gifv|mp4)$/i", $entry->getAttribute("href"))) {
ec482d28 237 _debug("Handling as imgur gifv", $debug);
5d429910 238
6322fc68 239 $source_stream = str_replace(".gifv", ".mp4", $entry->getAttribute("href"));
b8887ebb 240
49048482 241 if (strpos($source_stream, "imgur.com") !== FALSE)
b8887ebb
AD
242 $poster_url = str_replace(".mp4", "h.jpg", $source_stream);
243
ec482d28 244 $this->handle_as_video($doc, $entry, $source_stream, $poster_url, $debug);
98e20510 245
6322fc68
AD
246 $found = true;
247 }
9875d717 248
6322fc68 249 $matches = array();
43db5b99 250 if (!$found && preg_match("/youtube\.com\/v\/([\w-]+)/", $entry->getAttribute("href"), $matches) ||
0a361964
AD
251 preg_match("/youtube\.com\/.*?[\&\?]v=([\w-]+)/", $entry->getAttribute("href"), $matches) ||
252 preg_match("/youtube\.com\/watch\?v=([\w-]+)/", $entry->getAttribute("href"), $matches) ||
6322fc68 253 preg_match("/\/\/youtu.be\/([\w-]+)/", $entry->getAttribute("href"), $matches)) {
3b9ca4e6 254
6322fc68 255 $vid_id = $matches[1];
3b9ca4e6 256
ec482d28
AD
257 _debug("Handling as youtube: $vid_id", $debug);
258
6322fc68
AD
259 $iframe = $doc->createElement("iframe");
260 $iframe->setAttribute("class", "youtube-player");
261 $iframe->setAttribute("type", "text/html");
262 $iframe->setAttribute("width", "640");
263 $iframe->setAttribute("height", "385");
264 $iframe->setAttribute("src", "https://www.youtube.com/embed/$vid_id");
265 $iframe->setAttribute("allowfullscreen", "1");
266 $iframe->setAttribute("frameborder", "0");
3b9ca4e6 267
6322fc68
AD
268 $br = $doc->createElement('br');
269 $entry->parentNode->insertBefore($iframe, $entry);
270 $entry->parentNode->insertBefore($br, $entry);
3b9ca4e6 271
6322fc68
AD
272 $found = true;
273 }
3b9ca4e6 274
43db5b99 275 if (!$found && preg_match("/\.(jpg|jpeg|gif|png)(\?[0-9][0-9]*)?$/i", $entry->getAttribute("href")) ||
90e45935
AD
276 mb_strpos($entry->getAttribute("href"), "i.reddituploads.com") !== FALSE ||
277 mb_strpos($this->get_content_type($entry->getAttribute("href")), "image/") !== FALSE) {
eb95d1bd 278
ec482d28
AD
279 _debug("Handling as a picture", $debug);
280
6322fc68
AD
281 $img = $doc->createElement('img');
282 $img->setAttribute("src", $entry->getAttribute("href"));
cc85704f 283
6322fc68
AD
284 $br = $doc->createElement('br');
285 $entry->parentNode->insertBefore($img, $entry);
286 $entry->parentNode->insertBefore($br, $entry);
ce7d5e87 287
6322fc68
AD
288 $found = true;
289 }
ce7d5e87 290
58a44ecb 291 // wtf is this even
43db5b99 292 if (!$found && preg_match("/^https?:\/\/gyazo\.com\/([^\.\/]+$)/", $entry->getAttribute("href"), $matches)) {
58a44ecb
AD
293 $img_id = $matches[1];
294
ec482d28
AD
295 _debug("handling as gyazo: $img_id", $debug);
296
58a44ecb
AD
297 $img = $doc->createElement('img');
298 $img->setAttribute("src", "https://i.gyazo.com/$img_id.jpg");
299
300 $br = $doc->createElement('br');
301 $entry->parentNode->insertBefore($img, $entry);
302 $entry->parentNode->insertBefore($br, $entry);
303
304 $found = true;
305 }
b70c3daf
AD
306
307 // let's try meta properties
308 if (!$found) {
309 _debug("looking for meta og:image", $debug);
310
311 $content = fetch_file_contents(["url" => $entry->getAttribute("href"),
312 "http_accept" => "text/*"]);
313
314 if ($content) {
315 $cdoc = new DOMDocument();
316
317 if (@$cdoc->loadHTML($content)) {
318 $cxpath = new DOMXPath($cdoc);
319
320 $og_image = $cxpath->query("//meta[@property='og:image']")->item(0);
321
322 if ($og_image) {
323
324 $og_src = $og_image->getAttribute("content");
325
326 if ($og_src) {
327 $img = $doc->createElement('img');
328 $img->setAttribute("src", $og_src);
329
330 $br = $doc->createElement('br');
331 $entry->parentNode->insertBefore($img, $entry);
332 $entry->parentNode->insertBefore($br, $entry);
333
334 $found = true;
335 }
336 }
337 }
338 }
339 }
340
6322fc68
AD
341 }
342
343 // remove tiny thumbnails
344 if ($entry->hasAttribute("src")) {
345 if ($entry->parentNode && $entry->parentNode->parentNode) {
346 $entry->parentNode->parentNode->removeChild($entry->parentNode);
347 }
348 }
349 }
cc85704f 350
6322fc68
AD
351 return $found;
352 }
b90c4468 353
6322fc68 354 function hook_article_filter($article) {
b90c4468 355
6322fc68
AD
356 if (strpos($article["link"], "reddit.com/r/") !== FALSE) {
357 $doc = new DOMDocument();
358 @$doc->loadHTML($article["content"]);
359 $xpath = new DOMXPath($doc);
99bb8b3b 360
582ff3cf
AD
361 $content_link = $xpath->query("(//a[contains(., '[link]')])")->item(0);
362
891b77f9 363 if ($this->host->get($this, "enable_content_dupcheck")) {
902b1ac7 364
891b77f9 365 if ($content_link) {
11d1a8a6
AD
366 $content_href = $content_link->getAttribute("href");
367 $entry_guid = $article["guid_hashed"];
891b77f9 368 $owner_uid = $article["owner_uid"];
902b1ac7 369
891b77f9
AD
370 if (DB_TYPE == "pgsql") {
371 $interval_qpart = "date_entered < NOW() - INTERVAL '1 day'";
372 } else {
373 $interval_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY)";
374 }
902b1ac7 375
11d1a8a6 376 $sth = $this->pdo->prepare("SELECT COUNT(id) AS cid
891b77f9
AD
377 FROM ttrss_entries, ttrss_user_entries WHERE
378 ref_id = id AND
379 $interval_qpart AND
11d1a8a6
AD
380 guid != ? AND
381 owner_uid = ? AND
382 content LIKE ?");
383
384 $sth->execute([$entry_guid, $owner_uid, "%href=\"$content_href\">[link]%"]);
902b1ac7 385
11d1a8a6
AD
386 if ($row = $sth->fetch()) {
387 $num_found = $row['cid'];
902b1ac7 388
891b77f9
AD
389 if ($num_found > 0) $article["force_catchup"] = true;
390 }
902b1ac7 391 }
891b77f9 392 }
4f5204dd 393
4533b3ef 394 $found = $this->inline_stuff($article, $doc, $xpath);
b90c4468 395
6322fc68
AD
396 $node = $doc->getElementsByTagName('body')->item(0);
397
398 if ($node && $found) {
f3774b9d 399 $article["content"] = $doc->saveHTML($node);
e487e92d
AD
400 } else if ($content_link) {
401 $article = $this->readability($article, $content_link->getAttribute("href"), $doc, $xpath);
6322fc68 402 }
cc85704f
AD
403 }
404
405 return $article;
406 }
106a3de9
AD
407
408 function api_version() {
409 return 2;
410 }
411
ec482d28
AD
412 private function handle_as_video($doc, $entry, $source_stream, $poster_url = false, $debug = false) {
413
414 _debug("handle_as_video: $source_stream", $debug);
5d429910
AD
415
416 $video = $doc->createElement('video');
417 $video->setAttribute("autoplay", "1");
5dcc7bf1 418 $video->setAttribute("controls", "1");
5d429910
AD
419 $video->setAttribute("loop", "1");
420
b8887ebb
AD
421 if ($poster_url) $video->setAttribute("poster", $poster_url);
422
5d429910
AD
423 $source = $doc->createElement('source');
424 $source->setAttribute("src", $source_stream);
425 $source->setAttribute("type", "video/mp4");
426
427 $video->appendChild($source);
428
429 $br = $doc->createElement('br');
430 $entry->parentNode->insertBefore($video, $entry);
431 $entry->parentNode->insertBefore($br, $entry);
432
433 $img = $doc->createElement('img');
434 $img->setAttribute("src",
435 "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D");
436
437 $entry->parentNode->insertBefore($img, $entry);
438 }
ec482d28
AD
439
440 function testurl() {
441 $url = htmlspecialchars($_REQUEST["url"]);
442
443 header("Content-type: text/plain");
444
445 print "URL: $url\n";
446
447 $doc = new DOMDocument();
448 @$doc->loadHTML("<html><body><a href=\"$url\">[link]</a></body>");
449 $xpath = new DOMXPath($doc);
450
e487e92d
AD
451 $found = $this->inline_stuff([], $doc, $xpath, true);
452
453 print "Inline result: $found\n";
454
455 if (!$found) {
456 print "\nReadability result:\n";
ec482d28 457
e487e92d 458 $article = $this->readability([], $url, $doc, $xpath, true);
ec482d28 459
e487e92d
AD
460 print_r($article);
461 } else {
462 print "\nResulting HTML:\n";
ec482d28 463
e487e92d
AD
464 print $doc->saveHTML();
465 }
ec482d28 466 }
90e45935 467
b4b5236e 468 private function get_header($url, $useragent = SELF_USER_AGENT, $header) {
469 $ret = false;
90e45935
AD
470
471 if (function_exists("curl_init") && !defined("NO_CURL")) {
472 $ch = curl_init($url);
473 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
474 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
475 curl_setopt($ch, CURLOPT_HEADER, true);
476 curl_setopt($ch, CURLOPT_NOBODY, true);
477 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("open_basedir"));
478 curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
479
21ce7d9e 480 @curl_exec($ch);
b4b5236e 481 $ret = curl_getinfo($ch, $header);
90e45935
AD
482 }
483
b4b5236e 484 return $ret;
90e45935 485 }
e487e92d 486
b4b5236e 487 private function get_content_type($url, $useragent = SELF_USER_AGENT) {
488 return $this->get_header($url, $useragent, CURLINFO_CONTENT_TYPE);
489 }
8352d7c6 490
b4b5236e 491 private function get_location($url, $useragent = SELF_USER_AGENT) {
492 return $this->get_header($url, $useragent, CURLINFO_EFFECTIVE_URL);
8352d7c6 493 }
494
21ce7d9e
AD
495 /**
496 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
497 */
e487e92d
AD
498 private function readability($article, $url, $doc, $xpath, $debug = false) {
499
500 if (!defined('NO_CURL') && function_exists("curl_init") && $this->host->get($this, "enable_readability") &&
501 mb_strlen(strip_tags($article["content"])) <= 150) {
502
b22766fc 503 // do not try to embed posts linking back to other reddit posts
6d95e535
AD
504 // readability.php requires PHP 5.6
505 if ($url && strpos($url, "reddit.com") === FALSE && version_compare(PHP_VERSION, '5.6.0', '>=')) {
e487e92d
AD
506
507 /* link may lead to a huge video file or whatever, we need to check content type before trying to
508 parse it which p much requires curl */
509
510 $useragent_compat = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
511
512 $content_type = $this->get_content_type($url, $useragent_compat);
513
514 if ($content_type && strpos($content_type, "text/html") !== FALSE) {
515
b70c3daf
AD
516 $tmp = fetch_file_contents(["url" => $url,
517 "useragent" => $useragent_compat,
518 "http_accept" => "text/html"]);
e487e92d
AD
519
520 if ($debug) _debug("tmplen: " . mb_strlen($tmp));
521
522 if ($tmp && mb_strlen($tmp) < 1024 * 500) {
523
b22766fc 524 $r = new Readability(new Configuration());
e487e92d 525
b22766fc
AD
526 try {
527 if ($r->parse($tmp)) {
e487e92d 528
b22766fc 529 $tmpxpath = new DOMXPath($r->getDOMDocument());
e487e92d 530
b22766fc 531 $entries = $tmpxpath->query('(//a[@href]|//img[@src])');
e487e92d 532
b22766fc
AD
533 foreach ($entries as $entry) {
534 if ($entry->hasAttribute("href")) {
535 $entry->setAttribute("href",
536 rewrite_relative_url($url, $entry->getAttribute("href")));
e487e92d 537
b22766fc 538 }
e487e92d 539
b22766fc
AD
540 if ($entry->hasAttribute("src")) {
541 $entry->setAttribute("src",
542 rewrite_relative_url($url, $entry->getAttribute("src")));
543
544 }
e487e92d
AD
545
546 }
547
b22766fc 548 $article["content"] = $r->getContent() . "<hr/>" . $article["content"];
e487e92d 549 }
c925f4e3 550 } catch (Exception $e) {
b22766fc 551 //
e487e92d
AD
552 }
553 }
554 }
555 }
556 }
557
558 return $article;
559 }
cc85704f 560}