Backup.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Author: tp5er <tp5er@qq.com>
  4. // | QQ Group: 368683534
  5. // +----------------------------------------------------------------------
  6. namespace tp5er;
  7. use think\Db;
  8. use think\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 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. $info['filename'] = $name;
  138. if (preg_match('/^\\d{8,8}-\\d{6,6}-\\d+\\.sql(?:\\.gz)?$/', $name)) {
  139. $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d');
  140. $date = "{$name[0]}-{$name[1]}-{$name[2]}";
  141. $time = "{$name[3]}:{$name[4]}:{$name[5]}";
  142. $part = $name[6];
  143. if (isset($list["{$date} {$time}"])) {
  144. $info = $list["{$date} {$time}"];
  145. $info['part'] = max($info['part'], $part);
  146. $info['size'] = $info['size'] + $file->getSize();
  147. } else {
  148. $info['part'] = $part;
  149. $info['size'] = $file->getSize();
  150. }
  151. $extension = strtoupper(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
  152. $info['compress'] = $extension === 'SQL' ? '-' : $extension;
  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. ksort($list);
  183. $last = end($list);
  184. if (count($list) === $last[0]) {
  185. return $list;
  186. } else {
  187. throw new \Exception("File {$files['0']} may be damaged, please check again");
  188. }
  189. break;
  190. case 'pathname':
  191. return "{$this->config['path']}{$this->file['name']}-{$this->file['part']}.sql";
  192. break;
  193. case 'filename':
  194. return "{$this->file['name']}-{$this->file['part']}.sql";
  195. break;
  196. case 'filepath':
  197. return $this->config['path'];
  198. break;
  199. default:
  200. $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);
  201. return $arr;
  202. }
  203. }
  204. //删除备份文件
  205. public function delFile($time)
  206. {
  207. if ($time) {
  208. $file = $this->getFile('time', $time);
  209. array_map("unlink", $this->getFile('time', $time));
  210. if (count($this->getFile('time', $time))) {
  211. throw new \Exception("File {$path} deleted failed");
  212. } else {
  213. return $time;
  214. }
  215. } else {
  216. throw new \Exception("{$time} Time parameter is incorrect");
  217. }
  218. }
  219. /**
  220. * 下载备份
  221. * @Author: 浪哥 <939881475@qq.com>
  222. * @param string $time
  223. * @param integer $part
  224. * @return array|mixed|string
  225. */
  226. public function downloadFile($time, $part = 0)
  227. {
  228. $file = $this->getFile('time', $time);
  229. $fileName = $file[$part];
  230. if (file_exists($fileName)) {
  231. ob_end_clean();
  232. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  233. header('Content-Description: File Transfer');
  234. header('Content-Type: application/octet-stream');
  235. header('Content-Length: ' . filesize($fileName));
  236. header('Content-Disposition: attachment; filename=' . basename($fileName));
  237. readfile($fileName);
  238. } else {
  239. throw new \Exception("{$time} File is abnormal");
  240. }
  241. }
  242. public function import($start)
  243. {
  244. //还原数据
  245. $db = self::connect();
  246. if ($this->config['compress']) {
  247. $gz = gzopen($this->file[1], 'r');
  248. $size = 0;
  249. } else {
  250. $size = filesize($this->file[1]);
  251. $gz = fopen($this->file[1], 'r');
  252. }
  253. $sql = '';
  254. if ($start) {
  255. $this->config['compress'] ? gzseek($gz, $start) : fseek($gz, $start);
  256. }
  257. for ($i = 0; $i < 1000; $i++) {
  258. $sql .= $this->config['compress'] ? gzgets($gz) : fgets($gz);
  259. if (preg_match('/.*;$/', trim($sql))) {
  260. if (false !== $db->execute($sql)) {
  261. $start += strlen($sql);
  262. } else {
  263. return false;
  264. }
  265. $sql = '';
  266. } elseif ($this->config['compress'] ? gzeof($gz) : feof($gz)) {
  267. return 0;
  268. }
  269. }
  270. return array($start, $size);
  271. }
  272. /**
  273. * 写入初始数据
  274. * @return boolean true - 写入成功,false - 写入失败
  275. */
  276. public function Backup_Init()
  277. {
  278. $sql = "-- -----------------------------\n";
  279. $sql .= "-- Think MySQL Data Transfer \n";
  280. $sql .= "-- \n";
  281. $sql .= "-- Host : " . $this->dbconfig['hostname'] . "\n";
  282. $sql .= "-- Port : " . $this->dbconfig['hostport'] . "\n";
  283. $sql .= "-- Database : " . $this->dbconfig['database'] . "\n";
  284. $sql .= "-- \n";
  285. $sql .= "-- Part : #{$this->file['part']}\n";
  286. $sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n";
  287. $sql .= "-- -----------------------------\n\n";
  288. $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
  289. return $this->write($sql);
  290. }
  291. /**
  292. * 备份表结构
  293. * @param string $table 表名
  294. * @param integer $start 起始行数
  295. * @return boolean false - 备份失败
  296. */
  297. public function backup($table, $start)
  298. {
  299. $db = self::connect();
  300. // 备份表结构
  301. if (0 == $start) {
  302. $result = $db->query("SHOW CREATE TABLE `{$table}`");
  303. $sql = "\n";
  304. $sql .= "-- -----------------------------\n";
  305. $sql .= "-- Table structure for `{$table}`\n";
  306. $sql .= "-- -----------------------------\n";
  307. $sql .= "DROP TABLE IF EXISTS `{$table}`;\n";
  308. $sql .= trim($result[0]['Create Table']) . ";\n\n";
  309. if (false === $this->write($sql)) {
  310. return false;
  311. }
  312. }
  313. //数据总数
  314. $result = $db->query("SELECT COUNT(*) AS count FROM `{$table}`");
  315. $count = $result['0']['count'];
  316. //备份表数据
  317. if ($count) {
  318. //写入数据注释
  319. if (0 == $start) {
  320. $sql = "-- -----------------------------\n";
  321. $sql .= "-- Records of `{$table}`\n";
  322. $sql .= "-- -----------------------------\n";
  323. $this->write($sql);
  324. }
  325. //备份数据记录
  326. $result = $db->query("SELECT * FROM `{$table}` LIMIT {$start}, 1000");
  327. foreach ($result as $row) {
  328. $row = array_map('addslashes', $row);
  329. $sql = "INSERT INTO `{$table}` VALUES ('" . str_replace(array("\r", "\n"), array('\\r', '\\n'), implode("', '", $row)) . "');\n";
  330. if (false === $this->write($sql)) {
  331. return false;
  332. }
  333. }
  334. //还有更多数据
  335. if ($count > $start + 1000) {
  336. //return array($start + 1000, $count);
  337. return $this->backup($table, $start + 1000);
  338. }
  339. }
  340. //备份下一表
  341. return 0;
  342. }
  343. /**
  344. * 优化表
  345. * @param String $tables 表名
  346. * @return String $tables
  347. */
  348. public function optimize($tables = null)
  349. {
  350. if ($tables) {
  351. $db = self::connect();
  352. if (is_array($tables)) {
  353. $tables = implode('`,`', $tables);
  354. $list = $db->query("OPTIMIZE TABLE `{$tables}`");
  355. } else {
  356. $list = $db->query("OPTIMIZE TABLE `{$tables}`");
  357. }
  358. if ($list) {
  359. return $tables;
  360. } else {
  361. throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!");
  362. }
  363. } else {
  364. throw new \Exception("Please specify the table to be repaired!");
  365. }
  366. }
  367. /**
  368. * 修复表
  369. * @param String $tables 表名
  370. * @return String $tables
  371. */
  372. public function repair($tables = null)
  373. {
  374. if ($tables) {
  375. $db = self::connect();
  376. if (is_array($tables)) {
  377. $tables = implode('`,`', $tables);
  378. $list = $db->query("REPAIR TABLE `{$tables}`");
  379. } else {
  380. $list = $db->query("REPAIR TABLE `{$tables}`");
  381. }
  382. if ($list) {
  383. return $list;
  384. } else {
  385. throw new \Exception("data sheet'{$tables}'Repair mistakes please try again!");
  386. }
  387. } else {
  388. throw new \Exception("Please specify the table to be repaired!");
  389. }
  390. }
  391. /**
  392. * 写入SQL语句
  393. * @param string $sql 要写入的SQL语句
  394. * @return boolean true - 写入成功,false - 写入失败!
  395. */
  396. private function write($sql)
  397. {
  398. $size = strlen($sql);
  399. //由于压缩原因,无法计算出压缩后的长度,这里假设压缩率为50%,
  400. //一般情况压缩率都会高于50%;
  401. $size = $this->config['compress'] ? $size / 2 : $size;
  402. $this->open($size);
  403. return $this->config['compress'] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql);
  404. }
  405. /**
  406. * 打开一个卷,用于写入数据
  407. * @param integer $size 写入数据的大小
  408. */
  409. private function open($size)
  410. {
  411. if ($this->fp) {
  412. $this->size += $size;
  413. if ($this->size > $this->config['part']) {
  414. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  415. $this->fp = null;
  416. $this->file['part']++;
  417. session('backup_file', $this->file);
  418. $this->Backup_Init();
  419. }
  420. } else {
  421. $backuppath = $this->config['path'];
  422. $filename = "{$backuppath}{$this->file['name']}-{$this->file['part']}.sql";
  423. if ($this->config['compress']) {
  424. $filename = "{$filename}.gz";
  425. $this->fp = @gzopen($filename, "a{$this->config['level']}");
  426. } else {
  427. $this->fp = @fopen($filename, 'a');
  428. }
  429. $this->size = filesize($filename) + $size;
  430. }
  431. }
  432. /**
  433. * 检查目录是否可写
  434. * @param string $path 目录
  435. * @return boolean
  436. */
  437. protected function checkPath($path)
  438. {
  439. if (is_dir($path)) {
  440. return true;
  441. }
  442. if (mkdir($path, 0755, true)) {
  443. return true;
  444. } else {
  445. return false;
  446. }
  447. }
  448. /**
  449. * 析构方法,用于关闭文件资源
  450. */
  451. public function __destruct()
  452. {
  453. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  454. }
  455. }