Backup.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. $sql = "INSERT INTO `{$table}` VALUES ('" . str_replace(array("\r", "\n"), array('\\r', '\\n'), implode("', '", $row)) . "');\n";
  323. if (false === $this->write($sql)) {
  324. return false;
  325. }
  326. }
  327. //还有更多数据
  328. if ($count > $start + 1000) {
  329. return $this->backup($table, $start + 1000);
  330. }
  331. }
  332. //备份下一表
  333. return 0;
  334. }
  335. /**
  336. * 优化表
  337. * @param String $tables 表名
  338. * @return String $tables
  339. */
  340. public function optimize($tables = null)
  341. {
  342. if ($tables) {
  343. $db = self::connect();
  344. if (is_array($tables)) {
  345. $tables = implode('`,`', $tables);
  346. $list = $db->query("OPTIMIZE TABLE `{$tables}`");
  347. } else {
  348. $list = $db->query("OPTIMIZE TABLE `{$tables}`");
  349. }
  350. if ($list) {
  351. return $tables;
  352. } else {
  353. throw new \think\Exception("data sheet'{$tables}'Repair mistakes please try again!");
  354. }
  355. } else {
  356. throw new \think\Exception("Please specify the table to be repaired!");
  357. }
  358. }
  359. /**
  360. * 修复表
  361. * @param String $tables 表名
  362. * @return String $tables
  363. */
  364. public function repair($tables = null)
  365. {
  366. if ($tables) {
  367. $db = self::connect();
  368. if (is_array($tables)) {
  369. $tables = implode('`,`', $tables);
  370. $list = $db->query("REPAIR TABLE `{$tables}`");
  371. } else {
  372. $list = $db->query("REPAIR TABLE `{$tables}`");
  373. }
  374. if ($list) {
  375. return $list;
  376. } else {
  377. throw new \think\Exception("data sheet'{$tables}'Repair mistakes please try again!");
  378. }
  379. } else {
  380. throw new \think\Exception("Please specify the table to be repaired!");
  381. }
  382. }
  383. /**
  384. * 写入SQL语句
  385. * @param string $sql 要写入的SQL语句
  386. * @return boolean true - 写入成功,false - 写入失败!
  387. */
  388. private function write($sql)
  389. {
  390. $size = strlen($sql);
  391. //由于压缩原因,无法计算出压缩后的长度,这里假设压缩率为50%,
  392. //一般情况压缩率都会高于50%;
  393. $size = $this->config['compress'] ? $size / 2 : $size;
  394. $this->open($size);
  395. return $this->config['compress'] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql);
  396. }
  397. /**
  398. * 打开一个卷,用于写入数据
  399. * @param integer $size 写入数据的大小
  400. */
  401. private function open($size)
  402. {
  403. if ($this->fp) {
  404. $this->size += $size;
  405. if ($this->size > $this->config['part']) {
  406. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  407. $this->fp = null;
  408. $this->file['part']++;
  409. session('backup_file', $this->file);
  410. $this->Backup_Init();
  411. }
  412. } else {
  413. $backuppath = $this->config['path'];
  414. $filename = "{$backuppath}{$this->file['name']}-{$this->file['part']}.sql";
  415. if ($this->config['compress']) {
  416. $filename = "{$filename}.gz";
  417. $this->fp = @gzopen($filename, "a{$this->config['level']}");
  418. } else {
  419. $this->fp = @fopen($filename, 'a');
  420. }
  421. $this->size = filesize($filename) + $size;
  422. }
  423. }
  424. /**
  425. * 检查目录是否可写
  426. * @param string $path 目录
  427. * @return boolean
  428. */
  429. protected function checkPath($path)
  430. {
  431. if (is_dir($path)) {
  432. return true;
  433. }
  434. if (mkdir($path, 0755, true)) {
  435. return true;
  436. } else {
  437. return false;
  438. }
  439. }
  440. /**
  441. * 析构方法,用于关闭文件资源
  442. */
  443. public function __destruct()
  444. {
  445. if($this->fp){
  446. $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
  447. }
  448. }
  449. //判断某数据表是否存在
  450. public function check_table($table){
  451. $prefix = config('database.connections.mysql.prefix');
  452. $db = self::connect();
  453. $res = $db->query('SHOW TABLES LIKE '."'".$prefix.$table."'");
  454. if($res){
  455. return 1;
  456. }else{
  457. return 0;
  458. }
  459. }
  460. //判断某数据表中某字段是否存在
  461. public function check_column($table,$column){
  462. $prefix = config('database.mysql.prefix');
  463. $db = self::connect();
  464. $res = $db->query('select count(*) from information_schema.columns where table_name = '."'".$table."' ". 'and column_name ='."'".$column."'");
  465. if($res[0]['count(*)'] != 0){
  466. return 1;
  467. }else{
  468. return 0;
  469. }
  470. }
  471. //添加字段
  472. public function add_column($table,$column,$type,$condition,$after){
  473. $db = self::connect();
  474. $res = $db->execute('alter table'." `".$table."` ".'add'." `".$column."` ".$type." ".$condition." ".'after'." `".$after."`");
  475. if($res){
  476. return 1;
  477. }else{
  478. return 0;
  479. }
  480. }
  481. //删除字段
  482. public function del_column($table,$column){
  483. $db = self::connect();
  484. $res = $db->execute('alter table '."`".$table."`".' drop column'."`".$column."`");
  485. if($res){
  486. return 1;
  487. }else{
  488. return 0;
  489. }
  490. }
  491. //修改字段
  492. public function update_column($table,$old_column,$column,$type){
  493. //字段名和类型同时修改才会返回1不然返回0
  494. $db = self::connect();
  495. $res = $db->execute('alter table' ." `".$table."` ". 'change' ." `".$old_column."` " ."`".$column."`" .$type);
  496. if($res){
  497. return 1;
  498. }else{
  499. return 0;
  500. }
  501. }
  502. //执行sql
  503. public function run_sql($sql){
  504. $prefix = config('database.connections.mysql.prefix');
  505. $db = self::connect();
  506. $sql_array = preg_split("/;[\r\n]+/", str_replace("oa_", $prefix, $sql));
  507. foreach ($sql_array as $k => $v) {
  508. if (!empty($v)) {
  509. try {
  510. $res = $db->query($v);
  511. } catch (\Exception $e) {
  512. return 0;
  513. break;
  514. }
  515. }
  516. }
  517. return 1;
  518. }
  519. }