summaryrefslogtreecommitdiff
path: root/init.php
diff options
context:
space:
mode:
authorAndrew Dolgov <[email protected]>2023-06-09 08:36:15 +0300
committerAndrew Dolgov <[email protected]>2023-06-09 08:36:15 +0300
commit0b15471029dab95dc48e94ecaa73cdd9acd6fbaf (patch)
treeeb47a42ec14ab800b0ffd0d6b1e475b0201b5f69 /init.php
initial
Diffstat (limited to 'init.php')
-rw-r--r--init.php441
1 files changed, 441 insertions, 0 deletions
diff --git a/init.php b/init.php
new file mode 100644
index 0000000..739c2c3
--- /dev/null
+++ b/init.php
@@ -0,0 +1,441 @@
+<?php
+class Af_Lemmy extends Plugin {
+
+ /** @var PluginHost $host */
+ private $host;
+
+ /** @var array<string> */
+ private $domain_blacklist = [ "github.com" ];
+
+ /** @var array<int, array<int, string|null>> */
+ private $generated_enclosures = [];
+
+ function about() {
+ return array(null,
+ "Inline images (and other content) in Lemmy.ml RSS feeds",
+ "fox");
+ }
+
+ function flags() {
+ return array("needs_curl" => true);
+ }
+
+ function init($host) {
+ $this->host = $host;
+
+ $host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
+ $host->add_hook($host::HOOK_PRE_SUBSCRIBE, $this);
+ }
+
+ function hook_pre_subscribe(&$url, $auth_login, $auth_pass) {
+
+ // TODO
+
+ return false;
+ }
+
+ /**
+ * @param array<string, mixed> $article
+ * @param DOMDocument $doc
+ * @param DOMXPath $xpath
+ * @return bool
+ * @throws PDOException
+ */
+ private function inline_stuff(array &$article, DOMDocument &$doc, DOMXpath $xpath, string $origin_domain) : bool {
+
+ $found = false;
+ $this->generated_enclosures = [];
+ $entries = $xpath->query('//a[@href]');
+
+ foreach ($entries as $entry) {
+ $entry_href = UrlHelper::rewrite_relative($article["link"], $entry->getAttribute("href"), "a");
+
+ $matches = [];
+
+ /* skip links going back to origin (and any other blacklisted stuff, including /u/user profiles, except for /pictrs) */
+ if (!$found &&
+ strpos($entry_href, "/pictrs/") === FALSE &&
+ (strpos($entry_href, "/u/") !== FALSE || $this->is_blacklisted($entry_href, [$origin_domain]))) {
+ Debug::log("BODY: URL $entry_href is blacklisted, skipping", Debug::LOG_EXTENDED);
+ continue;
+ }
+
+ Debug::log("BODY: processing URL: " . $entry_href, Debug::LOG_VERBOSE);
+
+ if (!$found && preg_match("/^https?:\/\/twitter.com\/(.*?)\/status\/(.*)/", $entry_href, $matches)) {
+ Debug::log("handling as twitter: " . $matches[1] . " " . $matches[2], Debug::LOG_VERBOSE);
+
+ $oembed_result = UrlHelper::fetch("https://publish.twitter.com/oembed?url=" . urlencode($entry_href));
+
+ if ($oembed_result) {
+ $oembed_result = json_decode($oembed_result, true);
+
+ if ($oembed_result && isset($oembed_result["html"])) {
+
+ $tmp = new DOMDocument();
+ if (@$tmp->loadHTML('<?xml encoding="utf-8" ?>' . $oembed_result["html"])) {
+ $p = $doc->createElement("p");
+
+ $p->appendChild($doc->importNode(
+ $tmp->getElementsByTagName("blockquote")->item(0), TRUE));
+
+ $br = $doc->createElement('br');
+ $entry->parentNode->insertBefore($p, $entry);
+ $entry->parentNode->insertBefore($br, $entry);
+
+ $found = 1;
+ }
+ }
+ }
+ }
+
+ if (!$found && preg_match("/\.gfycat.com\/([a-z]+)?(\.[a-z]+)$/i", $entry_href, $matches)) {
+ $entry->setAttribute("href", "http://www.gfycat.com/".$matches[1]);
+ }
+
+ if (!$found && preg_match("/https?:\/\/(www\.)?gfycat.com\/([a-z]+)$/i", $entry_href, $matches)) {
+
+ Debug::log("Handling as Gfycat", Debug::LOG_VERBOSE);
+
+ $source_stream = 'https://giant.gfycat.com/' . $matches[2] . '.mp4';
+ $poster_url = 'https://thumbs.gfycat.com/' . $matches[2] . '-mobile.jpg';
+
+ $content_type = $this->get_content_type($source_stream);
+
+ if (strpos($content_type, "video/") !== false) {
+ $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
+ $found = 1;
+ }
+ }
+
+ // imgur .gif -> .gifv
+ if (!$found && preg_match("/i\.imgur\.com\/(.*?)\.gif$/i", $entry_href)) {
+ Debug::log("Handling as imgur gif (->gifv)", Debug::LOG_VERBOSE);
+
+ $entry->setAttribute("href",
+ str_replace(".gif", ".gifv", $entry_href));
+ }
+
+ if (!$found && preg_match("/\.(gifv|mp4)$/i", $entry_href)) {
+ Debug::log("Handling as imgur gifv", Debug::LOG_VERBOSE);
+
+ $source_stream = str_replace(".gifv", ".mp4", $entry_href);
+
+ if (strpos($source_stream, "imgur.com") !== false)
+ $poster_url = str_replace(".mp4", "h.jpg", $source_stream);
+ else
+ $poster_url = false;
+
+ $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
+
+ $found = true;
+ }
+
+ $matches = array();
+ if (!$found && $vid_id = UrlHelper::url_to_youtube_vid($entry_href)) {
+
+ Debug::log("Handling as youtube: $vid_id", Debug::LOG_VERBOSE);
+
+ /* normalize video URL for af_youtube_... plugins */
+ $video_url = "https://www.youtube.com/v/$vid_id";
+
+ /* push generated video URL to enclosures so that youtube embed plugins would deal with it later (if enabled) */
+ $this->generated_enclosures[] = [$video_url, "text/html", null, null, '', ''];
+
+ $found = true;
+ }
+
+ if (!$found && (preg_match("/\.(jpg|jpeg|gif|png)(\?[0-9][0-9]*)?[$\?]?/i", $entry_href) ||
+ /* mb_strpos($entry_href, "i.reddituploads.com") !== false || */
+ mb_strpos($this->get_content_type($entry_href), "image/") !== false)) {
+
+ Debug::log("Handling as a picture", Debug::LOG_VERBOSE);
+
+ $img = $doc->createElement('img');
+ $img->setAttribute("src", $entry_href);
+
+ $br = $doc->createElement('br');
+ $entry->parentNode->insertBefore($img, $entry);
+ $entry->parentNode->insertBefore($br, $entry);
+
+ $found = true;
+ }
+
+ // imgur via link rel="image_src" href="..."
+ if (!$found && preg_match("/imgur/", $entry_href)) {
+
+ Debug::log("handling as imgur page/whatever", Debug::LOG_VERBOSE);
+
+ $content_type = $this->get_content_type($entry_href);
+
+ if ($content_type && strpos($content_type, "text/html") !== false) {
+
+ $content = UrlHelper::fetch(["url" => $entry_href,
+ "http_accept" => "text/*"]);
+
+ if ($content) {
+ $cdoc = new DOMDocument();
+
+ if (@$cdoc->loadHTML($content)) {
+ $cxpath = new DOMXPath($cdoc);
+
+ /** @var ?DOMElement $rel_image */
+ $rel_image = $cxpath->query("//link[@rel='image_src']")->item(0);
+
+ if ($rel_image) {
+
+ $img = $doc->createElement('img');
+ $img->setAttribute("src", $rel_image->getAttribute("href"));
+
+ $br = $doc->createElement('br');
+ $entry->parentNode->insertBefore($img, $entry);
+ $entry->parentNode->insertBefore($br, $entry);
+
+ $found = true;
+ }
+ }
+ }
+
+ } else {
+ Debug::log("skipping imgur $entry_href because of content type: $content_type", Debug::LOG_VERBOSE);
+ }
+ }
+
+ // wtf is this even
+ if (!$found && preg_match("/^https?:\/\/gyazo\.com\/([^\.\/]+$)/", $entry_href, $matches)) {
+ $img_id = $matches[1];
+
+ Debug::log("handling as gyazo: $img_id", Debug::LOG_VERBOSE);
+
+ $img = $doc->createElement('img');
+ $img->setAttribute("src", "https://i.gyazo.com/$img_id.jpg");
+
+ $br = $doc->createElement('br');
+ $entry->parentNode->insertBefore($img, $entry);
+ $entry->parentNode->insertBefore($br, $entry);
+
+ $found = true;
+ }
+
+ // let's try meta properties
+ if (!$found) {
+ Debug::log("looking for meta og:image", Debug::LOG_VERBOSE);
+
+ $content_type = $this->get_content_type($entry_href);
+
+ if ($content_type && strpos($content_type, "text/html") !== false) {
+
+ $content = UrlHelper::fetch(["url" => $entry_href,
+ "http_accept" => "text/*"]);
+
+ if ($content) {
+ $cdoc = new DOMDocument();
+
+ if (@$cdoc->loadHTML($content)) {
+ $cxpath = new DOMXPath($cdoc);
+
+ /** @var ?DOMElement $og_image */
+ $og_image = $cxpath->query("//meta[@property='og:image']")->item(0);
+
+ /** @var ?DOMElement $og_video */
+ $og_video = $cxpath->query("//meta[@property='og:video']")->item(0);
+
+ if ($og_video) {
+
+ $source_stream = $og_video->getAttribute("content");
+
+ if ($source_stream) {
+
+ if ($og_image) {
+ $poster_url = $og_image->getAttribute("content");
+ } else {
+ $poster_url = false;
+ }
+
+ $this->handle_as_video($doc, $entry, $source_stream, $poster_url);
+ $found = true;
+ }
+
+ } else if ($og_image) {
+
+ $og_src = $og_image->getAttribute("content");
+
+ if ($og_src) {
+ $img = $doc->createElement('img');
+ $img->setAttribute("src", $og_src);
+
+ $br = $doc->createElement('br');
+ $entry->parentNode->insertBefore($img, $entry);
+ $entry->parentNode->insertBefore($br, $entry);
+
+ $found = true;
+ }
+ }
+ }
+ }
+ } else {
+ Debug::log("BODY: skipping $entry_href because of content type: $content_type", Debug::LOG_VERBOSE);
+ }
+ }
+ }
+
+ return $found > 0;
+ }
+
+ function hook_article_filter($article) {
+
+ if (preg_match("/lemmy.ml\/post\/[0-9]{1,}$/", $article['link']) !== false && !empty($article["content"])) {
+ $doc = new DOMDocument();
+
+ if (@$doc->loadHTML($article["content"])) {
+ $xpath = new DOMXPath($doc);
+
+ if ($this->is_blacklisted($article['link']))
+ return $article;
+
+ $origin_domain = parse_url($article["feed"]["site_url"] ?? '', PHP_URL_HOST);
+
+ $found = $this->inline_stuff($article, $doc, $xpath, $origin_domain);
+ $node = $doc->getElementsByTagName('body')->item(0);
+
+ if ($node && $found) {
+ $article["content"] = $doc->saveHTML($node);
+ $article["enclosures"] = $this->generated_enclosures;
+ } else {
+ // $article = $this->readability($article, $content_href, $doc, $xpath);
+ }
+ }
+ }
+
+ return $article;
+ }
+
+ private function handle_as_image(DOMDocument $doc, DOMElement $entry, string $image_url, string $link_url = "") : void {
+ $img = $doc->createElement("img");
+ $img->setAttribute("src", $image_url);
+
+ $p = $doc->createElement("p");
+
+ if ($link_url) {
+ $a = $doc->createElement("a");
+ $a->setAttribute("href", $link_url);
+
+ $a->appendChild($img);
+ $p->appendChild($a);
+ } else {
+ $p->appendChild($img);
+ }
+
+ $entry->parentNode->insertBefore($p, $entry);
+ }
+
+ private function handle_as_video(DOMDocument $doc, DOMElement $entry, string $source_stream, string $poster_url = "") : void {
+
+ Debug::log("handle_as_video: $source_stream", Debug::LOG_VERBOSE);
+
+ $video = $doc->createElement('video');
+ $video->setAttribute("autoplay", "1");
+ $video->setAttribute("controls", "1");
+ $video->setAttribute("loop", "1");
+
+ if ($poster_url) $video->setAttribute("poster", $poster_url);
+
+ $source = $doc->createElement('source');
+ $source->setAttribute("src", $source_stream);
+ $source->setAttribute("type", "video/mp4");
+
+ $video->appendChild($source);
+
+ $br = $doc->createElement('br');
+ $entry->parentNode->insertBefore($video, $entry);
+ $entry->parentNode->insertBefore($br, $entry);
+ }
+
+ /** $useragent defaults to Config::get_user_agent() */
+ private function get_header(string $url, int $header, string $useragent = "") : string {
+ $ret = "";
+
+ if (function_exists("curl_init")) {
+ $ch = curl_init($url);
+ curl_setopt($ch, CURLOPT_TIMEOUT, 5);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+ curl_setopt($ch, CURLOPT_HEADER, true);
+ curl_setopt($ch, CURLOPT_NOBODY, true);
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("open_basedir"));
+ curl_setopt($ch, CURLOPT_USERAGENT, $useragent ? $useragent : Config::get_user_agent());
+
+ @curl_exec($ch);
+ $ret = curl_getinfo($ch, $header);
+ }
+
+ return $ret;
+ }
+
+ private function get_content_type(string $url, string $useragent = "") : string {
+ return $this->get_header($url, CURLINFO_CONTENT_TYPE, $useragent);
+ }
+
+ /**
+ * @param array<string,mixed> $article
+ * @param string $url
+ * @param DOMDocument $doc
+ * @param DOMXPath $xpath
+ * @param bool $debug
+ * @return array<string,mixed>
+ * @throws PDOException
+ */
+ private function readability(array $article, string $url, DOMDocument $doc, DOMXpath $xpath, bool $debug = false) : array {
+
+ if (function_exists("curl_init") && $this->host->get($this, "enable_readability") &&
+ mb_strlen(strip_tags($article["content"])) <= 150) {
+
+ // do not try to embed posts linking back to other reddit posts
+ // readability.php requires PHP 5.6
+ if ($url && strpos($url, "reddit.com") === false) {
+
+ /* link may lead to a huge video file or whatever, we need to check content type before trying to
+ parse it which p much requires curl */
+
+ $useragent_compat = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
+ $content_type = $this->get_content_type($url, $useragent_compat);
+
+ if ($content_type && strpos($content_type, "text/html") !== false) {
+
+ $this->host->run_hooks_callback(PluginHost::HOOK_GET_FULL_TEXT,
+ function ($result) use (&$article) {
+ if ($result) {
+ $article["content"] = $result;
+ return true;
+ }
+ },
+ $url);
+ }
+ }
+ }
+
+ return $article;
+ }
+
+ /**
+ * @param string $src
+ * @param array<string> $also_blacklist
+ * @return bool
+ */
+ private function is_blacklisted(string $src, array $also_blacklist = []) : bool {
+ $src_domain = parse_url($src, PHP_URL_HOST);
+
+ if ($src_domain)
+ foreach ([...$this->domain_blacklist, ...$also_blacklist] as $domain) {
+ if (strstr($src_domain, $domain) !== false) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ function api_version() {
+ return 2;
+ }
+
+}