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