summaryrefslogtreecommitdiff
path: root/init.php
blob: 6af66cdf60f1719ca03fcd2f12f27f933e0141e0 (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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
<?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("/\.(jpe?g|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;
			}

			// 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, $article['link'], $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;
	}

}