3 namespace BookStack\Exports;
5 use BookStack\Activity\Models\Tag;
6 use BookStack\Entities\Models\Page;
7 use BookStack\Exceptions\ZipExportException;
8 use BookStack\Uploads\Attachment;
11 class ZipExportBuilder
13 protected array $data = [];
15 public function __construct(
16 protected ZipExportFiles $files
21 * @throws ZipExportException
23 public function buildForPage(Page $page): string
25 $this->data['page'] = $this->convertPage($page);
26 return $this->build();
29 protected function convertPage(Page $page): array
31 $tags = array_map($this->convertTag(...), $page->tags()->get()->all());
32 $attachments = array_map($this->convertAttachment(...), $page->attachments()->get()->all());
36 'name' => $page->name,
38 'markdown' => '', // TODO
39 'priority' => $page->priority,
40 'attachments' => $attachments,
41 'images' => [], // TODO
46 protected function convertAttachment(Attachment $attachment): array
49 'name' => $attachment->name,
50 'order' => $attachment->order,
53 if ($attachment->external) {
54 $data['link'] = $attachment->path;
56 $data['file'] = $this->files->referenceForAttachment($attachment);
62 protected function convertTag(Tag $tag): array
66 'value' => $tag->value,
67 'order' => $tag->order,
72 * @throws ZipExportException
74 protected function build(): string
76 $this->data['exported_at'] = date(DATE_ATOM);
77 $this->data['instance'] = [
78 'version' => trim(file_get_contents(base_path('version'))),
79 'id_ciphertext' => encrypt('bookstack'),
82 $zipFile = tempnam(sys_get_temp_dir(), 'bszip-');
83 $zip = new ZipArchive();
84 $opened = $zip->open($zipFile, ZipArchive::CREATE);
85 if ($opened !== true) {
86 throw new ZipExportException('Failed to create zip file for export.');
89 $zip->addFromString('data.json', json_encode($this->data));
90 $zip->addEmptyDir('files');
93 $this->files->extractEach(function ($filePath, $fileRef) use ($zip, &$toRemove) {
94 $zip->addFile($filePath, "files/$fileRef");
95 $toRemove[] = $filePath;
100 foreach ($toRemove as $file) {