summaryrefslogtreecommitdiff
path: root/init.php
blob: c3960a033b75b71707b5d087532228ac7a5a7945 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
<?php
class Af_Lemmy extends Plugin {

	/** @var array<string> */
	private $lemmy_domains = ["beehaw.org", "feddit.de", "sh.itjust.works", "lemmygrad.ml"];

	/** @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) {
		$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) {

		$origin_domain = parse_url($url, PHP_URL_HOST);

		if (strpos($origin_domain, "lemmy.") !== FALSE || in_array($origin_domain, $this->lemmy_domains)) {
			$content = UrlHelper::fetch(["url" => $url,
					"login" => $auth_login,
					"pass" => $auth_pass,
					"http_accept" => "text/*"]);

			if ($content) {
				$doc = new DOMDocument();

				if (@$doc->loadHTML($content)) {
					$xpath = new DOMXPath($doc);

					/** @var ?DOMElement $rss_url */
					$rss_url = $xpath->query("//a[contains(@href, '/feeds/')]")->item(0);

					if ($rss_url) {
						$url = UrlHelper::rewrite_relative($url, $rss_url->getAttribute('href'));
						return true;
					}
				}
			}
		}

		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 = [];

			if (!$found &&	!$this->can_embed($entry_href)) {
				Debug::log("BODY: not allowed to embed URL: $entry_href, 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 = 1;
			}

			$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";

				$enc = new FeedEnclosure();
				$enc->link = $video_url;
				$enc->type = "text/html";

				/* push generated video URL to enclosures so that youtube embed plugins would deal with it later (if enabled) */
				$this->generated_enclosures[] = $enc;

				$found = 1;
			}

			if (!$found && (preg_match("/\.(jpe?g|webp|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);

				$this->handle_as_image($doc, $entry, $entry_href, $entry_href);
				$found = 1;
			}

			// let's try meta properties
			if (!$found) {

				Debug::log("probing content-type...", Debug::LOG_EXTENDED);

				$content_type = $this->get_content_type($entry_href);

				Debug::log("got content-type: $content_type", Debug::LOG_VERBOSE);

				if ($content_type && strpos($content_type, "image/") !== FALSE) {
					Debug::log("Handling as a picture based on content-type", Debug::LOG_VERBOSE);

					$this->handle_as_image($doc, $entry, $entry_href, $entry_href);
					$found = 1;

				} else if ($content_type && strpos($content_type, "text/html") !== FALSE) {

					Debug::log("looking for meta og:image/video...", Debug::LOG_VERBOSE);

					$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 = 1;
								}

							} 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 = 1;
								}
							}
						}
					}

					// Debug::log("trying to extract full content using readability...", Debug::LOG_VERBOSE);

					// $this->host->run_hooks_callback(PluginHost::HOOK_GET_FULL_TEXT,
					// 	function ($result) use (&$article, &$found) {
					// 		if ($result && mb_strlen($result) >= 128) {
					// 			$article["content"] .= "<hr/>" . $result;
					// 			$found = true;
					// 			return true;
					// 		}
					// 	},
					// 	$entry_href);

				} else {
					Debug::log("BODY: skipping because of content type: $content_type", Debug::LOG_VERBOSE);
				}
			}
		}

		return $found > 0;
	}

	function hook_article_filter($article) {

		$origin_domain = parse_url($article["feed"]["site_url"] ?? '', PHP_URL_HOST);

		if ((strpos($origin_domain, "lemmy.") !== FALSE || in_array($origin_domain, $this->lemmy_domains)) &&
				preg_match("/\/post\/[0-9]{1,}$/", $article['guid']) && !empty($article["content"])) {

			$doc = new DOMDocument();

			if (@$doc->loadHTML($article["content"])) {
				$xpath = new DOMXPath($doc);

				$categories = [];
				$category_links = $xpath->query('//a[contains(@href, "/c/")]');

				foreach ($category_links as $link) {
					array_push($categories, $link->textContent);
				}

				$submitted_by = $xpath->query('//a[contains(@href, "/u/")]')->item(0);

				if ($submitted_by) {
					$article["author"] = $submitted_by->textContent;
				}

				array_push($article["tags"], ...FeedItem_Common::normalize_categories($categories));

				$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;
				}
			}
		}

		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);
	}

	private function can_embed(string $url) : bool {
		if (strpos($url, "/pictrs/") !== FALSE)
			return true;

		if (preg_match("#/u/|/c/|/post/#", $url))
			return false;

		$origin_domain = parse_url($url, PHP_URL_HOST);

		if (strpos($origin_domain, "lemmy.") !== FALSE)
			return true;

		return !in_array($origin_domain, $this->lemmy_domains);
	}

	function api_version() {
		return 2;
	}

}