Install.php 14 KB

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