Extension.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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 public function hasFile(string $filename): bool {
  162. if ($filename === '' || str_contains($filename, '..')) {
  163. return false;
  164. }
  165. return file_exists($this->getExtensionUserPath() . '/' . $filename);
  166. }
  167. /** Return the motification time of the user-specific, extension-specific, file or null if it does not exist */
  168. final public function mtimeFile(string $filename): ?int {
  169. if (!$this->hasFile($filename)) {
  170. return null;
  171. }
  172. return @filemtime($this->getExtensionUserPath() . '/' . $filename) ?: null;
  173. }
  174. /** Return the user-specific, extension-specific, file content or null if it does not exist */
  175. final public function getFile(string $filename): ?string {
  176. if (!$this->hasFile($filename)) {
  177. return null;
  178. }
  179. $content = @file_get_contents($this->getExtensionUserPath() . '/' . $filename);
  180. return is_string($content) ? $content : null;
  181. }
  182. /**
  183. * Return the url for a given file.
  184. *
  185. * @param string $filename name of the file to serve.
  186. * @param '' $type MIME type of the file to serve. Deprecated: always use the file extension.
  187. * @param bool $isStatic indicates if the file is a static file or a user file. Default is static.
  188. * @return string url corresponding to the file.
  189. */
  190. final public function getFileUrl(string $filename, string $type = '', bool $isStatic = true): string {
  191. if ($isStatic) {
  192. $dir = basename($this->path);
  193. $file_name_url = urlencode("{$dir}/static/{$filename}");
  194. $mtime = @filemtime("{$this->path}/static/{$filename}");
  195. return Minz_Url::display("/ext.php?f={$file_name_url}&amp;{$mtime}", 'php');
  196. } else {
  197. $username = Minz_User::name();
  198. if ($username == null) {
  199. return '';
  200. }
  201. return Minz_Url::display(['c' => 'extension', 'a' => 'serve', 'params' => [
  202. 'x' => $this->getName(),
  203. 'f' => $filename,
  204. 'm' => $this->mtimeFile($filename), // cache-busting
  205. ]]);
  206. }
  207. }
  208. /**
  209. * Register a controller in the Dispatcher.
  210. *
  211. * @param string $base_name the base name of the controller. Final name will be FreshExtension_<base_name>_Controller.
  212. */
  213. final protected function registerController(string $base_name): void {
  214. Minz_Dispatcher::registerController($base_name, $this->path);
  215. }
  216. /**
  217. * Register the views in order to be accessible by the application.
  218. */
  219. final protected function registerViews(): void {
  220. Minz_View::addBasePathname($this->path);
  221. }
  222. /**
  223. * Register i18n files from ext_dir/i18n/
  224. */
  225. final protected function registerTranslates(): void {
  226. $i18n_dir = $this->path . '/i18n';
  227. Minz_Translate::registerPath($i18n_dir);
  228. }
  229. /**
  230. * Register a new hook.
  231. *
  232. * @param string $hook_name the hook name (must exist).
  233. * @param callable $hook_function the function name to call (must be callable).
  234. */
  235. final protected function registerHook(string $hook_name, $hook_function): void {
  236. Minz_ExtensionManager::addHook($hook_name, $hook_function);
  237. }
  238. /** @param 'system'|'user' $type */
  239. private function isConfigurationEnabled(string $type): bool {
  240. if (!class_exists('FreshRSS_Context', false)) {
  241. return false;
  242. }
  243. switch ($type) {
  244. case 'system': return FreshRSS_Context::hasSystemConf();
  245. case 'user': return FreshRSS_Context::hasUserConf();
  246. default:
  247. return false;
  248. }
  249. }
  250. /** @param 'system'|'user' $type */
  251. private function isExtensionConfigured(string $type): bool {
  252. switch ($type) {
  253. case 'user':
  254. $conf = FreshRSS_Context::userConf();
  255. break;
  256. case 'system':
  257. $conf = FreshRSS_Context::systemConf();
  258. break;
  259. default:
  260. return false;
  261. }
  262. if (!$conf->hasParam('extensions')) {
  263. return false;
  264. }
  265. return array_key_exists($this->getName(), $conf->extensions);
  266. }
  267. /**
  268. * @return array<string,mixed>
  269. */
  270. final protected function getSystemConfiguration(): array {
  271. if ($this->isConfigurationEnabled('system') && $this->isExtensionConfigured('system')) {
  272. return FreshRSS_Context::systemConf()->extensions[$this->getName()];
  273. }
  274. return [];
  275. }
  276. /**
  277. * @return array<string,mixed>
  278. */
  279. final protected function getUserConfiguration(): array {
  280. if ($this->isConfigurationEnabled('user') && $this->isExtensionConfigured('user')) {
  281. return FreshRSS_Context::userConf()->extensions[$this->getName()];
  282. }
  283. return [];
  284. }
  285. final public function getSystemConfigurationValue(string $key, mixed $default = null): mixed {
  286. if (!is_array($this->system_configuration)) {
  287. $this->system_configuration = $this->getSystemConfiguration();
  288. }
  289. if (array_key_exists($key, $this->system_configuration)) {
  290. return $this->system_configuration[$key];
  291. }
  292. return $default;
  293. }
  294. final public function getUserConfigurationValue(string $key, mixed $default = null): mixed {
  295. if (!is_array($this->user_configuration)) {
  296. $this->user_configuration = $this->getUserConfiguration();
  297. }
  298. if (array_key_exists($key, $this->user_configuration)) {
  299. return $this->user_configuration[$key];
  300. }
  301. return $default;
  302. }
  303. /**
  304. * @param 'system'|'user' $type
  305. * @param array<string,mixed> $configuration
  306. */
  307. private function setConfiguration(string $type, array $configuration): void {
  308. switch ($type) {
  309. case 'system':
  310. $conf = FreshRSS_Context::systemConf();
  311. break;
  312. case 'user':
  313. $conf = FreshRSS_Context::userConf();
  314. break;
  315. default:
  316. return;
  317. }
  318. if ($conf->hasParam('extensions')) {
  319. $extensions = $conf->extensions;
  320. } else {
  321. $extensions = [];
  322. }
  323. $extensions[$this->getName()] = $configuration;
  324. $conf->extensions = $extensions;
  325. $conf->save();
  326. }
  327. /** @param array<string,mixed> $configuration */
  328. final protected function setSystemConfiguration(array $configuration): void {
  329. $this->setConfiguration('system', $configuration);
  330. $this->system_configuration = $configuration;
  331. }
  332. /** @param array<string,mixed> $configuration */
  333. final protected function setUserConfiguration(array $configuration): void {
  334. $this->setConfiguration('user', $configuration);
  335. $this->user_configuration = $configuration;
  336. }
  337. /** @phpstan-param 'system'|'user' $type */
  338. private function removeConfiguration(string $type): void {
  339. if (!$this->isConfigurationEnabled($type) || !$this->isExtensionConfigured($type)) {
  340. return;
  341. }
  342. switch ($type) {
  343. case 'system':
  344. $conf = FreshRSS_Context::systemConf();
  345. break;
  346. case 'user':
  347. $conf = FreshRSS_Context::userConf();
  348. break;
  349. default:
  350. return;
  351. }
  352. $extensions = $conf->extensions;
  353. unset($extensions[$this->getName()]);
  354. if (empty($extensions)) {
  355. $extensions = [];
  356. }
  357. $conf->extensions = $extensions;
  358. $conf->save();
  359. }
  360. final protected function removeSystemConfiguration(): void {
  361. $this->removeConfiguration('system');
  362. $this->system_configuration = null;
  363. }
  364. final protected function removeUserConfiguration(): void {
  365. $this->removeConfiguration('user');
  366. $this->user_configuration = null;
  367. }
  368. final protected function saveFile(string $filename, string $content): void {
  369. $path = $this->getExtensionUserPath();
  370. if (!file_exists($path)) {
  371. mkdir($path, 0777, true);
  372. }
  373. file_put_contents("{$path}/{$filename}", $content);
  374. }
  375. final protected function removeFile(string $filename): void {
  376. $path = $path = $this->getExtensionUserPath() . '/' . $filename;
  377. if (file_exists($path)) {
  378. unlink($path);
  379. }
  380. }
  381. /**
  382. * @param array<string,string> $policies
  383. */
  384. public function amendCsp(array &$policies): void {
  385. foreach ($this->csp_policies as $policy => $source) {
  386. if (isset($policies[$policy])) {
  387. $policies[$policy] .= ' ' . $source;
  388. } else {
  389. $policies[$policy] = $source;
  390. }
  391. }
  392. }
  393. }