Database.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. * DSMall多用户商城
  18. * ============================================================================
  19. * 版权所有 2014-2028 长沙德尚网络科技有限公司,并保留所有权利。
  20. * 网站地址: http://www.csdeshang.com
  21. * ----------------------------------------------------------------------------
  22. * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
  23. * 不允许对程序代码以任何形式任何目的的再发布。
  24. * ============================================================================
  25. * 控制器
  26. */
  27. class Database extends AdminControl {
  28. public function initialize() {
  29. parent::initialize();
  30. Lang::load(base_path() . 'admin/lang/'.config('lang.default_lang').'/db.lang.php');
  31. }
  32. public function db() {
  33. $dbtable_list = Db::query('SHOW TABLE STATUS');
  34. $total = 0;
  35. foreach ($dbtable_list as $k => $v) {
  36. $dbtable_list[$k]['size'] = format_bytes($v['Data_length'] + $v['Index_length']);
  37. $total += $v['Data_length'] + $v['Index_length'];
  38. }
  39. View::assign('dbtable_list', $dbtable_list);
  40. View::assign('total', format_bytes($total));
  41. View::assign('tableNum', count($dbtable_list));
  42. $this->setAdminCurItem('db');
  43. return View::fetch();
  44. }
  45. public function export($tables = null, $id = null, $start = null) {
  46. //防止备份数据过程超时
  47. function_exists('set_time_limit') && set_time_limit(0);
  48. if (request()->isPost() && !empty($tables) && is_array($tables)) { //初始化
  49. $path = DATA_BACKUP_PATH;
  50. if (!is_dir($path)) {
  51. mkdir($path, 0755, true);
  52. }
  53. //读取备份配置
  54. $config = array(
  55. 'path' => realpath($path) . DIRECTORY_SEPARATOR,
  56. 'part' => DATA_BACKUP_PART_SIZE,
  57. 'compress' => DATA_BACKUP_COMPRESS,
  58. 'level' => DATA_BACKUP_COMPRESS_LEVEL,
  59. );
  60. //检查是否有正在执行的任务
  61. $lock = "{$config['path']}backup.lock";
  62. if (is_file($lock)) {
  63. return json(array('info' => lang('file_conflict'), 'status' => 0, 'url' => ''));
  64. } else {
  65. //创建锁文件
  66. file_put_contents($lock, TIMESTAMP);
  67. }
  68. //检查备份目录是否可写
  69. if (!is_writeable($config['path'])) {
  70. return json(array('info' => lang('file_cannot_write'), 'status' => 0, 'url' => ''));
  71. }
  72. session('backup_config', $config);
  73. //生成备份文件信息
  74. $file = array(
  75. 'name' => date('Ymd-His', $_SERVER['REQUEST_TIME']),
  76. 'part' => 1,
  77. );
  78. session('backup_file', $file);
  79. //缓存要备份的表
  80. session('backup_tables', $tables);
  81. //创建备份文件
  82. $Database = new \mall\Backup($file, $config);
  83. if (false !== $Database->create()) {
  84. $tab = array('id' => 0, 'start' => 0);
  85. return json(array('tables' => $tables, 'tab' => $tab, 'info' => lang('init_success'), 'status' => 1, 'url' => ''));
  86. } else {
  87. return json(array('info' => lang('init_error'), 'status' => 0, 'url' => ''));
  88. }
  89. } elseif (request()->isGet() && is_numeric($id) && is_numeric($start)) { //备份数据
  90. $tables = session('backup_tables');
  91. //备份指定表
  92. $Database = new \mall\Backup(session('backup_file'), session('backup_config'));
  93. $start = $Database->backup($tables[$id], $start);
  94. if (false === $start) { //出错
  95. return json(array('info' => lang('back_error'), 'status' => 0, 'url' => ''));
  96. } elseif (0 === $start) { //下一表
  97. if (isset($tables[++$id])) {
  98. $tab = array('id' => $id, 'start' => 0);
  99. return json(array('tab' => $tab, 'info' => lang('back_finish'), 'status' => 1, 'url' => ''));
  100. } else { //备份完成,清空缓存
  101. unlink(session('backup_config.path') . 'backup.lock');
  102. session('backup_tables', null);
  103. session('backup_file', null);
  104. session('backup_config', null);
  105. return json(array('info' => lang('back_finish'), 'status' => 1, 'url' => ''));
  106. }
  107. } else {
  108. $tab = array('id' => $id, 'start' => $start[0]);
  109. $rate = floor(100 * ($start[0] / $start[1]));
  110. return json(array('tab' => $tab, 'info' => lang('backup_in_progress')."...({$rate}%)", 'status' => 1, 'url' => ''));
  111. }
  112. } else {
  113. //出错
  114. return json(array('info' => lang('param_error'), 'status' => 0, 'url' => ''));
  115. }
  116. }
  117. public function restore() {
  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. function_exists('set_time_limit') && set_time_limit(0);
  163. if (is_numeric($time) && is_null($part) && is_null($start)) { //初始化
  164. //获取备份文件信息
  165. $name = date('Ymd-His', $time) . '-*.sql*';
  166. $path = realpath(DATA_BACKUP_PATH) . DIRECTORY_SEPARATOR . $name;
  167. $files = glob($path);
  168. $list = array();
  169. foreach ($files as $name) {
  170. $basename = basename($name);
  171. $match = sscanf($basename, '%4s%2s%2s-%2s%2s%2s-%d');
  172. $gz = preg_match('/^\d{8,8}-\d{6,6}-\d+\.sql.gz$/', $basename);
  173. $list[$match[6]] = array($match[6], $name, $gz);
  174. }
  175. ksort($list);
  176. //检测文件正确性
  177. $last = end($list);
  178. if (count($list) === $last[0]) {
  179. session('backup_list', $list); //缓存备份列表
  180. $this->success(lang('init_success'), NULL ,['part'=>1,'start'=>0]);
  181. } else {
  182. $this->error(lang('file_break_please_check'));
  183. }
  184. } elseif (is_numeric($part) && is_numeric($start)) {
  185. $list = session('backup_list');
  186. $db = new \mall\Backup($list[$part], array(
  187. 'path' => realpath(DATA_BACKUP_PATH) . DIRECTORY_SEPARATOR,
  188. 'compress' => $list[$part][2])
  189. );
  190. $start = $db->import($start);
  191. if (false === $start) {
  192. $this->error(lang('recover_error'));
  193. } elseif (0 === $start) { //下一卷
  194. if (isset($list[++$part])) {
  195. $data = array('part' => $part, 'start' => 0);
  196. $this->success(lang('restoring')."...#{$part}", null, $data);
  197. } else {
  198. session('backup_list', null);
  199. $this->success(lang('recover_success'));
  200. }
  201. } else {
  202. $data = array('part' => $part, 'start' => $start[0]);
  203. if ($start[1]) {
  204. $rate = floor(100 * ($start[0] / $start[1]));
  205. $this->success(lang('restoring')."...#{$part} ({$rate}%)", null, $data);
  206. } else {
  207. $data['gz'] = 1;
  208. $this->success(lang('restoring')."...#{$part}", null, $data);
  209. }
  210. }
  211. } else {
  212. $this->error(lang('param_error'));
  213. }
  214. }
  215. /**
  216. * 优化
  217. */
  218. public function optimize() {
  219. $batchFlag = intval(input('param.batchFlag'));
  220. //批量删除
  221. if ($batchFlag) {
  222. $table = input('param.key');
  223. } else {
  224. $table[] = input('param.tablename');
  225. }
  226. if (empty($table)) {
  227. $this->error(lang('please_select_repire_table'));
  228. }
  229. $strTable = implode(',', $table);
  230. if (!Db::query("OPTIMIZE TABLE {$strTable} ")) {
  231. $strTable = '';
  232. }
  233. $this->success(lang('optimization_table_succ') . $strTable, (string)url('Database/db'));
  234. }
  235. /**
  236. * 修复
  237. */
  238. public function repair() {
  239. $batchFlag = intval(input('param.batchFlag'));
  240. //批量删除
  241. if ($batchFlag) {
  242. $table = I('key', array());
  243. } else {
  244. $table[] = input('param.tablename');
  245. }
  246. if (empty($table)) {
  247. $this->error(lang('please_repire_table'));
  248. }
  249. $strTable = implode(',', $table);
  250. if (!Db::query("REPAIR TABLE {$strTable} ")) {
  251. $strTable = '';
  252. }
  253. $this->success(lang('optimization_repair_succ') . $strTable, (string)url('Database/db'));
  254. }
  255. /**
  256. * 下载
  257. * @param int $time
  258. */
  259. public function downFile($time = 0) {
  260. $name = date('Ymd-His', $time) . '-*.sql*';
  261. $path = realpath(DATA_BACKUP_PATH) . DIRECTORY_SEPARATOR . $name;
  262. $files = glob($path);
  263. if (is_array($files)) {
  264. foreach ($files as $filePath) {
  265. if (!file_exists($filePath)) {
  266. $this->error(lang('file_not_exist'));
  267. } else {
  268. $filename = basename($filePath);
  269. header("Content-type: application/octet-stream");
  270. header('Content-Disposition: attachment; filename="' . $filename . '"');
  271. header("Content-Length: " . filesize($filePath));
  272. readfile($filePath);
  273. }
  274. }
  275. }
  276. }
  277. /**
  278. * 删除备份文件
  279. * @param Integer $time 备份时间
  280. */
  281. public function del($time = 0) {
  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(lang('back_file_drop_fail'));
  288. } else {
  289. $this->success(lang('back_file_drop_success'));
  290. }
  291. } else {
  292. $this->error(lang('param_error'));
  293. }
  294. }
  295. /**
  296. * 获取卖家栏目列表,针对控制器下的栏目
  297. */
  298. protected function getAdminItemList() {
  299. $menu_array = array(
  300. array(
  301. 'name' => 'db',
  302. 'text' => lang('data_backup'),
  303. 'url' => (string)url('Database/db')
  304. ),
  305. array(
  306. 'name' => 'restore',
  307. 'text' => lang('data_restoration'),
  308. 'url' => (string)url('Database/restore')
  309. ),
  310. );
  311. return $menu_array;
  312. }
  313. }
  314. ?>