forked from laysense/laysite
Launch LaySite visual editor and MCP workspace
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Content\SiteBackup;
|
||||
use App\Http\Request;
|
||||
use RuntimeException;
|
||||
use support\Response;
|
||||
use Throwable;
|
||||
use Workerman\Timer;
|
||||
|
||||
final class BackupController extends AdminController
|
||||
{
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
if ($failure = $this->guard($request)) {
|
||||
return $failure;
|
||||
}
|
||||
$error = '';
|
||||
if ($request->method() === 'POST') {
|
||||
$path = null;
|
||||
try {
|
||||
$file = $request->file('backup');
|
||||
if ($request->post('replace') !== '1' || !$file instanceof \Webman\Http\UploadFile || !$file->isValid()) {
|
||||
throw new RuntimeException('请选择备份文件并确认覆盖站点内容。');
|
||||
}
|
||||
$path = $this->temporary();
|
||||
if (!copy($file->getPathname(), $path)) {
|
||||
throw new RuntimeException('不能暂存备份文件。');
|
||||
}
|
||||
SiteBackup::import($path);
|
||||
return $this->success($request, '/admin/backup?restored=1');
|
||||
} catch (Throwable $ex) {
|
||||
$error = $ex instanceof RuntimeException && !$ex instanceof \PDOException
|
||||
? $ex->getMessage() : '备份无法导入。请检查文件格式或服务器日志。';
|
||||
} finally {
|
||||
if ($path && is_file($path)) {
|
||||
unlink($path);
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this->render($request, 'admin-backup', [
|
||||
'title' => '站点备份', 'error' => $error, 'restored' => $request->get('restored') === '1',
|
||||
], $error === '' ? 200 : 422);
|
||||
}
|
||||
|
||||
public function export(Request $request): Response
|
||||
{
|
||||
if ($failure = $this->guard($request)) {
|
||||
return $failure;
|
||||
}
|
||||
try {
|
||||
$path = $this->temporary();
|
||||
SiteBackup::export($path);
|
||||
Timer::add(600, static function () use ($path): void {
|
||||
if (is_file($path)) {
|
||||
unlink($path);
|
||||
}
|
||||
}, [], false);
|
||||
return (new Response(200, ['Content-Type' => 'application/x-tar', 'Cache-Control' => 'no-store',
|
||||
'X-Content-Type-Options' => 'nosniff', 'Content-Disposition' => 'attachment; filename="laysite-' . gmdate('Ymd-His') . '.tar"']))->withFile($path);
|
||||
} catch (Throwable $ex) {
|
||||
return $this->error($request, '无法创建站点备份,请检查文件权限和媒体文件。', 500);
|
||||
}
|
||||
}
|
||||
|
||||
private function temporary(): string
|
||||
{
|
||||
$directory = runtime_path('backups');
|
||||
if (!is_dir($directory) && !mkdir($directory, 0700, true) && !is_dir($directory)) {
|
||||
throw new RuntimeException('不能创建临时备份目录。');
|
||||
}
|
||||
|
||||
return $directory . '/' . bin2hex(random_bytes(20)) . '.tar';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user