extensionController.php 12 KB

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