Addon.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. <?php
  2. namespace app\admin\command;
  3. use think\addons\AddonException;
  4. use think\addons\Service;
  5. use think\Config;
  6. use think\console\Command;
  7. use think\console\Input;
  8. use think\console\input\Option;
  9. use think\console\Output;
  10. use think\Db;
  11. use think\Exception;
  12. use think\exception\PDOException;
  13. class Addon extends Command
  14. {
  15. protected function configure()
  16. {
  17. $this
  18. ->setName('addon')
  19. ->addOption('name', 'a', Option::VALUE_REQUIRED, 'addon name', null)
  20. ->addOption('action', 'c', Option::VALUE_REQUIRED, 'action(create/enable/disable/uninstall/refresh/package/move)', 'create')
  21. ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override', null)
  22. ->addOption('release', 'r', Option::VALUE_OPTIONAL, 'addon release version', null)
  23. ->addOption('uid', 'u', Option::VALUE_OPTIONAL, 'fastadmin uid', null)
  24. ->addOption('token', 't', Option::VALUE_OPTIONAL, 'fastadmin token', null)
  25. ->addOption('domain', 'd', Option::VALUE_OPTIONAL, 'domain', null)
  26. ->addOption('local', 'l', Option::VALUE_OPTIONAL, 'local package', null)
  27. ->setDescription('Addon manager');
  28. }
  29. protected function execute(Input $input, Output $output)
  30. {
  31. \think\Config::load(dirname(dirname(__FILE__)) . DS . 'config.php');
  32. $name = $input->getOption('name') ?: '';
  33. $action = $input->getOption('action') ?: '';
  34. if (stripos($name, 'addons' . DS) !== false) {
  35. $name = explode(DS, $name)[1];
  36. }
  37. //强制覆盖
  38. $force = $input->getOption('force');
  39. //版本
  40. $release = $input->getOption('release') ?: '';
  41. //uid
  42. $uid = $input->getOption('uid') ?: '';
  43. //token
  44. $token = $input->getOption('token') ?: '';
  45. include dirname(__DIR__) . DS . 'common.php';
  46. if (!$name && !in_array($action, ['refresh'])) {
  47. throw new Exception('Addon name could not be empty');
  48. }
  49. if (!$action || !in_array($action, ['create', 'disable', 'enable', 'install', 'uninstall', 'refresh', 'upgrade', 'package', 'move'])) {
  50. throw new Exception('Please input correct action name');
  51. }
  52. // 查询一次SQL,判断连接是否正常
  53. Db::execute("SELECT 1");
  54. $addonDir = ADDON_PATH . $name . DS;
  55. switch ($action) {
  56. case 'create':
  57. //非覆盖模式时如果存在则报错
  58. if (is_dir($addonDir) && !$force) {
  59. throw new Exception("addon already exists!\nIf you need to create again, use the parameter --force=true ");
  60. }
  61. //如果存在先移除
  62. if (is_dir($addonDir)) {
  63. rmdirs($addonDir);
  64. }
  65. mkdir($addonDir, 0755, true);
  66. mkdir($addonDir . DS . 'controller', 0755, true);
  67. $menuList = \app\common\library\Menu::export($name);
  68. $createMenu = $this->getCreateMenu($menuList);
  69. $prefix = Config::get('database.prefix');
  70. $createTableSql = '';
  71. try {
  72. $result = Db::query("SHOW CREATE TABLE `" . $prefix . $name . "`;");
  73. if (isset($result[0]) && isset($result[0]['Create Table'])) {
  74. $createTableSql = $result[0]['Create Table'];
  75. }
  76. } catch (PDOException $e) {
  77. }
  78. $data = [
  79. 'name' => $name,
  80. 'addon' => $name,
  81. 'addonClassName' => ucfirst($name),
  82. 'addonInstallMenu' => $createMenu ? "\$menu = " . var_export_short($createMenu) . ";\n\tMenu::create(\$menu);" : '',
  83. 'addonUninstallMenu' => $menuList ? 'Menu::delete("' . $name . '");' : '',
  84. 'addonEnableMenu' => $menuList ? 'Menu::enable("' . $name . '");' : '',
  85. 'addonDisableMenu' => $menuList ? 'Menu::disable("' . $name . '");' : '',
  86. ];
  87. $this->writeToFile("addon", $data, $addonDir . ucfirst($name) . '.php');
  88. $this->writeToFile("config", $data, $addonDir . 'config.php');
  89. $this->writeToFile("info", $data, $addonDir . 'info.ini');
  90. $this->writeToFile("controller", $data, $addonDir . 'controller' . DS . 'Index.php');
  91. if ($createTableSql) {
  92. $createTableSql = str_replace("`" . $prefix, '`__PREFIX__', $createTableSql);
  93. file_put_contents($addonDir . 'install.sql', $createTableSql);
  94. }
  95. $output->info("Create Successed!");
  96. break;
  97. case 'disable':
  98. case 'enable':
  99. try {
  100. //调用启用、禁用的方法
  101. Service::$action($name, 0);
  102. } catch (AddonException $e) {
  103. if ($e->getCode() != -3) {
  104. throw new Exception($e->getMessage());
  105. }
  106. if (!$force) {
  107. //如果有冲突文件则提醒
  108. $data = $e->getData();
  109. foreach ($data['conflictlist'] as $k => $v) {
  110. $output->warning($v);
  111. }
  112. $output->info("Are you sure you want to " . ($action == 'enable' ? 'override' : 'delete') . " all those files? Type 'yes' to continue: ");
  113. $line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r'));
  114. if (trim($line) != 'yes') {
  115. throw new Exception("Operation is aborted!");
  116. }
  117. }
  118. //调用启用、禁用的方法
  119. Service::$action($name, 1);
  120. } catch (Exception $e) {
  121. throw new Exception($e->getMessage());
  122. }
  123. $output->info(ucfirst($action) . " Successed!");
  124. break;
  125. case 'uninstall':
  126. //非覆盖模式时如果存在则报错
  127. if (!$force) {
  128. throw new Exception("If you need to uninstall addon, use the parameter --force=true ");
  129. }
  130. try {
  131. Service::uninstall($name, 0);
  132. } catch (AddonException $e) {
  133. if ($e->getCode() != -3) {
  134. throw new Exception($e->getMessage());
  135. }
  136. if (!$force) {
  137. //如果有冲突文件则提醒
  138. $data = $e->getData();
  139. foreach ($data['conflictlist'] as $k => $v) {
  140. $output->warning($v);
  141. }
  142. $output->info("Are you sure you want to delete all those files? Type 'yes' to continue: ");
  143. $line = fgets(defined('STDIN') ? STDIN : fopen('php://stdin', 'r'));
  144. if (trim($line) != 'yes') {
  145. throw new Exception("Operation is aborted!");
  146. }
  147. }
  148. Service::uninstall($name, 1);
  149. } catch (Exception $e) {
  150. throw new Exception($e->getMessage());
  151. }
  152. $output->info("Uninstall Successed!");
  153. break;
  154. case 'refresh':
  155. Service::refresh();
  156. $output->info("Refresh Successed!");
  157. break;
  158. case 'package':
  159. $infoFile = $addonDir . 'info.ini';
  160. if (!is_file($infoFile)) {
  161. throw new Exception(__('Addon info file was not found'));
  162. }
  163. $info = get_addon_info($name);
  164. if (!$info) {
  165. throw new Exception(__('Addon info file data incorrect'));
  166. }
  167. $infoname = $info['name'] ?? '';
  168. if (!$infoname || !preg_match("/^[a-z]+$/i", $infoname) || $infoname != $name) {
  169. throw new Exception(__('Addon info name incorrect'));
  170. }
  171. $infoversion = $info['version'] ?? '';
  172. if (!$infoversion || !preg_match("/^\d+\.\d+\.\d+$/i", $infoversion)) {
  173. throw new Exception(__('Addon info version incorrect'));
  174. }
  175. $addonTmpDir = RUNTIME_PATH . 'addons' . DS;
  176. if (!is_dir($addonTmpDir)) {
  177. @mkdir($addonTmpDir, 0755, true);
  178. }
  179. $addonFile = $addonTmpDir . $infoname . '-' . $infoversion . '.zip';
  180. if (!class_exists('ZipArchive')) {
  181. throw new Exception(__('ZinArchive not install'));
  182. }
  183. $zip = new \ZipArchive;
  184. $zip->open($addonFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
  185. $files = new \RecursiveIteratorIterator(
  186. new \RecursiveDirectoryIterator($addonDir), \RecursiveIteratorIterator::LEAVES_ONLY
  187. );
  188. foreach ($files as $name => $file) {
  189. if (!$file->isDir()) {
  190. $filePath = $file->getRealPath();
  191. $relativePath = str_replace(DS, '/', substr($filePath, strlen($addonDir)));
  192. if (!in_array($file->getFilename(), ['.git', '.DS_Store', 'Thumbs.db'])) {
  193. $zip->addFile($filePath, $relativePath);
  194. }
  195. }
  196. }
  197. $zip->close();
  198. $output->info("Package Successed!");
  199. break;
  200. case 'move':
  201. $movePath = [
  202. 'adminOnlySelfDir' => ['admin/behavior', 'admin/controller', 'admin/library', 'admin/model', 'admin/validate', 'admin/view'],
  203. 'adminAllSubDir' => ['admin/lang'],
  204. 'publicDir' => ['public/assets/addons', 'public/assets/js/backend']
  205. ];
  206. $paths = [];
  207. $appPath = str_replace('/', DS, APP_PATH);
  208. $rootPath = str_replace('/', DS, ROOT_PATH);
  209. foreach ($movePath as $k => $items) {
  210. switch ($k) {
  211. case 'adminOnlySelfDir':
  212. foreach ($items as $v) {
  213. $v = str_replace('/', DS, $v);
  214. $oldPath = $appPath . $v . DS . $name;
  215. $newPath = $rootPath . "addons" . DS . $name . DS . "application" . DS . $v . DS . $name;
  216. $paths[$oldPath] = $newPath;
  217. }
  218. break;
  219. case 'adminAllSubDir':
  220. foreach ($items as $v) {
  221. $v = str_replace('/', DS, $v);
  222. $vPath = $appPath . $v;
  223. $list = scandir($vPath);
  224. foreach ($list as $_v) {
  225. if (!in_array($_v, ['.', '..']) && is_dir($vPath . DS . $_v)) {
  226. $oldPath = $appPath . $v . DS . $_v . DS . $name;
  227. $newPath = $rootPath . "addons" . DS . $name . DS . "application" . DS . $v . DS . $_v . DS . $name;
  228. $paths[$oldPath] = $newPath;
  229. }
  230. }
  231. }
  232. break;
  233. case 'publicDir':
  234. foreach ($items as $v) {
  235. $v = str_replace('/', DS, $v);
  236. $oldPath = $rootPath . $v . DS . $name;
  237. $newPath = $rootPath . 'addons' . DS . $name . DS . $v . DS . $name;
  238. $paths[$oldPath] = $newPath;
  239. }
  240. break;
  241. }
  242. }
  243. foreach ($paths as $oldPath => $newPath) {
  244. if (is_dir($oldPath)) {
  245. if ($force) {
  246. if (is_dir($newPath)) {
  247. $list = scandir($newPath);
  248. foreach ($list as $_v) {
  249. if (!in_array($_v, ['.', '..'])) {
  250. $file = $newPath . DS . $_v;
  251. @chmod($file, 0777);
  252. @unlink($file);
  253. }
  254. }
  255. @rmdir($newPath);
  256. }
  257. }
  258. copydirs($oldPath, $newPath);
  259. }
  260. }
  261. break;
  262. default:
  263. break;
  264. }
  265. }
  266. /**
  267. * 获取创建菜单的数组
  268. * @param array $menu
  269. * @return array
  270. */
  271. protected function getCreateMenu($menu)
  272. {
  273. $result = [];
  274. foreach ($menu as $k => & $v) {
  275. $arr = [
  276. 'name' => $v['name'],
  277. 'title' => $v['title'],
  278. ];
  279. if ($v['icon'] != 'fa fa-circle-o') {
  280. $arr['icon'] = $v['icon'];
  281. }
  282. if ($v['ismenu']) {
  283. $arr['ismenu'] = $v['ismenu'];
  284. }
  285. if (isset($v['childlist']) && $v['childlist']) {
  286. $arr['sublist'] = $this->getCreateMenu($v['childlist']);
  287. }
  288. $result[] = $arr;
  289. }
  290. return $result;
  291. }
  292. /**
  293. * 写入到文件
  294. * @param string $name
  295. * @param array $data
  296. * @param string $pathname
  297. * @return mixed
  298. */
  299. protected function writeToFile($name, $data, $pathname)
  300. {
  301. $search = $replace = [];
  302. foreach ($data as $k => $v) {
  303. $search[] = "{%{$k}%}";
  304. $replace[] = $v;
  305. }
  306. $stub = file_get_contents($this->getStub($name));
  307. $content = str_replace($search, $replace, $stub);
  308. if (!is_dir(dirname($pathname))) {
  309. mkdir(strtolower(dirname($pathname)), 0755, true);
  310. }
  311. return file_put_contents($pathname, $content);
  312. }
  313. /**
  314. * 获取基础模板
  315. * @param string $name
  316. * @return string
  317. */
  318. protected function getStub($name)
  319. {
  320. return __DIR__ . '/Addon/stubs/' . $name . '.stub';
  321. }
  322. }