Files
FreshRSS/lib/favicons.php
Inverle 7915abd833 Implement custom feed favicons (#7646)
Closes #3789, #6503

Icon setting when no custom icon is set yet:

![image](https://github.com/user-attachments/assets/28b07dd0-7dac-4c76-b1d7-77035f91a87a)

- `Change...` button opens a file dialog, and after selecting a file shows the chosen icon in the preview on the left. `Submit` must be clicked after selecting the icon.
- `Reset to default` changes the preview icon to the default one, and also requires `Submit` to be clicked to apply the changes.

Full list of changes:
- CSP now includes `blob:` in `img-src` for
   - `indexAction()` and `feedAction()` in `subscriptionController.php`
   - all of the view actions in `indexController.php`
- Introduce new attribute `customFavicon (boolean)` for feeds that indicates if the feed has a custom favicon
   - `hashFavicon()` in `Feed.php` is dependent on this attribute
      - `hashFavicon()` has a new parameter called `skipCache (boolean)` that allows the reset of the favicon hash for the Feed object
      - `resetFaviconHash()` just calls `hashFavicon(skipCache: true)`
- `f.php` URLs now have the format of `/f.php?h=XXXXX&t=cachebuster`, where the `t` parameter is only used for serving custom favicons
   - if `t` parameter is set, `f.php` returns a `Cache-Control: immutable` header
- `stripos` and `strpos` were changed to `str_contains` in various places (refactor)
- JS for handling the custom favicon configuration logic is in `extra.js` inside `init_update_feed()` which is called when feed configuration is opened from the aside or when the subscription management page with the feed is loaded
   - Server-side code for uploading the icon in `subscriptionController.php` under `feedAction()`
   - Errors that may occur during the setting of a custom favicon:
      - Unsupported image file type (handled only server-side with `isImgMime()`)
      - When the file is bigger than 1 MiB (default), handled both client-side and server-side
      - Standard feed error when `updateFeed()` fails
- JS vars `javascript_vars.phtml` are no longer escaped with `htmlspecialchars()`, instead with json encoding,
- CSS for disabled buttons was added
- Max favicon file size is configurable with the `max_favicon_upload_size` option in `config.php` (not exposed via UI)
- Custom favicons are currently deleted only when they are either reset to the default icon, or the feed gets deleted. They do not get deleted when the user deletes their account without removing their feeds first.
- ` faviconPrepare()` and `faviconRebuild()` are not allowed to be called when the `customFavicon` attribute is `true`
- New i18n strings:
   - `'sub.feed.icon' => 'Icon'`
   - `'sub.feed.change_favicon' => 'Change…'`
   - `'sub.feed.reset_favicon' => 'Reset to default'`
   - `'sub.feed.favicon_changed_by_ext' => 'The icon has been set by the <b>%s</b> extension.'`
   - `'feedback.sub.feed.favicon.too_large' => 'Uploaded icon is too large. The maximum file size is <em>%s</em>.'`
   - `'feedback.sub.feed.favicon.unsupported_format' => 'Unsupported image file format!'`
- Extension hook `custom_favicon_hash`
   - `setCustomFavicon()` method
   - `resetCustomFavicon()` method
   - `customFaviconExt` and `customFaviconDisallowDel` attributes
   - example of usage: https://github.com/FreshRSS/Extensions/pull/337
- Extension hook `custom_favicon_btn_url`
   - Allows extensions to implement a button for setting a custom favicon for individual feeds by providing an URL. The URL will be sent a POST request with the `extAction` field set to either `query_icon_info` or `update_icon`, along with an `id` field which describes the feed's ID.
2025-06-30 12:01:56 +02:00

150 lines
4.1 KiB
PHP

<?php
declare(strict_types=1);
const FAVICONS_DIR = DATA_PATH . '/favicons/';
const DEFAULT_FAVICON = PUBLIC_PATH . '/themes/icons/default_favicon.ico';
function isImgMime(string $content): bool {
//Based on https://github.com/ArthurHoaro/favicon/blob/3a4f93da9bb24915b21771eb7873a21bde26f5d1/src/Favicon/Favicon.php#L311-L319
if ($content == '') {
return false;
}
if (!extension_loaded('fileinfo')) {
return true;
}
$fInfo = finfo_open(FILEINFO_MIME_TYPE);
if ($fInfo === false) {
return true;
}
$content = finfo_buffer($fInfo, $content);
$isImage = str_contains($content ?: '', 'image');
finfo_close($fInfo);
return $isImage;
}
/** @param array<int,int|bool|string> $curlOptions */
function downloadHttp(string &$url, array $curlOptions = []): string {
syslog(LOG_INFO, 'FreshRSS Favicon GET ' . $url);
$url2 = checkUrl($url);
if ($url2 == false) {
return '';
}
$url = $url2;
/** @var CurlHandle $ch */
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
CURLOPT_MAXREDIRS => 10,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => '', //Enable all encodings
//CURLOPT_VERBOSE => 1, // To debug sent HTTP headers
]);
FreshRSS_Context::initSystem();
if (FreshRSS_Context::hasSystemConf()) {
curl_setopt_array($ch, FreshRSS_Context::systemConf()->curl_options);
}
curl_setopt_array($ch, $curlOptions);
$response = curl_exec($ch);
if (!is_string($response)) {
$response = '';
}
$info = curl_getinfo($ch);
curl_close($ch);
if (!empty($info['url'])) {
$url2 = checkUrl($info['url']);
if ($url2 != false) {
$url = $url2; //Possible redirect
}
}
return is_array($info) && $info['http_code'] == 200 ? $response : '';
}
function searchFavicon(string &$url): string {
$dom = new DOMDocument();
$html = downloadHttp($url);
if ($html == '' || !@$dom->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING)) {
return '';
}
$xpath = new DOMXPath($dom);
$links = $xpath->query('//link[@href][translate(@rel, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="shortcut icon"'
. ' or translate(@rel, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="icon"]');
if (!($links instanceof DOMNodeList)) {
return '';
}
// Use the base element for relative paths, if there is one
$baseElements = $xpath->query('//base[@href]');
$baseElement = ($baseElements !== false && $baseElements->length > 0) ? $baseElements->item(0) : null;
$baseUrl = ($baseElement instanceof DOMElement) ? $baseElement->getAttribute('href') : $url;
foreach ($links as $link) {
if (!$link instanceof DOMElement) {
continue;
}
$href = trim($link->getAttribute('href'));
$urlParts = parse_url($url);
// Handle protocol-relative URLs by adding the current URL's scheme
if (substr($href, 0, 2) === '//') {
$href = ($urlParts['scheme'] ?? 'https') . ':' . $href;
}
$href = \SimplePie\IRI::absolutize($baseUrl, $href);
if ($href == false) {
return '';
}
$iri = $href->get_iri();
if ($iri == false) {
return '';
}
$favicon = downloadHttp($iri, [CURLOPT_REFERER => $url]);
if (isImgMime($favicon)) {
return $favicon;
}
}
return '';
}
function download_favicon(string $url, string $dest): bool {
$url = trim($url);
$favicon = searchFavicon($url);
if ($favicon == '') {
$rootUrl = preg_replace('%^(https?://[^/]+).*$%i', '$1/', $url) ?? $url;
if ($rootUrl != $url) {
$url = $rootUrl;
$favicon = searchFavicon($url);
}
if ($favicon == '') {
$link = $rootUrl . 'favicon.ico';
$favicon = downloadHttp($link, [CURLOPT_REFERER => $url]);
if (!isImgMime($favicon)) {
$favicon = '';
}
}
}
return ($favicon != '' && file_put_contents($dest, $favicon) > 0) ||
@copy(DEFAULT_FAVICON, $dest);
}
function contentType(string $ico): string {
$ico_content_type = 'image/x-icon';
if (function_exists('mime_content_type')) {
$ico_content_type = mime_content_type($ico) ?: $ico_content_type;
}
switch ($ico_content_type) {
case 'image/svg':
$ico_content_type = 'image/svg+xml';
break;
}
return $ico_content_type;
}