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