Extensions.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. <?php
  2. /**
  3. * This file is part of the ForkBB <https://github.com/forkbb>.
  4. *
  5. * @copyright (c) Visman <mio.visman@yandex.ru, https://github.com/MioVisman>
  6. * @license The MIT License (MIT)
  7. */
  8. declare(strict_types=1);
  9. namespace ForkBB\Models\Extension;
  10. use ForkBB\Models\Extension\Extension;
  11. use ForkBB\Models\Manager;
  12. use FilesystemIterator;
  13. use RecursiveDirectoryIterator;
  14. use RecursiveIteratorIterator;
  15. use RegexIterator;
  16. use RuntimeException;
  17. class Extensions extends Manager
  18. {
  19. /**
  20. * Ключ модели для контейнера
  21. */
  22. protected string $cKey = 'Extensions';
  23. /**
  24. * Список отсканированных папок
  25. */
  26. protected array $folders = [];
  27. /**
  28. * Текст ошибки
  29. */
  30. protected string|array $error = '';
  31. protected string $commonFile;
  32. protected string $preFile;
  33. /**
  34. * Возвращает action (или свойство) по его имени
  35. */
  36. public function __get(string $name): mixed
  37. {
  38. return 'error' === $name ? $this->error : parent::__get($name);
  39. }
  40. /**
  41. * Инициализирует менеджер
  42. */
  43. public function init(): Extensions
  44. {
  45. $this->commonFile = $this->c->DIR_CONFIG . '/ext/common.php';
  46. $this->preFile = $this->c->DIR_CONFIG . '/ext/pre.php';
  47. $this->fromDB();
  48. $list = $this->scan($this->c->DIR_EXT);
  49. $this->fromList($this->prepare($list));
  50. \uasort($this->repository, function (Extension $a, Extension $b) {
  51. return $a->dispalyName <=> $b->dispalyName;
  52. });
  53. return $this;
  54. }
  55. /**
  56. * Загружает в репозиторий из БД список расширений
  57. */
  58. protected function fromDB(): void
  59. {
  60. $query = 'SELECT ext_name, ext_status, ext_data
  61. FROM ::extensions
  62. ORDER BY ext_name';
  63. $stmt = $this->c->DB->query($query);
  64. while ($row = $stmt->fetch()) {
  65. $model = $this->c->ExtensionModel->setModelAttrs([
  66. 'name' => $row['ext_name'],
  67. 'dbStatus' => $row['ext_status'],
  68. 'dbData' => \json_decode($row['ext_data'], true, 512, \JSON_THROW_ON_ERROR),
  69. ]);
  70. $this->set($row['ext_name'], $model);
  71. }
  72. }
  73. /**
  74. * Заполняет массив данными из файлов composer.json
  75. */
  76. protected function scan(string $folder, array $result = []): array
  77. {
  78. $folder = \rtrim($folder, '\\/');
  79. if (
  80. empty($folder)
  81. || ! \is_dir($folder)
  82. ) {
  83. throw new RuntimeException("Not a directory: {$folder}");
  84. }
  85. $iterator = new RecursiveIteratorIterator(
  86. new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS)
  87. );
  88. $files = new RegexIterator($iterator, '%[\\\\/]composer\.json$%i', RegexIterator::MATCH);
  89. foreach ($files as $file) {
  90. $data = \file_get_contents($file->getPathname());
  91. if (\is_string($data)) {
  92. $data = \json_decode($data, true);
  93. }
  94. $result[$file->getPath()] = $data;
  95. }
  96. $this->folders[] = $folder;
  97. return $result;
  98. }
  99. /**
  100. * Подготавливает данные для моделей
  101. */
  102. protected function prepare(array $files): array
  103. {
  104. $v = clone $this->c->Validator;
  105. $v = $v->reset()
  106. ->addValidators([
  107. ])->addRules([
  108. 'name' => 'required|string|regex:%^[a-z0-9](?:[_.-]?[a-z0-9]+)*/[a-z0-9](?:[_.-]?[a-z0-9]+)*$%',
  109. 'type' => 'required|string|in:forkbb-extension',
  110. 'description' => 'required|string',
  111. 'homepage' => 'string',
  112. 'version' => 'required|string',
  113. 'time' => 'string',
  114. 'license' => 'string',
  115. 'authors' => 'required|array',
  116. 'authors.*.name' => 'required|string',
  117. 'authors.*.email' => 'string',
  118. 'authors.*.homepage' => 'string',
  119. 'authors.*.role' => 'string',
  120. 'autoload.psr-4' => 'array',
  121. 'autoload.psr-4.*' => 'required|string',
  122. 'require' => 'array',
  123. 'extra' => 'required|array',
  124. 'extra.display-name' => 'required|string',
  125. 'extra.requirements' => 'array',
  126. 'extra.symlinks' => 'array',
  127. 'extra.symlinks.*.type' => 'required|string|in:public',
  128. 'extra.symlinks.*.target' => 'required|string',
  129. 'extra.symlinks.*.link' => 'required|string',
  130. 'extra.templates' => 'array',
  131. 'extra.templates.*.type' => 'required|string|in:pre',
  132. 'extra.templates.*.template' => 'required|string',
  133. 'extra.templates.*.name' => 'string',
  134. 'extra.templates.*.priority' => 'integer',
  135. 'extra.templates.*.file' => 'string',
  136. ])->addAliases([
  137. ])->addArguments([
  138. ])->addMessages([
  139. ]);
  140. $result = [];
  141. foreach ($files as $path => $file) {
  142. if (! \is_array($file)) {
  143. continue;
  144. } elseif (! $v->validation($file)) {
  145. continue;
  146. }
  147. $data = $v->getData(true);
  148. $data['path'] = $path;
  149. $result[$v->name] = $data;
  150. }
  151. return $result;
  152. }
  153. /**
  154. * Дополняет репозиторий данными из файлов composer.json
  155. */
  156. protected function fromList(array $list): void
  157. {
  158. foreach ($list as $name => $data) {
  159. $model = $this->get($name);
  160. if (! $model instanceof Extension) {
  161. $model = $this->c->ExtensionModel->setModelAttrs([
  162. 'name' => $name,
  163. 'fileData' => $data,
  164. ]);
  165. $this->set($name, $model);
  166. } else {
  167. $model->setModelAttr('fileData', $data);
  168. }
  169. }
  170. }
  171. /**
  172. * Устанавливает расширение
  173. */
  174. public function install(Extension $ext): bool
  175. {
  176. if (true !== $ext->canInstall) {
  177. $this->error = 'Invalid action';
  178. return false;
  179. }
  180. $result = $ext->prepare();
  181. if (true !== $result) {
  182. $this->error = $result;
  183. return false;
  184. }
  185. $vars = [
  186. ':name' => $ext->name,
  187. ':data' => \json_encode($ext->fileData, FORK_JSON_ENCODE),
  188. ];
  189. $query = 'INSERT INTO ::extensions (ext_name, ext_status, ext_data)
  190. VALUES(?s:name, 1, ?s:data)';
  191. $ext->setModelAttrs([
  192. 'name' => $ext->name,
  193. 'dbStatus' => 1,
  194. 'dbData' => $ext->fileData,
  195. 'fileData' => $ext->fileData,
  196. ]);
  197. if (true !== $this->updateCommon($ext)) {
  198. $this->error = 'An error occurred in updateCommon';
  199. return false;
  200. }
  201. $this->setSymlinks($ext);
  202. $this->updateIndividual();
  203. $this->c->DB->exec($query, $vars);
  204. return true;
  205. }
  206. /**
  207. * Удаляет расширение
  208. */
  209. public function uninstall(Extension $ext): bool
  210. {
  211. if (true !== $ext->canUninstall) {
  212. $this->error = 'Invalid action';
  213. return false;
  214. }
  215. $oldStatus = $ext->dbStatus;
  216. $vars = [
  217. ':name' => $ext->name,
  218. ];
  219. $query = 'DELETE
  220. FROM ::extensions
  221. WHERE ext_name=?s:name';
  222. $ext->setModelAttrs([
  223. 'name' => $ext->name,
  224. 'dbStatus' => null,
  225. 'dbData' => null,
  226. 'fileData' => $ext->fileData,
  227. ]);
  228. $this->removeSymlinks($ext);
  229. if (true !== $this->updateCommon($ext)) {
  230. $this->error = 'An error occurred in updateCommon';
  231. return false;
  232. }
  233. if ($oldStatus) {
  234. $this->updateIndividual();
  235. }
  236. $this->c->DB->exec($query, $vars);
  237. return true;
  238. }
  239. /**
  240. * Обновляет расширение
  241. */
  242. public function update(Extension $ext): bool
  243. {
  244. if (true === $ext->canUpdate) {
  245. return $this->updown($ext);
  246. } else {
  247. $this->error = 'Invalid action';
  248. return false;
  249. }
  250. }
  251. /**
  252. * Обновляет расширение
  253. */
  254. public function downdate(Extension $ext): bool
  255. {
  256. if (true === $ext->canDowndate) {
  257. return $this->updown($ext);
  258. } else {
  259. $this->error = 'Invalid action';
  260. return false;
  261. }
  262. }
  263. protected function updown(Extension $ext): bool
  264. {
  265. $oldStatus = $ext->dbStatus;
  266. $result = $ext->prepare();
  267. if (true !== $result) {
  268. $this->error = $result;
  269. return false;
  270. }
  271. $vars = [
  272. ':name' => $ext->name,
  273. ':data' => \json_encode($ext->fileData, FORK_JSON_ENCODE),
  274. ];
  275. $query = 'UPDATE ::extensions SET ext_data=?s:data
  276. WHERE ext_name=?s:name';
  277. $ext->setModelAttrs([
  278. 'name' => $ext->name,
  279. 'dbStatus' => $ext->dbStatus,
  280. 'dbData' => $ext->fileData,
  281. 'fileData' => $ext->fileData,
  282. ]);
  283. $this->removeSymlinks($ext);
  284. if (true !== $this->updateCommon($ext)) {
  285. $this->error = 'An error occurred in updateCommon';
  286. return false;
  287. }
  288. $this->setSymlinks($ext);
  289. if ($oldStatus) {
  290. $this->updateIndividual();
  291. }
  292. $this->c->DB->exec($query, $vars);
  293. return true;
  294. }
  295. /**
  296. * Включает расширение
  297. */
  298. public function enable(Extension $ext): bool
  299. {
  300. if (true !== $ext->canEnable) {
  301. $this->error = 'Invalid action';
  302. return false;
  303. }
  304. $vars = [
  305. ':name' => $ext->name,
  306. ];
  307. $query = 'UPDATE ::extensions SET ext_status=1
  308. WHERE ext_name=?s:name';
  309. $ext->setModelAttrs([
  310. 'name' => $ext->name,
  311. 'dbStatus' => 1,
  312. 'dbData' => $ext->dbData,
  313. 'fileData' => $ext->fileData,
  314. ]);
  315. $this->setSymlinks($ext);
  316. $this->updateIndividual();
  317. $this->c->DB->exec($query, $vars);
  318. return true;
  319. }
  320. /**
  321. * Выключает расширение
  322. */
  323. public function disable(Extension $ext): bool
  324. {
  325. if (true !== $ext->canDisable) {
  326. $this->error = 'Invalid action';
  327. return false;
  328. }
  329. $vars = [
  330. ':name' => $ext->name,
  331. ];
  332. $query = 'UPDATE ::extensions SET ext_status=0
  333. WHERE ext_name=?s:name';
  334. $ext->setModelAttrs([
  335. 'name' => $ext->name,
  336. 'dbStatus' => 0,
  337. 'dbData' => $ext->dbData,
  338. 'fileData' => $ext->fileData,
  339. ]);
  340. $this->removeSymlinks($ext);
  341. $this->updateIndividual();
  342. $this->c->DB->exec($query, $vars);
  343. return true;
  344. }
  345. /**
  346. * Возвращает данные из файла с общими данными по расширениям
  347. */
  348. protected function loadDataFromFile(string $file): array
  349. {
  350. if (\is_file($file)) {
  351. return include $file;
  352. } else {
  353. return [];
  354. }
  355. }
  356. /**
  357. * Обновляет файл с общими данными по расширениям
  358. */
  359. protected function updateCommon(Extension $ext): bool
  360. {
  361. $data = $this->loadDataFromFile($this->commonFile);
  362. if ($ext::NOT_INSTALLED === $ext->status) {
  363. unset($data[$ext->name]);
  364. } else {
  365. $data[$ext->name] = $ext->prepareData();
  366. }
  367. return $this->putData($this->commonFile, $data);
  368. }
  369. /**
  370. * Записывает данные в указанный файл
  371. */
  372. protected function putData(string $file, mixed $data): bool
  373. {
  374. $content = "<?php\n\nreturn " . \var_export($data, true) . ";\n";
  375. if (false === \file_put_contents($file, $content, \LOCK_EX)) {
  376. return false;
  377. } else {
  378. if (\function_exists('\\opcache_invalidate')) {
  379. \opcache_invalidate($file, true);
  380. } elseif (\function_exists('\\apc_delete_file')) {
  381. \apc_delete_file($file);
  382. }
  383. return true;
  384. }
  385. }
  386. /**
  387. * Обновляет индивидуальные файлы с данными по расширениям
  388. */
  389. protected function updateIndividual(): bool
  390. {
  391. $oldPre = $this->loadDataFromFile($this->preFile);
  392. $templates = [];
  393. $commonData = $this->loadDataFromFile($this->commonFile);
  394. $pre = [];
  395. $newPre = [];
  396. // выделение данных
  397. foreach ($this->repository as $ext) {
  398. if (1 !== $ext->dbStatus) {
  399. continue;
  400. }
  401. if (isset($commonData[$ext->name]['templates']['pre'])) {
  402. $pre = \array_merge_recursive($pre, $commonData[$ext->name]['templates']['pre']);
  403. }
  404. }
  405. // PRE-данные шаблонов
  406. foreach ($pre as $template => $names) {
  407. $templates[$template] = $template;
  408. foreach ($names as $name => $list) {
  409. \uasort($list, function (array $a, array $b) {
  410. return $b['priority'] <=> $a['priority'];
  411. });
  412. $result = '';
  413. foreach ($list as $value) {
  414. $result .= $value['data'];
  415. }
  416. $newPre[$template][$name] = $result;
  417. }
  418. }
  419. $this->putData($this->preFile, $newPre);
  420. // удаление скомпилированных шаблонов
  421. foreach (\array_merge($this->diffPre($oldPre, $newPre), $this->diffPre($newPre, $oldPre)) as $template) {
  422. $this->c->View->delete($template);
  423. }
  424. return true;
  425. }
  426. /**
  427. * Вычисляет расхождение для PRE-данных
  428. */
  429. protected function diffPre(array $a, array $b): array
  430. {
  431. $result = [];
  432. foreach ($a as $template => $names) {
  433. if (! isset($b[$template])) {
  434. $result[$template] = $template;
  435. continue;
  436. }
  437. foreach ($names as $name => $value) {
  438. if (
  439. ! isset($b[$template][$name])
  440. || $value !== $b[$template][$name]
  441. ) {
  442. $result[$template] = $template;
  443. continue 2;
  444. }
  445. }
  446. }
  447. return $result;
  448. }
  449. protected function setSymlinks(Extension $ext): bool
  450. {
  451. $data = $this->loadDataFromFile($this->commonFile);
  452. $symlinks = $data[$ext->name]['symlinks'] ?? [];
  453. foreach ($symlinks as $target => $link) {
  454. \symlink($target, $link);
  455. }
  456. return true;
  457. }
  458. protected function removeSymlinks(Extension $ext): bool
  459. {
  460. $data = $this->loadDataFromFile($this->commonFile);
  461. $symlinks = $data[$ext->name]['symlinks'] ?? [];
  462. foreach ($symlinks as $target => $link) {
  463. if (\is_link($link)) {
  464. \is_file($link) ? \unlink($link) : \rmdir($link);
  465. }
  466. }
  467. return true;
  468. }
  469. }