Db.php 12 KB

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