Database.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. * 版权所有 2014-2028 浙江惠利玛产业互联网有限公司,并保留所有权利。
  20. * 网站地址: https://www.valimart.net/
  21. * ----------------------------------------------------------------------------
  22. *
  23. * ============================================================================
  24. * 控制器
  25. */
  26. class Database extends AdminControl {
  27. public function initialize() {
  28. parent::initialize();
  29. Lang::load(base_path() . 'admin/lang/'.config('lang.default_lang').'/db.lang.php');
  30. }
  31. public function db() {
  32. $dbtable_list = Db::query('SHOW TABLE STATUS');
  33. $total = 0;
  34. foreach ($dbtable_list as $k => $v) {
  35. $dbtable_list[$k]['size'] = format_bytes($v['Data_length'] + $v['Index_length']);
  36. $total += $v['Data_length'] + $v['Index_length'];
  37. }
  38. View::assign('dbtable_list', $dbtable_list);
  39. View::assign('total', format_bytes($total));
  40. View::assign('tableNum', count($dbtable_list));
  41. $this->setAdminCurItem('db');
  42. return View::fetch();
  43. }
  44. public function export($tables = null, $id = null, $start = null) {
  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. $path = DATA_BACKUP_PATH;
  118. if (!is_dir($path)) {
  119. mkdir($path, 0755, true);
  120. }
  121. $path = realpath($path);
  122. $flag = \FilesystemIterator::KEY_AS_FILENAME;
  123. $glob = new \FilesystemIterator($path, $flag);
  124. $restore_list = array();
  125. $filenum = $total = 0;
  126. foreach ($glob as $name => $file) {
  127. if (preg_match('/^\d{8,8}-\d{6,6}-\d+\.sql(?:\.gz)?$/', $name)) {
  128. $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d');
  129. $date = "{$name[0]}-{$name[1]}-{$name[2]}";
  130. $time = "{$name[3]}:{$name[4]}:{$name[5]}";
  131. $part = $name[6];
  132. $info = pathinfo($file);
  133. if (isset($restore_list["{$date} {$time}"])) {
  134. $info = $restore_list["{$date} {$time}"];
  135. $info['part'] = max($info['part'], $part);
  136. $info['size'] = $info['size'] + $file->getSize();
  137. } else {
  138. $info['part'] = $part;
  139. $info['size'] = $file->getSize();
  140. }
  141. $info['compress'] = ($info['extension'] === 'sql') ? '-' : $info['extension'];
  142. $info['time'] = strtotime("{$date} {$time}");
  143. $filenum++;
  144. $total += $info['size'];
  145. $restore_list["{$date} {$time}"] = $info;
  146. }
  147. }
  148. View::assign('restore_list', $restore_list);
  149. View::assign('filenum', $filenum);
  150. View::assign('total', $total);
  151. $this->setAdminCurItem('restore');
  152. return View::fetch();
  153. }
  154. /**
  155. * 执行还原数据库操作
  156. * @param int $time
  157. * @param null $part
  158. * @param null $start
  159. */
  160. public function import($time = 0, $part = null, $start = null) {
  161. function_exists('set_time_limit') && set_time_limit(0);
  162. if (is_numeric($time) && is_null($part) && is_null($start)) { //初始化
  163. //获取备份文件信息
  164. $name = date('Ymd-His', $time) . '-*.sql*';
  165. $path = realpath(DATA_BACKUP_PATH) . DIRECTORY_SEPARATOR . $name;
  166. $files = glob($path);
  167. $list = array();
  168. foreach ($files as $name) {
  169. $basename = basename($name);
  170. $match = sscanf($basename, '%4s%2s%2s-%2s%2s%2s-%d');
  171. $gz = preg_match('/^\d{8,8}-\d{6,6}-\d+\.sql.gz$/', $basename);
  172. $list[$match[6]] = array($match[6], $name, $gz);
  173. }
  174. ksort($list);
  175. //检测文件正确性
  176. $last = end($list);
  177. if (count($list) === $last[0]) {
  178. session('backup_list', $list); //缓存备份列表
  179. $this->success(lang('init_success'), NULL ,['part'=>1,'start'=>0]);
  180. } else {
  181. $this->error(lang('file_break_please_check'));
  182. }
  183. } elseif (is_numeric($part) && is_numeric($start)) {
  184. $list = session('backup_list');
  185. $db = new \mall\Backup($list[$part], array(
  186. 'path' => realpath(DATA_BACKUP_PATH) . DIRECTORY_SEPARATOR,
  187. 'compress' => $list[$part][2])
  188. );
  189. $start = $db->import($start);
  190. if (false === $start) {
  191. $this->error(lang('recover_error'));
  192. } elseif (0 === $start) { //下一卷
  193. if (isset($list[++$part])) {
  194. $data = array('part' => $part, 'start' => 0);
  195. $this->success(lang('restoring')."...#{$part}", null, $data);
  196. } else {
  197. session('backup_list', null);
  198. $this->success(lang('recover_success'));
  199. }
  200. } else {
  201. $data = array('part' => $part, 'start' => $start[0]);
  202. if ($start[1]) {
  203. $rate = floor(100 * ($start[0] / $start[1]));
  204. $this->success(lang('restoring')."...#{$part} ({$rate}%)", null, $data);
  205. } else {
  206. $data['gz'] = 1;
  207. $this->success(lang('restoring')."...#{$part}", null, $data);
  208. }
  209. }
  210. } else {
  211. $this->error(lang('param_error'));
  212. }
  213. }
  214. /**
  215. * 优化
  216. */
  217. public function optimize() {
  218. $batchFlag = intval(input('param.batchFlag'));
  219. //批量删除
  220. if ($batchFlag) {
  221. $table = input('param.key');
  222. } else {
  223. $table[] = input('param.tablename');
  224. }
  225. if (empty($table)) {
  226. $this->error(lang('please_select_repire_table'));
  227. }
  228. $strTable = implode(',', $table);
  229. if (!Db::query("OPTIMIZE TABLE {$strTable} ")) {
  230. $strTable = '';
  231. }
  232. $this->success(lang('optimization_table_succ') . $strTable, (string)url('Database/db'));
  233. }
  234. /**
  235. * 修复
  236. */
  237. public function repair() {
  238. $batchFlag = intval(input('param.batchFlag'));
  239. //批量删除
  240. if ($batchFlag) {
  241. $table = I('key', array());
  242. } else {
  243. $table[] = input('param.tablename');
  244. }
  245. if (empty($table)) {
  246. $this->error(lang('please_repire_table'));
  247. }
  248. $strTable = implode(',', $table);
  249. if (!Db::query("REPAIR TABLE {$strTable} ")) {
  250. $strTable = '';
  251. }
  252. $this->success(lang('optimization_repair_succ') . $strTable, (string)url('Database/db'));
  253. }
  254. /**
  255. * 下载
  256. * @param int $time
  257. */
  258. public function downFile($time = 0) {
  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(lang('file_not_exist'));
  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. if ($time) {
  282. $name = date('Ymd-His', $time) . '-*.sql*';
  283. $path = realpath(DATA_BACKUP_PATH) . DIRECTORY_SEPARATOR . $name;
  284. array_map("unlink", glob($path));
  285. if (count(glob($path))) {
  286. $this->error(lang('back_file_drop_fail'));
  287. } else {
  288. $this->success(lang('back_file_drop_success'));
  289. }
  290. } else {
  291. $this->error(lang('param_error'));
  292. }
  293. }
  294. /**
  295. * 获取卖家栏目列表,针对控制器下的栏目
  296. */
  297. protected function getAdminItemList() {
  298. $menu_array = array(
  299. array(
  300. 'name' => 'db',
  301. 'text' => lang('data_backup'),
  302. 'url' => (string)url('Database/db')
  303. ),
  304. array(
  305. 'name' => 'restore',
  306. 'text' => lang('data_restoration'),
  307. 'url' => (string)url('Database/restore')
  308. ),
  309. );
  310. return $menu_array;
  311. }
  312. }
  313. ?>