Install.php 14 KB

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