Skip to content

Commit 2be918a

Browse files
committed
fix: use finfo buffer instead of mime_content_type on streams
Avoids copying the whole file to disk for mime detection. Reads only the first 4096 bytes into a buffer and uses finfo::buffer() to detect the mime type, which does not require stream_cast() support. Addresses maintainer feedback on #592. Signed-off-by: Simon Holzman <simon.holzman@verizon.net>
1 parent 3ece3ab commit 2be918a

1 file changed

Lines changed: 4 additions & 25 deletions

File tree

‎lib/Service/AssistantService.php‎

Lines changed: 4 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -743,7 +743,8 @@ public function saveOutputFile(string $userId, int $ocpTaskId, int $fileId): arr
743743
* @throws NotPermittedException
744744
*/
745745
private function getTargetFileName(File $file): string {
746-
$mimeType = $this->detectMimeType($file->fopen('rb'));
746+
$head = fread($file->fopen('rb'), 4096);
747+
$mimeType = (new \finfo(FILEINFO_MIME_TYPE))->buffer($head);
747748
$fileName = $file->getName();
748749

749750
$mimes = new \Mimey\MimeTypes;
@@ -755,29 +756,6 @@ private function getTargetFileName(File $file): string {
755756
return $fileName;
756757
}
757758

758-
/**
759-
* Wraps mime_content_type() to avoid a PHP warning when given a stream
760-
* that does not implement stream_cast() (e.g. Icewind\Streams\CallbackWrapper,
761-
* returned by File::fopen() for some storage backends). The stream is
762-
* drained into a temp file first so mime_content_type() can operate on a
763-
* real path instead of the unsupported stream resource.
764-
*
765-
* @param resource $stream
766-
* @return string|false
767-
*/
768-
private function detectMimeType($stream) {
769-
$tmpFile = tempnam(sys_get_temp_dir(), 'nc_assistant_mime_');
770-
$tmpHandle = fopen($tmpFile, 'wb');
771-
stream_copy_to_stream($stream, $tmpHandle);
772-
fclose($tmpHandle);
773-
if (is_resource($stream)) {
774-
fclose($stream);
775-
}
776-
$mimeType = mime_content_type($tmpFile);
777-
unlink($tmpFile);
778-
return $mimeType;
779-
}
780-
781759
/**
782760
* @param Task $task
783761
* @return array
@@ -830,7 +808,8 @@ private function extractFileIdsFromTask(Task $task): array {
830808
*/
831809
public function getOutputFilePreviewFile(string $userId, int $taskId, int $fileId, ?int $x = 100, ?int $y = 100): ?array {
832810
$taskOutputFile = $this->getTaskOutputFile($userId, $taskId, $fileId);
833-
$realMime = $this->detectMimeType($taskOutputFile->fopen('rb'));
811+
$head = fread($taskOutputFile->fopen('rb'), 4096);
812+
$realMime = (new \finfo(FILEINFO_MIME_TYPE))->buffer($head);
834813
return $this->previewService->getFilePreviewFile($taskOutputFile, $x, $y, $realMime ?: null);
835814
}
836815

0 commit comments

Comments
 (0)