Skip to content

Commit 6d7ff59

Browse files
committed
ZIP Exports: Improved temp file tracking & clean-up
1 parent 980a684 commit 6d7ff59

File tree

6 files changed

+70
-8
lines changed

6 files changed

+70
-8
lines changed

app/Exports/Controllers/BookExportController.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,6 @@ public function zip(string $bookSlug, ZipExportBuilder $builder)
7575
$book = $this->queries->findVisibleBySlugOrFail($bookSlug);
7676
$zip = $builder->buildForBook($book);
7777

78-
return $this->download()->streamedDirectly(fopen($zip, 'r'), $bookSlug . '.zip', filesize($zip));
78+
return $this->download()->streamedFileDirectly($zip, $bookSlug . '.zip', filesize($zip), true);
7979
}
8080
}

app/Exports/Controllers/ChapterExportController.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,6 @@ public function zip(string $bookSlug, string $chapterSlug, ZipExportBuilder $bui
8181
$chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug);
8282
$zip = $builder->buildForChapter($chapter);
8383

84-
return $this->download()->streamedDirectly(fopen($zip, 'r'), $chapterSlug . '.zip', filesize($zip));
84+
return $this->download()->streamedFileDirectly($zip, $chapterSlug . '.zip', filesize($zip), true);
8585
}
8686
}

app/Exports/Controllers/PageExportController.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,6 @@ public function zip(string $bookSlug, string $pageSlug, ZipExportBuilder $builde
8585
$page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug);
8686
$zip = $builder->buildForPage($page);
8787

88-
return $this->download()->streamedDirectly(fopen($zip, 'r'), $pageSlug . '.zip', filesize($zip));
88+
return $this->download()->streamedFileDirectly($zip, $pageSlug . '.zip', filesize($zip), true);
8989
}
9090
}

app/Exports/ZipExports/ZipExportBuilder.php

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,10 +84,27 @@ protected function build(): string
8484
$zip->addEmptyDir('files');
8585

8686
$toRemove = [];
87-
$this->files->extractEach(function ($filePath, $fileRef) use ($zip, &$toRemove) {
88-
$zip->addFile($filePath, "files/$fileRef");
89-
$toRemove[] = $filePath;
90-
});
87+
$addedNames = [];
88+
89+
try {
90+
$this->files->extractEach(function ($filePath, $fileRef) use ($zip, &$toRemove, &$addedNames) {
91+
$entryName = "files/$fileRef";
92+
$zip->addFile($filePath, $entryName);
93+
$toRemove[] = $filePath;
94+
$addedNames[] = $entryName;
95+
});
96+
} catch (\Exception $exception) {
97+
// Cleanup the files we've processed so far and respond back with error
98+
foreach ($toRemove as $file) {
99+
unlink($file);
100+
}
101+
foreach ($addedNames as $name) {
102+
$zip->deleteName($name);
103+
}
104+
$zip->close();
105+
unlink($zipFile);
106+
throw new ZipExportException("Failed to add files for ZIP export, received error: " . $exception->getMessage());
107+
}
91108

92109
$zip->close();
93110

app/Http/DownloadResponseFactory.php

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
class DownloadResponseFactory
1010
{
1111
public function __construct(
12-
protected Request $request
12+
protected Request $request,
1313
) {
1414
}
1515

@@ -35,6 +35,32 @@ public function streamedDirectly($stream, string $fileName, int $fileSize): Stre
3535
);
3636
}
3737

38+
/**
39+
* Create a response that downloads the given file via a stream.
40+
* Has the option to delete the provided file once the stream is closed.
41+
*/
42+
public function streamedFileDirectly(string $filePath, string $fileName, int $fileSize, bool $deleteAfter = false): StreamedResponse
43+
{
44+
$stream = fopen($filePath, 'r');
45+
46+
if ($deleteAfter) {
47+
// Delete the given file if it still exists after the app terminates
48+
$callback = function () use ($filePath) {
49+
if (file_exists($filePath)) {
50+
unlink($filePath);
51+
}
52+
};
53+
54+
// We watch both app terminate and php shutdown to cover both normal app termination
55+
// as well as other potential scenarios (connection termination).
56+
app()->terminating($callback);
57+
register_shutdown_function($callback);
58+
}
59+
60+
return $this->streamedDirectly($stream, $fileName, $fileSize);
61+
}
62+
63+
3864
/**
3965
* Create a file download response that provides the file with a content-type
4066
* correct for the file, in a way so the browser can show the content in browser,

tests/Exports/ZipExportTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use BookStack\Entities\Tools\PageContent;
88
use BookStack\Uploads\Attachment;
99
use BookStack\Uploads\Image;
10+
use FilesystemIterator;
1011
use Illuminate\Support\Carbon;
1112
use Illuminate\Testing\TestResponse;
1213
use Tests\TestCase;
@@ -60,6 +61,24 @@ public function test_export_metadata()
6061
$this->assertEquals($instanceId, $zipInstanceId);
6162
}
6263

64+
public function test_export_leaves_no_temp_files()
65+
{
66+
$tempDir = sys_get_temp_dir();
67+
$startTempFileCount = iterator_count((new FileSystemIterator($tempDir, FilesystemIterator::SKIP_DOTS)));
68+
69+
$page = $this->entities->pageWithinChapter();
70+
$this->asEditor();
71+
$pageResp = $this->get($page->getUrl("/export/zip"));
72+
$pageResp->streamedContent();
73+
$pageResp->assertOk();
74+
$this->get($page->chapter->getUrl("/export/zip"))->assertOk();
75+
$this->get($page->book->getUrl("/export/zip"))->assertOk();
76+
77+
$afterTempFileCount = iterator_count((new FileSystemIterator($tempDir, FilesystemIterator::SKIP_DOTS)));
78+
79+
$this->assertEquals($startTempFileCount, $afterTempFileCount);
80+
}
81+
6382
public function test_page_export()
6483
{
6584
$page = $this->entities->page();

0 commit comments

Comments
 (0)