Install.php 32 KB

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