3 namespace BookStack\Exports;
5 use BookStack\Entities\Models\Page;
6 use BookStack\Exceptions\ZipExportException;
7 use BookStack\Exports\ZipExportModels\ZipExportPage;
10 class ZipExportBuilder
12 protected array $data = [];
14 public function __construct(
15 protected ZipExportFiles $files,
16 protected ZipExportReferences $references,
21 * @throws ZipExportException
23 public function buildForPage(Page $page): string
25 $exportPage = ZipExportPage::fromModel($page, $this->files);
26 $this->data['page'] = $exportPage;
28 $this->references->addPage($exportPage);
30 return $this->build();
34 * @throws ZipExportException
36 protected function build(): string
38 $this->references->buildReferences($this->files);
40 $this->data['exported_at'] = date(DATE_ATOM);
41 $this->data['instance'] = [
42 'version' => trim(file_get_contents(base_path('version'))),
43 'id_ciphertext' => encrypt('bookstack'),
46 $zipFile = tempnam(sys_get_temp_dir(), 'bszip-');
47 $zip = new ZipArchive();
48 $opened = $zip->open($zipFile, ZipArchive::CREATE);
49 if ($opened !== true) {
50 throw new ZipExportException('Failed to create zip file for export.');
53 $zip->addFromString('data.json', json_encode($this->data));
54 $zip->addEmptyDir('files');
57 $this->files->extractEach(function ($filePath, $fileRef) use ($zip, &$toRemove) {
58 $zip->addFile($filePath, "files/$fileRef");
59 $toRemove[] = $filePath;
64 foreach ($toRemove as $file) {