Addon.php 15 KB

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