Install.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php
  2. namespace app\admin\command;
  3. use fast\Random;
  4. use PDO;
  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\Lang;
  13. use think\Request;
  14. use think\View;
  15. class Install extends Command
  16. {
  17. protected $model = null;
  18. /**
  19. * @var \think\View 视图类实例
  20. */
  21. protected $view;
  22. /**
  23. * @var \think\Request Request 实例
  24. */
  25. protected $request;
  26. protected function configure()
  27. {
  28. $config = Config::get('database');
  29. $this
  30. ->setName('install')
  31. ->addOption('hostname', 'a', Option::VALUE_OPTIONAL, 'mysql hostname', $config['hostname'])
  32. ->addOption('hostport', 'o', Option::VALUE_OPTIONAL, 'mysql hostport', $config['hostport'])
  33. ->addOption('database', 'd', Option::VALUE_OPTIONAL, 'mysql database', $config['database'])
  34. ->addOption('prefix', 'r', Option::VALUE_OPTIONAL, 'table prefix', $config['prefix'])
  35. ->addOption('username', 'u', Option::VALUE_OPTIONAL, 'mysql username', $config['username'])
  36. ->addOption('password', 'p', Option::VALUE_OPTIONAL, 'mysql password', $config['password'])
  37. ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override', false)
  38. ->setDescription('New installation of FastAdmin');
  39. }
  40. /**
  41. * 命令行安装
  42. */
  43. protected function execute(Input $input, Output $output)
  44. {
  45. define('INSTALL_PATH', APP_PATH . 'admin' . DS . 'command' . DS . 'Install' . DS);
  46. // 覆盖安装
  47. $force = $input->getOption('force');
  48. $hostname = $input->getOption('hostname');
  49. $hostport = $input->getOption('hostport');
  50. $database = $input->getOption('database');
  51. $prefix = $input->getOption('prefix');
  52. $username = $input->getOption('username');
  53. $password = $input->getOption('password');
  54. $installLockFile = INSTALL_PATH . "install.lock";
  55. if (is_file($installLockFile) && !$force) {
  56. throw new Exception("\nFastAdmin already installed!\nIf you need to reinstall again, use the parameter --force=true ");
  57. }
  58. $adminUsername = 'admin';
  59. $adminPassword = Random::alnum(10);
  60. $adminEmail = 'admin@admin.com';
  61. $siteName = __('My Website');
  62. $adminName = $this->installation($hostname, $hostport, $database, $username, $password, $prefix, $adminUsername, $adminPassword, $adminEmail, $siteName);
  63. if ($adminName) {
  64. $output->highlight("Admin url:http://www.yoursite.com/{$adminName}");
  65. }
  66. $output->highlight("Admin username:{$adminUsername}");
  67. $output->highlight("Admin password:{$adminPassword}");
  68. \think\Cache::rm('__menu__');
  69. $output->info("Install Successed!");
  70. }
  71. /**
  72. * PC端安装
  73. */
  74. public function index()
  75. {
  76. $this->view = View::instance(Config::get('template'), Config::get('view_replace_str'));
  77. $this->request = Request::instance();
  78. define('INSTALL_PATH', APP_PATH . 'admin' . DS . 'command' . DS . 'Install' . DS);
  79. $langSet = strtolower($this->request->langset());
  80. if (!$langSet || in_array($langSet, ['zh-cn', 'zh-hans-cn'])) {
  81. Lang::load(INSTALL_PATH . 'zh-cn.php');
  82. }
  83. $installLockFile = INSTALL_PATH . "install.lock";
  84. if (is_file($installLockFile)) {
  85. echo __('The system has been installed. If you need to reinstall, please remove %s first', 'install.lock');
  86. exit;
  87. }
  88. $output = function ($code, $msg, $url = null, $data = null) {
  89. return json(['code' => $code, 'msg' => $msg, 'url' => $url, 'data' => $data]);
  90. };
  91. if ($this->request->isPost()) {
  92. $mysqlHostname = $this->request->post('mysqlHostname', '127.0.0.1');
  93. $mysqlHostport = $this->request->post('mysqlHostport', '3306');
  94. $hostArr = explode(':', $mysqlHostname);
  95. if (count($hostArr) > 1) {
  96. $mysqlHostname = $hostArr[0];
  97. $mysqlHostport = $hostArr[1];
  98. }
  99. $mysqlUsername = $this->request->post('mysqlUsername', 'root');
  100. $mysqlPassword = $this->request->post('mysqlPassword', '');
  101. $mysqlDatabase = $this->request->post('mysqlDatabase', '');
  102. $mysqlPrefix = $this->request->post('mysqlPrefix', 'fa_');
  103. $adminUsername = $this->request->post('adminUsername', 'admin');
  104. $adminPassword = $this->request->post('adminPassword', '');
  105. $adminPasswordConfirmation = $this->request->post('adminPasswordConfirmation', '');
  106. $adminEmail = $this->request->post('adminEmail', 'admin@admin.com');
  107. $siteName = $this->request->post('siteName', __('My Website'));
  108. if ($adminPassword !== $adminPasswordConfirmation) {
  109. return $output(0, __('The two passwords you entered did not match'));
  110. }
  111. $adminName = '';
  112. try {
  113. $adminName = $this->installation($mysqlHostname, $mysqlHostport, $mysqlDatabase, $mysqlUsername, $mysqlPassword, $mysqlPrefix, $adminUsername, $adminPassword, $adminEmail, $siteName);
  114. } catch (\PDOException $e) {
  115. throw new Exception($e->getMessage());
  116. } catch (\Exception $e) {
  117. return $output(0, $e->getMessage());
  118. }
  119. return $output(1, __('Install Successed'), null, ['adminName' => $adminName]);
  120. }
  121. $errInfo = '';
  122. try {
  123. $this->checkenv();
  124. } catch (\Exception $e) {
  125. $errInfo = $e->getMessage();
  126. }
  127. return $this->view->fetch(INSTALL_PATH . "install.html", ['errInfo' => $errInfo]);
  128. }
  129. /**
  130. * 执行安装
  131. */
  132. protected function installation($mysqlHostname, $mysqlHostport, $mysqlDatabase, $mysqlUsername, $mysqlPassword, $mysqlPrefix, $adminUsername, $adminPassword, $adminEmail = null, $siteName = null)
  133. {
  134. $this->checkenv();
  135. if ($mysqlDatabase == '') {
  136. throw new Exception(__('Please input correct database'));
  137. }
  138. if (!preg_match("/^\w{3,12}$/", $adminUsername)) {
  139. throw new Exception(__('Please input correct username'));
  140. }
  141. if (!preg_match("/^[\S]{6,16}$/", $adminPassword)) {
  142. throw new Exception(__('Please input correct password'));
  143. }
  144. if ($siteName == '' || preg_match("/fast" . "admin/i", $siteName)) {
  145. throw new Exception(__('Please input correct website'));
  146. }
  147. $sql = file_get_contents(INSTALL_PATH . 'fastadmin.sql');
  148. $sql = str_replace("`fa_", "`{$mysqlPrefix}", $sql);
  149. // 先尝试能否自动创建数据库
  150. $config = Config::get('database');
  151. try {
  152. $pdo = new PDO("{$config['type']}:host={$mysqlHostname}" . ($mysqlHostport ? ";port={$mysqlHostport}" : ''), $mysqlUsername, $mysqlPassword);
  153. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  154. $pdo->query("CREATE DATABASE IF NOT EXISTS `{$mysqlDatabase}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
  155. // 连接install命令中指定的数据库
  156. $instance = Db::connect([
  157. 'type' => "{$config['type']}",
  158. 'hostname' => "{$mysqlHostname}",
  159. 'hostport' => "{$mysqlHostport}",
  160. 'database' => "{$mysqlDatabase}",
  161. 'username' => "{$mysqlUsername}",
  162. 'password' => "{$mysqlPassword}",
  163. 'prefix' => "{$mysqlPrefix}",
  164. ]);
  165. // 查询一次SQL,判断连接是否正常
  166. $instance->execute("SELECT 1");
  167. // 调用原生PDO对象进行批量查询
  168. $instance->getPdo()->exec($sql);
  169. } catch (\PDOException $e) {
  170. throw new Exception($e->getMessage());
  171. }
  172. // 后台入口文件
  173. $adminFile = ROOT_PATH . 'public' . DS . 'admin.php';
  174. // 数据库配置文件
  175. $dbConfigFile = APP_PATH . 'database.php';
  176. $dbConfigText = @file_get_contents($dbConfigFile);
  177. $callback = function ($matches) use ($mysqlHostname, $mysqlHostport, $mysqlUsername, $mysqlPassword, $mysqlDatabase, $mysqlPrefix) {
  178. $field = "mysql" . ucfirst($matches[1]);
  179. $replace = $$field;
  180. if ($matches[1] == 'hostport' && $mysqlHostport == 3306) {
  181. $replace = '';
  182. }
  183. return "'{$matches[1]}'{$matches[2]}=>{$matches[3]}Env::get('database.{$matches[1]}', '{$replace}'),";
  184. };
  185. $dbConfigText = preg_replace_callback("/'(hostname|database|username|password|hostport|prefix)'(\s+)=>(\s+)Env::get\((.*)\)\,/", $callback, $dbConfigText);
  186. // 检测能否成功写入数据库配置
  187. $result = @file_put_contents($dbConfigFile, $dbConfigText);
  188. if (!$result) {
  189. throw new Exception(__('The current permissions are insufficient to write the file %s', 'application/database.php'));
  190. }
  191. // 设置新的Token随机密钥key
  192. $oldTokenKey = config('token.key');
  193. $newTokenKey = \fast\Random::alnum(32);
  194. $coreConfigFile = CONF_PATH . 'config.php';
  195. $coreConfigText = @file_get_contents($coreConfigFile);
  196. $coreConfigText = preg_replace("/'key'(\s+)=>(\s+)'{$oldTokenKey}'/", "'key'\$1=>\$2'{$newTokenKey}'", $coreConfigText);
  197. $result = @file_put_contents($coreConfigFile, $coreConfigText);
  198. if (!$result) {
  199. throw new Exception(__('The current permissions are insufficient to write the file %s', 'application/config.php'));
  200. }
  201. // 变更默认管理员密码
  202. $adminPassword = $adminPassword ? $adminPassword : Random::alnum(8);
  203. $adminEmail = $adminEmail ? $adminEmail : "admin@admin.com";
  204. $newSalt = substr(md5(uniqid(true)), 0, 6);
  205. $newPassword = md5(md5($adminPassword) . $newSalt);
  206. $data = ['username' => $adminUsername, 'email' => $adminEmail, 'password' => $newPassword, 'salt' => $newSalt];
  207. $instance->name('admin')->where('username', 'admin')->update($data);
  208. // 变更前台默认用户的密码,随机生成
  209. $newSalt = substr(md5(uniqid(true)), 0, 6);
  210. $newPassword = md5(md5(Random::alnum(8)) . $newSalt);
  211. $instance->name('user')->where('username', 'admin')->update(['password' => $newPassword, 'salt' => $newSalt]);
  212. // 修改后台入口
  213. $adminName = '';
  214. if (is_file($adminFile)) {
  215. $adminName = Random::alpha(10) . '.php';
  216. rename($adminFile, ROOT_PATH . 'public' . DS . $adminName);
  217. }
  218. //修改站点名称
  219. if ($siteName != config('site.name')) {
  220. $instance->name('config')->where('name', 'name')->update(['value' => $siteName]);
  221. $siteConfigFile = CONF_PATH . 'extra' . DS . 'site.php';
  222. $siteConfig = include $siteConfigFile;
  223. $configList = $instance->name("config")->select();
  224. foreach ($configList as $k => $value) {
  225. if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
  226. $value['value'] = explode(',', $value['value']);
  227. }
  228. if ($value['type'] == 'array') {
  229. $value['value'] = (array)json_decode($value['value'], true);
  230. }
  231. $siteConfig[$value['name']] = $value['value'];
  232. }
  233. $siteConfig['name'] = $siteName;
  234. file_put_contents($siteConfigFile, '<?php' . "\n\nreturn " . var_export_short($siteConfig) . ";\n");
  235. }
  236. $installLockFile = INSTALL_PATH . "install.lock";
  237. //检测能否成功写入lock文件
  238. $result = @file_put_contents($installLockFile, 1);
  239. if (!$result) {
  240. throw new Exception(__('The current permissions are insufficient to write the file %s', 'application/admin/command/Install/install.lock'));
  241. }
  242. return $adminName;
  243. }
  244. /**
  245. * 检测环境
  246. */
  247. protected function checkenv()
  248. {
  249. // 检测目录是否存在
  250. $checkDirs = [
  251. 'thinkphp',
  252. 'vendor',
  253. 'public' . DS . 'assets' . DS . 'libs'
  254. ];
  255. //数据库配置文件
  256. $dbConfigFile = APP_PATH . 'database.php';
  257. if (version_compare(PHP_VERSION, '7.1.0', '<')) {
  258. throw new Exception(__("The current version %s is too low, please use PHP 7.1 or higher", PHP_VERSION));
  259. }
  260. if (!extension_loaded("PDO")) {
  261. throw new Exception(__("PDO is not currently installed and cannot be installed"));
  262. }
  263. if (!is_really_writable($dbConfigFile)) {
  264. throw new Exception(__('The current permissions are insufficient to write the configuration file application/database.php'));
  265. }
  266. foreach ($checkDirs as $k => $v) {
  267. if (!is_dir(ROOT_PATH . $v)) {
  268. throw new Exception(__('Please go to the official website to download the full package or resource package and try to install'));
  269. break;
  270. }
  271. }
  272. return true;
  273. }
  274. }