Install.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. $weakPasswordArr = ['123456', '12345678', '123456789', '654321', '111111', '000000', 'password', 'qwerty', 'abc123', '1qaz2wsx'];
  145. if (in_array($adminPassword, $weakPasswordArr)) {
  146. throw new Exception(__('Password is too weak'));
  147. }
  148. if ($siteName == '' || preg_match("/fast" . "admin/i", $siteName)) {
  149. throw new Exception(__('Please input correct website'));
  150. }
  151. $sql = file_get_contents(INSTALL_PATH . 'fastadmin.sql');
  152. $sql = str_replace("`fa_", "`{$mysqlPrefix}", $sql);
  153. // 先尝试能否自动创建数据库
  154. $config = Config::get('database');
  155. try {
  156. $pdo = new PDO("{$config['type']}:host={$mysqlHostname}" . ($mysqlHostport ? ";port={$mysqlHostport}" : ''), $mysqlUsername, $mysqlPassword);
  157. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  158. $pdo->query("CREATE DATABASE IF NOT EXISTS `{$mysqlDatabase}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
  159. // 连接install命令中指定的数据库
  160. $instance = Db::connect([
  161. 'type' => "{$config['type']}",
  162. 'hostname' => "{$mysqlHostname}",
  163. 'hostport' => "{$mysqlHostport}",
  164. 'database' => "{$mysqlDatabase}",
  165. 'username' => "{$mysqlUsername}",
  166. 'password' => "{$mysqlPassword}",
  167. 'prefix' => "{$mysqlPrefix}",
  168. ]);
  169. // 查询一次SQL,判断连接是否正常
  170. $instance->execute("SELECT 1");
  171. // 调用原生PDO对象进行批量查询
  172. $instance->getPdo()->exec($sql);
  173. } catch (\PDOException $e) {
  174. throw new Exception($e->getMessage());
  175. }
  176. // 后台入口文件
  177. $adminFile = ROOT_PATH . 'public' . DS . 'admin.php';
  178. // 数据库配置文件
  179. $dbConfigFile = APP_PATH . 'database.php';
  180. $dbConfigText = @file_get_contents($dbConfigFile);
  181. $callback = function ($matches) use ($mysqlHostname, $mysqlHostport, $mysqlUsername, $mysqlPassword, $mysqlDatabase, $mysqlPrefix) {
  182. $field = "mysql" . ucfirst($matches[1]);
  183. $replace = $$field;
  184. if ($matches[1] == 'hostport' && $mysqlHostport == 3306) {
  185. $replace = '';
  186. }
  187. return "'{$matches[1]}'{$matches[2]}=>{$matches[3]}Env::get('database.{$matches[1]}', '{$replace}'),";
  188. };
  189. $dbConfigText = preg_replace_callback("/'(hostname|database|username|password|hostport|prefix)'(\s+)=>(\s+)Env::get\((.*)\)\,/", $callback, $dbConfigText);
  190. // 检测能否成功写入数据库配置
  191. $result = @file_put_contents($dbConfigFile, $dbConfigText);
  192. if (!$result) {
  193. throw new Exception(__('The current permissions are insufficient to write the file %s', 'application/database.php'));
  194. }
  195. // 设置新的Token随机密钥key
  196. $oldTokenKey = config('token.key');
  197. $newTokenKey = \fast\Random::alnum(32);
  198. $coreConfigFile = CONF_PATH . 'config.php';
  199. $coreConfigText = @file_get_contents($coreConfigFile);
  200. $coreConfigText = preg_replace("/'key'(\s+)=>(\s+)'{$oldTokenKey}'/", "'key'\$1=>\$2'{$newTokenKey}'", $coreConfigText);
  201. $result = @file_put_contents($coreConfigFile, $coreConfigText);
  202. if (!$result) {
  203. throw new Exception(__('The current permissions are insufficient to write the file %s', 'application/config.php'));
  204. }
  205. $avatar = request()->domain() . '/assets/img/avatar.png';
  206. // 变更默认管理员密码
  207. $adminPassword = $adminPassword ? $adminPassword : Random::alnum(8);
  208. $adminEmail = $adminEmail ? $adminEmail : "admin@admin.com";
  209. $newSalt = substr(md5(uniqid(true)), 0, 6);
  210. $newPassword = md5(md5($adminPassword) . $newSalt);
  211. $data = ['username' => $adminUsername, 'email' => $adminEmail, 'avatar' => $avatar, 'password' => $newPassword, 'salt' => $newSalt];
  212. $instance->name('admin')->where('username', 'admin')->update($data);
  213. // 变更前台默认用户的密码,随机生成
  214. $newSalt = substr(md5(uniqid(true)), 0, 6);
  215. $newPassword = md5(md5(Random::alnum(8)) . $newSalt);
  216. $instance->name('user')->where('username', 'admin')->update(['avatar' => $avatar, 'password' => $newPassword, 'salt' => $newSalt]);
  217. // 修改后台入口
  218. $adminName = '';
  219. if (is_file($adminFile)) {
  220. $adminName = Random::alpha(10) . '.php';
  221. rename($adminFile, ROOT_PATH . 'public' . DS . $adminName);
  222. }
  223. //修改站点名称
  224. if ($siteName != config('site.name')) {
  225. $instance->name('config')->where('name', 'name')->update(['value' => $siteName]);
  226. $siteConfigFile = CONF_PATH . 'extra' . DS . 'site.php';
  227. $siteConfig = include $siteConfigFile;
  228. $configList = $instance->name("config")->select();
  229. foreach ($configList as $k => $value) {
  230. if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
  231. $value['value'] = is_array($value['value']) ? $value['value'] : explode(',', $value['value']);
  232. }
  233. if ($value['type'] == 'array') {
  234. $value['value'] = (array)json_decode($value['value'], true);
  235. }
  236. $siteConfig[$value['name']] = $value['value'];
  237. }
  238. $siteConfig['name'] = $siteName;
  239. file_put_contents($siteConfigFile, '<?php' . "\n\nreturn " . var_export_short($siteConfig) . ";\n");
  240. }
  241. $installLockFile = INSTALL_PATH . "install.lock";
  242. //检测能否成功写入lock文件
  243. $result = @file_put_contents($installLockFile, 1);
  244. if (!$result) {
  245. throw new Exception(__('The current permissions are insufficient to write the file %s', 'application/admin/command/Install/install.lock'));
  246. }
  247. return $adminName;
  248. }
  249. /**
  250. * 检测环境
  251. */
  252. protected function checkenv()
  253. {
  254. // 检测目录是否存在
  255. $checkDirs = [
  256. 'thinkphp',
  257. 'vendor',
  258. 'public' . DS . 'assets' . DS . 'libs'
  259. ];
  260. //数据库配置文件
  261. $dbConfigFile = APP_PATH . 'database.php';
  262. if (version_compare(PHP_VERSION, '7.1.0', '<')) {
  263. throw new Exception(__("The current version %s is too low, please use PHP 7.1 or higher", PHP_VERSION));
  264. }
  265. if (!extension_loaded("PDO")) {
  266. throw new Exception(__("PDO is not currently installed and cannot be installed"));
  267. }
  268. if (!is_really_writable($dbConfigFile)) {
  269. throw new Exception(__('The current permissions are insufficient to write the configuration file application/database.php'));
  270. }
  271. foreach ($checkDirs as $k => $v) {
  272. if (!is_dir(ROOT_PATH . $v)) {
  273. throw new Exception(__('Please go to the official website to download the full package or resource package and try to install'));
  274. break;
  275. }
  276. }
  277. return true;
  278. }
  279. }