'./Data/', 'part' => 20971520, 'compress' => 0, 'level' => 9, ]; public function __construct(array $config = []) { $this->config = array_merge($this->config, $config); $this->setFile(); $this->setDbConn(); if (!$this->checkPath($this->config['path'])) { throw new RuntimeException('The current directory is not writable'); } } public function setDbConn(array $dbconfig = []): self { if ($dbconfig === []) { $dbconfig = Config::get('database'); $this->dbconfig = $dbconfig['connections'][$dbconfig['default']]; } else { $this->dbconfig = $dbconfig; } return $this; } public function setFile(?array $file = null): self { if ($file === null) { $this->file = ['name' => date('Ymd-His'), 'part' => 1]; } elseif (!array_key_exists('name', $file) && !array_key_exists('part', $file)) { $this->file = $file[1]; } else { $this->file = $file; } return $this; } private static function connect() { return Db::connect(); } public function fileList(): array { $path = $this->absoluteBackupPath(); $list = []; foreach (new \FilesystemIterator($path, \FilesystemIterator::KEY_AS_FILENAME) as $name => $backupFile) { if (!preg_match('/^\d{8}-\d{6}-\d+\.sql(?:\.gz)?$/', $name)) { continue; } $parts = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d'); $key = "{$parts[0]}-{$parts[1]}-{$parts[2]} {$parts[3]}:{$parts[4]}:{$parts[5]}"; $info = $list[$key] ?? ['part' => 0, 'size' => 0]; $info['part'] = max($info['part'], $parts[6]); $info['size'] += $backupFile->getSize(); $info['compress'] = strtoupper(pathinfo($backupFile->getFilename(), PATHINFO_EXTENSION)) === 'SQL' ? '-' : 'GZ'; $info['time'] = strtotime($key); $list[$key] = $info; } return $list; } public function getFile(string $type = '', int $time = 0) { if (in_array($type, ['time', 'timeverif'], true) && $time <= 0) { throw new RuntimeException('Time parameter is incorrect'); } if ($type === 'time' || $type === 'timeverif') { $files = glob($this->absoluteBackupPath() . DIRECTORY_SEPARATOR . date('Ymd-His', $time) . '-*.sql*') ?: []; if ($type === 'time') { return $files; } $list = []; foreach ($files as $filename) { $parts = sscanf(basename($filename), '%4s%2s%2s-%2s%2s%2s-%d'); $list[$parts[6]] = [$parts[6], $filename, str_ends_with($filename, '.gz') ? 1 : 0]; } ksort($list); $last = end($list); if ($last === false || count($list) !== $last[0]) { throw new RuntimeException('Backup file may be damaged, please check again'); } return $list; } $pathname = $this->backupFilename(); return match ($type) { 'pathname' => $pathname, 'filename' => basename($pathname), 'filepath' => $this->config['path'], default => ['pathname' => $pathname, 'filename' => basename($pathname), 'filepath' => $this->config['path'], 'file' => $this->file], }; } public function delFile(int $time): int { $files = $this->getFile('time', $time); if ($files === []) { throw new RuntimeException('Backup file does not exist'); } foreach ($files as $file) { if (!unlink($file)) { throw new RuntimeException("Unable to delete backup file: {$file}"); } } return $time; } public function import(int $start) { $compressed = (bool) $this->config['compress']; $filename = $this->file[1]; $handle = $compressed ? gzopen($filename, 'rb') : fopen($filename, 'rb'); if ($handle === false) { return false; } $size = $compressed ? 0 : filesize($filename); if ($start > 0) { $compressed ? gzseek($handle, $start) : fseek($handle, $start); } try { $sql = ''; for ($i = 0; $i < 1000; $i++) { $line = $compressed ? gzgets($handle) : fgets($handle); if ($line === false) { return 0; } $sql .= $line; if (preg_match('/.*;$/', trim($sql))) { if (self::connect()->execute($sql) === false) { return false; } $start += strlen($sql); $sql = ''; } } return [$start, $size]; } finally { $compressed ? gzclose($handle) : fclose($handle); } } public function dataList(?string $table = null): array { $db = self::connect(); $rows = $table === null ? $db->query('SHOW TABLE STATUS') : $db->query("SHOW COLUMNS FROM `{$table}`"); return array_map('array_change_key_case', $rows); } public function Backup_Init(): bool { $sql = "-- -----------------------------\n-- Think MySQL Data Transfer\n-- \n"; $sql .= "-- Host : {$this->dbconfig['hostname']}\n-- Port : {$this->dbconfig['hostport']}\n-- Database : {$this->dbconfig['database']}\n-- \n"; $sql .= "-- Part : #{$this->file['part']}\n-- Date : " . date('Y-m-d H:i:s') . "\n-- -----------------------------\n\nSET FOREIGN_KEY_CHECKS = 0;\n\n"; return $this->write($sql); } public function backup(string $table, int $start) { $db = self::connect(); if ($start === 0) { $result = $db->query("SHOW CREATE TABLE `{$table}`"); $sql = "\n-- -----------------------------\n-- Table structure for `{$table}`\n-- -----------------------------\nDROP TABLE IF EXISTS `{$table}`;\n"; $sql .= trim($result[0]['Create Table']) . ";\n\n"; if (!$this->write($sql)) { return false; } } $count = (int) $db->query("SELECT COUNT(*) AS count FROM `{$table}`")[0]['count']; if ($count === 0) { return 0; } if ($start === 0 && !$this->write("-- -----------------------------\n-- Records of `{$table}`\n-- -----------------------------\n")) { return false; } foreach ($db->query("SELECT * FROM `{$table}` LIMIT {$start}, 1000") as $row) { $values = array_map(static fn ($value) => addslashes((string) $value), $row); $values = str_replace(["''", "\n"], ['null', '\\n'], "'" . implode("', '", $values) . "'"); if (!$this->write("INSERT INTO `{$table}` VALUES ({$values});\n")) { return false; } } return $count > $start + 1000 ? [$start + 1000, $count] : 0; } private function write(string $sql): bool { $this->open((int) (strlen($sql) / ($this->config['compress'] ? 2 : 1))); return $this->config['compress'] ? gzwrite($this->fp, $sql) !== false : fwrite($this->fp, $sql) !== false; } private function open(int $size): void { if ($this->fp !== null && $this->size + $size > $this->config['part']) { $this->config['compress'] ? gzclose($this->fp) : fclose($this->fp); $this->fp = null; $this->file['part']++; session('backup_file', $this->file); } if ($this->fp === null) { $filename = $this->backupFilename() . ($this->config['compress'] ? '.gz' : ''); $this->fp = $this->config['compress'] ? gzopen($filename, "ab{$this->config['level']}") : fopen($filename, 'ab'); if ($this->fp === false) { throw new RuntimeException("Unable to open backup file: {$filename}"); } $this->size = filesize($filename) + $size; } else { $this->size += $size; } } private function absoluteBackupPath(): string { if (!$this->checkPath($this->config['path'])) { throw new RuntimeException('The current directory is not writable'); } $path = realpath($this->config['path']); if ($path === false) { throw new RuntimeException('Unable to resolve backup directory'); } return $path; } private function backupFilename(): string { return rtrim($this->config['path'], '/\\') . DIRECTORY_SEPARATOR . "{$this->file['name']}-{$this->file['part']}.sql"; } private function checkPath(string $path): bool { return is_dir($path) || mkdir($path, 0755, true); } public function __destruct() { if ($this->fp !== null) { $this->config['compress'] ? gzclose($this->fp) : fclose($this->fp); } } }