4
0

Extension.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * The extension base class.
  5. *
  6. * @phpstan-type ExtensionMetadata array{name:string,entrypoint:string,author?:string,description?:string,version?:string,type?:'system'|'user',path:string}
  7. */
  8. abstract class Minz_Extension {
  9. private readonly string $name;
  10. private readonly string $entrypoint;
  11. private readonly string $path;
  12. private string $author;
  13. private string $description;
  14. private string $version;
  15. /** @var 'system'|'user' */
  16. private string $type;
  17. /** @var array<string,mixed>|null */
  18. private ?array $user_configuration = null;
  19. /** @var array<string,mixed>|null */
  20. private ?array $system_configuration = null;
  21. /** @var array{0:'system',1:'user'} */
  22. public static array $authorized_types = [
  23. 'system',
  24. 'user',
  25. ];
  26. private bool $is_enabled;
  27. /** @var array<string,string> */
  28. protected array $csp_policies = [];
  29. /**
  30. * The constructor to assign specific information to the extension.
  31. *
  32. * Available fields are:
  33. * - name: the name of the extension (required).
  34. * - entrypoint: the extension class name (required).
  35. * - path: the pathname to the extension files (required).
  36. * - author: the name and / or email address of the extension author.
  37. * - description: a short description to describe the extension role.
  38. * - version: a version for the current extension.
  39. * - type: "system" or "user" (default).
  40. *
  41. * @param ExtensionMetadata $meta_info
  42. * contains information about the extension.
  43. */
  44. final public function __construct(array $meta_info) {
  45. if (!is_string($meta_info['name'] ?? null) || $meta_info['name'] === '') {
  46. throw new Minz_ExtensionException('Invalid `name` info!');
  47. }
  48. $this->name = $meta_info['name'];
  49. if (!is_string($meta_info['entrypoint'] ?? null) || $meta_info['entrypoint'] === '') {
  50. throw new Minz_ExtensionException('Invalid `entrypoint` info!', $this->name);
  51. }
  52. $this->entrypoint = $meta_info['entrypoint'];
  53. if (!is_string($meta_info['path'] ?? null) || $meta_info['path'] === '') {
  54. throw new Minz_ExtensionException('Invalid `path` info!', $this->name);
  55. }
  56. $this->path = $meta_info['path'];
  57. $this->author = isset($meta_info['author']) ? $meta_info['author'] : '';
  58. $this->description = isset($meta_info['description']) ? $meta_info['description'] : '';
  59. $this->version = isset($meta_info['version']) ? (string)$meta_info['version'] : '0.1';
  60. $this->setType(isset($meta_info['type']) ? $meta_info['type'] : 'user');
  61. $this->is_enabled = false;
  62. }
  63. /**
  64. * Used when installing an extension (e.g. update the database scheme).
  65. *
  66. * @return string|true true if the extension has been installed or a string explaining the problem.
  67. */
  68. public function install() {
  69. return true;
  70. }
  71. /**
  72. * Used when uninstalling an extension (e.g. revert the database scheme to
  73. * cancel changes from install).
  74. *
  75. * @return string|true true if the extension has been uninstalled or a string explaining the problem.
  76. */
  77. public function uninstall() {
  78. return true;
  79. }
  80. /**
  81. * Call at the initialization of the extension (i.e. when the extension is
  82. * enabled by the extension manager).
  83. * @return void
  84. */
  85. public function init() {
  86. $this->migrateExtensionUserPath();
  87. }
  88. /**
  89. * Set the current extension to enable.
  90. */
  91. final public function enable(): void {
  92. $this->is_enabled = true;
  93. }
  94. final public function disable(): void {
  95. $this->is_enabled = false;
  96. }
  97. /**
  98. * Return if the extension is currently enabled.
  99. *
  100. * @return bool true if extension is enabled, false otherwise.
  101. */
  102. final public function isEnabled(): bool {
  103. return $this->is_enabled;
  104. }
  105. /**
  106. * Return the content of the configure view for the current extension.
  107. *
  108. * @return string|false html content from ext_dir/configure.phtml, false if it does not exist.
  109. */
  110. final public function getConfigureView(): string|false {
  111. $filename = $this->path . '/configure.phtml';
  112. if (!file_exists($filename)) {
  113. return false;
  114. }
  115. ob_start();
  116. include $filename;
  117. return ob_get_clean();
  118. }
  119. /**
  120. * Handle the configure action.
  121. * @return void
  122. */
  123. public function handleConfigureAction() {
  124. $this->migrateExtensionUserPath();
  125. }
  126. /**
  127. * @return non-empty-string
  128. */
  129. final public function getName(): string {
  130. return $this->name;
  131. }
  132. /**
  133. * @return non-empty-string
  134. */
  135. final public function getEntrypoint(): string {
  136. return $this->entrypoint;
  137. }
  138. /**
  139. * @return non-empty-string
  140. */
  141. final public function getPath(): string {
  142. return $this->path;
  143. }
  144. final public function getAuthor(): string {
  145. return $this->author;
  146. }
  147. final public function getDescription(): string {
  148. return $this->description;
  149. }
  150. final public function getVersion(): string {
  151. return $this->version;
  152. }
  153. /** @return 'system'|'user' */
  154. final public function getType(): string {
  155. return $this->type;
  156. }
  157. /** @param 'user'|'system' $type */
  158. private function setType(string $type): void {
  159. if (!in_array($type, ['user', 'system'], true)) {
  160. throw new Minz_ExtensionException('invalid `type` info', $this->name);
  161. }
  162. $this->type = $type;
  163. }
  164. /** Return the user-specific, extension-specific, folder where this extension can save user-specific data */
  165. final protected function getExtensionUserPath(): string {
  166. $username = Minz_User::name() ?: '_';
  167. return USERS_PATH . "/{$username}/extensions/{$this->getEntrypoint()}";
  168. }
  169. private function migrateExtensionUserPath(): void {
  170. $username = Minz_User::name() ?: '_';
  171. $old_extension_user_path = USERS_PATH . "/{$username}/extensions/{$this->getName()}";
  172. $new_extension_user_path = $this->getExtensionUserPath();
  173. if (is_dir($old_extension_user_path)) {
  174. rename($old_extension_user_path, $new_extension_user_path);
  175. }
  176. }
  177. /** Return whether a user-specific, extension-specific, file exists */
  178. final public function hasFile(string $filename): bool {
  179. if ($filename === '' || str_contains($filename, '..')) {
  180. return false;
  181. }
  182. return file_exists($this->getExtensionUserPath() . '/' . $filename);
  183. }
  184. /** Return the motification time of the user-specific, extension-specific, file or null if it does not exist */
  185. final public function mtimeFile(string $filename): ?int {
  186. if (!$this->hasFile($filename)) {
  187. return null;
  188. }
  189. return @filemtime($this->getExtensionUserPath() . '/' . $filename) ?: null;
  190. }
  191. /** Return the user-specific, extension-specific, file content or null if it does not exist */
  192. final public function getFile(string $filename): ?string {
  193. if (!$this->hasFile($filename)) {
  194. return null;
  195. }
  196. $content = @file_get_contents($this->getExtensionUserPath() . '/' . $filename);
  197. return is_string($content) ? $content : null;
  198. }
  199. /**
  200. * Return the url for a given file.
  201. *
  202. * @param string $filename name of the file to serve.
  203. * @param '' $type MIME type of the file to serve. Deprecated: always use the file extension.
  204. * @param bool $isStatic indicates if the file is a static file or a user file. Default is static.
  205. * @return string url corresponding to the file.
  206. */
  207. final public function getFileUrl(string $filename, string $type = '', bool $isStatic = true): string {
  208. if ($isStatic) {
  209. $dir = basename($this->path);
  210. $file_name_url = urlencode("{$dir}/static/{$filename}");
  211. $mtime = @filemtime("{$this->path}/static/{$filename}");
  212. return Minz_Url::display("/ext.php?f={$file_name_url}&amp;{$mtime}", 'php');
  213. } else {
  214. $username = Minz_User::name();
  215. if ($username == null) {
  216. return '';
  217. }
  218. return Minz_Url::display(['c' => 'extension', 'a' => 'serve', 'params' => [
  219. 'x' => $this->getName(),
  220. 'f' => $filename,
  221. 'm' => $this->mtimeFile($filename), // cache-busting
  222. ]]);
  223. }
  224. }
  225. /**
  226. * Register a controller in the Dispatcher.
  227. *
  228. * @param string $base_name the base name of the controller. Final name will be FreshExtension_<base_name>_Controller.
  229. */
  230. final protected function registerController(string $base_name): void {
  231. Minz_Dispatcher::registerController($base_name, $this->path);
  232. }
  233. /**
  234. * Register the views in order to be accessible by the application.
  235. */
  236. final protected function registerViews(): void {
  237. Minz_View::addBasePathname($this->path);
  238. }
  239. /**
  240. * Register i18n files from ext_dir/i18n/
  241. */
  242. final protected function registerTranslates(): void {
  243. $i18n_dir = $this->path . '/i18n';
  244. Minz_Translate::registerPath($i18n_dir);
  245. }
  246. /**
  247. * Register a new hook.
  248. *
  249. * @param Minz_HookType|string $hook_name the hook name (must exist).
  250. * @param callable $hook_function the function name to call (must be callable).
  251. * @param int $priority the priority of the hook, default priority is 0, the higher the value the lower the priority
  252. */
  253. final protected function registerHook(Minz_HookType|string $hook_name, $hook_function, int $priority = Minz_Hook::DEFAULT_PRIORITY): void {
  254. Minz_ExtensionManager::addHook($hook_name, $hook_function, $priority);
  255. }
  256. /** @param 'system'|'user' $type */
  257. private function isConfigurationEnabled(string $type): bool {
  258. if (!class_exists('FreshRSS_Context', false)) {
  259. return false;
  260. }
  261. switch ($type) {
  262. case 'system': return FreshRSS_Context::hasSystemConf();
  263. case 'user': return FreshRSS_Context::hasUserConf();
  264. default:
  265. return false;
  266. }
  267. }
  268. /** @param 'system'|'user' $type */
  269. private function isExtensionConfigured(string $type): bool {
  270. switch ($type) {
  271. case 'user':
  272. $conf = FreshRSS_Context::userConf();
  273. break;
  274. case 'system':
  275. $conf = FreshRSS_Context::systemConf();
  276. break;
  277. default:
  278. return false;
  279. }
  280. if (!$conf->hasParam('extensions')) {
  281. return false;
  282. }
  283. return array_key_exists($this->getName(), $conf->extensions);
  284. }
  285. /**
  286. * @return array<string,mixed>
  287. * @deprecated Use typed versions instead. Will soon be marked as private.
  288. * @internal
  289. */
  290. final protected function getSystemConfiguration(): array {
  291. if ($this->isConfigurationEnabled('system') && $this->isExtensionConfigured('system')) {
  292. return FreshRSS_Context::systemConf()->extensions[$this->getName()];
  293. }
  294. return [];
  295. }
  296. /**
  297. * @return array<string,mixed>
  298. * @deprecated Use typed versions instead. Will soon be marked as private.
  299. * @internal
  300. */
  301. final protected function getUserConfiguration(): array {
  302. if ($this->isConfigurationEnabled('user') && $this->isExtensionConfigured('user')) {
  303. return FreshRSS_Context::userConf()->extensions[$this->getName()];
  304. }
  305. return [];
  306. }
  307. /**
  308. * @deprecated Use typed versions instead. Will soon be marked as private.
  309. * @internal
  310. */
  311. final public function getSystemConfigurationValue(string $key, mixed $default = null): mixed {
  312. if (!is_array($this->system_configuration)) {
  313. $this->system_configuration = $this->getSystemConfiguration();
  314. }
  315. if (array_key_exists($key, $this->system_configuration)) {
  316. return $this->system_configuration[$key];
  317. }
  318. return $default;
  319. }
  320. /**
  321. * @param non-empty-string $key
  322. * @return array<int|string,mixed>|null
  323. */
  324. final public function getSystemConfigurationArray(string $key): ?array {
  325. /** @phpstan-ignore method.deprecated */
  326. $a = $this->getSystemConfigurationValue($key);
  327. return is_array($a) ? $a : null;
  328. }
  329. /** @param non-empty-string $key */
  330. final public function getSystemConfigurationBool(string $key): ?bool {
  331. /** @phpstan-ignore method.deprecated */
  332. $a = $this->getSystemConfigurationValue($key);
  333. return is_bool($a) ? $a : null;
  334. }
  335. /** @param non-empty-string $key */
  336. final public function getSystemConfigurationInt(string $key): ?int {
  337. /** @phpstan-ignore method.deprecated */
  338. $a = $this->getSystemConfigurationValue($key);
  339. return is_numeric($a) ? (int)$a : null;
  340. }
  341. /** @param non-empty-string $key */
  342. final public function getSystemConfigurationString(string $key): ?string {
  343. /** @phpstan-ignore method.deprecated */
  344. $a = $this->getSystemConfigurationValue($key);
  345. return is_string($a) ? $a : null;
  346. }
  347. /**
  348. * @deprecated Use typed versions instead. Will soon be marked as private.
  349. * @internal
  350. */
  351. final public function getUserConfigurationValue(string $key, mixed $default = null): mixed {
  352. if (!is_array($this->user_configuration)) {
  353. $this->user_configuration = $this->getUserConfiguration();
  354. }
  355. if (array_key_exists($key, $this->user_configuration)) {
  356. return $this->user_configuration[$key];
  357. }
  358. return $default;
  359. }
  360. /**
  361. * @param non-empty-string $key
  362. * @return array<int|string,mixed>|null
  363. */
  364. final public function getUserConfigurationArray(string $key): ?array {
  365. // @phpstan-ignore-next-line method.deprecated
  366. $a = $this->getUserConfigurationValue($key);
  367. return is_array($a) ? $a : null;
  368. }
  369. /** @param non-empty-string $key */
  370. final public function getUserConfigurationBool(string $key): ?bool {
  371. // @phpstan-ignore-next-line method.deprecated
  372. $a = $this->getUserConfigurationValue($key);
  373. return is_bool($a) ? $a : null;
  374. }
  375. /** @param non-empty-string $key */
  376. final public function getUserConfigurationInt(string $key): ?int {
  377. // @phpstan-ignore-next-line method.deprecated
  378. $a = $this->getUserConfigurationValue($key);
  379. return is_numeric($a) ? (int)$a : null;
  380. }
  381. /** @param non-empty-string $key */
  382. final public function getUserConfigurationString(string $key): ?string {
  383. // @phpstan-ignore-next-line method.deprecated
  384. $a = $this->getUserConfigurationValue($key);
  385. return is_string($a) ? $a : null;
  386. }
  387. /**
  388. * @param 'system'|'user' $type
  389. * @param array<string,mixed> $configuration
  390. */
  391. private function setConfiguration(string $type, array $configuration): void {
  392. switch ($type) {
  393. case 'system':
  394. $conf = FreshRSS_Context::systemConf();
  395. break;
  396. case 'user':
  397. $conf = FreshRSS_Context::userConf();
  398. break;
  399. default:
  400. return;
  401. }
  402. if ($conf->hasParam('extensions')) {
  403. $extensions = $conf->extensions;
  404. } else {
  405. $extensions = [];
  406. }
  407. $extensions[$this->getName()] = $configuration;
  408. $conf->extensions = $extensions;
  409. $conf->save();
  410. }
  411. /**
  412. * @param array<string,mixed> $configuration
  413. * @deprecated Use {@see setSystemConfigurationValue()} instead. Will soon be marked as private.
  414. * @internal
  415. */
  416. final protected function setSystemConfiguration(array $configuration): void {
  417. $this->setConfiguration('system', $configuration);
  418. $this->system_configuration = $configuration;
  419. }
  420. /**
  421. * @param non-empty-string $key
  422. * @param array<string,mixed>|mixed|null $value
  423. */
  424. final protected function setSystemConfigurationValue(string $key, $value = null): void {
  425. if (!is_array($this->system_configuration)) {
  426. /** @phpstan-ignore method.deprecated */
  427. $this->system_configuration = $this->getSystemConfiguration();
  428. }
  429. if (isset($this->system_configuration[$key]) && $value === null) {
  430. unset($this->system_configuration[$key]);
  431. } elseif ($value !== null) {
  432. $this->system_configuration[$key] = $value;
  433. }
  434. $this->setConfiguration('system', $this->system_configuration);
  435. }
  436. /**
  437. * @param array<string,mixed> $configuration
  438. * @deprecated Use {@see setUserConfigurationValue()} instead. Will soon be marked as private.
  439. * @internal
  440. */
  441. final protected function setUserConfiguration(array $configuration): void {
  442. $this->setConfiguration('user', $configuration);
  443. $this->user_configuration = $configuration;
  444. }
  445. /**
  446. * @param non-empty-string $key
  447. * @param array<string,mixed>|mixed|null $value
  448. */
  449. final protected function setUserConfigurationValue(string $key, $value = null): void {
  450. if (!is_array($this->user_configuration)) {
  451. /** @phpstan-ignore method.deprecated */
  452. $this->user_configuration = $this->getUserConfiguration();
  453. }
  454. if (isset($this->user_configuration[$key]) && $value === null) {
  455. unset($this->user_configuration[$key]);
  456. } elseif ($value !== null) {
  457. $this->user_configuration[$key] = $value;
  458. }
  459. $this->setConfiguration('user', $this->user_configuration);
  460. }
  461. /** @phpstan-param 'system'|'user' $type */
  462. private function removeConfiguration(string $type): void {
  463. if (!$this->isConfigurationEnabled($type) || !$this->isExtensionConfigured($type)) {
  464. return;
  465. }
  466. switch ($type) {
  467. case 'system':
  468. $conf = FreshRSS_Context::systemConf();
  469. break;
  470. case 'user':
  471. $conf = FreshRSS_Context::userConf();
  472. break;
  473. default:
  474. return;
  475. }
  476. $extensions = $conf->extensions;
  477. unset($extensions[$this->getName()]);
  478. if (empty($extensions)) {
  479. $extensions = [];
  480. }
  481. $conf->extensions = $extensions;
  482. $conf->save();
  483. }
  484. final protected function removeSystemConfiguration(): void {
  485. $this->removeConfiguration('system');
  486. $this->system_configuration = null;
  487. }
  488. final protected function removeUserConfiguration(): void {
  489. $this->removeConfiguration('user');
  490. $this->user_configuration = null;
  491. }
  492. final protected function saveFile(string $filename, string $content): void {
  493. $path = $this->getExtensionUserPath();
  494. if (!file_exists($path)) {
  495. mkdir($path, 0777, true);
  496. }
  497. file_put_contents("{$path}/{$filename}", $content);
  498. }
  499. final protected function removeFile(string $filename): void {
  500. $path = $path = $this->getExtensionUserPath() . '/' . $filename;
  501. if (file_exists($path)) {
  502. unlink($path);
  503. }
  504. }
  505. /**
  506. * @param array<string,string> $policies
  507. */
  508. public function amendCsp(array &$policies): void {
  509. foreach ($this->csp_policies as $policy => $source) {
  510. if (isset($policies[$policy])) {
  511. $policies[$policy] .= ' ' . $source;
  512. } else {
  513. $policies[$policy] = $source;
  514. }
  515. }
  516. }
  517. }