Extension.php 12 KB

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