Backup.php 15 KB

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