Database.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. <?php
  2. namespace app\admin\controller;
  3. use think\facade\View;
  4. use think\facade\Db;
  5. use think\facade\Lang;
  6. //数据库备份根路径
  7. define('DATA_BACKUP_PATH', 'uploads/sqldata/');
  8. //数据库备份卷大小 20971520表示为 20M
  9. //define('DATA_BACKUP_PART_SIZE', 20971520);
  10. define('DATA_BACKUP_PART_SIZE', 1024 * 1024 * 10);
  11. //数据库备份文件是否启用压缩
  12. define('DATA_BACKUP_COMPRESS', 0);
  13. //数据库备份文件压缩级别
  14. define('DATA_BACKUP_COMPRESS_LEVEL', 9);
  15. /**
  16. *
  17. *
  18. * ----------------------------------------------------------------------------
  19. *
  20. * 控制器
  21. */
  22. class Database extends AdminControl
  23. {
  24. public function initialize()
  25. {
  26. parent::initialize();
  27. Lang::load(base_path() . 'admin/lang/' . config('lang.default_lang') . '/db.lang.php');
  28. }
  29. public function db()
  30. {
  31. $dbtable_list = Db::query('SHOW TABLE STATUS');
  32. $total = 0;
  33. foreach ($dbtable_list as $k => $v) {
  34. $dbtable_list[$k]['size'] = format_bytes($v['Data_length'] + $v['Index_length']);
  35. $total += $v['Data_length'] + $v['Index_length'];
  36. }
  37. View::assign('dbtable_list', $dbtable_list);
  38. View::assign('total', format_bytes($total));
  39. View::assign('tableNum', count($dbtable_list));
  40. $this->setAdminCurItem('db');
  41. return View::fetch();
  42. }
  43. public function export($tables = null, $id = null, $start = null)
  44. {
  45. //防止备份数据过程超时
  46. function_exists('set_time_limit') && set_time_limit(0);
  47. if (request()->isPost() && !empty($tables) && is_array($tables)) { //初始化
  48. $path = DATA_BACKUP_PATH;
  49. if (!is_dir($path)) {
  50. mkdir($path, 0755, true);
  51. }
  52. //读取备份配置
  53. $config = array(
  54. 'path' => realpath($path) . DIRECTORY_SEPARATOR,
  55. 'part' => DATA_BACKUP_PART_SIZE,
  56. 'compress' => DATA_BACKUP_COMPRESS,
  57. 'level' => DATA_BACKUP_COMPRESS_LEVEL,
  58. );
  59. //检查是否有正在执行的任务
  60. $lock = "{$config['path']}backup.lock";
  61. if (is_file($lock)) {
  62. return json(array('info' => lang('file_conflict'), 'status' => 0, 'url' => ''));
  63. } else {
  64. //创建锁文件
  65. file_put_contents($lock, TIMESTAMP);
  66. }
  67. //检查备份目录是否可写
  68. if (!is_writeable($config['path'])) {
  69. return json(array('info' => lang('file_cannot_write'), 'status' => 0, 'url' => ''));
  70. }
  71. session('backup_config', $config);
  72. //生成备份文件信息
  73. $file = array(
  74. 'name' => date('Ymd-His', $_SERVER['REQUEST_TIME']),
  75. 'part' => 1,
  76. );
  77. session('backup_file', $file);
  78. //缓存要备份的表
  79. session('backup_tables', $tables);
  80. //创建备份文件
  81. $Database = new \mall\Backup($file, $config);
  82. if (false !== $Database->create()) {
  83. $tab = array('id' => 0, 'start' => 0);
  84. return json(array('tables' => $tables, 'tab' => $tab, 'info' => lang('init_success'), 'status' => 1, 'url' => ''));
  85. } else {
  86. return json(array('info' => lang('init_error'), 'status' => 0, 'url' => ''));
  87. }
  88. } elseif (request()->isGet() && is_numeric($id) && is_numeric($start)) { //备份数据
  89. $tables = session('backup_tables');
  90. //备份指定表
  91. $Database = new \mall\Backup(session('backup_file'), session('backup_config'));
  92. $start = $Database->backup($tables[$id], $start);
  93. if (false === $start) { //出错
  94. return json(array('info' => lang('back_error'), 'status' => 0, 'url' => ''));
  95. } elseif (0 === $start) { //下一表
  96. if (isset($tables[++$id])) {
  97. $tab = array('id' => $id, 'start' => 0);
  98. return json(array('tab' => $tab, 'info' => lang('back_finish'), 'status' => 1, 'url' => ''));
  99. } else { //备份完成,清空缓存
  100. unlink(session('backup_config.path') . 'backup.lock');
  101. session('backup_tables', null);
  102. session('backup_file', null);
  103. session('backup_config', null);
  104. return json(array('info' => lang('back_finish'), 'status' => 1, 'url' => ''));
  105. }
  106. } else {
  107. $tab = array('id' => $id, 'start' => $start[0]);
  108. $rate = floor(100 * ($start[0] / $start[1]));
  109. return json(array('tab' => $tab, 'info' => lang('backup_in_progress') . "...({$rate}%)", 'status' => 1, 'url' => ''));
  110. }
  111. } else {
  112. //出错
  113. return json(array('info' => lang('param_error'), 'status' => 0, 'url' => ''));
  114. }
  115. }
  116. public function restore()
  117. {
  118. $path = DATA_BACKUP_PATH;
  119. if (!is_dir($path)) {
  120. mkdir($path, 0755, true);
  121. }
  122. $path = realpath($path);
  123. $flag = \FilesystemIterator::KEY_AS_FILENAME;
  124. $glob = new \FilesystemIterator($path, $flag);
  125. $restore_list = array();
  126. $filenum = $total = 0;
  127. foreach ($glob as $name => $file) {
  128. if (preg_match('/^\d{8,8}-\d{6,6}-\d+\.sql(?:\.gz)?$/', $name)) {
  129. $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d');
  130. $date = "{$name[0]}-{$name[1]}-{$name[2]}";
  131. $time = "{$name[3]}:{$name[4]}:{$name[5]}";
  132. $part = $name[6];
  133. $info = pathinfo($file);
  134. if (isset($restore_list["{$date} {$time}"])) {
  135. $info = $restore_list["{$date} {$time}"];
  136. $info['part'] = max($info['part'], $part);
  137. $info['size'] = $info['size'] + $file->getSize();
  138. } else {
  139. $info['part'] = $part;
  140. $info['size'] = $file->getSize();
  141. }
  142. $info['compress'] = ($info['extension'] === 'sql') ? '-' : $info['extension'];
  143. $info['time'] = strtotime("{$date} {$time}");
  144. $filenum++;
  145. $total += $info['size'];
  146. $restore_list["{$date} {$time}"] = $info;
  147. }
  148. }
  149. View::assign('restore_list', $restore_list);
  150. View::assign('filenum', $filenum);
  151. View::assign('total', $total);
  152. $this->setAdminCurItem('restore');
  153. return View::fetch();
  154. }
  155. /**
  156. * 执行还原数据库操作
  157. * @param int $time
  158. * @param null $part
  159. * @param null $start
  160. */
  161. public function import($time = 0, $part = null, $start = null)
  162. {
  163. function_exists('set_time_limit') && set_time_limit(0);
  164. if (is_numeric($time) && is_null($part) && is_null($start)) { //初始化
  165. //获取备份文件信息
  166. $name = date('Ymd-His', $time) . '-*.sql*';
  167. $path = realpath(DATA_BACKUP_PATH) . DIRECTORY_SEPARATOR . $name;
  168. $files = glob($path);
  169. $list = array();
  170. foreach ($files as $name) {
  171. $basename = basename($name);
  172. $match = sscanf($basename, '%4s%2s%2s-%2s%2s%2s-%d');
  173. $gz = preg_match('/^\d{8,8}-\d{6,6}-\d+\.sql.gz$/', $basename);
  174. $list[$match[6]] = array($match[6], $name, $gz);
  175. }
  176. ksort($list);
  177. //检测文件正确性
  178. $last = end($list);
  179. if (count($list) === $last[0]) {
  180. session('backup_list', $list); //缓存备份列表
  181. $this->success(lang('init_success'), NULL, ['part' => 1, 'start' => 0]);
  182. } else {
  183. $this->error(lang('file_break_please_check'));
  184. }
  185. } elseif (is_numeric($part) && is_numeric($start)) {
  186. $list = session('backup_list');
  187. $db = new \mall\Backup(
  188. $list[$part],
  189. array(
  190. 'path' => realpath(DATA_BACKUP_PATH) . DIRECTORY_SEPARATOR,
  191. 'compress' => $list[$part][2]
  192. )
  193. );
  194. $start = $db->import($start);
  195. if (false === $start) {
  196. $this->error(lang('recover_error'));
  197. } elseif (0 === $start) { //下一卷
  198. if (isset($list[++$part])) {
  199. $data = array('part' => $part, 'start' => 0);
  200. $this->success(lang('restoring') . "...#{$part}", null, $data);
  201. } else {
  202. session('backup_list', null);
  203. $this->success(lang('recover_success'));
  204. }
  205. } else {
  206. $data = array('part' => $part, 'start' => $start[0]);
  207. if ($start[1]) {
  208. $rate = floor(100 * ($start[0] / $start[1]));
  209. $this->success(lang('restoring') . "...#{$part} ({$rate}%)", null, $data);
  210. } else {
  211. $data['gz'] = 1;
  212. $this->success(lang('restoring') . "...#{$part}", null, $data);
  213. }
  214. }
  215. } else {
  216. $this->error(lang('param_error'));
  217. }
  218. }
  219. /**
  220. * 优化
  221. */
  222. public function optimize()
  223. {
  224. $batchFlag = intval(input('param.batchFlag'));
  225. //批量删除
  226. if ($batchFlag) {
  227. $table = input('param.key');
  228. } else {
  229. $table[] = input('param.tablename');
  230. }
  231. if (empty($table)) {
  232. $this->error(lang('please_select_repire_table'));
  233. }
  234. $strTable = implode(',', $table);
  235. if (!Db::query("OPTIMIZE TABLE {$strTable} ")) {
  236. $strTable = '';
  237. }
  238. $this->success(lang('optimization_table_succ') . $strTable, (string)url('Database/db'));
  239. }
  240. /**
  241. * 修复
  242. */
  243. public function repair()
  244. {
  245. $batchFlag = intval(input('param.batchFlag'));
  246. //批量删除
  247. if ($batchFlag) {
  248. $table = I('key', array());
  249. } else {
  250. $table[] = input('param.tablename');
  251. }
  252. if (empty($table)) {
  253. $this->error(lang('please_repire_table'));
  254. }
  255. $strTable = implode(',', $table);
  256. if (!Db::query("REPAIR TABLE {$strTable} ")) {
  257. $strTable = '';
  258. }
  259. $this->success(lang('optimization_repair_succ') . $strTable, (string)url('Database/db'));
  260. }
  261. /**
  262. * 下载
  263. * @param int $time
  264. */
  265. public function downFile($time = 0)
  266. {
  267. $name = date('Ymd-His', $time) . '-*.sql*';
  268. $path = realpath(DATA_BACKUP_PATH) . DIRECTORY_SEPARATOR . $name;
  269. $files = glob($path);
  270. if (is_array($files)) {
  271. foreach ($files as $filePath) {
  272. if (!file_exists($filePath)) {
  273. $this->error(lang('file_not_exist'));
  274. } else {
  275. $filename = basename($filePath);
  276. header("Content-type: application/octet-stream");
  277. header('Content-Disposition: attachment; filename="' . $filename . '"');
  278. header("Content-Length: " . filesize($filePath));
  279. readfile($filePath);
  280. }
  281. }
  282. }
  283. }
  284. /**
  285. * 删除备份文件
  286. * @param Integer $time 备份时间
  287. */
  288. public function del($time = 0)
  289. {
  290. if ($time) {
  291. $name = date('Ymd-His', $time) . '-*.sql*';
  292. $path = realpath(DATA_BACKUP_PATH) . DIRECTORY_SEPARATOR . $name;
  293. array_map("unlink", glob($path));
  294. if (count(glob($path))) {
  295. $this->error(lang('back_file_drop_fail'));
  296. } else {
  297. $this->success(lang('back_file_drop_success'));
  298. }
  299. } else {
  300. $this->error(lang('param_error'));
  301. }
  302. }
  303. /**
  304. * 获取卖家栏目列表,针对控制器下的栏目
  305. */
  306. protected function getAdminItemList()
  307. {
  308. $menu_array = array(
  309. array(
  310. 'name' => 'db',
  311. 'text' => lang('data_backup'),
  312. 'url' => (string)url('Database/db')
  313. ),
  314. array(
  315. 'name' => 'restore',
  316. 'text' => lang('data_restoration'),
  317. 'url' => (string)url('Database/restore')
  318. ),
  319. );
  320. return $menu_array;
  321. }
  322. }