Addon.php 13 KB

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