Install.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\controller;
  12. use crmeb\basic\BaseController;
  13. use Redis;
  14. use think\App;
  15. use think\Exception;
  16. use think\exception\ValidateException;
  17. use think\facade\Config;
  18. use think\facade\View;
  19. use think\Request;
  20. use think\Response;
  21. use Throwable;
  22. use ZipArchive;
  23. use ZipStream\ZipStream;
  24. class Install //extends BaseController
  25. {
  26. /**
  27. * Request实例
  28. * @var Request
  29. */
  30. protected $request;
  31. /**
  32. * 应用实例
  33. * @var App
  34. */
  35. protected $app;
  36. /**
  37. * sql文件
  38. * @var App
  39. */
  40. public $sqlFile = 'crmeb_merchant.sql';
  41. /**
  42. * 配置文件
  43. * @var App
  44. */
  45. public $configFile = '.env';
  46. public $env;
  47. public $installHost;
  48. public $_url;
  49. public function __construct(App $app)
  50. {
  51. if (file_exists(__DIR__ . '/../../install/install.lock')) {
  52. throw new ValidateException('你已经安装过该系统,如果想重新安装,请先删除install目录下的 install.lock 文件,然后再安装。');
  53. }
  54. if (!file_exists(__DIR__ . '/../../install/' . $this->sqlFile)) {
  55. throw new ValidateException('缺少数据库文件:"install/'.$this->sqlFile.'"');
  56. }
  57. if (!file_exists(__DIR__ . '/../../install/' . $this->configFile)) {
  58. throw new ValidateException('缺少配置文件:"install/'.$this->configFile.'"');
  59. }
  60. $this->app = $app;
  61. $this->request = $this->app->request;
  62. $this->env = [];
  63. $this->installHost = $this->request->domain();
  64. if (substr($this->installHost, 0, 5) == 'https'){
  65. $this->_url = str_replace('//' ,'\\\/\\\/', $this->installHost);
  66. } else {
  67. $this->_url = str_replace('http://' ,'http:\\\/\\\/', $this->installHost);
  68. }
  69. }
  70. /**
  71. * TODO 1 开始安装
  72. * @return string
  73. * @author Qinii
  74. * @day 2020-07-16
  75. */
  76. public function begin()
  77. {
  78. return View::fetch('/install/step1');
  79. }
  80. /**
  81. * TODO 2 环境检测
  82. * @return string
  83. * @author Qinii
  84. * @day 2020-07-16
  85. */
  86. public function environment()
  87. {
  88. $phpv = @ phpversion();
  89. $os = PHP_OS;
  90. $tmp = function_exists('gd_info') ? gd_info() : array();
  91. $max_execution_time = ini_get('max_execution_time');
  92. $allow_reference = (ini_get('allow_call_time_pass_reference') ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');
  93. $allow_url_fopen = (ini_get('allow_url_fopen') ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');
  94. $safe_mode = (ini_get('safe_mode') ? '<font color=red>[×]On</font>' : '<font color=green>[√]Off</font>');
  95. $err = 0;
  96. if (empty($tmp['GD Version'])) {
  97. $gd = '<font color=red>[×]Off</font>';
  98. $err++;
  99. } else {
  100. $gd = '<font color=green>[√]On</font> ' . $tmp['GD Version'];
  101. }
  102. if (function_exists('mysqli_connect')) {
  103. $mysql = '<span class="correct_span">&radic;</span> 已安装';
  104. } else {
  105. $mysql = '<span class="correct_span error_span">&radic;</span> 请安装mysqli扩展';
  106. $err++;
  107. }
  108. if (ini_get('file_uploads')) {
  109. $uploadSize = '<span class="correct_span">&radic;</span> ' . ini_get('upload_max_filesize');
  110. } else {
  111. $uploadSize = '<span class="correct_span error_span">&radic;</span>禁止上传';
  112. }
  113. if (function_exists('session_start')) {
  114. $session = '<span class="correct_span">&radic;</span> 支持';
  115. } else {
  116. $session = '<span class="correct_span error_span">&radic;</span> 不支持';
  117. $err++;
  118. }
  119. if (extension_loaded('zip')) {
  120. $zip = '<font color=green>[√]支持</font> ';
  121. } else {
  122. $zip = '<font color=red>[×]不支持</font>';
  123. $err++;
  124. }
  125. if (extension_loaded(('redis'))) {
  126. $redis = '<font color=green>[√]支持</font> ';
  127. } else {
  128. $redis = '<font color=red>[×]不支持</font>';
  129. $err++;
  130. }
  131. if (extension_loaded('swoole')) {
  132. $swoole = '<font color=green>[√]支持</font> ';
  133. } else {
  134. $swoole = '<font color=red>[×]不支持</font>';
  135. $err++;
  136. }
  137. if (extension_loaded('swoole_loader')) {
  138. $swooleCompiler = '<font color=green>[√]支持</font> ';
  139. } else {
  140. $swooleCompiler = '<a href="/install/loader" target="_blank"><span class="correct_span error_span">&radic;</span> 请安装swoole_loader扩展</a>';
  141. $err++;
  142. }
  143. if (function_exists('curl_init')) {
  144. $curl = '<font color=green>[√]支持</font> ';
  145. } else {
  146. $curl = '<font color=red>[×]不支持</font>';
  147. $err++;
  148. }
  149. if (function_exists('bcadd')) {
  150. $bcmath = '<font color=green>[√]支持</font> ';
  151. } else {
  152. $bcmath = '<font color=red>[×]不支持</font>';
  153. $err++;
  154. }
  155. if (function_exists('openssl_encrypt')) {
  156. $openssl = '<font color=green>[√]支持</font> ';
  157. } else {
  158. $openssl = '<font color=red>[×]不支持</font>';
  159. $err++;
  160. }
  161. if (function_exists('finfo_open')) {
  162. $finfo_open = '<font color=green>[√]支持</font> ';
  163. } else {
  164. $finfo_open = '<font color=red>[×]不支持</font>';
  165. $err++;
  166. }
  167. $folder = array(
  168. 'public/install',
  169. 'public/uploads',
  170. 'runtime',
  171. '.env',
  172. );
  173. //必须开启函数
  174. if (function_exists('file_put_contents')) {
  175. $file_put_contents = '<font color=green>[√]开启</font> ';
  176. } else {
  177. $file_put_contents = '<font color=red>[×]关闭</font>';
  178. $err++;
  179. }
  180. if (function_exists('imagettftext')) {
  181. $imagettftext = '<font color=green>[√]开启</font> ';
  182. } else {
  183. $imagettftext = '<font color=red>[×]关闭</font>';
  184. $err++;
  185. }
  186. if (function_exists('pcntl_alarm')) {
  187. $pcntl_alarm = '<font color=green>[√]开启</font> ';
  188. } else {
  189. $pcntl_alarm = '<font color=red>[×]关闭</font>';
  190. $err++;
  191. }
  192. if (function_exists('proc_open')) {
  193. $proc_open = '<font color=green>[√]开启</font> ';
  194. } else {
  195. $proc_open = '<font color=red>[×]关闭</font>';
  196. $err++;
  197. }
  198. if (function_exists('pcntl_signal')) {
  199. $pcntl_signal = '<font color=green>[√]开启</font> ';
  200. } else {
  201. $pcntl_signal = '<font color=red>[×]关闭</font>';
  202. $err++;
  203. }
  204. View::assign([
  205. 'max_execution_time' => $max_execution_time,
  206. 'allow_reference' => $allow_reference,
  207. 'swooleCompiler' => $swooleCompiler,
  208. 'phpv' => $phpv,
  209. 'allow_url_fopen' => $allow_url_fopen,
  210. 'safe_mode' => $safe_mode,
  211. 'gd' => $gd,
  212. 'mysql' => $mysql,
  213. 'uploadSize' => $uploadSize,
  214. 'redis' => $redis,
  215. 'session' => $session,
  216. 'swoole' => $swoole,
  217. 'curl' => $curl,
  218. 'bcmath' => $bcmath,
  219. 'openssl' => $openssl,
  220. 'finfo_open' => $finfo_open,
  221. 'file_put_contents' => $file_put_contents,
  222. 'imagettftext' => $imagettftext,
  223. 'folder' => $folder,
  224. 'zip' => $zip,
  225. 'proc_open' => $proc_open,
  226. 'pcntl_alarm' => $pcntl_alarm,
  227. 'pcntl_signal' => $pcntl_signal,
  228. ]);
  229. return View::fetch('/install/step2', ['err' => $err]);
  230. }
  231. /**
  232. * TODO 3 数据库填写表单
  233. * @return string
  234. * @author Qinii
  235. * @day 2020-07-15
  236. */
  237. public function databases()
  238. {
  239. return View::fetch('/install/step3');
  240. }
  241. /**
  242. * TODO 4 安装数据库
  243. * @return string
  244. * @author Qinii
  245. * @day 2020-07-16
  246. */
  247. public function create()
  248. {
  249. $data = $this->request->params(['dbhost', 'dbport', 'dbname', 'dbuser', 'dbpw', ['dbprefix','eb_'], 'manager', 'manager_pwd', ['rbhost', '127.0.0.1'], ['rbport', 6379], 'rbpw', ['rbselect', 0], 'demo']);
  250. $mysql = $this->checkDatabsaces($data);
  251. if ($mysql !== 1) throw new ValidateException('数据库链接失败' . $mysql);
  252. return View::fetch('/install/step4', ['data' => $data]);
  253. }
  254. /**
  255. * TODO 5 安装完成
  256. * @return string
  257. * @author Qinii
  258. * @day 2020-07-16
  259. */
  260. public function end()
  261. {
  262. $ip = $this->get_client_ip();
  263. $server = $this->request->server();
  264. $host = $server['HTTP_HOST'];
  265. $version = get_crmeb_version('未知');
  266. $this->installlog();
  267. @touch(__DIR__ . '/../../install/install.lock');
  268. $this->unzip();
  269. return View::fetch('/install/step5', [
  270. 'host' => $host,
  271. 'ip' => $ip,
  272. 'version' => $version,
  273. 'merchant' => Config::get('admin.merchant_prefix'),
  274. 'system' => Config::get('admin.admin_prefix'),
  275. ]);
  276. }
  277. /**
  278. * TODO 链接数据库 读取sql
  279. * @param $n
  280. * @return array
  281. * @author Qinii
  282. * @day 2020-07-16
  283. */
  284. public function perform($n)
  285. {
  286. $data = $this->request->param();
  287. $dbName = strtolower(trim($data['dbname']));
  288. $conn = @mysqli_connect($data['dbhost'], $data['dbuser'], $data['dbpw'], NULL, $data['dbport']);
  289. if (mysqli_connect_errno($conn)) {
  290. throw new ValidateException("连接数据库失败!" . mysqli_connect_error($conn));
  291. }
  292. if (!mysqli_select_db($conn, $dbName)) {
  293. //创建数据时同时设置编码
  294. if (!mysqli_query($conn, "CREATE DATABASE IF NOT EXISTS `" . $dbName . "` DEFAULT CHARACTER SET utf8;")) {
  295. throw new ValidateException('数据库 ' . $dbName . ' 不存在,也没权限创建新的数据库!');
  296. }
  297. }
  298. mysqli_select_db($conn, $dbName);
  299. mysqli_query($conn, 'SET NAMES utf8;');
  300. //读取数据文件
  301. $sqldata = file_get_contents(__DIR__ . '/../../install/' . $this->sqlFile);
  302. $sqlFormat = $this->sql_split($sqldata, $data['dbprefix']);
  303. $counts = count($sqlFormat);
  304. if ($n <= $counts && isset($sqlFormat[$n])) {
  305. $sql = trim($sqlFormat[$n]);
  306. $message = $this->install($sql, $conn, $data['dbprefix']);
  307. $n++;
  308. } else {
  309. if ($data['demo'] == '')
  310. $this->clear($conn, $data['dbprefix']);
  311. $this->setConfig($data);
  312. $message = $this->setDatabase($conn, $data);
  313. $n = -1;
  314. }
  315. return [
  316. 'n' => $n,
  317. 'msg' => $message
  318. ];
  319. }
  320. /**
  321. * TODO 执行数据库文件安装
  322. * @param $sql
  323. * @param $conn
  324. * @param $dbPrefix
  325. * @return string
  326. * @author Qinii
  327. * @day 2020-07-16
  328. */
  329. public function install($sql, $conn, $dbPrefix)
  330. {
  331. // 建表
  332. if (strstr($sql, 'CREATE TABLE')) {
  333. preg_match('/CREATE TABLE `eb_([^ ]*)`/is', $sql, $matches);
  334. mysqli_query($conn, "DROP TABLE IF EXISTS `$matches[1]");
  335. $sql = str_replace('`eb_', '`' . $dbPrefix, $sql);//替换表前缀
  336. $ret = mysqli_query($conn, $sql);
  337. if ($ret) {
  338. $message = '<li><span class="correct_span">&radic;</span>创建数据表[' . $dbPrefix . $matches[1] . ']完成!<span style="float: right;">' . date('Y-m-d H:i:s') . '</span></li> ';
  339. } else {
  340. $message = '<li><span class="correct_span error_span">&radic;</span>创建数据表[' . $dbPrefix . $matches[1] . ']失败!<span style="float: right;">' . date('Y-m-d H:i:s') . '</span></li>';
  341. }
  342. } //插入数据
  343. else {
  344. $message = '';
  345. if (trim($sql) !== '') {
  346. $sql = str_replace('`eb_', '`' . $dbPrefix, $sql);//替换表前缀
  347. $sql = str_replace('https://mer1.crmeb.net', $this->installHost , $sql);
  348. $sql = str_replace('https:\\\/\\\/mer1.crmeb.net', $this->_url , $sql);
  349. $ret = mysqli_query($conn, $sql);
  350. $sql = htmlspecialchars($sql);
  351. $msg = substr($sql, 0, 30);
  352. if ($ret) {
  353. $message = '<li><span class="correct_span">&radic;</span>执行 [' . $msg . '...]成功!<span style="float: right;">' . date('Y-m-d H:i:s') . '</span></li> ';
  354. } else {
  355. $message = '<li><span class="correct_span error_span">&radic;</span>执行[' . $msg . '..]失败!<span style="float: right;">' . date('Y-m-d H:i:s') . '</span></li>';
  356. }
  357. }
  358. }
  359. return $message;
  360. }
  361. /**
  362. * TODO 清除测试数据
  363. * @param $conn
  364. * @param $dbPrefix
  365. * @author Qinii
  366. * @day 2020-07-16
  367. */
  368. public function clear($conn, $dbPrefix)
  369. {
  370. $result = mysqli_query($conn, "show tables");
  371. $tables = mysqli_fetch_all($result);//参数MYSQL_ASSOC、MYSQLI_NUM、MYSQLI_BOTH规定产生数组类型
  372. $bl_table = array(
  373. 'eb_system_admin',
  374. 'eb_system_menu',
  375. 'eb_system_role',
  376. 'eb_system_group',
  377. 'eb_system_group_data',
  378. 'eb_system_city',
  379. 'eb_express',
  380. 'eb_system_config',
  381. 'eb_system_config_classify',
  382. 'eb_system_config_value',
  383. 'eb_template_message',
  384. 'system_notice_config',
  385. 'eb_city_area',
  386. 'eb_diy',
  387. 'eb_page_category',
  388. 'eb_page_link',
  389. 'eb_system_notice_config'
  390. );
  391. foreach ($bl_table as $k => $v) {
  392. $bl_table[$k] = str_replace('eb_', $dbPrefix, $v);
  393. }
  394. foreach ($tables as $key => $val) {
  395. if (!in_array($val[0], $bl_table)) {
  396. mysqli_query($conn, "truncate table " . $val[0]);
  397. }
  398. }
  399. }
  400. /**
  401. * TODO 创建.env文件
  402. * @param $data
  403. * @author Qinii
  404. * @day 2020-07-16
  405. */
  406. public function setConfig($data)
  407. {
  408. //读取配置文件,并替换真实配置数据1
  409. $strConfig = file_get_contents(__DIR__ . '/../../install/' . $this->configFile);
  410. //'dbhost', 'dbport', 'dbname', 'dbuser', 'dbpw', 'dbprefix', 'manager', 'manager_pwd', ['rbhost', '127.0.0.1'], ['rbport', 6379], 'rbpw', ['rbselect', 0]
  411. $strConfig = str_replace('#DB_HOST#', $data['dbhost'], $strConfig);
  412. $strConfig = str_replace('#DB_NAME#', $data['dbname'], $strConfig);
  413. $strConfig = str_replace('#DB_USER#', $data['dbuser'], $strConfig);
  414. $strConfig = str_replace('#DB_PWD#', $data['dbpw'], $strConfig);
  415. $strConfig = str_replace('#DB_PORT#', $data['dbport'], $strConfig);
  416. $strConfig = str_replace('#DB_PREFIX#', $data['dbprefix'], $strConfig);
  417. $strConfig = str_replace('#DB_CHARSET#', 'utf8', $strConfig);
  418. //redis数据库信息
  419. $strConfig = str_replace('#RB_HOST#', $data['rbhost'], $strConfig);
  420. $strConfig = str_replace('#RB_PORT#', $data['rbport'], $strConfig);
  421. $strConfig = str_replace('#RB_PWD#', $data['rbpw'], $strConfig);
  422. $strConfig = str_replace('#RB_SELECT#', $data['rbselect'], $strConfig);
  423. $strConfig = str_replace('#APP_KEY#', md5(time() . random_int(10000000, 99999999)), $strConfig);
  424. @chmod(__DIR__ . '/../../.env', 0777);
  425. @file_put_contents(__DIR__ . '/../../.env', $strConfig); //数据库配置文件的地址
  426. }
  427. /**
  428. * TODO 修改后台管理员用户
  429. * @param $conn
  430. * @param $data
  431. * @return string
  432. * @author Qinii
  433. * @day 2020-07-16
  434. */
  435. public function setDatabase($conn, $data)
  436. {
  437. $time = date('Y-m-d H:i:s');
  438. $ip = $this->get_client_ip();
  439. $ip = empty($ip) ? "0.0.0.0" : $ip;
  440. $password = password_hash(trim($data['manager_pwd']), PASSWORD_BCRYPT);
  441. mysqli_query($conn, "truncate table {$data['dbprefix']}system_admin");
  442. $addadminsql = "INSERT INTO `{$data['dbprefix']}system_admin` (`admin_id`, `account`, `pwd`, `real_name`, `roles`, `last_ip`, `last_time`, `create_time`, `login_count`, `level`, `status`, `is_del`) VALUES
  443. (1, '" . $data['manager'] . "', '" . $password . "', '', '1', '" . $ip . "','$time' , '$time', 0, 0, 1, 0)";
  444. $res = mysqli_query($conn, $addadminsql);
  445. if ($res) {
  446. $message = '成功添加管理员<br />成功写入配置文件<br>安装完成.';
  447. } else {
  448. $message = '添加管理员失败<br />成功写入配置文件<br>安装完成.';
  449. }
  450. return $message;
  451. }
  452. /**
  453. * TODO 检测数据库链接是否成功以及版本
  454. * @param $data
  455. * @return false|int|string
  456. * @author Qinii
  457. * @day 2020-07-16
  458. */
  459. public function checkDatabsaces($data)
  460. {
  461. $dbName = strtolower(trim($data['dbname']));
  462. $conn = @mysqli_connect($data['dbhost'], $data['dbuser'], $data['dbpw'], NULL, $data['dbport']);
  463. if (mysqli_connect_errno($conn)) return 0;
  464. $result = mysqli_query($conn, "SELECT @@global.sql_mode");
  465. $result = $result->fetch_array();
  466. $version = mysqli_get_server_info($conn);
  467. if ($version < 5.6) return (json_encode(-4));
  468. if (strstr($result[0], 'STRICT_TRANS_TABLES') || strstr($result[0], 'STRICT_ALL_TABLES') || strstr($result[0], 'TRADITIONAL') || strstr($result[0], 'ANSI'))
  469. return ($version < 8.0) ? -1 : -2;
  470. $result = mysqli_query($conn, "select count(table_name) as c from information_schema.`TABLES` where table_schema='$dbName'");
  471. $result = $result->fetch_array();
  472. if ($result['c'] > 0) return -3;
  473. return 1;
  474. }
  475. /**
  476. * TODO 验证数据库及redis是否正常
  477. * @return false|int|string
  478. * @author Qinii
  479. * @day 2020-07-15
  480. */
  481. public function databasesCheck()
  482. {
  483. $data = $this->request->params(['dbhost', 'dbport', 'dbname', 'dbuser', 'dbpw',['dbprefix','eb_'], ['rbhost', '127.0.0.1'], ['rbport', 6379], 'rbpw', ['rbselect', 0]]);
  484. // mysql 检测
  485. $mysql = $this->checkDatabsaces($data);
  486. if ($mysql !== 1) return $mysql;
  487. // redis检测
  488. try {
  489. $redis = new Redis();
  490. $redis->connect($data['rbhost'], $data['rbport']);
  491. if ($data['rbpw']) $redis->auth($data['rbpw']);
  492. if ($data['rbselect']) $redis->select($data['rbselect']);
  493. $res = $redis->set('install', 1, 10);
  494. return $res ? 1 : -5;
  495. } catch (Throwable $e) {
  496. return -5;
  497. }
  498. }
  499. /**
  500. * TODO 安装记录文件生成
  501. * @author Qinii
  502. * @day 2020-07-16
  503. */
  504. public function installlog()
  505. {
  506. $mt_rand_str = $this->sp_random_string(6);
  507. $str_constant = "<?php" . PHP_EOL . "define('INSTALL_DATE'," . time() . ");" . PHP_EOL . "define('SERIALNUMBER','" . $mt_rand_str . "');";
  508. @file_put_contents(__DIR__ . '/../../.constant', $str_constant);
  509. }
  510. /**
  511. * TODO 随机字符串
  512. * @param int $len
  513. * @return string
  514. * @author Qinii
  515. * @day 2020-07-16
  516. */
  517. public function sp_random_string($len = 8)
  518. {
  519. $chars = array(
  520. "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
  521. "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
  522. "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
  523. "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
  524. "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
  525. "3", "4", "5", "6", "7", "8", "9"
  526. );
  527. $charsLen = count($chars) - 1;
  528. shuffle($chars); // 将数组打乱
  529. $output = "";
  530. for ($i = 0; $i < $len; $i++) {
  531. $output .= $chars[mt_rand(0, $charsLen)];
  532. }
  533. return $output;
  534. }
  535. /**
  536. * TODO 格式化mysql文件
  537. * @param $sql
  538. * @param $tablepre
  539. * @return array
  540. * @author Qinii
  541. * @day 2020-07-16
  542. */
  543. public function sql_split($sql, $tablepre)
  544. {
  545. if ($tablepre != "tp_")
  546. $sql = str_replace("tp_", $tablepre, $sql);
  547. $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8", $sql);
  548. $sql = str_replace("\r", "\n", $sql);
  549. $ret = array();
  550. $num = 0;
  551. $queriesarray = explode(";\n", trim($sql, "\xEF\xBB\xBF"));
  552. unset($sql);
  553. foreach ($queriesarray as $query) {
  554. $ret[$num] = '';
  555. $queries = explode("\n", trim($query));
  556. $queries = array_filter($queries);
  557. foreach ($queries as $query) {
  558. $str1 = substr($query, 0, 1);
  559. if ($str1 != '#' && $str1 != '-')
  560. $ret[$num] .= $query;
  561. }
  562. $num++;
  563. }
  564. return $ret;
  565. }
  566. /**
  567. * TODO 获取ip地址
  568. * @return string|null
  569. * @author Qinii
  570. * @day 2020-07-16
  571. */
  572. public function get_client_ip()
  573. {
  574. $server = $this->request->server();
  575. if (isset($server['REMOTE_ADDR']))
  576. $ip = $server['REMOTE_ADDR'];
  577. // IP地址合法验证
  578. $ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0';
  579. return $ip;
  580. }
  581. /**
  582. * 生成基础文件
  583. * @Author:Qinii
  584. * @Date: 2020/8/31
  585. */
  586. public function unzip()
  587. {
  588. update_crmeb_compiled();
  589. }
  590. /**
  591. * TODO swoole_loader 安装向导
  592. * @Author:Qinii
  593. * @Date: 2020/9/10
  594. */
  595. public function swooleCompiler()
  596. {
  597. // Check os type
  598. $this->env['os'] = [];
  599. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  600. $this->env['os']['name'] = "windows";
  601. $this->env['os']['raw_name'] = php_uname();
  602. } else {
  603. $this->env['os']['name'] = "unix";
  604. $this->env['os']['raw_name'] = php_uname();
  605. }
  606. // Check php
  607. $this->env['php'] = [];
  608. $this->env['php']['version'] = phpversion();
  609. // Check run mode
  610. $sapi_type = php_sapi_name();
  611. if ("cli" == $sapi_type) {
  612. $this->env['php']['run_mode'] = "cli";
  613. } else {
  614. $this->env['php']['run_mode'] = "web";
  615. }
  616. // Check php bit
  617. if (PHP_INT_SIZE == 4) {
  618. $this->env['php']['bit'] = 32;
  619. } else {
  620. $this->env['php']['bit'] = 64;
  621. }
  622. $this->env['php']['sapi'] = $sapi_type;
  623. $this->env['php']['ini_loaded_file'] = php_ini_loaded_file();
  624. $this->env['php']['ini_scanned_files'] = php_ini_scanned_files();
  625. $this->env['php']['loaded_extensions'] = get_loaded_extensions();
  626. $this->env['php']['incompatible_extensions'] = ['xdebug', 'ionCube', 'zend_loader'];
  627. $this->env['php']['loaded_incompatible_extensions'] = [];
  628. $this->env['php']['extension_dir'] = ini_get('extension_dir');
  629. // Check incompatible extensions
  630. if (is_array($this->env['php']['loaded_extensions'])) {
  631. foreach ($this->env['php']['loaded_extensions'] as $loaded_extension) {
  632. foreach ($this->env['php']['incompatible_extensions'] as $incompatible_extension) {
  633. if (strpos(strtolower($loaded_extension), strtolower($incompatible_extension)) !== false) {
  634. $this->env['php']['loaded_incompatible_extensions'][] = $loaded_extension;
  635. }
  636. }
  637. }
  638. }
  639. $this->env['php']['loaded_incompatible_extensions'] = array_unique($this->env['php']['loaded_incompatible_extensions']);
  640. // Parse System Environment Info
  641. $sysInfo = $this->w_getSysInfo();
  642. // Check php thread safety
  643. $this->env['php']['raw_thread_safety'] = isset($sysInfo['thread_safety']) ? $sysInfo['thread_safety'] : false;
  644. if (isset($sysInfo['thread_safety'])) {
  645. $this->env['php']['thread_safety'] = $sysInfo['thread_safety'] ? '线程安全' : '非线程安全';
  646. } else {
  647. $this->env['php']['thread_safety'] = '未知';
  648. }
  649. // Check swoole loader installation
  650. if (isset($sysInfo['swoole_loader']) and isset($sysInfo['swoole_loader_version'])) {
  651. $this->env['php']['swoole_loader']['status'] = $sysInfo['swoole_loader'] ? "<span style='color: #007bff;'>已安装</span>"
  652. : '未安装';
  653. if ($sysInfo['swoole_loader_version'] !== false) {
  654. $this->env['php']['swoole_loader']['version'] = "<span style='color: #007bff;'>" . $sysInfo['swoole_loader_version'] . "</span>";
  655. } else {
  656. $this->env['php']['swoole_loader']['version'] = '未知';
  657. }
  658. } else {
  659. $this->env['php']['swoole_loader']['status'] = '未安装';
  660. $this->env['php']['swoole_loader']['version'] = '未知';
  661. }
  662. $this->html($sysInfo);
  663. }
  664. /**
  665. * 页面输出内容
  666. * @Author:Qinii
  667. * @Date: 2020/9/10
  668. * @param $this ->>env
  669. * @param $sysInfo
  670. */
  671. public function html($sysInfo)
  672. {
  673. $html = '';
  674. // Header
  675. $html_header = '<!doctype html>
  676. <html lang="en">
  677. <head>
  678. <!-- Required meta tags -->
  679. <meta charset="utf-8">
  680. <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  681. <!-- Bootstrap CSS -->
  682. <link href="https://lib.baomitu.com/twitter-bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet">
  683. <title>%s</title>
  684. <style>
  685. .list_info {display: inline-block; width: 12rem;}
  686. .bold_text {font-weight: bold;}
  687. .code {color:#007bff;font-size: medium;}
  688. </style>
  689. </head>
  690. <body class="bg-light">
  691. ';
  692. $html_header = sprintf($html_header, 'CRMEB Swoole Compiler 安装向导');
  693. $html_body = '<div class="container">';
  694. $html_body_nav = '<div class="py-5 text-center" style="padding-bottom: 1rem!important;">';
  695. $html_body_nav .= '<h2>CRMEB Swoole Compiler 安装向导</h2>';
  696. $html_body_nav .= '<p class="lead"> Version:2.0.2 Date:2019-01-09</p>';
  697. $html_body_nav .= '</div><hr>';
  698. // Environment information
  699. $html_body_environment = '
  700. <div class="col-12" style="padding-top: 1rem!important;">
  701. <h5 class="text-center">检查当前环境</h5>
  702. <ul class="list-unstyled text-small">';
  703. $html_body_environment .= '<li><span class="list_info">操作系统 : </span>' . $this->env['os']['raw_name'] . '</li>';
  704. $html_body_environment .= '<li><span class="list_info">PHP版本 : </span>' . $this->env['php']['version'] . '</li>';
  705. $html_body_environment .= '<li><span class="list_info">PHP运行环境 : </span>' . $this->env['php']['sapi'] . '</li>';
  706. $html_body_environment .= '<li><span class="list_info">PHP配置文件 : </span>' . $this->env['php']['ini_loaded_file'] . '</li>';
  707. $html_body_environment .= '<li><span class="list_info">PHP扩展安装目录 : </span>' . $this->env['php']['extension_dir'] . '</li>';
  708. $html_body_environment .= '<li><span class="list_info">PHP是否线程安全 : </span>' . $this->env['php']['thread_safety'] . '</li>';
  709. $html_body_environment .= '<li><span class="list_info">是否安装swoole_loader : </span>' . $this->env['php']['swoole_loader']['status'] . '</li>';
  710. if (isset($sysInfo['swoole_loader']) and $sysInfo['swoole_loader']) {
  711. $html_body_environment .= '<li><span class="list_info">swoole_loader版本 : </span>' . $this->env['php']['swoole_loader']['version'] . '</li>';
  712. }
  713. if ($this->env['php']['bit'] == 32) {
  714. $html_body_environment .= '<li><span style="color:red">温馨提示:当前环境使用的PHP为 ' . $this->env['php']['bit'] . ' 位的PHP,Compiler 目前不支持 Debug 版本或 32 位的PHP,可在 phpinfo() 中查看对应位数,如果误报请忽略此提示</span></li>';
  715. }
  716. $html_body_environment .= ' </ul></div>';
  717. // Error infomation
  718. $html_error = "";
  719. if (!empty($this->env['php']['loaded_incompatible_extensions'])) {
  720. $html_error = '<hr>
  721. <div class="col-12" style="padding-top: 1rem!important;">
  722. <h5 class="text-center" style="color:red">错误信息</h5>
  723. <p class="text-center" style="color:red">%s</p>
  724. </div>
  725. ';
  726. $err_msg = "当前PHP包含与swoole_compiler_loader扩展不兼容的扩展" . implode(',', $this->env['php']['loaded_incompatible_extensions']) . ",请移除不兼容的扩展。";
  727. $html_error = sprintf($html_error, $err_msg);
  728. }
  729. // Check Loader Status
  730. $html_body_loader = '<hr>';
  731. if (empty($html_error)) {
  732. $html_body_loader .= '<div class="col-12" style="padding-top: 1rem!important;">';
  733. $html_body_loader .= '<h5 class="text-center">安装和配置Swoole Loader</h5>';
  734. $phpversion = substr($this->env['php']['version'], 0, 3);
  735. $phpversion = str_replace('.', '', $phpversion);
  736. $loaderFileName = '';
  737. if ($this->env['os']['name'] == "windows") {
  738. $loaderFileName = 'php_swoole_loader_php' . $phpversion;
  739. if ($this->env['php']['thread_safety'] == '非线程安全') {
  740. $loaderFileName .= '_nzts_x64.dll';
  741. } else {
  742. $loaderFileName .= '_zts_x64.dll';
  743. }
  744. } else {
  745. if ($this->env['php']['thread_safety'] != '非线程安全') {
  746. $loaderFileName = 'swoole_loader' . $phpversion . '_zts.so';
  747. } else {
  748. $loaderFileName = 'swoole_loader' . $phpversion . '.so';
  749. }
  750. }
  751. $html_body_loader .= '<p><span class="bold_text">1 - 安装Swoole Loader</span></p><p>前往根目录 /install/swoole-loader/' . $loaderFileName . '扩展文件上传到当前PHP的扩展安装目录中:<br/><pre class="code">' . $this->env['php']['extension_dir'] . '</pre></p>';
  752. $html_body_loader .= '<p><span class="bold_text">2 - 修改php.ini配置</span>(如已修改配置,请忽略此步骤,不必重复添加)</p><p>';
  753. $html_body_loader .= '编辑此PHP配置文件:<span class="code">' . $this->env['php']['ini_loaded_file'] . '</span>,在此文件底部结尾处加入如下配置<br/>';
  754. if ($this->env['os']['name'] == "windows") {
  755. $html_body_loader .= '<pre class="code">extension=' . $this->env['php']['extension_dir'] . DIRECTORY_SEPARATOR . $loaderFileName . '</pre>注意:需要名称和刚才上传到当前PHP的扩展安装目录中的文件名一致';
  756. } else {
  757. $html_body_loader .= '<pre class="code">extension=' . $this->env['php']['extension_dir'] . DIRECTORY_SEPARATOR . $loaderFileName . '</pre>注意:需要名称和刚才上传到当前PHP的扩展安装目录中的文件名一致';
  758. }
  759. $html_body_loader .= '</p>';
  760. $html_body_loader .= '<p><span class="bold_text">3 - 重启服务</span></p><p>重启或重载PHP配置</p>';
  761. $html_body_loader .= '</div>';
  762. }
  763. // Body footer
  764. $html_body_footer = '<footer class="my-5 pt-5 text-muted text-center text-small">
  765. <p class="mb-1">CopyRight © 2018 - ' . date('Y') . ' Swoole.com 上海识沃网络科技有限公司</p>
  766. </footer>';
  767. $html_body .= $html_body_nav . '<div class="row">' . $html_body_environment . $html_error . $html_body_loader . '</div>' . $html_body_footer;
  768. $html_body .= '</div>';
  769. // Footer
  770. $html_footer = '
  771. <script src="https://lib.baomitu.com/jquery/3.3.1/jquery.min.js"></script>
  772. <script src="https://lib.baomitu.com/axios/0.18.0/axios.min.js"></script>
  773. <script src="https://lib.baomitu.com/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script>
  774. </body>
  775. </html>';
  776. $html = $html_header . $html_body . $html_footer;
  777. return Response::create()->content($html)->send();
  778. }
  779. public function w_getSysInfo()
  780. {
  781. $sysEnv = [];
  782. // Get content of phpinfo
  783. ob_start();
  784. phpinfo();
  785. $sysInfo = ob_get_contents();
  786. ob_end_clean();
  787. // Explode phpinfo content
  788. if ($this->env['php']['run_mode'] == 'cli') {
  789. $sysInfoList = explode('\n', $sysInfo);
  790. } else {
  791. $sysInfoList = explode('</tr>', $sysInfo);
  792. }
  793. foreach ($sysInfoList as $sysInfoItem) {
  794. if (preg_match('/thread safety/i', $sysInfoItem)) {
  795. $sysEnv['thread_safety'] = (preg_match('/(enabled|yes)/i', $sysInfoItem) != 0);
  796. }
  797. if (preg_match('/swoole_loader support/i', $sysInfoItem)) {
  798. $sysEnv['swoole_loader'] = (preg_match('/(enabled|yes)/i', $sysInfoItem) != 0);
  799. }
  800. if (preg_match('/swoole_loader version/i', $sysInfoItem)) {
  801. preg_match('/\d+.\d+.\d+/s', $sysInfoItem, $match);
  802. $sysEnv['swoole_loader_version'] = isset($match[0]) ? $match[0] : false;
  803. }
  804. }
  805. return $sysEnv;
  806. }
  807. }