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