Service.php 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. <?php
  2. namespace think\addons;
  3. use fast\Http;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\Exception\TransferException;
  6. use PhpZip\Exception\ZipException;
  7. use PhpZip\ZipFile;
  8. use RecursiveDirectoryIterator;
  9. use RecursiveIteratorIterator;
  10. use Symfony\Component\VarExporter\VarExporter;
  11. use think\Cache;
  12. use think\Db;
  13. use think\Exception;
  14. /**
  15. * 插件服务
  16. * @package think\addons
  17. */
  18. class Service
  19. {
  20. /**
  21. * 远程下载插件
  22. *
  23. * @param string $name 插件名称
  24. * @param array $extend 扩展参数
  25. * @return string
  26. */
  27. public static function download($name, $extend = [])
  28. {
  29. $addonsTempDir = self::getAddonsBackupDir();
  30. $tmpFile = $addonsTempDir . $name . ".zip";
  31. try {
  32. $client = self::getClient();
  33. $response = $client->get('/addon/download', ['query' => array_merge(['name' => $name], $extend)]);
  34. $body = $response->getBody();
  35. $content = $body->getContents();
  36. if (substr($content, 0, 1) === '{') {
  37. $json = (array)json_decode($content, true);
  38. //如果传回的是一个下载链接,则再次下载
  39. if ($json['data'] && isset($json['data']['url'])) {
  40. $response = $client->get($json['data']['url']);
  41. $body = $response->getBody();
  42. $content = $body->getContents();
  43. } else {
  44. //下载返回错误,抛出异常
  45. throw new AddonException($json['msg'], $json['code'], $json['data']);
  46. }
  47. }
  48. } catch (TransferException $e) {
  49. throw new Exception("Addon package download failed");
  50. }
  51. if ($write = fopen($tmpFile, 'w')) {
  52. fwrite($write, $content);
  53. fclose($write);
  54. return $tmpFile;
  55. }
  56. throw new Exception("No permission to write temporary files");
  57. }
  58. /**
  59. * 解压插件
  60. *
  61. * @param string $name 插件名称
  62. * @return string
  63. * @throws Exception
  64. */
  65. public static function unzip($name)
  66. {
  67. if (!$name) {
  68. throw new Exception('Invalid parameters');
  69. }
  70. $addonsBackupDir = self::getAddonsBackupDir();
  71. $file = $addonsBackupDir . $name . '.zip';
  72. // 打开插件压缩包
  73. $zip = new ZipFile();
  74. try {
  75. $zip->openFile($file);
  76. } catch (ZipException $e) {
  77. $zip->close();
  78. throw new Exception('Unable to open the zip file');
  79. }
  80. $dir = self::getAddonDir($name);
  81. if (!is_dir($dir)) {
  82. @mkdir($dir, 0755);
  83. }
  84. // 解压插件压缩包
  85. try {
  86. $zip->extractTo($dir);
  87. } catch (ZipException $e) {
  88. throw new Exception('Unable to extract the file');
  89. } finally {
  90. $zip->close();
  91. }
  92. return $dir;
  93. }
  94. /**
  95. * 离线安装
  96. * @param string $file 插件压缩包
  97. * @param array $extend
  98. */
  99. public static function local($file, $extend = [])
  100. {
  101. $addonsTempDir = self::getAddonsBackupDir();
  102. if (!$file || !$file instanceof \think\File) {
  103. throw new Exception('No file upload or server upload limit exceeded');
  104. }
  105. $uploadFile = $file->rule('uniqid')->validate(['size' => 102400000, 'ext' => 'zip,fastaddon'])->move($addonsTempDir);
  106. if (!$uploadFile) {
  107. // 上传失败获取错误信息
  108. throw new Exception(__($file->getError()));
  109. }
  110. $tmpFile = $addonsTempDir . $uploadFile->getSaveName();
  111. $info = [];
  112. $zip = new ZipFile();
  113. try {
  114. // 打开插件压缩包
  115. try {
  116. $zip->openFile($tmpFile);
  117. } catch (ZipException $e) {
  118. @unlink($tmpFile);
  119. throw new Exception('Unable to open the zip file');
  120. }
  121. $config = self::getInfoIni($zip);
  122. // 判断插件标识
  123. $name = isset($config['name']) ? $config['name'] : '';
  124. if (!$name) {
  125. throw new Exception('Addon info file data incorrect');
  126. }
  127. // 判断插件是否存在
  128. if (!preg_match("/^[a-zA-Z0-9]+$/", $name)) {
  129. throw new Exception('Addon name incorrect');
  130. }
  131. // 判断新插件是否存在
  132. $newAddonDir = self::getAddonDir($name);
  133. if (is_dir($newAddonDir)) {
  134. throw new Exception('Addon already exists');
  135. }
  136. // 追加MD5和Data数据
  137. $extend['md5'] = md5_file($tmpFile);
  138. $extend['data'] = $zip->getArchiveComment();
  139. $extend['unknownsources'] = config('app_debug') && config('fastadmin.unknownsources');
  140. $extend['faversion'] = config('fastadmin.version');
  141. $params = array_merge($config, $extend);
  142. // 压缩包验证、版本依赖判断
  143. Service::valid($params);
  144. //创建插件目录
  145. @mkdir($newAddonDir, 0755, true);
  146. // 解压到插件目录
  147. try {
  148. $zip->extractTo($newAddonDir);
  149. } catch (ZipException $e) {
  150. @unlink($newAddonDir);
  151. throw new Exception('Unable to extract the file');
  152. }
  153. Db::startTrans();
  154. try {
  155. //默认禁用该插件
  156. $info = get_addon_info($name);
  157. if ($info['state']) {
  158. $info['state'] = 0;
  159. set_addon_info($name, $info);
  160. }
  161. //执行插件的安装方法
  162. $class = get_addon_class($name);
  163. if (class_exists($class)) {
  164. $addon = new $class();
  165. $addon->install();
  166. }
  167. Db::commit();
  168. } catch (\Exception $e) {
  169. Db::rollback();
  170. @rmdirs($newAddonDir);
  171. throw new Exception(__($e->getMessage()));
  172. }
  173. //导入SQL
  174. Service::importsql($name);
  175. } catch (AddonException $e) {
  176. throw new AddonException($e->getMessage(), $e->getCode(), $e->getData());
  177. } catch (Exception $e) {
  178. throw new Exception(__($e->getMessage()));
  179. } finally {
  180. $zip->close();
  181. unset($uploadFile);
  182. @unlink($tmpFile);
  183. }
  184. $info['config'] = get_addon_config($name) ? 1 : 0;
  185. $info['bootstrap'] = is_file(Service::getBootstrapFile($name));
  186. return $info;
  187. }
  188. /**
  189. * 验证压缩包、依赖验证
  190. * @param array $params
  191. * @return bool
  192. * @throws Exception
  193. */
  194. public static function valid($params = [])
  195. {
  196. $client = self::getClient();
  197. $multipart = [];
  198. foreach ($params as $name => $value) {
  199. $multipart[] = ['name' => $name, 'contents' => $value];
  200. }
  201. try {
  202. $response = $client->post('/addon/valid', ['multipart' => $multipart]);
  203. $content = $response->getBody()->getContents();
  204. } catch (TransferException $e) {
  205. throw new Exception("Network error");
  206. }
  207. $json = (array)json_decode($content, true);
  208. if ($json && isset($json['code'])) {
  209. if ($json['code']) {
  210. return true;
  211. } else {
  212. throw new Exception($json['msg'] ?? "Invalid addon package");
  213. }
  214. } else {
  215. throw new Exception("Unknown data format");
  216. }
  217. }
  218. /**
  219. * 备份插件
  220. * @param string $name 插件名称
  221. * @return bool
  222. * @throws Exception
  223. */
  224. public static function backup($name)
  225. {
  226. $addonsBackupDir = self::getAddonsBackupDir();
  227. $file = $addonsBackupDir . $name . '-backup-' . date("YmdHis") . '.zip';
  228. $zipFile = new ZipFile();
  229. try {
  230. $zipFile
  231. ->addDirRecursive(self::getAddonDir($name))
  232. ->saveAsFile($file)
  233. ->close();
  234. } catch (ZipException $e) {
  235. } finally {
  236. $zipFile->close();
  237. }
  238. return true;
  239. }
  240. /**
  241. * 检测插件是否完整
  242. *
  243. * @param string $name 插件名称
  244. * @return boolean
  245. * @throws Exception
  246. */
  247. public static function check($name)
  248. {
  249. if (!$name || !is_dir(ADDON_PATH . $name)) {
  250. throw new Exception('Addon not exists');
  251. }
  252. $addonClass = get_addon_class($name);
  253. if (!$addonClass) {
  254. throw new Exception("The addon file does not exist");
  255. }
  256. $addon = new $addonClass();
  257. if (!$addon->checkInfo()) {
  258. throw new Exception("The configuration file content is incorrect");
  259. }
  260. return true;
  261. }
  262. /**
  263. * 是否有冲突
  264. *
  265. * @param string $name 插件名称
  266. * @return boolean
  267. * @throws AddonException
  268. */
  269. public static function noconflict($name)
  270. {
  271. // 检测冲突文件
  272. $list = self::getGlobalFiles($name, true);
  273. if ($list) {
  274. //发现冲突文件,抛出异常
  275. throw new AddonException(__("Conflicting file found"), -3, ['conflictlist' => $list]);
  276. }
  277. return true;
  278. }
  279. /**
  280. * 导入SQL
  281. *
  282. * @param string $name 插件名称
  283. * @return boolean
  284. */
  285. public static function importsql($name)
  286. {
  287. $sqlFile = self::getAddonDir($name) . 'install.sql';
  288. if (is_file($sqlFile)) {
  289. $lines = file($sqlFile);
  290. $templine = '';
  291. foreach ($lines as $line) {
  292. if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*') {
  293. continue;
  294. }
  295. $templine .= $line;
  296. if (substr(trim($line), -1, 1) == ';') {
  297. $templine = str_ireplace('__PREFIX__', config('database.prefix'), $templine);
  298. $templine = str_ireplace('INSERT INTO ', 'INSERT IGNORE INTO ', $templine);
  299. try {
  300. Db::getPdo()->exec($templine);
  301. } catch (\PDOException $e) {
  302. //$e->getMessage();
  303. }
  304. $templine = '';
  305. }
  306. }
  307. }
  308. return true;
  309. }
  310. /**
  311. * 刷新插件缓存文件
  312. *
  313. * @return boolean
  314. * @throws Exception
  315. */
  316. public static function refresh()
  317. {
  318. //刷新addons.js
  319. $addons = get_addon_list();
  320. $bootstrapArr = [];
  321. foreach ($addons as $name => $addon) {
  322. $bootstrapFile = self::getBootstrapFile($name);
  323. if ($addon['state'] && is_file($bootstrapFile)) {
  324. $bootstrapArr[] = file_get_contents($bootstrapFile);
  325. }
  326. }
  327. $addonsFile = ROOT_PATH . str_replace("/", DS, "public/assets/js/addons.js");
  328. if ($handle = fopen($addonsFile, 'w')) {
  329. $tpl = <<<EOD
  330. define([], function () {
  331. {__JS__}
  332. });
  333. EOD;
  334. fwrite($handle, str_replace("{__JS__}", implode("\n", $bootstrapArr), $tpl));
  335. fclose($handle);
  336. } else {
  337. throw new Exception(__("Unable to open file '%s' for writing", "addons.js"));
  338. }
  339. Cache::rm("addons");
  340. Cache::rm("hooks");
  341. $file = self::getExtraAddonsFile();
  342. $config = get_addon_autoload_config(true);
  343. if ($config['autoload']) {
  344. return;
  345. }
  346. if (!is_really_writable($file)) {
  347. throw new Exception(__("Unable to open file '%s' for writing", "addons.php"));
  348. }
  349. if ($handle = fopen($file, 'w')) {
  350. fwrite($handle, "<?php\n\n" . "return " . VarExporter::export($config) . ";\n");
  351. fclose($handle);
  352. } else {
  353. throw new Exception(__("Unable to open file '%s' for writing", "addons.php"));
  354. }
  355. return true;
  356. }
  357. /**
  358. * 安装插件
  359. *
  360. * @param string $name 插件名称
  361. * @param boolean $force 是否覆盖
  362. * @param array $extend 扩展参数
  363. * @return boolean
  364. * @throws Exception
  365. * @throws AddonException
  366. */
  367. public static function install($name, $force = false, $extend = [])
  368. {
  369. if (!$name || (is_dir(ADDON_PATH . $name) && !$force)) {
  370. throw new Exception('Addon already exists');
  371. }
  372. // 远程下载插件
  373. $tmpFile = Service::download($name, $extend);
  374. $addonDir = self::getAddonDir($name);
  375. try {
  376. // 解压插件压缩包到插件目录
  377. Service::unzip($name);
  378. // 检查插件是否完整
  379. Service::check($name);
  380. if (!$force) {
  381. Service::noconflict($name);
  382. }
  383. } catch (AddonException $e) {
  384. @rmdirs($addonDir);
  385. throw new AddonException($e->getMessage(), $e->getCode(), $e->getData());
  386. } catch (Exception $e) {
  387. @rmdirs($addonDir);
  388. throw new Exception($e->getMessage());
  389. } finally {
  390. // 移除临时文件
  391. @unlink($tmpFile);
  392. }
  393. // 默认启用该插件
  394. $info = get_addon_info($name);
  395. Db::startTrans();
  396. try {
  397. if (!$info['state']) {
  398. $info['state'] = 1;
  399. set_addon_info($name, $info);
  400. }
  401. // 执行安装脚本
  402. $class = get_addon_class($name);
  403. if (class_exists($class)) {
  404. $addon = new $class();
  405. $addon->install();
  406. }
  407. Db::commit();
  408. } catch (Exception $e) {
  409. @rmdirs($addonDir);
  410. Db::rollback();
  411. throw new Exception($e->getMessage());
  412. }
  413. // 导入
  414. Service::importsql($name);
  415. // 启用插件
  416. Service::enable($name, true);
  417. $info['config'] = get_addon_config($name) ? 1 : 0;
  418. $info['bootstrap'] = is_file(Service::getBootstrapFile($name));
  419. return $info;
  420. }
  421. /**
  422. * 卸载插件
  423. *
  424. * @param string $name
  425. * @param boolean $force 是否强制卸载
  426. * @return boolean
  427. * @throws Exception
  428. */
  429. public static function uninstall($name, $force = false)
  430. {
  431. if (!$name || !is_dir(ADDON_PATH . $name)) {
  432. throw new Exception('Addon not exists');
  433. }
  434. if (!$force) {
  435. Service::noconflict($name);
  436. }
  437. // 移除插件全局资源文件
  438. if ($force) {
  439. $list = Service::getGlobalFiles($name);
  440. foreach ($list as $k => $v) {
  441. @unlink(ROOT_PATH . $v);
  442. }
  443. }
  444. // 执行卸载脚本
  445. try {
  446. $class = get_addon_class($name);
  447. if (class_exists($class)) {
  448. $addon = new $class();
  449. $addon->uninstall();
  450. }
  451. } catch (Exception $e) {
  452. throw new Exception($e->getMessage());
  453. }
  454. // 移除插件目录
  455. rmdirs(ADDON_PATH . $name);
  456. // 刷新
  457. Service::refresh();
  458. return true;
  459. }
  460. /**
  461. * 启用
  462. * @param string $name 插件名称
  463. * @param boolean $force 是否强制覆盖
  464. * @return boolean
  465. */
  466. public static function enable($name, $force = false)
  467. {
  468. if (!$name || !is_dir(ADDON_PATH . $name)) {
  469. throw new Exception('Addon not exists');
  470. }
  471. if (!$force) {
  472. Service::noconflict($name);
  473. }
  474. //备份冲突文件
  475. if (config('fastadmin.backup_global_files')) {
  476. $conflictFiles = self::getGlobalFiles($name, true);
  477. if ($conflictFiles) {
  478. $zip = new ZipFile();
  479. try {
  480. foreach ($conflictFiles as $k => $v) {
  481. $zip->addFile(ROOT_PATH . $v, $v);
  482. }
  483. $addonsBackupDir = self::getAddonsBackupDir();
  484. $zip->saveAsFile($addonsBackupDir . $name . "-conflict-enable-" . date("YmdHis") . ".zip");
  485. } catch (Exception $e) {
  486. } finally {
  487. $zip->close();
  488. }
  489. }
  490. }
  491. $addonDir = self::getAddonDir($name);
  492. $sourceAssetsDir = self::getSourceAssetsDir($name);
  493. $destAssetsDir = self::getDestAssetsDir($name);
  494. $files = self::getGlobalFiles($name);
  495. if ($files) {
  496. //刷新插件配置缓存
  497. Service::config($name, ['files' => $files]);
  498. }
  499. // 复制文件
  500. if (is_dir($sourceAssetsDir)) {
  501. copydirs($sourceAssetsDir, $destAssetsDir);
  502. }
  503. // 复制application和public到全局
  504. foreach (self::getCheckDirs() as $k => $dir) {
  505. if (is_dir($addonDir . $dir)) {
  506. copydirs($addonDir . $dir, ROOT_PATH . $dir);
  507. }
  508. }
  509. //插件纯净模式时将插件目录下的application、public和assets删除
  510. if (config('fastadmin.addon_pure_mode')) {
  511. // 删除插件目录已复制到全局的文件
  512. @rmdirs($sourceAssetsDir);
  513. foreach (self::getCheckDirs() as $k => $dir) {
  514. @rmdirs($addonDir . $dir);
  515. }
  516. }
  517. //执行启用脚本
  518. try {
  519. $class = get_addon_class($name);
  520. if (class_exists($class)) {
  521. $addon = new $class();
  522. if (method_exists($class, "enable")) {
  523. $addon->enable();
  524. }
  525. }
  526. } catch (Exception $e) {
  527. throw new Exception($e->getMessage());
  528. }
  529. $info = get_addon_info($name);
  530. $info['state'] = 1;
  531. unset($info['url']);
  532. set_addon_info($name, $info);
  533. // 刷新
  534. Service::refresh();
  535. return true;
  536. }
  537. /**
  538. * 禁用
  539. *
  540. * @param string $name 插件名称
  541. * @param boolean $force 是否强制禁用
  542. * @return boolean
  543. * @throws Exception
  544. */
  545. public static function disable($name, $force = false)
  546. {
  547. if (!$name || !is_dir(ADDON_PATH . $name)) {
  548. throw new Exception('Addon not exists');
  549. }
  550. $file = self::getExtraAddonsFile();
  551. if (!is_really_writable($file)) {
  552. throw new Exception(__("Unable to open file '%s' for writing", "addons.php"));
  553. }
  554. if (!$force) {
  555. Service::noconflict($name);
  556. }
  557. if (config('fastadmin.backup_global_files')) {
  558. //仅备份修改过的文件
  559. $conflictFiles = Service::getGlobalFiles($name, true);
  560. if ($conflictFiles) {
  561. $zip = new ZipFile();
  562. try {
  563. foreach ($conflictFiles as $k => $v) {
  564. $zip->addFile(ROOT_PATH . $v, $v);
  565. }
  566. $addonsBackupDir = self::getAddonsBackupDir();
  567. $zip->saveAsFile($addonsBackupDir . $name . "-conflict-disable-" . date("YmdHis") . ".zip");
  568. } catch (Exception $e) {
  569. } finally {
  570. $zip->close();
  571. }
  572. }
  573. }
  574. $config = Service::config($name);
  575. $addonDir = self::getAddonDir($name);
  576. //插件资源目录
  577. $destAssetsDir = self::getDestAssetsDir($name);
  578. // 移除插件全局文件
  579. $list = Service::getGlobalFiles($name);
  580. //插件纯净模式时将原有的文件复制回插件目录
  581. //当无法获取全局文件列表时也将列表复制回插件目录
  582. if (config('fastadmin.addon_pure_mode') || !$list) {
  583. if ($config && isset($config['files']) && is_array($config['files'])) {
  584. foreach ($config['files'] as $index => $item) {
  585. //避免切换不同服务器后导致路径不一致
  586. $item = str_replace(['/', '\\'], DS, $item);
  587. //插件资源目录,无需重复复制
  588. if (stripos($item, str_replace(ROOT_PATH, '', $destAssetsDir)) === 0) {
  589. continue;
  590. }
  591. //检查目录是否存在,不存在则创建
  592. $itemBaseDir = dirname($addonDir . $item);
  593. if (!is_dir($itemBaseDir)) {
  594. @mkdir($itemBaseDir, 0755, true);
  595. }
  596. if (is_file(ROOT_PATH . $item)) {
  597. @copy(ROOT_PATH . $item, $addonDir . $item);
  598. }
  599. }
  600. $list = $config['files'];
  601. }
  602. //复制插件目录资源
  603. if (is_dir($destAssetsDir)) {
  604. @copydirs($destAssetsDir, $addonDir . 'assets' . DS);
  605. }
  606. }
  607. $dirs = [];
  608. foreach ($list as $k => $v) {
  609. $file = ROOT_PATH . $v;
  610. $dirs[] = dirname($file);
  611. @unlink($file);
  612. }
  613. // 移除插件空目录
  614. $dirs = array_filter(array_unique($dirs));
  615. foreach ($dirs as $k => $v) {
  616. remove_empty_folder($v);
  617. }
  618. $info = get_addon_info($name);
  619. $info['state'] = 0;
  620. unset($info['url']);
  621. set_addon_info($name, $info);
  622. // 执行禁用脚本
  623. try {
  624. $class = get_addon_class($name);
  625. if (class_exists($class)) {
  626. $addon = new $class();
  627. if (method_exists($class, "disable")) {
  628. $addon->disable();
  629. }
  630. }
  631. } catch (Exception $e) {
  632. throw new Exception($e->getMessage());
  633. }
  634. // 刷新
  635. Service::refresh();
  636. return true;
  637. }
  638. /**
  639. * 升级插件
  640. *
  641. * @param string $name 插件名称
  642. * @param array $extend 扩展参数
  643. */
  644. public static function upgrade($name, $extend = [])
  645. {
  646. $info = get_addon_info($name);
  647. if ($info['state']) {
  648. throw new Exception(__('Please disable addon first'));
  649. }
  650. $config = get_addon_config($name);
  651. if ($config) {
  652. //备份配置
  653. }
  654. // 远程下载插件
  655. $tmpFile = Service::download($name, $extend);
  656. // 备份插件文件
  657. Service::backup($name);
  658. $addonDir = self::getAddonDir($name);
  659. // 删除插件目录下的application和public
  660. $files = self::getCheckDirs();
  661. foreach ($files as $index => $file) {
  662. @rmdirs($addonDir . $file);
  663. }
  664. try {
  665. // 解压插件
  666. Service::unzip($name);
  667. } catch (Exception $e) {
  668. throw new Exception($e->getMessage());
  669. } finally {
  670. // 移除临时文件
  671. @unlink($tmpFile);
  672. }
  673. if ($config) {
  674. // 还原配置
  675. set_addon_config($name, $config);
  676. }
  677. // 导入
  678. Service::importsql($name);
  679. // 执行升级脚本
  680. try {
  681. $addonName = ucfirst($name);
  682. //创建临时类用于调用升级的方法
  683. $sourceFile = $addonDir . $addonName . ".php";
  684. $destFile = $addonDir . $addonName . "Upgrade.php";
  685. $classContent = str_replace("class {$addonName} extends", "class {$addonName}Upgrade extends", file_get_contents($sourceFile));
  686. //创建临时的类文件
  687. file_put_contents($destFile, $classContent);
  688. $className = "\\addons\\" . $name . "\\" . $addonName . "Upgrade";
  689. $addon = new $className($name);
  690. //调用升级的方法
  691. if (method_exists($addon, "upgrade")) {
  692. $addon->upgrade();
  693. }
  694. //移除临时文件
  695. @unlink($destFile);
  696. } catch (Exception $e) {
  697. throw new Exception($e->getMessage());
  698. }
  699. // 刷新
  700. Service::refresh();
  701. //必须变更版本号
  702. $info['version'] = isset($extend['version']) ? $extend['version'] : $info['version'];
  703. $info['config'] = get_addon_config($name) ? 1 : 0;
  704. $info['bootstrap'] = is_file(Service::getBootstrapFile($name));
  705. return $info;
  706. }
  707. /**
  708. * 读取或修改插件配置
  709. * @param string $name
  710. * @param array $changed
  711. * @return array
  712. */
  713. public static function config($name, $changed = [])
  714. {
  715. $addonDir = self::getAddonDir($name);
  716. $addonConfigFile = $addonDir . '.addonrc';
  717. $config = [];
  718. if (is_file($addonConfigFile)) {
  719. $config = (array)json_decode(file_get_contents($addonConfigFile), true);
  720. }
  721. $config = array_merge($config, $changed);
  722. if ($changed) {
  723. file_put_contents($addonConfigFile, json_encode($config, JSON_UNESCAPED_UNICODE));
  724. }
  725. return $config;
  726. }
  727. /**
  728. * 获取插件在全局的文件
  729. *
  730. * @param string $name 插件名称
  731. * @param boolean $onlyconflict 是否只返回冲突文件
  732. * @return array
  733. */
  734. public static function getGlobalFiles($name, $onlyconflict = false)
  735. {
  736. $list = [];
  737. $addonDir = self::getAddonDir($name);
  738. $checkDirList = self::getCheckDirs();
  739. $checkDirList = array_merge($checkDirList, ['assets']);
  740. $assetDir = self::getDestAssetsDir($name);
  741. // 扫描插件目录是否有覆盖的文件
  742. foreach ($checkDirList as $k => $dirName) {
  743. //检测目录是否存在
  744. if (!is_dir($addonDir . $dirName)) {
  745. continue;
  746. }
  747. //匹配出所有的文件
  748. $files = new RecursiveIteratorIterator(
  749. new RecursiveDirectoryIterator($addonDir . $dirName, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
  750. );
  751. foreach ($files as $fileinfo) {
  752. if ($fileinfo->isFile()) {
  753. $filePath = $fileinfo->getPathName();
  754. //如果名称为assets需要做特殊处理
  755. if ($dirName === 'assets') {
  756. $path = str_replace(ROOT_PATH, '', $assetDir) . str_replace($addonDir . $dirName . DS, '', $filePath);
  757. } else {
  758. $path = str_replace($addonDir, '', $filePath);
  759. }
  760. if ($onlyconflict) {
  761. $destPath = ROOT_PATH . $path;
  762. if (is_file($destPath)) {
  763. if (filesize($filePath) != filesize($destPath) || md5_file($filePath) != md5_file($destPath)) {
  764. $list[] = $path;
  765. }
  766. }
  767. } else {
  768. $list[] = $path;
  769. }
  770. }
  771. }
  772. }
  773. $list = array_filter(array_unique($list));
  774. return $list;
  775. }
  776. /**
  777. * 获取插件行为、路由配置文件
  778. * @return string
  779. */
  780. public static function getExtraAddonsFile()
  781. {
  782. return CONF_PATH . 'extra' . DS . 'addons.php';
  783. }
  784. /**
  785. * 获取bootstrap.js路径
  786. * @return string
  787. */
  788. public static function getBootstrapFile($name)
  789. {
  790. return ADDON_PATH . $name . DS . 'bootstrap.js';
  791. }
  792. /**
  793. * 获取指定插件的目录
  794. */
  795. public static function getAddonDir($name)
  796. {
  797. $dir = ADDON_PATH . $name . DS;
  798. return $dir;
  799. }
  800. /**
  801. * 获取插件备份目录
  802. */
  803. public static function getAddonsBackupDir()
  804. {
  805. $dir = RUNTIME_PATH . 'addons' . DS;
  806. if (!is_dir($dir)) {
  807. @mkdir($dir, 0755, true);
  808. }
  809. return $dir;
  810. }
  811. /**
  812. * 获取插件源资源文件夹
  813. * @param string $name 插件名称
  814. * @return string
  815. */
  816. protected static function getSourceAssetsDir($name)
  817. {
  818. return ADDON_PATH . $name . DS . 'assets' . DS;
  819. }
  820. /**
  821. * 获取插件目标资源文件夹
  822. * @param string $name 插件名称
  823. * @return string
  824. */
  825. protected static function getDestAssetsDir($name)
  826. {
  827. $assetsDir = ROOT_PATH . str_replace("/", DS, "public/assets/addons/{$name}/");
  828. return $assetsDir;
  829. }
  830. /**
  831. * 获取远程服务器
  832. * @return string
  833. */
  834. protected static function getServerUrl()
  835. {
  836. return config('fastadmin.api_url');
  837. }
  838. /**
  839. * 获取检测的全局文件夹目录
  840. * @return array
  841. */
  842. protected static function getCheckDirs()
  843. {
  844. return [
  845. 'application',
  846. 'public'
  847. ];
  848. }
  849. /**
  850. * 获取请求对象
  851. * @return Client
  852. */
  853. protected static function getClient()
  854. {
  855. $options = [
  856. 'base_uri' => self::getServerUrl(),
  857. 'timeout' => 30,
  858. 'connect_timeout' => 30,
  859. 'verify' => false,
  860. 'http_errors' => false,
  861. 'headers' => [
  862. 'X-REQUESTED-WITH' => 'XMLHttpRequest',
  863. 'Referer' => dirname(request()->root(true)),
  864. 'User-Agent' => 'FastAddon',
  865. ]
  866. ];
  867. static $client;
  868. if (empty($client)) {
  869. $client = new Client($options);
  870. }
  871. return $client;
  872. }
  873. /**
  874. * 匹配配置文件中info信息
  875. * @param ZipFile $zip
  876. * @return array|false
  877. * @throws Exception
  878. */
  879. protected static function getInfoIni($zip)
  880. {
  881. $config = [];
  882. // 读取插件信息
  883. try {
  884. $info = $zip->getEntryContents('info.ini');
  885. $config = parse_ini_string($info);
  886. } catch (ZipException $e) {
  887. throw new Exception('Unable to extract the file');
  888. }
  889. return $config;
  890. }
  891. }