Backup.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Author: tp5er <tp5er@qq.com>
  4. // | QQ Group: 368683534
  5. // +----------------------------------------------------------------------
  6. namespace app\admin\controller;
  7. use think\facade\Db;
  8. use think\facade\Config;
  9. class Backup
  10. {
  11. /**
  12. * 文件指针
  13. * @var resource
  14. */
  15. private $fp;
  16. /**
  17. * 备份文件信息 part - 卷号,name - 文件名
  18. * @var array
  19. */
  20. private $file;
  21. /**
  22. * 当前打开文件大小
  23. * @var integer
  24. */
  25. private $size = 0;
  26. /**
  27. * 数据库配置
  28. * @var integer
  29. */
  30. private $dbconfig = array();
  31. /**
  32. * 备份配置
  33. * @var integer
  34. */
  35. private $config = array(
  36. 'path' => './Data/',
  37. //数据库备份路径
  38. 'part' => 20971520,
  39. //数据库备份卷大小
  40. 'compress' => 0,
  41. //数据库备份文件是否启用压缩 0不压缩 1 压缩
  42. 'level' => 9,
  43. );
  44. /**
  45. * 数据库备份构造方法
  46. * @param array $file 备份或还原的文件信息
  47. * @param array $config 备份配置信息
  48. */
  49. public function __construct($config = [])
  50. {
  51. $this->config = array_merge($this->config, $config);
  52. //初始化文件名
  53. $this->setFile();
  54. //初始化数据库连接参数
  55. $this->setDbConn();
  56. //检查文件是否可写
  57. if (!$this->checkPath($this->config['path'])) {
  58. throw new \Exception("The current directory is not writable");
  59. }
  60. }
  61. /**
  62. * 设置脚本运行超时时间
  63. * 0表示不限制,支持连贯操作
  64. */
  65. public function setTimeout($time=null)
  66. {
  67. if (!is_null($time)) {
  68. set_time_limit($time)||ini_set("max_execution_time", $time);
  69. }
  70. return $this;
  71. }
  72. /**
  73. * 设置数据库连接必备参数
  74. * @param array $dbconfig 数据库连接配置信息
  75. * @return object
  76. */
  77. public function setDbConn($dbconfig = [])
  78. {
  79. if (empty($dbconfig)) {
  80. $this->dbconfig = config('database');
  81. //$this->dbconfig = Config::get('database');
  82. } else {
  83. $this->dbconfig = $dbconfig;
  84. }
  85. return $this;
  86. }
  87. /**
  88. * 设置备份文件名
  89. * @param Array $file 文件名字
  90. * @return object
  91. */
  92. public function setFile($file = null)
  93. {
  94. if (is_null($file)) {
  95. $this->file = ['name' => date('Ymd-His'), 'part' => 1];
  96. } else {
  97. if (!array_key_exists("name", $file) && !array_key_exists("part", $file)) {
  98. $this->file = $file['1'];
  99. } else {
  100. $this->file = $file;
  101. }
  102. }
  103. return $this;
  104. }
  105. //数据类连接
  106. public static function connect()
  107. {
  108. return \think\facade\Db::connect();
  109. }
  110. //数据库表列表
  111. public function dataList($table = null,$type=1)
  112. {
  113. $db = self::connect();
  114. if (is_null($table)) {
  115. $list = $db->query("SHOW TABLE STATUS");
  116. } else {
  117. if ($type) {
  118. $list = $db->query("SHOW FULL COLUMNS FROM {$table}");
  119. }else{
  120. $list = $db->query("show columns from {$table}");
  121. }
  122. }
  123. return array_map('array_change_key_case', $list);
  124. //$list;
  125. }
  126. //数据库备份文件列表
  127. public function fileList()
  128. {
  129. if (!is_dir($this->config['path'])) {
  130. mkdir($this->config['path'], 0755, true);
  131. }
  132. $path = realpath($this->config['path']);
  133. $flag = \FilesystemIterator::KEY_AS_FILENAME;
  134. $glob = new \FilesystemIterator($path, $flag);
  135. $list = array();
  136. foreach ($glob as $name => $file) {
  137. if (preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql(?:\\.gz)?$/', $name)) {
  138. $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d');
  139. $date = "{$name[0]}-{$name[1]}-{$name[2]}";
  140. $time = "{$name[3]}:{$name[4]}:{$name[5]}";
  141. $part = $name[6];
  142. if (isset($list["{$date} {$time}"])) {
  143. $info = $list["{$date} {$time}"];
  144. $info['part'] = max($info['part'], $part);
  145. $info['size'] = $info['size'] + $file->getSize();
  146. } else {
  147. $info['part'] = $part;
  148. $info['size'] = $file->getSize();
  149. }
  150. $extension = strtoupper(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
  151. $info['compress'] = $extension === 'SQL' ? '-' : $extension;
  152. $info['name'] = $file->getFilename();
  153. $info['time'] = strtotime("{$date} {$time}");
  154. $list["{$date} {$time}"] = $info;
  155. }
  156. }
  157. return $list;
  158. }
  159. public function getFile($type = '', $time = 0)
  160. {
  161. //
  162. if (!is_numeric($time)) {
  163. throw new \Exception("{$time} Illegal data type");
  164. }
  165. switch ($type) {
  166. case 'time':
  167. $name = date('Ymd-His', $time) . '-*.sql*';
  168. $path = realpath($this->config['path']) . DIRECTORY_SEPARATOR . $name;
  169. return glob($path);
  170. break;
  171. case 'timeverif':
  172. $name = date('Ymd-His', $time) . '-*.sql*';
  173. $path = realpath($this->config['path']) . DIRECTORY_SEPARATOR . $name;
  174. $files = glob($path);
  175. $list = array();
  176. foreach ($files as $name) {
  177. $basename = basename($name);
  178. $match = sscanf($basename, '%4s%2s%2s-%2s%2s%2s-%d');
  179. $gz = preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql.gz$/', $basename);
  180. $list[$match[6]] = array($match[6], $name, $gz);
  181. }
  182. $last = end($list);
  183. if (count($list) === $last[0]) {
  184. return $list;
  185. } else {
  186. throw new \Exception("File {$files['0']} may be damaged, please check again");
  187. }
  188. break;
  189. case 'pathname':
  190. return "{$this->config['path']}{$this->file['name']}-{$this->file['part']}.sql";
  191. break;
  192. case 'filename':
  193. return "{$this->file['name']}-{$this->file['part']}.sql";
  194. break;
  195. case 'filepath':
  196. return $this->config['path'];
  197. break;
  198. default:
  199. $arr = array('pathname' => "{$this->config['path']}{$this->file['name']}-{$this->file['part']}.sql", 'filename' => "{$this->file['name']}-{$this->file['part']}.sql", 'filepath' => $this->config['path'], 'file' => $this->file);
  200. return $arr;
  201. }
  202. }
  203. //删除备份文件
  204. public function delFile($time)
  205. {
  206. if ($time) {
  207. $file = $this->getFile('time', $time);
  208. array_map("unlink", $this->getFile('time', $time));
  209. if (count($this->getFile('time', $time))) {
  210. throw new \Exception("File {$path} deleted failed");
  211. } else {
  212. return $time;
  213. }
  214. } else {
  215. throw new \Exception("{$time} Time parameter is incorrect");
  216. }
  217. }
  218. /**
  219. * 下载备份
  220. * @Author: 浪哥 <939881475@qq.com>
  221. * @param string $time
  222. * @param integer $part
  223. * @return array|mixed|string
  224. */
  225. public function downloadFile($time, $part = 0)
  226. {
  227. $file = $this->getFile('time', $time);
  228. $fileName = $file[$part];
  229. if (file_exists($fileName)) {
  230. ob_end_clean();
  231. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  232. header('Content-Description: File Transfer');
  233. header('Content-Type: application/octet-stream');
  234. header('Content-Length: ' . filesize($fileName));
  235. header('Content-Disposition: attachment; filename=' . basename($fileName));
  236. readfile($fileName);
  237. } else {
  238. throw new \Exception("{$time} File is abnormal");
  239. }
  240. }
  241. public function import($start)
  242. {
  243. //还原数据
  244. $db = self::connect();
  245. if ($this->config['compress']) {
  246. $gz = gzopen($this->file[1], 'r');
  247. $size = 0;
  248. } else {
  249. $size = filesize($this->file[1]);
  250. $gz = fopen($this->file[1], 'r');
  251. }
  252. $sql = '';
  253. if ($start) {
  254. $this->config['compress'] ? gzseek($gz, $start) : fseek($gz, $start);
  255. }
  256. for ($i = 0; $i < 1000; $i++) {
  257. $sql .= $this->config['compress'] ? gzgets($gz) : fgets($gz);
  258. if (preg_match('/.*;$/', trim($sql))) {
  259. if (false !== $db->execute($sql)) {
  260. $start += strlen($sql);
  261. } else {
  262. return false;
  263. }
  264. $sql = '';
  265. } elseif ($this->config['compress'] ? gzeof($gz) : feof($gz)) {
  266. return 0;
  267. }
  268. }
  269. return array($start, $size);
  270. }
  271. /**
  272. * 写入初始数据
  273. * @return boolean true - 写入成功,false - 写入失败
  274. */
  275. public function Backup_Init()
  276. {
  277. $sql = "-- -----------------------------\n";
  278. $sql .= "-- Think MySQL Data Transfer \n";
  279. $sql .= "-- \n";
  280. $sql .= "-- Host : " . $this->dbconfig['hostname'] . "\n";
  281. $sql .= "-- Port : " . $this->dbconfig['hostport'] . "\n";
  282. $sql .= "-- Database : " . $this->dbconfig['database'] . "\n";
  283. $sql .= "-- \n";
  284. $sql .= "-- Part : #{$this->file['part']}\n";
  285. $sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n";
  286. $sql .= "-- -----------------------------\n\n";
  287. $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
  288. return $this->write($sql);
  289. }
  290. /**
  291. * 备份表结构
  292. * @param string $table 表名
  293. * @param integer $start 起始行数
  294. * @return boolean false - 备份失败
  295. */
  296. public function backup($table, $start)
  297. {
  298. $db = self::connect();
  299. // 备份表结构
  300. if (0 == $start) {
  301. $result = $db->query("SHOW CREATE TABLE `{$table}`");
  302. $sql = "\n";
  303. $sql .= "-- -----------------------------\n";
  304. $sql .= "-- Table structure for `{$table}`\n";
  305. $sql .= "-- -----------------------------\n";
  306. $sql .= "DROP TABLE IF EXISTS `{$table}`;\n";
  307. $sql .= trim($result[0]['Create Table']) . ";\n\n";
  308. if (false === $this->write($sql)) {
  309. return false;
  310. }
  311. }
  312. //数据总数
  313. $result = $db->query("SELECT COUNT(*) AS count FROM `{$table}`");
  314. $count = $result['0']['count'];
  315. //备份表数据
  316. if ($count) {
  317. //写入数据注释
  318. if (0 == $start) {
  319. $sql = "-- -----------------------------\n";
  320. $sql .= "-- Records of `{$table}`\n";
  321. $sql .= "-- -----------------------------\n";
  322. $this->write($sql);
  323. }
  324. //备份数据记录
  325. $result = $db->query("SELECT * FROM `{$table}` LIMIT {$start}, 1000");
  326. foreach ($result as $row) {
  327. $row = array_map('addslashes', $row);
  328. $sql = "INSERT INTO `{$table}` VALUES ('" . str_replace(array("\r", "\n"), array('\\r', '\\n'), implode("', '", $row)) . "');\n";
  329. if (false === $this->write($sql)) {
  330. return false;
  331. }
  332. }
  333. //还有更多数据
  334. if ($count > $start + 1000) {
  335. //return array($start + 1000, $count);
  336. return $this->backup($table, $start + 1000);
  337. }
  338. }
  339. //备份下一表
  340. return 0;
  341. }
  342. /**
  343. * 优化表
  344. * @param String $tables 表名
  345. * @return String $tables
  346. */
  347. public function optimize($tables = null)
  348. {
  349. if ($tables) {
  350. $db = self::connect();
  351. if (is_array($tables)) {
  352. $tables = implode('`,`', $tables);
  353. $list = $db->query("OPTIMIZE TABLE `{$tables}`");
  354. } else {
  355. $list = $db->query("OPTIMIZE TABLE `{$tables}`");
  356. }
  357. if ($list) {
  358. return $tables;
  359. } else {
  360. throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!");
  361. }
  362. } else {
  363. throw new \Exception("Please specify the table to be repaired!");
  364. }
  365. }
  366. /**
  367. * 修复表
  368. * @param String $tables 表名
  369. * @return String $tables
  370. */
  371. public function repair($tables = null)
  372. {
  373. if ($tables) {
  374. $db = self::connect();
  375. if (is_array($tables)) {
  376. $tables = implode('`,`', $tables);
  377. $list = $db->query("REPAIR TABLE `{$tables}`");
  378. } else {
  379. $list = $db->query("REPAIR TABLE `{$tables}`");
  380. }
  381. if ($list) {
  382. return $list;
  383. } else {
  384. throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!");
  385. }
  386. } else {
  387. throw new \Exception("Please specify the table to be repaired!");
  388. }
  389. }
  390. /**
  391. * 写入SQL语句
  392. * @param string $sql 要写入的SQL语句
  393. * @return boolean true - 写入成功,false - 写入失败!
  394. */
  395. private function write($sql)
  396. {
  397. $size = strlen($sql);
  398. //由于压缩原因,无法计算出压缩后的长度,这里假设压缩率为50%,
  399. //一般情况压缩率都会高于50%;
  400. $size = $this->config['compress'] ? $size / 2 : $size;
  401. $this->open($size);
  402. return $this->config['compress'] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql);
  403. }
  404. /**
  405. * 打开一个卷,用于写入数据
  406. * @param integer $size 写入数据的大小
  407. */
  408. private function open($size)
  409. {
  410. if ($this->fp) {
  411. $this->size += $size;
  412. if ($this->size > $this->config['part']) {
  413. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  414. $this->fp = null;
  415. $this->file['part']++;
  416. session('backup_file', $this->file);
  417. $this->Backup_Init();
  418. }
  419. } else {
  420. $backuppath = $this->config['path'];
  421. $filename = "{$backuppath}{$this->file['name']}-{$this->file['part']}.sql";
  422. if ($this->config['compress']) {
  423. $filename = "{$filename}.gz";
  424. $this->fp = @gzopen($filename, "a{$this->config['level']}");
  425. } else {
  426. $this->fp = @fopen($filename, 'a');
  427. }
  428. $this->size = filesize($filename) + $size;
  429. }
  430. }
  431. /**
  432. * 检查目录是否可写
  433. * @param string $path 目录
  434. * @return boolean
  435. */
  436. protected function checkPath($path)
  437. {
  438. if (is_dir($path)) {
  439. return true;
  440. }
  441. if (mkdir($path, 0755, true)) {
  442. return true;
  443. } else {
  444. return false;
  445. }
  446. }
  447. /**
  448. * 析构方法,用于关闭文件资源
  449. */
  450. public function __destruct()
  451. {
  452. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  453. }
  454. }