forked from Victrid/freshrss-image-cache-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextension.php
627 lines (547 loc) · 21 KB
/
extension.php
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
<?php
use ImageCache\Settings;
class ImageCacheExtension extends Minz_Extension
{
public array $CACHE = [];
public Settings $settings;
public function autoload(string $class_name): void
{
$namespaceName = 'ImageCache';
if (str_starts_with($class_name, $namespaceName)) {
$class_name = substr($class_name, strlen($namespaceName) + 1);
include $this->getPath() . DIRECTORY_SEPARATOR . str_replace('\\', '/', $class_name) . '.php';
}
}
public function init(): void
{
spl_autoload_register([$this, 'autoload']);
$this->settings = new Settings($this->getUserConfiguration());
$this->registerTranslates();
$this->registerCss();
$this->registerScript();
$this->registerHook("entry_before_display", [$this, "content_modification_hook"]);
$this->registerHook("entry_before_insert", [$this, "image_upload_hook"]);
}
private function registerCss(): void
{
$css_file_name = "style.css";
$this->saveFile($css_file_name, <<<EOT
img.cache-image, video.cache-image {
min-width: 100px;
width: auto !important;
min-height: 100px;
height: auto !important;
max-height: 50vh !important;
object-fit: contain;
background-color: red;
}
EOT
);
Minz_View::appendStyle($this->getFileUrl($css_file_name, 'css', false));
}
private function registerScript(): void
{
$script_file_name = "script.js";
$defaultVolume = $this->getDefaultVolume();
$this->saveFile($script_file_name, <<<EOT
document.getElementById("stream").addEventListener("play", function(e) {
if(e.target && e.target.nodeName == "video") {
e.target.volume = $defaultVolume;
console.log("Loaded data ", e);
}
});
EOT
);
Minz_View::appendStyle($this->getFileUrl($script_file_name, 'js', false));
}
public function handleConfigureAction(): void
{
$this->registerTranslates();
if (Minz_Request::isPost()) {
$configuration = [
'image_cache_url' => Minz_Request::paramString('image_cache_url'),
'image_cache_post_url' => Minz_Request::paramString('image_cache_post_url'),
'image_cache_access_token' => Minz_Request::paramString('image_cache_access_token'),
'image_cache_disabled_url' => Minz_Request::paramString('image_cache_disabled_url'),
'image_recache_url' => Minz_Request::paramString('image_recache_url'),
'video_default_volume' => Minz_Request::paramString('video_default_volume'),
'upload_retry_count' => Minz_Request::paramInt('upload_retry_count'),
'max_cache_elements' => Minz_Request::paramInt('max_cache_elements'),
'remove_wrong_tag' => Minz_Request::paramBoolean('remove_wrong_tag'),
];
$this->setUserConfiguration($configuration);
}
}
/**
* @throws FreshRSS_Context_Exception
* @throws Minz_ConfigurationParamException
* @throws Minz_PermissionDeniedException
*/
public function content_modification_hook(FreshRSS_Entry $entry): FreshRSS_Entry
{
$entry->_content(self::swapUrls($entry->content()));
return $entry;
}
/**
* @throws FreshRSS_Context_Exception
* @throws Minz_ConfigurationParamException
* @throws Minz_PermissionDeniedException
*/
public function image_upload_hook(FreshRSS_Entry $entry): FreshRSS_Entry
{
self::uploadUrls($entry->content());
return $entry;
}
/**
* @throws FreshRSS_Context_Exception
* @throws Minz_ConfigurationParamException
* @throws Minz_PermissionDeniedException
*/
private function swapUrls(string $content): string
{
if (empty($content)) {
return $content;
}
$doc = self::loadContentAsDOM($content);
self::handleImages($doc,
"display",
[$this, "getCachedUrl"],
[$this, "getCachedSetUrl"]
);
return $doc->saveHTML();
}
/**
* @throws FreshRSS_Context_Exception
* @throws Minz_ConfigurationParamException
* @throws Minz_PermissionDeniedException
*/
private function uploadUrls(string $content): void
{
if (empty($content)) {
return;
}
$doc = self::loadContentAsDOM($content);
self::handleImages($doc,
"insert",
[$this, "uploadUrl"],
[$this, "uploadSetUrls"]
);
}
private function appendAfter(DOMNode $node, DOMNode $add): DOMNode|false
{
try {
return $node->parentNode->insertBefore($add, $node->nextSibling);
} catch (\Exception $e) {
return $node->parentNode->appendChild($add);
}
}
/**
* @throws FreshRSS_Context_Exception
* @throws Minz_ConfigurationParamException
* @throws Minz_PermissionDeniedException
*/
private function handleImages(DOMDocument $doc, string $callSource, callable $singleElementCallback, callable $imgSetCallback): void
{
Minz_Log::debug("ImageCache[$callSource]: Scanning new document");
$images = $doc->getElementsByTagName("img");
$videos = $doc->getElementsByTagName("video");
$links = $doc->getElementsByTagName("a");
foreach ($images as $image) {
if ($image->hasAttribute("src")) {
$src = $image->getAttribute("src");
if ($this->isDisabled($src)) {
Minz_Log::debug("ImageCache[$callSource]: Found disabled image $src");
continue;
}
Minz_Log::debug("ImageCache[$callSource]: Found image $src");
$result = $singleElementCallback($src);
if ($result) {
$image->setAttribute("previous-src", $src);
$image->setAttribute("src", $result);
$this->addDefaultImageAttributes($image);
Minz_Log::debug("ImageCache[$callSource]: Replaced image with $result");
if ($this->isVideoLink($src)) {
$this->appendVideo($doc, $image, $src, $result);
if ($this->settings->isRemoveWrongTag()){
$image->parentNode->removeChild($image);
}
}
} else {
Minz_Log::debug("ImageCache[$callSource]: Failed replacing image");
}
}
if ($image->hasAttribute("srcset")) {
$srcSet = $image->getAttribute("srcset");
Minz_Log::debug("ImageCache[$callSource]: Found image set $srcSet");
$result = preg_replace_callback("/(?:([^\s,]+)(\s*(?:\s+\d+[wx])(?:,\s*)?))/", $imgSetCallback, $srcSet);
$result = array_filter($result);
if ($result) {
$image->setAttribute("previous-srcset", $srcSet);
$image->setAttribute("srcset", $result);
$this->addDefaultImageAttributes($image);
Minz_Log::debug("ImageCache[$callSource]: Replaced with $result");
} else {
Minz_Log::debug("ImageCache[$callSource]: Failed replacing image set");
}
}
}
foreach ($videos as $video) {
Minz_Log::debug("ImageCache[$callSource]: Found video");
if ($video->hasAttribute("src")) {
$src = $video->getAttribute("src");
if ($this->isDisabled($src)) {
Minz_Log::debug("ImageCache[$callSource]: Found disabled video $src");
continue;
}
Minz_Log::debug("ImageCache[$callSource]: Found video src $src");
$result = $singleElementCallback($src);
if ($result) {
$video->setAttribute("previous-src", $src);
$video->setAttribute("src", $result);
$this->addDefaultVideoAttributes($video);
Minz_Log::debug("ImageCache[$callSource]: Replaced with $result");
} else {
Minz_Log::debug("ImageCache[$callSource]: Failed replacing video src");
}
}
if ($video->hasAttribute("poster")) {
$poster = $video->getAttribute("poster");
if ($this->isDisabled($poster)) {
Minz_Log::debug("ImageCache[$callSource]: Found disabled video poster $poster");
continue;
}
Minz_Log::debug("ImageCache[$callSource]: Found video poster $poster");
$result = $singleElementCallback($poster);
if ($result) {
$video->setAttribute("previous-poster", $poster);
$video->setAttribute("poster", $result);
Minz_Log::debug("ImageCache[$callSource]: Replaced with $result");
} else {
Minz_Log::debug("ImageCache[$callSource]: Failed replacing video poster");
}
}
foreach ($video->childNodes as $source) {
if ($source->nodeName == 'source') {
if (!$source->hasAttribute("src")) {
continue;
}
$src = $source->getAttribute("src");
if ($this->isDisabled($src)) {
Minz_Log::debug("ImageCache[$callSource]: Found disabled video $src");
continue;
}
Minz_Log::debug("ImageCache[$callSource]: Found video source $src");
$result = $singleElementCallback($src);
if ($result) {
$source->setAttribute("previous-src", $src);
$source->setAttribute("src", $result);
$this->addDefaultVideoAttributes($video);
$this->addClass($video, "cache-image");
Minz_Log::debug("ImageCache[$callSource]: Replaced with $result");
} else {
Minz_Log::debug("ImageCache[$callSource]: Failed replacing video source");
}
}
}
}
foreach ($links as $link) {
if (!$link->hasAttribute("href")) {
continue;
}
$href = $link->getAttribute("href");
if (!$this->isImageLink($href) && !$this->isVideoLink($href)) {
Minz_Log::debug("ImageCache[$callSource]: Found skipped link $href");
continue;
}
if ($this->isDisabled($href)) {
Minz_Log::debug("ImageCache[$callSource]: Found disabled link $href");
continue;
}
Minz_Log::debug("ImageCache[$callSource]: Found link $href");
$result = $singleElementCallback($href);
if (!$result) {
Minz_Log::debug("ImageCache[$callSource]: Failed replacing link");
continue;
}
if ($this->isVideoLink($href)) {
$this->appendVideo($doc, $link, $href, $result);
} else {
$this->appendImage($doc, $link, $href, $result);
}
}
Minz_Log::debug("ImageCache[$callSource]: Done scanning document");
}
private function addClass(DOMElement $node, string $clazz): void
{
$previous = $node->getAttribute('class');
if (!str_contains($previous, $clazz)) {
$node->setAttribute('class', "$previous $clazz");
}
}
/**
* @throws Minz_PermissionDeniedException
*/
private function appendImage(DOMDocument $doc, DOMElement $node, string $originalLink, string $newLink): void
{
try {
$image = $doc->createElement('img');
$image->setAttribute('src', $newLink);
$image->setAttribute('previous-src', $originalLink);
$this->addDefaultImageAttributes($image);
$this->appendAfter($node, $this->wrapElement($doc, $image));
Minz_Log::debug("[ImageCache]: Added image link with $originalLink => $newLink");
} catch (Exception $e) {
Minz_Log::error("[ImageCache]: Failed to create new DOM element $e");
}
}
/**
* @throws Minz_PermissionDeniedException
*/
private function appendVideo(DOMDocument $doc, DOMElement $node, string $originalLink, string $newLink): void
{
try {
$source = $doc->createElement('source');
$source->setAttribute('src', $newLink);
$source->setAttribute('previous-src', $originalLink);
$video = $doc->createElement('video');
$this->addDefaultVideoAttributes($video);
$video->appendChild($source);
$this->appendAfter($node, $this->wrapElement($doc, $video));
Minz_Log::debug("[ImageCache]: Added video link with $originalLink => $newLink");
} catch (Exception $e) {
Minz_Log::error("[ImageCache]: Failed to create new DOM element $e");
}
}
/**
* @throws DOMException
*/
private function wrapElement(DOMDocument $doc, DOMElement $node): DOMElement
{
$div = $doc->createElement('div');
$div->appendChild($node);
return $div;
}
/**
* @throws Minz_PermissionDeniedException
*/
private function getCachedSetUrl(array $matches): string
{
return str_replace($matches[1], self::getCachedUrl($matches[1]), $matches[0]);
}
/**
* @throws Minz_PermissionDeniedException
*/
private function getCachedUrl(string $url): string
{
$image_cache_url = $this->settings->getImageCacheUrl();
if (str_starts_with($url, $image_cache_url)) {
Minz_Log::debug("ImageCache: URL $url already starts with $image_cache_url");
return $url;
}
if ($this->isRecache($url) && !$this->isUrlCached($url)) {
Minz_Log::debug("ImageCache: Re-caching $url");
$this->uploadUrl($url);
}
$encoded_url = rawurlencode($url);
return $image_cache_url . $encoded_url;
}
private function isUrlCached(string $url): bool
{
if ($this->isCachedOnRemote($url)) {
return true;
}
$encoded_url = rawurlencode($url);
$cache_url = $this->settings->getImageCacheUrl() . $encoded_url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $cache_url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code == 404) {
return false;
}
if ($this->isRecache($url)) {
$this->setCachedOnRemote($url);
}
return true;
}
private function uploadSetUrls(array $matches): bool
{
return self::uploadUrl($matches[1]);
}
private function uploadUrl(string $to_cache_cache_url): bool
{
if ($this->isCachedOnRemote($to_cache_cache_url)) {
Minz_Log::debug("ImageCache: URL $to_cache_cache_url is already cached on remote");
return true;
}
$max_tries = 1 + $this->settings->getUploadRetryCount();
for ($i = 1; $i <= $max_tries; $i++) {
$cached = self::postUrl($this->settings->getImageCachePostUrl(), [
"access_token" => $this->settings->getImageCacheAccessToken(),
"url" => $to_cache_cache_url
]);
Minz_Log::debug("ImageCache: Try $i, $to_cache_cache_url cache result : $cached");
if ($cached) {
if ($this->isRecache($to_cache_cache_url)) {
$this->setCachedOnRemote($to_cache_cache_url);
}
return true;
}
sleep($this->settings->getUploadRetryDelay());
}
return false;
}
private function postUrl(string $url, array $data): bool
{
$data = json_encode($data);
$dataLength = strlen($data);
$curl = curl_init();
$headers = [];
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
"Content-Type: application/json;charset='utf-8'",
"Content-Length: $dataLength",
"Accept: application/json"
]);
curl_setopt($curl, CURLOPT_HEADERFUNCTION,
function ($ch, $header) use (&$headers) {
$len = strlen($header);
$header = explode(':', $header, 2);
// ignore invalid headers
if (count($header) < 2) {
return $len;
}
$headers[strtolower(trim($header[0]))][] = trim($header[1]);
return $len;
}
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
$response = curl_exec($curl);
curl_close($curl);
Minz_Log::debug("ImageCache: Upload response : $response");
if (!$response) {
return false;
}
$jsonPayload = json_decode($response, associative: true);
if (!isset($jsonPayload["cached"])) {
return false;
}
return !!$jsonPayload["cached"];
}
private function loadContentAsDOM(string $content): DOMDocument
{
$doc = new DOMDocument();
libxml_use_internal_errors(true); // prevent tag soup errors from showing
$newContent = mb_encode_numericentity($content, [0x80, 0x10FFFF, 0, ~0], 'UTF-8');
$doc->loadHTML($newContent);
return $doc;
}
private function isDisabled(string $src): bool
{
$disabledStr = $this->settings->getImageDisabledUrl();
if (!$disabledStr) {
return false;
}
$disabledEntries = explode(',', $disabledStr);
foreach ($disabledEntries as $disabledEntry) {
if (str_contains($src, $disabledEntry)) {
return true;
}
}
return false;
}
private function isRecache(string $src): bool
{
$recacheStr = $this->settings->getImageRecacheUrl();
if (!$recacheStr) {
return false;
}
$recacheEntries = explode(',', $recacheStr);
foreach ($recacheEntries as $recacheEntry) {
if (str_contains($src, $recacheEntry)) {
return true;
}
}
return false;
}
private function isVideoLink(string $src): bool
{
$parsed_url = parse_url($src);
if (isset($parsed_url['host'])) {
$host = $parsed_url['host'];
if (str_contains($host, 'redgifs.com')
|| str_contains($host, 'vidble.com')
) {
return true;
}
}
if (isset($parsed_url['path'])) {
$path = $parsed_url['path'];
if (str_ends_with($path, ".mp4")
// || str_ends_with($path, ".gifv")
) {
return true;
}
}
return false;
}
private function isImageLink(string $src): bool
{
$parsed_url = parse_url($src);
if (isset($parsed_url['host'])) {
$host = $parsed_url['host'];
if (str_contains($host, 'imgur.com')
|| str_contains($host, 'i.redd.it')
) {
return true;
}
}
return false;
}
private function isCachedOnRemote(string $url): bool
{
return array_key_exists($url, $this->CACHE);
}
private function setCachedOnRemote(string $url): void
{
$count = count($this->CACHE);
if ($count >= $this->settings->getMaxCacheElements()) {
array_shift($this->CACHE);
}
$this->CACHE[] = $url;
}
private function getDefaultVolume(): float
{
return max(0, min(1, $this->settings->getVideoDefaultVolume()));
}
private function addDefaultImageAttributes(DOMElement $image): void
{
$this->addClass($image, "cache-image");
$this->addClass($image, "reddit-image");
}
private function addDefaultVideoAttributes(DOMElement $video): void
{
$this->addClass($video, "cache-image");
$this->addClass($video, "reddit-image");
if (!$video->hasAttribute("controls")) {
$video->setAttribute("controls", "true");
}
if (!$video->hasAttribute("autoplay")) {
$video->setAttribute('autoplay', 'true');
}
if (!$video->hasAttribute("loop")) {
$video->setAttribute("loop", "true");
}
if (!$video->hasAttribute("muted")) {
if ($this->getDefaultVolume() <= 0) {
$video->setAttribute('muted', 'true');
}
}
}
}