SystemUpgradeclient.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. <?php
  2. namespace app\admin\controller\system;
  3. use app\admin\controller\AuthController;
  4. use crmeb\services\JsonService as Json;
  5. use crmeb\services\MysqlBackupService;
  6. use crmeb\services\UpgradeService as uService;
  7. use think\facade\Db;
  8. /**
  9. * 在线升级控制器
  10. * Class SystemUpgradeclient
  11. * @package app\admin\controller\system
  12. *
  13. */
  14. class SystemUpgradeclient extends AuthController
  15. {
  16. protected $serverweb = array('version' => '1.0', 'version_code' => 0);//本站点信息
  17. public function initialize()
  18. {
  19. parent::initialize();
  20. //屏蔽所有错误避免操作文件夹发生错误提示
  21. ini_set('display_errors', 0);
  22. error_reporting(0);
  23. self::snyweninfo();//更新站点信息
  24. $this->assign(['auth' => self::isauth(), 'app' => uService::isWritable(app()->getRootPath()), 'extend' => uService::isWritable(EXTEND_PATH), 'public' => uService::isWritable(app()->getRootPath() . 'public')]);
  25. }
  26. //同步更新站点信息
  27. public function snyweninfo()
  28. {
  29. $this->serverweb['ip'] = $this->request->ip();
  30. $this->serverweb['host'] = $this->request->host();
  31. $this->serverweb['https'] = !empty($this->request->domain()) ? $this->request->domain() : sys_config('site_url');
  32. $this->serverweb['webname'] = sys_config('site_name');
  33. $local = uService::getVersion();
  34. if ($local['code'] == 200 && isset($local['msg']['version']) && isset($local['msg']['version_code'])) {
  35. $this->serverweb['version'] = uService::replace($local['msg']['version']);
  36. $this->serverweb['version_code'] = (int)uService::replace($local['msg']['version_code']);
  37. }
  38. uService::snyweninfo($this->serverweb);
  39. }
  40. //是否授权
  41. public function isauth()
  42. {
  43. return uService::isauth();
  44. }
  45. public function index()
  46. {
  47. $server = uService::start();
  48. $version = $this->serverweb['version'];
  49. $version_code = $this->serverweb['version_code'];
  50. $this->assign(compact('server', 'version', 'version_code'));
  51. return $this->fetch();
  52. }
  53. public function get_list()
  54. {
  55. $list = uService::request_post(uService::$isList, ['page' => input('post.page/d'), 'limit' => input('post.limit/d')]);
  56. if (is_array($list) && isset($list['code']) && isset($list['data']) && $list['code'] == 200) {
  57. $list = $list['data'];
  58. } else {
  59. $list = [];
  60. }
  61. Json::successful('ok', ['list' => $list, 'page' => input('post.page/d') + 1]);
  62. }
  63. //删除备份文件
  64. public function setcopydel()
  65. {
  66. $post = input('post.');
  67. if (!isset($post['id'])) Json::fail('删除备份文件失败,缺少参数ID');
  68. if (!isset($post['ids'])) Json::fail('删除备份文件失败,缺少参数IDS');
  69. $fileservice = new uService;
  70. if (is_array($post['ids'])) {
  71. foreach ($post['ids'] as $file) {
  72. $fileservice->del_dir(app()->getRootPath() . 'public' . DS . 'copyfile' . $file);
  73. }
  74. }
  75. if ($post['id']) {
  76. $copyFile = app()->getRootPath() . 'public' . DS . 'copyfile' . $post['id'];
  77. $fileservice->del_dir($copyFile);
  78. }
  79. Json::successful('删除成功');
  80. }
  81. public function get_new_version_conte()
  82. {
  83. $post = $this->request->post();
  84. if (!isset($post['id'])) Json::fail('缺少参数ID');
  85. $versionInfo = uService::request_post(uService::$NewVersionCount, ['id' => $post['id']]);
  86. if (isset($versionInfo['code']) && isset($versionInfo['data']['count']) && $versionInfo['code'] == 200) {
  87. return Json::successful(['count' => $versionInfo['data']['count']]);
  88. } else {
  89. return Json::fail('服务器异常');
  90. }
  91. }
  92. //一键升级
  93. public function auto_upgrad()
  94. {
  95. $prefix = config('database.prefix');
  96. $fileservice = new uService;
  97. $post = $this->request->post();
  98. if (!isset($post['id'])) Json::fail('缺少参数ID');
  99. $versionInfo = $fileservice->request_post(uService::$isNowVersion, ['id' => $post['id']]);
  100. if ($versionInfo === null) Json::fail('服务器异常,请稍后再试');
  101. if (isset($versionInfo['code']) && $versionInfo['code'] == 400) Json::fail(isset($versionInfo['msg']) ? $versionInfo['msg'] : '您暂时没有权限升级,请联系管理员!');
  102. if (is_array($versionInfo) && isset($versionInfo['data'])) {
  103. $list = $versionInfo['data'];
  104. $id = [];
  105. foreach ($list as $key => $val) {
  106. $savefile = app()->getRootPath() . 'public' . DS . 'upgrade_lv';
  107. //1,检查远程下载文件,并下载
  108. if (($save_path = $fileservice->check_remote_file_exists($val['zip_name'], $savefile)) === false) Json::fail('远程升级包不存在');
  109. //2,首先解压文件
  110. $savename = app()->getRootPath() . 'public' . DS . 'upgrade_lv' . DS . time();
  111. $fileservice->zipopen($save_path, $savename);
  112. //3,执行SQL文件
  113. Db::startTrans();
  114. try {
  115. //参数3不介意大小写的
  116. $sqlfile = $fileservice->list_dir_info($savename . DS, true, 'sql');
  117. if (is_array($sqlfile) && !empty($sqlfile)) {
  118. foreach ($sqlfile as $file) {
  119. if (file_exists($file)) {
  120. //为一键安装做工作记得表前缀要改为[#DB_PREFIX#]哦
  121. $execute_sql = explode(";\r", str_replace(['[#DB_PREFIX#]', "\n"], [$prefix, "\r"], file_get_contents($file)));
  122. foreach ($execute_sql as $_sql) {
  123. if ($query_string = trim(str_replace(array(
  124. "\r",
  125. "\n",
  126. "\t"
  127. ), '', $_sql))) Db::execute($query_string);
  128. }
  129. //执行完sql记得删掉哦
  130. $fileservice->unlink_file($file);
  131. }
  132. }
  133. }
  134. Db::commit();
  135. } catch (\Exception $e) {
  136. Db::rollback();
  137. //删除解压下的文件
  138. $fileservice->del_dir(app()->getRootPath() . 'public' . DS . 'upgrade_lv');
  139. //删除压缩包
  140. $fileservice->unlink_file($save_path);
  141. //升级失败发送错误信息
  142. $fileservice->request_post(uService::$isInsertLog, [
  143. 'content' => '升级失败,错误信息为:' . $e->getMessage(),
  144. 'add_time' => time(),
  145. 'ip' => $this->request->ip(),
  146. 'http' => $this->request->domain(),
  147. 'type' => 'error',
  148. 'version' => $val['version']
  149. ]);
  150. return Json::fail('升级失败SQL文件执行有误');
  151. }
  152. //4,备份文件
  153. $copyFile = app()->getRootPath() . 'public' . DS . 'copyfile' . $val['id'];
  154. $copyList = $fileservice->get_dirs($savename . DS);
  155. if (isset($copyList['dir'])) {
  156. if ($copyList['dir'][0] == '.' && $copyList['dir'][1] == '..') {
  157. array_shift($copyList['dir']);
  158. array_shift($copyList['dir']);
  159. }
  160. foreach ($copyList['dir'] as $dir) {
  161. if (file_exists(app()->getRootPath() . $dir, $copyFile . DS . $dir)) {
  162. $fileservice->copy_dir(app()->getRootPath() . $dir, $copyFile . DS . $dir);
  163. }
  164. }
  165. }
  166. //5,覆盖文件
  167. $fileservice->handle_dir($savename, app()->getRootPath());
  168. //6,删除升级生成的目录
  169. $fileservice->del_dir(app()->getRootPath() . 'public' . DS . 'upgrade_lv');
  170. //7,删除压缩包
  171. $fileservice->unlink_file($save_path);
  172. //8,改写本地升级文件
  173. $handle = fopen(app()->getRootPath() . '.version', 'w+');
  174. if ($handle === false) Json::fail(app()->getRootPath() . '.version' . '无法写入打开');
  175. $content = <<<EOT
  176. version={$val['version']}
  177. version_code={$val['id']}
  178. EOT;
  179. if (fwrite($handle, $content) === false) Json::fail('升级包写入失败');
  180. fclose($handle);
  181. //9,向服务端发送升级日志
  182. $posts = [
  183. 'ip' => $this->request->ip(),
  184. 'https' => $this->request->domain(),
  185. 'update_time' => time(),
  186. 'content' => '一键升级成功,升级版本号为:' . $val['version'] . '。版本code为:' . $val['id'],
  187. 'type' => 'log',
  188. 'versionbefor' => $this->serverweb['version'],
  189. 'versionend' => $val['version']
  190. ];
  191. $inset = $fileservice->request_post(uService::$isInsertLog, $posts);
  192. $id[] = $val['id'];
  193. }
  194. //10,升级完成
  195. Json::successful('升级成功', ['code' => end($id), 'version' => $val['version']]);
  196. } else {
  197. Json::fail('服务器异常,请稍后再试');
  198. }
  199. }
  200. //在线升级
  201. public function online_upgrad()
  202. {
  203. $prefix = config('database.prefix');
  204. $fileservice = new uService;
  205. $post = $this->request->post();
  206. if (!isset($post['id'])) Json::fail('缺少参数ID');
  207. //获取升级列表
  208. $versionInfo = $fileservice->request_post(uService::$isNowVersion, ['id' => 18]);
  209. if ($versionInfo === null) Json::fail('服务器异常,请稍后再试');
  210. //检测授权
  211. if(!$fileservice->isauth()) Json::fail('请先去授权后在升级');
  212. if (isset($versionInfo['code']) && $versionInfo['code'] == 400) Json::fail(isset($versionInfo['msg']) ? $versionInfo['msg'] : '您暂时没有权限升级,请联系管理员!');
  213. if(!is_array($versionInfo) || !isset($versionInfo['data'])) Json::fail('服务器异常,请稍后再试');
  214. $rootpath = app()->getRootPath();
  215. $list = $versionInfo['data'];
  216. $id = [];
  217. $savefile = $rootpath . 'public' . DS . 'upgrade_lv';
  218. foreach ($list as $key => $val) {
  219. //1,检查远程下载文件,并下载
  220. if (($save_path = $fileservice->check_remote_file_exists($val['zip_name'], $savefile)) === false) Json::fail('远程升级包不存在');
  221. //2,首先解压文件
  222. $savename = $rootpath . 'public' . DS . 'upgrade_lv' . DS . time();
  223. $fileservice->zipopen($save_path, $savename);
  224. }
  225. //3,备份文件
  226. $saveDir = $rootpath . 'backup\\'.date('Ymd',time()).'\\';
  227. $filepath = $saveDir . 'crmeb_'.time().'.zip';
  228. $zip = new \ZipArchive();
  229. if(!$zip->open($filepath,\ZIPARCHIVE::CREATE))
  230. {
  231. Json::fail("创建[$filepath]失败");
  232. }
  233. try{
  234. $this->createZip($rootpath,$zip);
  235. }catch (\think\Exception $e){
  236. $message = '[异常时间]: '. date('Y-m-d H:i:s') . PHP_EOL;
  237. $message .= '[异常消息]: '. $e->getMessage() . PHP_EOL;
  238. $message .= '[异常文件]: '. $e->getFile() . PHP_EOL;
  239. $message .= '[异常行数]: '. $e->getLine() . PHP_EOL;
  240. Json::fail($message);
  241. }
  242. $zip->close();
  243. //4 备份sql
  244. if(!$this->backupSql($saveDir)){
  245. Json::fail('备份数据库失败');
  246. }
  247. //5 执行SQL文件
  248. Db::startTrans();
  249. try {
  250. //参数3不介意大小写的
  251. $sqlfile = $fileservice->list_dir_info($savename . DS, true, 'sql');
  252. if (is_array($sqlfile) && !empty($sqlfile)) {
  253. foreach ($sqlfile as $file) {
  254. if (file_exists($file)) {
  255. //为一键安装做工作记得表前缀要改为[#DB_PREFIX#]哦
  256. $execute_sql = explode(";\r", str_replace(['[#DB_PREFIX#]', "\n"], [$prefix, "\r"], file_get_contents($file)));
  257. foreach ($execute_sql as $_sql) {
  258. if ($query_string = trim(str_replace(array(
  259. "\r",
  260. "\n",
  261. "\t"
  262. ), '', $_sql))) Db::execute($query_string);
  263. }
  264. //执行完sql记得删掉哦
  265. $fileservice->unlink_file($file);
  266. }
  267. }
  268. }
  269. Db::commit();
  270. } catch (\Exception $e) {
  271. Db::rollback();
  272. //删除解压下的文件
  273. $fileservice->del_dir(app()->getRootPath() . 'public' . DS . 'upgrade_lv');
  274. //删除压缩包
  275. $fileservice->unlink_file($save_path);
  276. //升级失败发送错误信息
  277. $fileservice->request_post(uService::$isInsertLog, [
  278. 'content' => '升级失败,错误信息为:' . $e->getMessage(),
  279. 'add_time' => time(),
  280. 'ip' => $this->request->ip(),
  281. 'http' => $this->request->domain(),
  282. 'type' => 'error',
  283. 'version' => $val['version']
  284. ]);
  285. return Json::fail('升级失败SQL文件执行有误');
  286. }
  287. //6 覆盖文件
  288. $fileservice->handle_dir($savename, app()->getRootPath());
  289. //7 删除升级生成的目录
  290. $fileservice->del_dir(app()->getRootPath() . 'public' . DS . 'upgrade_lv');
  291. //8 删除压缩包
  292. $fileservice->unlink_file($save_path);
  293. //9 改写本地升级文件
  294. $handle = fopen(app()->getRootPath() . '.version', 'w+');
  295. if ($handle === false) Json::fail(app()->getRootPath() . '.version' . '无法写入打开');
  296. $content = <<<EOT
  297. version={$val['version']}
  298. version_code={$val['id']}
  299. EOT;
  300. if (fwrite($handle, $content) === false) Json::fail('升级包写入失败');
  301. fclose($handle);
  302. //10 向服务端发送升级日志
  303. $posts = [
  304. 'ip' => $this->request->ip(),
  305. 'https' => $this->request->domain(),
  306. 'update_time' => time(),
  307. 'content' => '一键升级成功,升级版本号为:' . $val['version'] . '。版本code为:' . $val['id'],
  308. 'type' => 'log',
  309. 'versionbefor' => $this->serverweb['version'],
  310. 'versionend' => $val['version']
  311. ];
  312. $inset = $fileservice->request_post(uService::$isInsertLog, $posts);
  313. $id[] = $val['id'];
  314. //11 升级完成
  315. Json::successful('升级成功', ['code' => end($id), 'version' => $val['version']]);
  316. }
  317. //备份sql
  318. public function backupSql($saveDir)
  319. {
  320. $config = array(
  321. 'path'=>$saveDir,
  322. //数据库备份卷大小
  323. 'compress' => 1,
  324. //数据库备份文件是否启用压缩 0不压缩 1 压缩
  325. 'level' => 5,
  326. );
  327. $back = new MysqlBackupService($config);
  328. $list = $back->dataList(null);
  329. $tables = array_column($list,'name');
  330. $back->setFile(['name'=>'crmeb','part'=>time()]);
  331. $data = '';
  332. foreach ($tables as $t) {
  333. $res = $back->backup($t, 0);
  334. if ($res == false && $res != 0) {
  335. $data .= $t . '|';
  336. }
  337. }
  338. return $data ? false : true;
  339. }
  340. //创建zip
  341. private function createZip($dir,$zipObj)
  342. {
  343. $dir_source = opendir($dir);
  344. while(($file = readdir($dir_source)) != false)
  345. {
  346. if($file=="." || $file==".." ) continue;
  347. $sub_file = $dir.'/'.$file;
  348. if(is_dir($sub_file) && $file != 'backup' && $file != 'runtime' && $file = 'uploads')
  349. {
  350. $zipObj->addEmptyDir($sub_file);
  351. $this->createZip($sub_file,$zipObj);
  352. }
  353. if(is_file($sub_file))
  354. {
  355. $zipObj->addFile($sub_file);
  356. }
  357. }
  358. }
  359. }