Extension.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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 string $name;
  10. private string $entrypoint;
  11. private 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. $this->name = $meta_info['name'];
  46. $this->entrypoint = $meta_info['entrypoint'];
  47. $this->path = $meta_info['path'];
  48. $this->author = isset($meta_info['author']) ? $meta_info['author'] : '';
  49. $this->description = isset($meta_info['description']) ? $meta_info['description'] : '';
  50. $this->version = isset($meta_info['version']) ? (string)$meta_info['version'] : '0.1';
  51. $this->setType(isset($meta_info['type']) ? $meta_info['type'] : 'user');
  52. $this->is_enabled = false;
  53. }
  54. /**
  55. * Used when installing an extension (e.g. update the database scheme).
  56. *
  57. * @return string|true true if the extension has been installed or a string explaining the problem.
  58. */
  59. public function install() {
  60. return true;
  61. }
  62. /**
  63. * Used when uninstalling an extension (e.g. revert the database scheme to
  64. * cancel changes from install).
  65. *
  66. * @return string|true true if the extension has been uninstalled or a string explaining the problem.
  67. */
  68. public function uninstall() {
  69. return true;
  70. }
  71. /**
  72. * Call at the initialization of the extension (i.e. when the extension is
  73. * enabled by the extension manager).
  74. * @return void
  75. */
  76. public function init() {
  77. $this->migrateExtensionUserPath();
  78. }
  79. /**
  80. * Set the current extension to enable.
  81. */
  82. final public function enable(): void {
  83. $this->is_enabled = true;
  84. }
  85. final public function disable(): void {
  86. $this->is_enabled = false;
  87. }
  88. /**
  89. * Return if the extension is currently enabled.
  90. *
  91. * @return bool true if extension is enabled, false otherwise.
  92. */
  93. final public function isEnabled(): bool {
  94. return $this->is_enabled;
  95. }
  96. /**
  97. * Return the content of the configure view for the current extension.
  98. *
  99. * @return string|false html content from ext_dir/configure.phtml, false if it does not exist.
  100. */
  101. final public function getConfigureView(): string|false {
  102. $filename = $this->path . '/configure.phtml';
  103. if (!file_exists($filename)) {
  104. return false;
  105. }
  106. ob_start();
  107. include $filename;
  108. return ob_get_clean();
  109. }
  110. /**
  111. * Handle the configure action.
  112. * @return void
  113. */
  114. public function handleConfigureAction() {
  115. $this->migrateExtensionUserPath();
  116. }
  117. /**
  118. * Getters and setters.
  119. */
  120. final public function getName(): string {
  121. return $this->name;
  122. }
  123. final public function getEntrypoint(): string {
  124. return $this->entrypoint;
  125. }
  126. final public function getPath(): string {
  127. return $this->path;
  128. }
  129. final public function getAuthor(): string {
  130. return $this->author;
  131. }
  132. final public function getDescription(): string {
  133. return $this->description;
  134. }
  135. final public function getVersion(): string {
  136. return $this->version;
  137. }
  138. /** @return 'system'|'user' */
  139. final public function getType(): string {
  140. return $this->type;
  141. }
  142. /** @param 'user'|'system' $type */
  143. private function setType(string $type): void {
  144. if (!in_array($type, ['user', 'system'], true)) {
  145. throw new Minz_ExtensionException('invalid `type` info', $this->name);
  146. }
  147. $this->type = $type;
  148. }
  149. /** Return the user-specific, extension-specific, folder where this extension can save user-specific data */
  150. final protected function getExtensionUserPath(): string {
  151. $username = Minz_User::name() ?: '_';
  152. return USERS_PATH . "/{$username}/extensions/{$this->getEntrypoint()}";
  153. }
  154. private function migrateExtensionUserPath(): void {
  155. $username = Minz_User::name() ?: '_';
  156. $old_extension_user_path = USERS_PATH . "/{$username}/extensions/{$this->getName()}";
  157. $new_extension_user_path = $this->getExtensionUserPath();
  158. if (is_dir($old_extension_user_path)) {
  159. rename($old_extension_user_path, $new_extension_user_path);
  160. }
  161. }
  162. /** Return whether a user-specific, extension-specific, file exists */
  163. final public function hasFile(string $filename): bool {
  164. if ($filename === '' || str_contains($filename, '..')) {
  165. return false;
  166. }
  167. return file_exists($this->getExtensionUserPath() . '/' . $filename);
  168. }
  169. /** Return the motification time of the user-specific, extension-specific, file or null if it does not exist */
  170. final public function mtimeFile(string $filename): ?int {
  171. if (!$this->hasFile($filename)) {
  172. return null;
  173. }
  174. return @filemtime($this->getExtensionUserPath() . '/' . $filename) ?: null;
  175. }
  176. /** Return the user-specific, extension-specific, file content or null if it does not exist */
  177. final public function getFile(string $filename): ?string {
  178. if (!$this->hasFile($filename)) {
  179. return null;
  180. }
  181. $content = @file_get_contents($this->getExtensionUserPath() . '/' . $filename);
  182. return is_string($content) ? $content : null;
  183. }
  184. /**
  185. * Return the url for a given file.
  186. *
  187. * @param string $filename name of the file to serve.
  188. * @param '' $type MIME type of the file to serve. Deprecated: always use the file extension.
  189. * @param bool $isStatic indicates if the file is a static file or a user file. Default is static.
  190. * @return string url corresponding to the file.
  191. */
  192. final public function getFileUrl(string $filename, string $type = '', bool $isStatic = true): string {
  193. if ($isStatic) {
  194. $dir = basename($this->path);
  195. $file_name_url = urlencode("{$dir}/static/{$filename}");
  196. $mtime = @filemtime("{$this->path}/static/{$filename}");
  197. return Minz_Url::display("/ext.php?f={$file_name_url}&amp;{$mtime}", 'php');
  198. } else {
  199. $username = Minz_User::name();
  200. if ($username == null) {
  201. return '';
  202. }
  203. return Minz_Url::display(['c' => 'extension', 'a' => 'serve', 'params' => [
  204. 'x' => $this->getName(),
  205. 'f' => $filename,
  206. 'm' => $this->mtimeFile($filename), // cache-busting
  207. ]]);
  208. }
  209. }
  210. /**
  211. * Register a controller in the Dispatcher.
  212. *
  213. * @param string $base_name the base name of the controller. Final name will be FreshExtension_<base_name>_Controller.
  214. */
  215. final protected function registerController(string $base_name): void {
  216. Minz_Dispatcher::registerController($base_name, $this->path);
  217. }
  218. /**
  219. * Register the views in order to be accessible by the application.
  220. */
  221. final protected function registerViews(): void {
  222. Minz_View::addBasePathname($this->path);
  223. }
  224. /**
  225. * Register i18n files from ext_dir/i18n/
  226. */
  227. final protected function registerTranslates(): void {
  228. $i18n_dir = $this->path . '/i18n';
  229. Minz_Translate::registerPath($i18n_dir);
  230. }
  231. /**
  232. * Register a new hook.
  233. *
  234. * @param Minz_HookType|string $hook_name the hook name (must exist).
  235. * @param callable $hook_function the function name to call (must be callable).
  236. * @param int $priority the priority of the hook, default priority is 0, the higher the value the lower the priority
  237. */
  238. final protected function registerHook(Minz_HookType|string $hook_name, $hook_function, int $priority = Minz_Hook::DEFAULT_PRIORITY): void {
  239. Minz_ExtensionManager::addHook($hook_name, $hook_function, $priority);
  240. }
  241. /** @param 'system'|'user' $type */
  242. private function isConfigurationEnabled(string $type): bool {
  243. if (!class_exists('FreshRSS_Context', false)) {
  244. return false;
  245. }
  246. switch ($type) {
  247. case 'system': return FreshRSS_Context::hasSystemConf();
  248. case 'user': return FreshRSS_Context::hasUserConf();
  249. default:
  250. return false;
  251. }
  252. }
  253. /** @param 'system'|'user' $type */
  254. private function isExtensionConfigured(string $type): bool {
  255. switch ($type) {
  256. case 'user':
  257. $conf = FreshRSS_Context::userConf();
  258. break;
  259. case 'system':
  260. $conf = FreshRSS_Context::systemConf();
  261. break;
  262. default:
  263. return false;
  264. }
  265. if (!$conf->hasParam('extensions')) {
  266. return false;
  267. }
  268. return array_key_exists($this->getName(), $conf->extensions);
  269. }
  270. /**
  271. * @return array<string,mixed>
  272. */
  273. final protected function getSystemConfiguration(): array {
  274. if ($this->isConfigurationEnabled('system') && $this->isExtensionConfigured('system')) {
  275. return FreshRSS_Context::systemConf()->extensions[$this->getName()];
  276. }
  277. return [];
  278. }
  279. /**
  280. * @return array<string,mixed>
  281. */
  282. final protected function getUserConfiguration(): array {
  283. if ($this->isConfigurationEnabled('user') && $this->isExtensionConfigured('user')) {
  284. return FreshRSS_Context::userConf()->extensions[$this->getName()];
  285. }
  286. return [];
  287. }
  288. final public function getSystemConfigurationValue(string $key, mixed $default = null): mixed {
  289. if (!is_array($this->system_configuration)) {
  290. $this->system_configuration = $this->getSystemConfiguration();
  291. }
  292. if (array_key_exists($key, $this->system_configuration)) {
  293. return $this->system_configuration[$key];
  294. }
  295. return $default;
  296. }
  297. final public function getUserConfigurationValue(string $key, mixed $default = null): mixed {
  298. if (!is_array($this->user_configuration)) {
  299. $this->user_configuration = $this->getUserConfiguration();
  300. }
  301. if (array_key_exists($key, $this->user_configuration)) {
  302. return $this->user_configuration[$key];
  303. }
  304. return $default;
  305. }
  306. /**
  307. * @param 'system'|'user' $type
  308. * @param array<string,mixed> $configuration
  309. */
  310. private function setConfiguration(string $type, array $configuration): void {
  311. switch ($type) {
  312. case 'system':
  313. $conf = FreshRSS_Context::systemConf();
  314. break;
  315. case 'user':
  316. $conf = FreshRSS_Context::userConf();
  317. break;
  318. default:
  319. return;
  320. }
  321. if ($conf->hasParam('extensions')) {
  322. $extensions = $conf->extensions;
  323. } else {
  324. $extensions = [];
  325. }
  326. $extensions[$this->getName()] = $configuration;
  327. $conf->extensions = $extensions;
  328. $conf->save();
  329. }
  330. /** @param array<string,mixed> $configuration */
  331. final protected function setSystemConfiguration(array $configuration): void {
  332. $this->setConfiguration('system', $configuration);
  333. $this->system_configuration = $configuration;
  334. }
  335. /** @param array<string,mixed> $configuration */
  336. final protected function setUserConfiguration(array $configuration): void {
  337. $this->setConfiguration('user', $configuration);
  338. $this->user_configuration = $configuration;
  339. }
  340. /** @phpstan-param 'system'|'user' $type */
  341. private function removeConfiguration(string $type): void {
  342. if (!$this->isConfigurationEnabled($type) || !$this->isExtensionConfigured($type)) {
  343. return;
  344. }
  345. switch ($type) {
  346. case 'system':
  347. $conf = FreshRSS_Context::systemConf();
  348. break;
  349. case 'user':
  350. $conf = FreshRSS_Context::userConf();
  351. break;
  352. default:
  353. return;
  354. }
  355. $extensions = $conf->extensions;
  356. unset($extensions[$this->getName()]);
  357. if (empty($extensions)) {
  358. $extensions = [];
  359. }
  360. $conf->extensions = $extensions;
  361. $conf->save();
  362. }
  363. final protected function removeSystemConfiguration(): void {
  364. $this->removeConfiguration('system');
  365. $this->system_configuration = null;
  366. }
  367. final protected function removeUserConfiguration(): void {
  368. $this->removeConfiguration('user');
  369. $this->user_configuration = null;
  370. }
  371. final protected function saveFile(string $filename, string $content): void {
  372. $path = $this->getExtensionUserPath();
  373. if (!file_exists($path)) {
  374. mkdir($path, 0777, true);
  375. }
  376. file_put_contents("{$path}/{$filename}", $content);
  377. }
  378. final protected function removeFile(string $filename): void {
  379. $path = $path = $this->getExtensionUserPath() . '/' . $filename;
  380. if (file_exists($path)) {
  381. unlink($path);
  382. }
  383. }
  384. /**
  385. * @param array<string,string> $policies
  386. */
  387. public function amendCsp(array &$policies): void {
  388. foreach ($this->csp_policies as $policy => $source) {
  389. if (isset($policies[$policy])) {
  390. $policies[$policy] .= ' ' . $source;
  391. } else {
  392. $policies[$policy] = $source;
  393. }
  394. }
  395. }
  396. }