3 namespace BookStack\Http;
5 use BookStack\Util\WebSafeMimeSniffer;
6 use Symfony\Component\HttpFoundation\HeaderBag;
8 class RangeSupportedStream
10 protected string $sniffContent;
12 public function __construct(
14 protected int $fileSize,
15 protected HeaderBag $requestHeaders,
20 * Sniff a mime type from the stream.
22 public function sniffMime(): string
24 $offset = min(2000, $this->fileSize);
25 $this->sniffContent = fread($this->stream, $offset);
27 return (new WebSafeMimeSniffer())->sniff($this->sniffContent);
31 * Output the current stream to stdout before closing out the stream.
33 public function outputAndClose(): void
35 // End & flush the output buffer, if we're in one, otherwise we still use memory.
36 // Output buffer may or may not exist depending on PHP `output_buffering` setting.
37 // Ignore in testing since output buffers are used to gather a response.
38 if (!empty(ob_get_status()) && !app()->runningUnitTests()) {
42 $outStream = fopen('php://output', 'w');
45 if (!empty($this->sniffContent)) {
46 fwrite($outStream, $this->sniffContent);
47 $offset = strlen($this->sniffContent);
50 $toWrite = $this->fileSize - $offset;
51 stream_copy_to_stream($this->stream, $outStream, $toWrite);
52 fpassthru($this->stream);
54 fclose($this->stream);