Extension.php 12 KB

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