Index.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | A3Mall
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Author: xzncit <158373108@qq.com>
  8. // +----------------------------------------------------------------------
  9. namespace app\install\controller;
  10. use app\BaseController;
  11. use app\install\validate\Database;
  12. use mall\utils\Tool;
  13. use think\facade\Cache;
  14. use think\facade\Db;
  15. use think\facade\Request;
  16. use think\facade\Session;
  17. use think\facade\View;
  18. class Index extends BaseController {
  19. protected $path = '';
  20. protected function initialize(){
  21. $this->path = dirname(dirname(__FILE__)) . '/data';
  22. if (file_exists( $this->path.'/install.lock')) {
  23. exit('程序已安装,如果需要重新安装,请删除 install 模块下 data 目录下的 install.lock 文件');
  24. }
  25. }
  26. public function index(){
  27. //Session::set("step",1);
  28. return View::fetch();
  29. }
  30. public function check(){
  31. Session::set("step",2);
  32. Session::set("error",false);
  33. // 环境检测
  34. $env = $this->check_env();
  35. // 目录文件读写检测
  36. $dirFile = $this->check_dirfile();
  37. // 函数检测
  38. $func = $this->check_func();
  39. return View::fetch("",[
  40. "env"=>$env,
  41. "dirFile"=>$dirFile,
  42. "func"=>$func,
  43. "isNext"=>false == Session::get('error')
  44. ]);
  45. }
  46. public function config(){
  47. if(Request::isAjax()){
  48. $data = Request::param();
  49. try {
  50. validate(Database::class)->check($data);
  51. }catch (\Exception $ex){
  52. return json(["status"=>0,"msg"=>$ex->getMessage()]);
  53. }
  54. // 缓存配置数据
  55. $data['type'] = 'mysql';
  56. Session::set('installData', $data);
  57. try {
  58. $mysqli = mysqli_connect(
  59. $data['hostname'],
  60. $data['username'],
  61. $data['password']
  62. );
  63. if(!$mysqli){
  64. throw new \Exception("连接数据库失败,请检查配置是否正确。");
  65. }
  66. // 检测数据库连接并检测版本
  67. $r = mysqli_query($mysqli,'select version() as version limit 1;');
  68. $version = mysqli_fetch_assoc($r);
  69. if (version_compare($version['version'], '5.5.3', '<')) {
  70. throw new \Exception('数据库版本过低,必须 5.5.3 及以上');
  71. }
  72. // 检测是否已存在数据库
  73. $sql = 'SELECT count(*) as count FROM information_schema.schemata WHERE schema_name="'.$data['database'].'"';
  74. $result = mysqli_query($mysqli,$sql);
  75. $row = mysqli_fetch_assoc($result);
  76. if ($row["count"] <= 0) {
  77. // 创建数据库
  78. $sql = "CREATE DATABASE IF NOT EXISTS `{$data['database']}` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;";
  79. if (!mysqli_query($mysqli,$sql)) {
  80. throw new \Exception("新建数据库失败,请手动建立数据库。");
  81. }
  82. }
  83. mysqli_close($mysqli);
  84. } catch (\Exception $e) {
  85. return json(["status"=>0,"msg"=>$e->getMessage()]);
  86. }
  87. // 准备工作完成
  88. return json(["status"=>1,"msg"=>"ok","url"=>str_replace('/install/','/',createUrl('index/install'))]);
  89. }
  90. if (Session::get('step') != 2) {
  91. $this->redirect("check");
  92. }
  93. Cache::clear();
  94. Session::set("step",3);
  95. return View::fetch();
  96. }
  97. public function install(){
  98. if(Request::isAjax()){
  99. // 数据准备
  100. $data = Session::get('installData');
  101. $type = Request::param('type');
  102. $result = ['code' => 1, "data"=>['type' => $type]];
  103. if (!$type) {
  104. $result['data']['type'] = 'database';
  105. $result['data']['status'] = 1;
  106. $result['msg'] = '开始安装数据库表';
  107. $result['url'] = str_replace('/install/','/',createUrl('index/install'));
  108. return json($result);
  109. }
  110. // 连接数据库
  111. $db = null;
  112. if (in_array($type, ['database', 'config'])) {
  113. try {
  114. $db = mysqli_connect($data['hostname'],$data['username'],$data['password'],$data['database'],$data['hostport']);
  115. } catch (\Exception $e) {
  116. $result['code'] = 0;
  117. $result['msg'] = $e->getMessage();
  118. return json($result);
  119. }
  120. $db->set_charset('utf8mb4');
  121. }
  122. if ('database' == $type) {
  123. $database = Cache::remember('database', function () {
  124. $data = Session::get('installData');
  125. $sql = file_get_contents($this->path . '/a3mall' . ($data['is_demo'] == 1 ? '_demo' : '') . '.sql');
  126. //$sql = str_replace("`mall_","`".$data["prefix"],$sql);
  127. $sql = str_replace("\r", "\n", $sql);
  128. $sql = explode(";\n", $sql);
  129. Cache::tag('install', 'database');
  130. return $sql;
  131. });
  132. // 数据库表安装完成
  133. $msg = '';
  134. $idx = Request::param('idx','0','intval');
  135. if ($idx >= count($database)) {
  136. $result['data']['type'] = 'config';
  137. $result['data']['status'] = 1;
  138. $result['msg'] = '开始安装配置文件';
  139. $result['url'] = str_replace('/install/','/',createUrl('index/install'));
  140. return json($result);
  141. }
  142. // 插入数据库表
  143. if (array_key_exists($idx, $database)) {
  144. $sql = $value = trim($database[$idx]);
  145. if (!empty($value)) {
  146. try {
  147. if (false !== mysqli_query($db,$sql)) {
  148. $msg = $this->get_sql_message($sql);
  149. } else {
  150. throw new \Exception(mysqli_error($db));
  151. }
  152. } catch (\Exception $e) {
  153. $result['code'] = 0;
  154. $result['msg'] = $e->getMessage();
  155. return json($result);
  156. }
  157. }
  158. }
  159. // 返回下一步
  160. $result['data']['status'] = 1;
  161. $result['msg'] = $msg;
  162. $result['url'] = str_replace('/install/','/',createUrl('index/install',['idx'=>$idx+1]));
  163. return json($result);
  164. }
  165. // 安装配置文件
  166. if ('config' == $type) {
  167. // 创建数据库配置文件
  168. $domain = trim(Request::domain(),"/") . "/";
  169. $string = <<<EOF
  170. APP_DEBUG = false
  171. [APP]
  172. DEFAULT_TIMEZONE = Asia/Shanghai
  173. [DATABASE]
  174. TYPE = mysql
  175. HOSTNAME = {$data['hostname']}
  176. DATABASE = {$data['database']}
  177. PREFIX = {$data['prefix']}
  178. USERNAME = {$data['username']}
  179. PASSWORD = {$data['password']}
  180. HOSTPORT = {$data['hostport']}
  181. CHARSET = utf8mb4
  182. DEBUG = false
  183. [LANG]
  184. default_lang = zh-cn
  185. [WEB]
  186. app_web_url = {$domain}
  187. [JWT]
  188. ENCRYPTION = {$this->getRandString(35)}
  189. SIGN = {$this->getRandString(10)}
  190. EOF;
  191. if (!file_put_contents(Tool::getRootPath() . '.env', $string)) {
  192. $result['code'] = 0;
  193. $result['msg'] = "数据库配置文件写入失败。";
  194. return json($result);
  195. }
  196. // 创建超级管理员
  197. $adminData = [
  198. 'id' => 1,
  199. 'role_id' => 1,
  200. 'username' => $data["admin_user"],
  201. 'password' => md5($data['admin_password']),
  202. 'lock' => 1,
  203. 'status' => 0,
  204. 'count' => 1,
  205. 'time' => time()
  206. ];
  207. try {
  208. $u = mysqli_query($db,"select * from {$data['prefix']}system_users where id=1");
  209. $users = mysqli_fetch_assoc($u);
  210. if(!empty($users)){
  211. $sql = "UPDATE `{$data['prefix']}system_users` SET ";
  212. unset($adminData['id']);
  213. foreach($adminData as $k=>$v){
  214. $sql .= '`'.$k.'` = ' . "'" . $v . "',";
  215. }
  216. $sql = trim($sql,',');
  217. $sql .= " WHERE `id` = 1;";
  218. mysqli_query($db,$sql);
  219. }else{
  220. $sql = "INSERT INTO `{$data['prefix']}system_users` (".implode(",",array_keys($adminData)).") VALUES (".("'".implode("','",array_values($adminData)) . "'").")";
  221. mysqli_query($db,$sql);
  222. }
  223. } catch (\Exception $e) {
  224. $result['code'] = 0;
  225. $result['msg'] = $e->getMessage();
  226. return json($result);
  227. }
  228. $result['data']['status'] = 0;
  229. $result['msg'] = '安装完成!';
  230. $result['url'] = str_replace('/install/','/',createUrl('index/complete'));
  231. return json($result);
  232. }
  233. $result['code'] = 0;
  234. $result['msg'] = "安装出现错误,未完成安装。";
  235. return json($result);
  236. }
  237. if (Session::get('step') != 3) {
  238. $this->redirect("config");
  239. }
  240. Session::set('step', 4);
  241. return View::fetch();
  242. }
  243. public function complete(){
  244. Cache::clear();
  245. file_put_contents($this->path . '/install.lock', '');
  246. return View::fetch("",[
  247. "data"=>Session::get('installData')
  248. ]);
  249. }
  250. private function check_env(){
  251. $items = [
  252. 'os' => ['操作系统', '不限制', '类Unix', PHP_OS, 'check'],
  253. 'php' => ['PHP版本', '7.1', '7.2+', PHP_VERSION, 'check'],
  254. 'upload' => ['附件上传', '不限制', '2M+', '未知', 'check'],
  255. 'gd' => ['GD库', '2.0', '2.0+', '未知', 'check'],
  256. 'disk' => ['磁盘空间', '100M', '不限制', '未知', 'check'],
  257. ];
  258. // PHP环境检测
  259. if ($items['php'][3] < $items['php'][1]) {
  260. $items['php'][4] = 'error';
  261. Session::set('error', true);
  262. }
  263. // 附件上传检测
  264. if (@ini_get('file_uploads'))
  265. $items['upload'][3] = ini_get('upload_max_filesize');
  266. // GD库检测
  267. $tmp = function_exists('gd_info') ? gd_info() : [];
  268. if (empty($tmp['GD Version'])) {
  269. $items['gd'][3] = '未安装';
  270. $items['gd'][4] = 'error';
  271. Session::set('error', true);
  272. } else {
  273. $items['gd'][3] = $tmp['GD Version'];
  274. }
  275. unset($tmp);
  276. // 磁盘空间检测
  277. if (function_exists('disk_free_space')) {
  278. $disk_size = floor(disk_free_space(Tool::getRootPath()) / (1024 * 1024));
  279. $items['disk'][3] = $disk_size . 'M';
  280. if ($disk_size < 100) {
  281. $items['disk'][4] = 'error';
  282. Session::set('error', true);
  283. }
  284. }
  285. return $items;
  286. }
  287. private function check_dirfile(){
  288. $items = [
  289. ['file', '可写', 'check', '.env'],
  290. ['dir', '可写', 'check', 'app'],
  291. ['dir', '可写', 'check', 'runtime'],
  292. ['dir', '可写', 'check', 'mall'],
  293. ['dir', '可写', 'check', 'public/static'],
  294. ['dir', '可写', 'check', 'public/uploads'],
  295. ];
  296. foreach ($items as &$val) {
  297. $item = Tool::getRootPath() . $val[3];
  298. if ('dir' == $val[0]) {
  299. if (!is_writable($item)) {
  300. if (is_dir($item)) {
  301. $val[1] = '可读';
  302. $val[2] = 'error';
  303. Session::set('error', true);
  304. } else {
  305. $val[1] = '不存在';
  306. $val[2] = 'error';
  307. Session::set('error', true);
  308. }
  309. }
  310. } else {
  311. if (file_exists($item)) {
  312. if (!is_writable($item)) {
  313. $val[1] = '不可写';
  314. $val[2] = 'error';
  315. Session::set('error', true);
  316. }
  317. } else {
  318. if (!is_writable(dirname($item))) {
  319. $val[1] = '不存在';
  320. $val[2] = 'error';
  321. Session::set('error', true);
  322. }
  323. }
  324. }
  325. }
  326. return $items;
  327. }
  328. private function check_func(){
  329. $items = [
  330. ['pdo', '支持', 'check', '类'],
  331. ['pdo_mysql', '支持', 'check', '模块'],
  332. ['openssl', '支持', 'check', '模块'],
  333. ['curl', '支持', 'check', '模块'],
  334. ['bcmath', '支持', 'check', '模块'],
  335. ['mbstring', '支持', 'check', '模块'],
  336. ['scandir', '支持', 'check', '函数'],
  337. ['file_get_contents', '支持', 'check', '函数'],
  338. ['version_compare', '支持', 'check', '函数'],
  339. ];
  340. foreach ($items as &$val) {
  341. if (('类' == $val[3] && !class_exists($val[0]))
  342. || ('模块' == $val[3] && !extension_loaded($val[0]))
  343. || ('函数' == $val[3] && !function_exists($val[0]))
  344. ) {
  345. $val[1] = '不支持';
  346. $val[2] = 'error';
  347. Session::set('error', true);
  348. }
  349. }
  350. return $items;
  351. }
  352. private function get_sql_message($sql){
  353. if (preg_match('/CREATE TABLE? `([^ ]*)`/is', $sql, $matches)) {
  354. return !empty($matches[1]) ? "创建数据库表 {$matches[1]} 完成" : '';
  355. }
  356. if (preg_match('/INSERT INTO? `([^ ]*)`/is', $sql, $matches)) {
  357. return !empty($matches[1]) ? "插入数据库行 {$matches[1]} 完成" : '';
  358. }
  359. if (preg_match('/ALTER TABLE? `([^ ]*)`/is', $sql, $matches)) {
  360. if (mb_strpos($sql, 'MODIFY')) {
  361. return !empty($matches[1]) ? "调整数据库索引 {$matches[1]} 完成" : '';
  362. } else {
  363. return !empty($matches[1]) ? "创建数据库索引 {$matches[1]} 完成" : '';
  364. }
  365. }
  366. return '';
  367. }
  368. private function getRandString($len=10){
  369. $string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  370. $length = strlen($string)-1;
  371. $s = '';
  372. for ($i=0;$i<$len;$i++) {
  373. $num=mt_rand(0,$length);
  374. $s .= $string[$num];
  375. }
  376. return $s;
  377. }
  378. }