extensionController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * The controller to manage extensions.
  5. *
  6. * @phpstan-type ExtensionFullMetadata array{name:string,entrypoint:string,author:string,description:string,version:string,type:'system'|'user',url:string,method:string,directory:string,compatibility:string}
  7. */
  8. class FreshRSS_extension_Controller extends FreshRSS_ActionController {
  9. /**
  10. * This action is called before every other action in that class. It is
  11. * the common boiler plate for every action. It is triggered by the
  12. * underlying framework.
  13. */
  14. #[\Override]
  15. public function firstAction(): void {
  16. if (!FreshRSS_Auth::hasAccess()) {
  17. Minz_Error::error(403);
  18. }
  19. }
  20. /**
  21. * This action lists all the extensions available to the current user.
  22. */
  23. public function indexAction(): void {
  24. FreshRSS_View::prependTitle(_t('admin.extensions.title') . ' · ');
  25. $this->view->extension_list = [
  26. 'system' => [],
  27. 'user' => [],
  28. ];
  29. $this->view->extensions_installed = [];
  30. $extensions = Minz_ExtensionManager::listExtensions();
  31. foreach ($extensions as $ext) {
  32. $this->view->extension_list[$ext->getType()][] = $ext;
  33. $this->view->extensions_installed[$ext->getEntrypoint()] = $ext->getVersion();
  34. }
  35. $this->view->available_extensions = $this->getAvailableExtensionList();
  36. }
  37. /**
  38. * Fetch extension list from GitHub
  39. * @phpstan-return list<ExtensionFullMetadata>
  40. */
  41. protected function getAvailableExtensionList(): array {
  42. $extensionListUrl = 'https://raw.githubusercontent.com/FreshRSS/Extensions/refs/heads/main/extensions.json';
  43. $cacheFile = CACHE_PATH . '/extension_list.json';
  44. $fetchResult = null;
  45. if (FreshRSS_Context::userConf()->retrieve_extension_list === true) {
  46. if (!file_exists($cacheFile) || (time() - (filemtime($cacheFile) ?: 0) > 86400)) {
  47. $fetchResult = FreshRSS_http_Util::httpGet($extensionListUrl, $cacheFile, 'json');
  48. $json = $fetchResult['body'];
  49. } else {
  50. $json = @file_get_contents($cacheFile) ?: '';
  51. }
  52. } else {
  53. Minz_Log::warning('The extension list retrieval is disabled in privacy configuration');
  54. return [];
  55. }
  56. // we ran into problems, simply ignore them
  57. if ($json === '') {
  58. $details = '';
  59. if (is_array($fetchResult)) {
  60. $status = $fetchResult['status'];
  61. $error = $fetchResult['error'];
  62. $details = ' (HTTP status ' . $status . ($error !== '' ? '; ' . $error : '') . ')';
  63. }
  64. Minz_Log::error('Could not fetch available extension list from GitHub' . $details);
  65. return [];
  66. }
  67. // fetch the list as an array
  68. /** @var array<string,mixed> $list*/
  69. $list = json_decode($json, true);
  70. if (!is_array($list) || empty($list['extensions']) || !is_array($list['extensions'])) {
  71. Minz_Log::warning('Failed to convert extension file list');
  72. return [];
  73. }
  74. // By now, all the needed data is kept in the main extension file.
  75. // In the future we could fetch detail information from the extensions metadata.json, but I tend to stick with
  76. // the current implementation for now, unless it becomes too much effort maintain the extension list manually
  77. $extensions = [];
  78. foreach ($list['extensions'] as $extension) {
  79. if (!is_array($extension)) {
  80. continue;
  81. }
  82. if (isset($extension['version']) && is_numeric($extension['version'])) {
  83. $extension['version'] = (string)$extension['version'];
  84. }
  85. if (!array_key_exists('compatibility', $extension)) {
  86. $extension['compatibility'] = '✔';
  87. }
  88. $keys = ['author', 'description', 'directory', 'entrypoint', 'method', 'name', 'type', 'url', 'version', 'compatibility'];
  89. $extension = array_intersect_key($extension, array_flip($keys)); // Keep only valid keys
  90. $extension = array_filter($extension, 'is_string');
  91. foreach ($keys as $key) {
  92. if (empty($extension[$key])) {
  93. continue 2;
  94. }
  95. }
  96. if (!in_array($extension['type'], ['system', 'user'], true) || trim($extension['name']) === '') {
  97. continue;
  98. }
  99. /** @var ExtensionFullMetadata $extension */
  100. $extensions[] = $extension;
  101. }
  102. return array_map(static function (array $extension) {
  103. if ($extension['compatibility'] !== '✔') {
  104. $extension['compatibility'] = version_compare($extension['compatibility'], FRESHRSS_VERSION, '>=') ? '✔' : '✘';
  105. }
  106. return $extension;
  107. }, $extensions);
  108. }
  109. /**
  110. * This action handles configuration of a given extension.
  111. *
  112. * Only administrator can configure a system extension.
  113. *
  114. * Parameters are:
  115. * - e: the extension name (urlencoded)
  116. * - additional parameters which should be handle by the extension
  117. * handleConfigureAction() method (POST request).
  118. */
  119. public function configureAction(): void {
  120. if (Minz_Request::paramBoolean('ajax')) {
  121. $this->view->_layout(null);
  122. } elseif (Minz_Request::paramBoolean('slider')) {
  123. $this->indexAction();
  124. $this->view->_path('extension/index.phtml');
  125. }
  126. $ext_name = urldecode(Minz_Request::paramString('e'));
  127. $ext = Minz_ExtensionManager::findExtension($ext_name);
  128. if ($ext === null) {
  129. Minz_Error::error(404);
  130. return;
  131. }
  132. if ($ext->getType() === 'system' && !FreshRSS_Auth::hasAccess('admin')) {
  133. Minz_Error::error(403);
  134. return;
  135. }
  136. FreshRSS_View::prependTitle($ext->getName() . ' · ' . _t('admin.extensions.title') . ' · ');
  137. $this->view->extension = $ext;
  138. try {
  139. $this->view->extension->handleConfigureAction();
  140. } catch (Minz_Exception $e) { // @phpstan-ignore catch.neverThrown (Thrown by extensions)
  141. Minz_Log::error('Error while configuring extension ' . $ext->getName() . ': ' . $e->getMessage());
  142. Minz_Request::bad(_t('feedback.extensions.enable.ko', $ext_name, _url('index', 'logs')), ['c' => 'extension', 'a' => 'index']);
  143. }
  144. }
  145. /**
  146. * This action enables a disabled extension for the current user.
  147. *
  148. * System extensions can only be enabled by an administrator.
  149. * This action must be reached by a POST request.
  150. *
  151. * Parameter is:
  152. * - e: the extension name (urlencoded).
  153. */
  154. public function enableAction(): void {
  155. $url_redirect = ['c' => 'extension', 'a' => 'index'];
  156. if (Minz_Request::isPost()) {
  157. $ext_name = urldecode(Minz_Request::paramString('e'));
  158. $ext = Minz_ExtensionManager::findExtension($ext_name);
  159. if (is_null($ext)) {
  160. Minz_Request::bad(_t('feedback.extensions.not_found', $ext_name), $url_redirect);
  161. return;
  162. }
  163. if ($ext->isEnabled()) {
  164. Minz_Request::bad(_t('feedback.extensions.already_enabled', $ext_name), $url_redirect);
  165. }
  166. $type = $ext->getType();
  167. if ($type !== 'user' && !FreshRSS_Auth::hasAccess('admin')) {
  168. Minz_Request::bad(_t('feedback.extensions.no_access', $ext_name), $url_redirect);
  169. return;
  170. }
  171. $conf = null;
  172. if ($type === 'system') {
  173. $conf = FreshRSS_Context::systemConf();
  174. } elseif ($type === 'user') {
  175. $conf = FreshRSS_Context::userConf();
  176. }
  177. $res = $ext->install();
  178. if ($conf !== null && $res === true) {
  179. $ext_list = $conf->extensions_enabled;
  180. $ext_list = array_filter($ext_list, static function (string $key) use ($type) {
  181. // Remove from list the extensions that have disappeared or changed type
  182. $extension = Minz_ExtensionManager::findExtension($key);
  183. return $extension !== null && $extension->getType() === $type;
  184. }, ARRAY_FILTER_USE_KEY);
  185. $ext_list[$ext_name] = true;
  186. $conf->extensions_enabled = $ext_list;
  187. $conf->save();
  188. Minz_Request::good(
  189. _t('feedback.extensions.enable.ok', $ext_name),
  190. $url_redirect,
  191. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  192. );
  193. } else {
  194. Minz_Log::warning('Cannot enable extension ' . $ext_name . ': ' . $res);
  195. Minz_Request::bad(_t('feedback.extensions.enable.ko', $ext_name, _url('index', 'logs')), $url_redirect);
  196. }
  197. }
  198. Minz_Request::forward($url_redirect, true);
  199. }
  200. /**
  201. * This action disables an enabled extension for the current user.
  202. *
  203. * System extensions can only be disabled by an administrator.
  204. * This action must be reached by a POST request.
  205. *
  206. * Parameter is:
  207. * - e: the extension name (urlencoded).
  208. */
  209. public function disableAction(): void {
  210. $url_redirect = ['c' => 'extension', 'a' => 'index'];
  211. if (Minz_Request::isPost()) {
  212. $ext_name = urldecode(Minz_Request::paramString('e'));
  213. $ext = Minz_ExtensionManager::findExtension($ext_name);
  214. if (is_null($ext)) {
  215. Minz_Request::bad(_t('feedback.extensions.not_found', $ext_name), $url_redirect);
  216. return;
  217. }
  218. if (!$ext->isEnabled()) {
  219. Minz_Request::bad(_t('feedback.extensions.not_enabled', $ext_name), $url_redirect);
  220. }
  221. $type = $ext->getType();
  222. if ($type !== 'user' && !FreshRSS_Auth::hasAccess('admin')) {
  223. Minz_Request::bad(_t('feedback.extensions.no_access', $ext_name), $url_redirect);
  224. return;
  225. }
  226. $conf = null;
  227. if ($type === 'system') {
  228. $conf = FreshRSS_Context::systemConf();
  229. } elseif ($type === 'user') {
  230. $conf = FreshRSS_Context::userConf();
  231. }
  232. $res = $ext->uninstall();
  233. if ($conf !== null && $res === true) {
  234. $ext_list = $conf->extensions_enabled;
  235. $ext_list = array_filter($ext_list, static function (string $key) use ($type) {
  236. // Remove from list the extensions that have disappeared or changed type
  237. $extension = Minz_ExtensionManager::findExtension($key);
  238. return $extension !== null && $extension->getType() === $type;
  239. }, ARRAY_FILTER_USE_KEY);
  240. $ext_list[$ext_name] = false;
  241. $conf->extensions_enabled = $ext_list;
  242. $conf->save();
  243. Minz_Request::good(
  244. _t('feedback.extensions.disable.ok', $ext_name),
  245. $url_redirect,
  246. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  247. );
  248. } else {
  249. Minz_Log::warning('Cannot disable extension ' . $ext_name . ': ' . $res);
  250. Minz_Request::bad(_t('feedback.extensions.disable.ko', $ext_name, _url('index', 'logs')), $url_redirect);
  251. }
  252. }
  253. Minz_Request::forward($url_redirect, true);
  254. }
  255. /**
  256. * This action handles deletion of an extension.
  257. *
  258. * Only administrator can remove an extension.
  259. * This action must be reached by a POST request.
  260. *
  261. * Parameter is:
  262. * -e: extension name (urlencoded)
  263. */
  264. public function removeAction(): void {
  265. if (!FreshRSS_Auth::hasAccess('admin')) {
  266. Minz_Error::error(403);
  267. }
  268. $url_redirect = ['c' => 'extension', 'a' => 'index'];
  269. if (Minz_Request::isPost()) {
  270. $ext_name = urldecode(Minz_Request::paramString('e'));
  271. $ext = Minz_ExtensionManager::findExtension($ext_name);
  272. if (is_null($ext)) {
  273. Minz_Request::bad(_t('feedback.extensions.not_found', $ext_name), $url_redirect);
  274. return;
  275. }
  276. $res = recursive_unlink($ext->getPath());
  277. if ($res) {
  278. Minz_Request::good(
  279. _t('feedback.extensions.removed', $ext_name),
  280. $url_redirect,
  281. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  282. );
  283. } else {
  284. Minz_Request::bad(_t('feedback.extensions.cannot_remove', $ext_name), $url_redirect);
  285. }
  286. }
  287. Minz_Request::forward($url_redirect, true);
  288. }
  289. // Supported types with their associated content type
  290. public const MIME_TYPES = [
  291. 'css' => 'text/css; charset=UTF-8',
  292. 'gif' => 'image/gif',
  293. 'jpeg' => 'image/jpeg',
  294. 'jpg' => 'image/jpeg',
  295. 'js' => 'application/javascript; charset=UTF-8',
  296. 'png' => 'image/png',
  297. 'svg' => 'image/svg+xml',
  298. ];
  299. public function serveAction(): void {
  300. $extensionName = Minz_Request::paramString('x');
  301. $filename = Minz_Request::paramString('f');
  302. $mimeType = pathinfo($filename, PATHINFO_EXTENSION);
  303. if ($extensionName === '' || $filename === '' || $mimeType === '' || empty(self::MIME_TYPES[$mimeType])) {
  304. header('HTTP/1.1 400 Bad Request');
  305. die('Bad Request!');
  306. }
  307. $extension = Minz_ExtensionManager::findExtension($extensionName);
  308. if ($extension === null || !$extension->isEnabled() || ($mtime = $extension->mtimeFile($filename)) === null) {
  309. header('HTTP/1.1 404 Not Found');
  310. die('Not Found!');
  311. }
  312. $this->view->_layout(null);
  313. $content_type = self::MIME_TYPES[$mimeType];
  314. header("Content-Type: {$content_type}");
  315. header("Content-Disposition: inline; filename='{$filename}'");
  316. header('Referrer-Policy: same-origin');
  317. if (file_exists(DATA_PATH . '/no-cache.txt') || !httpConditional($mtime, cacheSeconds: 604800, cachePrivacy: 2)) {
  318. echo $extension->getFile($filename);
  319. }
  320. }
  321. }