Repository navigation
Expand file tree
/
Copy pathextension.php
More file actions
649 lines (557 loc) · 20.4 KB
/
Copy pathextension.php
File metadata and controls
649 lines (557 loc) · 20.4 KB
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
<?php
declare(strict_types=1);
/**
* Class YouTubeExtension
*
* @author Kevin Papst, Inverle
*/
final class YouTubeExtension extends Minz_Extension
{
/**
* Whether videos should be embedded in the article content
*/
private bool $embedVideos = true;
/**
* Whether the video player should use responsive sizing
*/
private bool $autoSize = false;
/**
* Video player width
*/
private int $width = 560;
/**
* Video player height
*/
private int $height = 315;
/**
* Whether we display the original feed content
*/
private bool $showContent = false;
/**
* Whether channel icons should be automatically downloaded and set for feeds
*/
private bool $downloadIcons = false;
/**
* Switch to enable the Youtube No-Cookie domain
*/
private bool $useNoCookie = false;
/**
* Initialize this extension
*/
#[\Override]
public function init(): void {
Minz_View::appendStyle($this->getFileUrl('style.css'));
$this->registerHook('entry_before_display', $this->embedYouTubeVideo(...));
$this->registerHook('check_url_before_add', self::convertYoutubeFeedUrl(...));
$this->registerHook('custom_favicon_hash', $this->iconHashParams(...));
$this->registerHook('custom_favicon_btn_url', $this->iconBtnUrl(...));
$this->registerHook('feed_before_insert', $this->feedBeforeInsert(...));
if (Minz_Request::controllerName() === 'extension') {
$this->registerHook('js_vars', self::jsVars(...));
Minz_View::appendScript($this->getFileUrl('fetchIcons.js'));
}
$this->registerTranslates();
}
/**
* @param array<string,mixed> $vars
* @return array<string,mixed>
*/
public static function jsVars(array $vars): array {
$vars['yt_i18n'] = [
'fetching_icons' => _t('ext.yt_videos.fetching_icons'),
];
return $vars;
}
public function isYtFeed(string $website): bool {
return str_starts_with($website, 'https://www.youtube.com/');
}
public function isShort(string $website): bool {
return str_starts_with($website, 'https://www.youtube.com/shorts');
}
public function convertShortToWatch(string $shortUrl): string {
$prefix = 'https://www.youtube.com/shorts/';
if (str_starts_with($shortUrl, $prefix)) {
$videoId = str_replace($prefix, '', $shortUrl);
return 'https://www.youtube.com/watch?v=' . $videoId;
}
return $shortUrl;
}
public function iconBtnUrl(FreshRSS_Feed $feed): ?string {
if (!$this->isYtFeed($feed->website()) || $feed->attributeString('customFaviconExt') === $this->getName()) {
return null;
}
return _url('extension', 'configure', 'e', urlencode($this->getName()));
}
public function iconHashParams(FreshRSS_Feed $feed): ?string {
if ($feed->customFaviconExt() !== $this->getName()) {
return null;
}
return 'yt' . $feed->website() . $feed->proxyParam();
}
/**
* @throws Minz_PDOConnectionException
* @throws Minz_ConfigurationNamespaceException
*/
public function ajaxGetYtFeeds(): void {
$feedDAO = FreshRSS_Factory::createFeedDao();
$ids = $feedDAO->listFeedsIds();
$feeds = [];
foreach ($ids as $feedId) {
$feed = $feedDAO->searchById($feedId);
if ($feed === null) {
continue;
}
if ($this->isYtFeed($feed->website())) {
$feeds[] = [
'id' => $feed->id(),
'title' => $feed->name(true),
];
}
}
header('Content-Type: application/json; charset=UTF-8');
exit(json_encode($feeds));
}
/**
* @throws Minz_PDOConnectionException
* @throws Minz_ConfigurationNamespaceException
* @throws Minz_PermissionDeniedException
* @throws FreshRSS_UnsupportedImageFormat_Exception
* @throws FreshRSS_Context_Exception
*/
public function ajaxFetchIcon(): void {
$feedDAO = FreshRSS_Factory::createFeedDao();
$feed = $feedDAO->searchById(Minz_Request::paramInt('id'));
if ($feed === null) {
Minz_Error::error(404);
return;
}
$this->setIconForFeed($feed, setValues: true);
exit('OK');
}
/**
* @throws Minz_PDOConnectionException
* @throws Minz_ConfigurationNamespaceException
* @throws Minz_PermissionDeniedException
*/
public function resetAllIcons(): void {
$feedDAO = FreshRSS_Factory::createFeedDao();
$ids = $feedDAO->listFeedsIds();
foreach ($ids as $feedId) {
$feed = $feedDAO->searchById($feedId);
if ($feed === null) {
continue;
}
if ($feed->customFaviconExt() === $this->getName()) {
$v = [];
try {
$feed->resetCustomFavicon(values: $v);
} catch (FreshRSS_Feed_Exception $_) {
$this->warnLog('Failed to reset favicon for feed “' . $feed->name(true) . '”: feed error!');
}
}
}
}
/**
* @throws Minz_PermissionDeniedException
*/
public function warnLog(string $s): void {
Minz_Log::warning('[' . $this->getName() . '] ' . $s);
}
/**
* @throws Minz_PermissionDeniedException
*/
public function debugLog(string $s): void {
Minz_Log::debug('[' . $this->getName() . '] ' . $s);
}
/**
* @throws FreshRSS_Context_Exception
* @throws Minz_PermissionDeniedException
* @throws FreshRSS_UnsupportedImageFormat_Exception
*/
public function feedBeforeInsert(FreshRSS_Feed $feed): FreshRSS_Feed {
$this->loadConfigValues();
if ($this->downloadIcons) {
return $this->setIconForFeed($feed);
}
return $feed;
}
/**
* @throws Minz_PermissionDeniedException
* @throws FreshRSS_UnsupportedImageFormat_Exception
* @throws FreshRSS_Context_Exception
*/
public function setIconForFeed(FreshRSS_Feed $feed, bool $setValues = false): FreshRSS_Feed {
if (!$this->isYtFeed($feed->website())) {
return $feed;
}
// Return early if the icon had already been downloaded before
$v = $setValues ? [] : null;
$oldAttributes = $feed->attributes();
try {
$path = $feed->setCustomFavicon(extName: $this->getName(), disallowDelete: true, values: $v);
if ($path === null) {
$feed->_attributes($oldAttributes);
return $feed;
} elseif (file_exists($path)) {
$this->debugLog('Icon had already been downloaded before for feed “' . $feed->name(true) . '”: returning early!');
return $feed;
}
} catch (FreshRSS_Feed_Exception $_) {
$this->warnLog('Failed to set custom favicon for feed “' . $feed->name(true) . '”: feed error!');
$feed->_attributes($oldAttributes);
return $feed;
}
$feed->_attributes($oldAttributes);
$this->debugLog('downloading icon for feed “' . $feed->name(true) . '"');
$url = $feed->website();
/** @var array<int, bool|int|string> */
$curlOptions = $feed->attributeArray('curl_params') ?? [];
$ch = curl_init();
if ($ch === false || $url === '') {
return $feed;
}
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
]);
curl_setopt_array($ch, FreshRSS_Context::systemConf()->curl_options);
curl_setopt_array($ch, $curlOptions);
$html = curl_exec($ch);
$dom = new DOMDocument();
if (!is_string($html) || !@$dom->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING)) {
$this->warnLog('Fail while downloading icon for feed “' . $feed->name(true) . '”: failed to load HTML!');
return $feed;
}
$xpath = new DOMXPath($dom);
$metaElem = $xpath->query('//meta[@name="twitter:image"]');
if ($metaElem === false) {
$this->warnLog('Fail while downloading icon for feed “' . $feed->name(true) . '”: icon URL couldn’t be found!');
return $feed;
}
$iconElem = $metaElem->item(0);
if (!($iconElem instanceof DOMElement)) {
$this->warnLog('Fail while downloading icon for feed “' . $feed->name(true) . '”: icon URL couldn’t be found!');
return $feed;
}
$iconUrl = $iconElem->getAttribute('content');
if ($iconUrl == '') {
$this->warnLog('Fail while downloading icon for feed “' . $feed->name(true) . '”: icon URL is empty!');
return $feed;
}
curl_setopt($ch, CURLOPT_URL, $iconUrl);
$contents = curl_exec($ch);
if (!is_string($contents)) {
$this->warnLog('Fail while downloading icon for feed “' . $feed->name(true) . '”: empty contents!');
return $feed;
}
try {
$feed->setCustomFavicon($contents, extName: $this->getName(), disallowDelete: true, values: $v, overrideCustomIcon: true);
} catch (FreshRSS_UnsupportedImageFormat_Exception $_) {
$this->warnLog('Failed to set custom favicon for feed “' . $feed->name(true) . '”: unsupported image format!');
return $feed;
} catch (FreshRSS_Feed_Exception $_) {
$this->warnLog('Failed to set custom favicon for feed “' . $feed->name(true) . '”: feed error!');
return $feed;
}
return $feed;
}
public static function convertYoutubeFeedUrl(string $url): string {
$matches = [];
if (preg_match('#^https?://www\.youtube\.com/channel/([0-9a-zA-Z_-]{6,36})#', $url, $matches) === 1) {
return 'https://www.youtube.com/feeds/videos.xml?channel_id=' . $matches[1];
}
if (preg_match('#^https?://www\.youtube\.com/user/([0-9a-zA-Z_-]{6,36})#', $url, $matches) === 1) {
return 'https://www.youtube.com/feeds/videos.xml?user=' . $matches[1];
}
return $url;
}
/**
* Initializes the extension configuration, if the user context is available.
* Do not call that in your extensions init() method, it can't be used there.
* @throws FreshRSS_Context_Exception
*/
public function loadConfigValues(): void {
if (!class_exists('FreshRSS_Context', false) || !FreshRSS_Context::hasUserConf()) {
return;
}
$embedVideos = FreshRSS_Context::userConf()->attributeBool('yt_embed_videos');
if ($embedVideos !== null) {
$this->embedVideos = $embedVideos;
}
$autoSize = FreshRSS_Context::userConf()->attributeBool('yt_player_autosize');
if ($autoSize !== null) {
$this->autoSize = $autoSize;
}
$width = FreshRSS_Context::userConf()->attributeInt('yt_player_width');
if ($width !== null) {
$this->width = $width;
}
$height = FreshRSS_Context::userConf()->attributeInt('yt_player_height');
if ($height !== null) {
$this->height = $height;
}
$showContent = FreshRSS_Context::userConf()->attributeBool('yt_show_content');
if ($showContent !== null) {
$this->showContent = $showContent;
}
$downloadIcons = FreshRSS_Context::userConf()->attributeBool('yt_download_channel_icons');
if ($downloadIcons !== null) {
$this->downloadIcons = $downloadIcons;
}
$noCookie = FreshRSS_Context::userConf()->attributeBool('yt_nocookie');
if ($noCookie !== null) {
$this->useNoCookie = $noCookie;
}
}
/**
* Returns whether videos are embedded in the article content.
* You have to call loadConfigValues() before this one, otherwise you get the default value.
*/
public function isEmbedVideos(): bool {
return $this->embedVideos;
}
/**
* Returns whether responsive sizing is enabled for the video player iframe.
* You have to call loadConfigValues() before this one, otherwise you get the default value.
*/
public function isAutoSize(): bool {
return $this->autoSize;
}
/**
* Returns the width in pixel for the YouTube player iframe.
* You have to call loadConfigValues() before this one, otherwise you get default values.
*/
public function getWidth(): int {
return $this->width;
}
/**
* Returns the height in pixel for the YouTube player iframe.
* You have to call loadConfigValues() before this one, otherwise you get default values.
*/
public function getHeight(): int {
return $this->height;
}
/**
* Returns whether this extension displays the content of the YouTube feed.
* You have to call loadConfigValues() before this one, otherwise you get default values.
*/
public function isShowContent(): bool {
return $this->showContent;
}
/**
* Returns whether the automatic icon download option is enabled.
* You have to call loadConfigValues() before this one, otherwise you get default values.
*/
public function isDownloadIcons(): bool {
return $this->downloadIcons;
}
/**
* Returns if this extension should use youtube-nocookie.com instead of youtube.com.
* You have to call loadConfigValues() before this one, otherwise you get default values.
*/
public function isUseNoCookieDomain(): bool {
return $this->useNoCookie;
}
/**
* Inserts the YouTube video iframe into the content of an entry, if the entries link points to a YouTube watch URL.
* @throws FreshRSS_Context_Exception
*/
public function embedYouTubeVideo(FreshRSS_Entry $entry): FreshRSS_Entry {
$link = $entry->link();
if ($this->isShort($link)) {
$link = $this->convertShortToWatch($link);
}
if (preg_match('#^https?://www\.youtube\.com/watch\?v=|/videos/watch/[0-9a-f-]{36}$#', $link) !== 1) {
return $entry;
}
$this->loadConfigValues();
if (!$this->embedVideos) {
return $entry;
}
if (stripos($entry->content(), '<iframe class="youtube-plugin-video"') !== false) {
return $entry;
}
if (stripos($link, 'www.youtube.com/watch?v=') !== false) {
$html = $this->getHtmlContentForLink($entry, $link);
} else { //peertube
$html = $this->getHtmlPeerTubeContentForLink($entry, $link);
}
$entry->_content($html);
return $entry;
}
/**
* Returns an HTML <iframe> for a given Youtube watch URL (www.youtube.com/watch?v=)
*/
public function getHtmlContentForLink(FreshRSS_Entry $entry, string $link): string {
$domain = 'www.youtube.com';
if ($this->useNoCookie) {
$domain = 'www.youtube-nocookie.com';
}
$url = str_replace('//www.youtube.com/watch?v=', '//' . $domain . '/embed/', $link);
$url = str_replace('http://', 'https://', $url);
return $this->getHtml($entry, $url);
}
/**
* Returns an HTML <iframe> for a given PeerTube watch URL
*/
public function getHtmlPeerTubeContentForLink(FreshRSS_Entry $entry, string $link): string {
$url = str_replace('/watch', '/embed', $link);
return $this->getHtml($entry, $url);
}
/**
* Returns true if the content string contains a YouTube enclosure structure as opposed to arbitrary feed content.
*/
private function hasEnclosureStructure(string $content): bool {
return stripos($content, 'class="enclosure"') !== false
|| stripos($content, 'enclosure-title') !== false
|| stripos($content, 'enclosure-description') !== false;
}
/**
* Returns hidden references to the URLs of the thumbnail and enclosures of an entry.
* When displaying an entry, FreshRSS appends the thumbnail and enclosures whose URL is not found in the content,
* which would show them again after the video player that replaces them.
*/
private function getEnclosureReferences(FreshRSS_Entry $entry): string {
$urls = [];
$thumbnail = $entry->thumbnail(searchEnclosures: false);
if ($thumbnail !== null) {
$urls[] = $thumbnail['url'];
}
foreach ($entry->enclosures() as $enclosure) {
$urls[] = $enclosure['url'];
}
$references = '';
foreach (array_unique($urls) as $url) {
if ($url === '') {
continue;
}
$references .= '<p hidden data-xextension-youtube-original-src="' . $url . '"></p>';
}
return $references;
}
/**
* Returns an HTML <iframe> for a given URL for the configured width and height, with content ignored, appended or formatted.
*/
public function getHtml(FreshRSS_Entry $entry, string $url): string {
$content = '';
$iframeAttributes = $this->autoSize
? 'class="youtube-plugin-video yt-player-autosize"'
: 'class="youtube-plugin-video" width="' . $this->width . '" height="' . $this->height . '"';
$iframe = '<iframe ' . $iframeAttributes . '
src="' . $url . '"
frameborder="0"
referrerpolicy="strict-origin-when-cross-origin"
allowFullScreen></iframe>';
if ($this->showContent) {
$doc = new DOMDocument();
$doc->encoding = 'UTF-8';
$doc->recover = true;
$doc->strictErrorChecking = false;
if ($doc->loadHTML('<?xml encoding="utf-8" ?>' . $entry->content(), LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING)) {
$xpath = new DOMXPath($doc);
/** @var DOMNodeList<DOMElement> $titles */
$titles = $xpath->evaluate("//*[@class='enclosure-title']");
/** @var DOMNodeList<DOMElement> $thumbnails */
$thumbnails = $xpath->evaluate("//*[@class='enclosure-thumbnail']/@src");
/** @var DOMNodeList<DOMElement> $descriptions */
$descriptions = $xpath->evaluate("//*[@class='enclosure-description']");
$content = '<div class="enclosure">';
// We hide the title so it doesn't appear in the final article, which would be redundant with the RSS article title,
// but we keep it in the content anyway, so RSS clients can extract it if needed.
if ($titles->length > 0 && $titles[0] instanceof DOMNode) {
$content .= '<p class="enclosure-title" hidden>' . $titles[0]->nodeValue . '</p>';
}
// We hide the thumbnail so it doesn't appear in the final article, which would be redundant with the YouTube player preview,
// but we keep it in the content anyway, so RSS clients can extract it to display a preview where it wants (in article listing,
// by example, like with Reeder).
if ($thumbnails->length > 0 && $thumbnails[0] instanceof DOMNode) {
$content .= '<p hidden><img class="enclosure-thumbnail" src="' . $thumbnails[0]->nodeValue . '" alt="" /></p>';
}
$content .= $iframe;
if ($descriptions->length > 0 && $descriptions[0] instanceof DOMNode) {
$content .= '<p class="enclosure-description">' .
nl2br(htmlspecialchars($descriptions[0]->nodeValue ?? '', ENT_COMPAT, 'UTF-8'), use_xhtml: true) . '</p>';
}
$content .= "</div>\n";
// Append original content if it is not a YouTube enclosure structure
$originalContent = $entry->content();
if (!$this->hasEnclosureStructure($originalContent) && $originalContent !== '') {
$content .= $originalContent;
}
} else {
$content = $iframe . $entry->content();
}
} else {
$originalContent = $entry->content();
// Preserve non-enclosure original content — wrap iframe in enclosure div and append it.
if (!$this->hasEnclosureStructure($originalContent) && $originalContent !== '') {
$content = '<div class="enclosure">' . $iframe . "</div>\n" . $originalContent;
} else {
$content = $iframe;
}
}
return $content . $this->getEnclosureReferences($entry);
}
/**
* This function is called by FreshRSS when the configuration page is loaded, and when configuration is saved.
* - We save configuration in case of a post.
* - We (re)load configuration in all case, so they are in-sync after a save and before a page load.
* @throws FreshRSS_Context_Exception
* @throws Minz_PDOConnectionException
* @throws Minz_ConfigurationNamespaceException
* @throws FreshRSS_UnsupportedImageFormat_Exception
* @throws Minz_PermissionDeniedException
*/
#[\Override]
public function handleConfigureAction(): void {
$this->registerTranslates();
if (Minz_Request::isPost()) {
// for handling requests from `custom_favicon_btn_url` hook
$extAction = Minz_Request::paramStringNull('extAction');
if ($extAction !== null) {
$feedDAO = FreshRSS_Factory::createFeedDao();
$feed = $feedDAO->searchById(Minz_Request::paramInt('id'));
if ($feed === null || !$this->isYtFeed($feed->website())) {
Minz_Error::error(404);
return;
}
$this->setIconForFeed($feed, setValues: $extAction === 'update_icon');
if ($extAction === 'query_icon_info') {
header('Content-Type: application/json; charset=UTF-8');
exit(json_encode([
'extName' => $this->getName(),
'iconUrl' => $feed->favicon(),
]));
}
exit('OK');
}
// for handling configure page
switch (Minz_Request::paramString('yt_action_btn')) {
case 'ajaxGetYtFeeds':
$this->ajaxGetYtFeeds();
return;
case 'ajaxFetchIcon':
$this->ajaxFetchIcon();
return;
// non-ajax actions
case 'iconFetchFinish': // called after final ajaxFetchIcon call
Minz_Request::good(_t('ext.yt_videos.finished_fetching_icons'), ['c' => 'extension']);
break;
case 'resetIcons':
$this->resetAllIcons();
break;
}
FreshRSS_Context::userConf()->_attribute('yt_embed_videos', Minz_Request::paramBoolean('yt_embed_videos'));
FreshRSS_Context::userConf()->_attribute('yt_player_autosize', Minz_Request::paramBoolean('yt_autosize'));
FreshRSS_Context::userConf()->_attribute('yt_player_height', Minz_Request::paramInt('yt_height'));
FreshRSS_Context::userConf()->_attribute('yt_player_width', Minz_Request::paramInt('yt_width'));
FreshRSS_Context::userConf()->_attribute('yt_show_content', Minz_Request::paramBoolean('yt_show_content'));
FreshRSS_Context::userConf()->_attribute('yt_download_channel_icons', Minz_Request::paramBoolean('yt_download_channel_icons'));
FreshRSS_Context::userConf()->_attribute('yt_nocookie', Minz_Request::paramBoolean('yt_nocookie'));
FreshRSS_Context::userConf()->save();
}
$this->loadConfigValues();
}
}