Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions src/Assets/ExtractInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,34 @@

namespace Statamic\Assets;

use GuzzleHttp\Psr7\StreamWrapper;
use Illuminate\Filesystem\AwsS3V3Adapter;
use Statamic\Contracts\Assets\Asset;

class ExtractInfo
{
public function fromAsset(Asset $asset): array
{
$disk = $asset->disk()->filesystem();
$path = $asset->path();
$disk = $asset->disk()->filesystem();
$size = $disk->size($path);
$stream = $disk instanceof AwsS3V3Adapter
? StreamWrapper::getResource(new S3MetadataStream($disk, $path, $size))
: $disk->readStream($path);

try {
$id3 = new \getID3;

if ($disk instanceof AwsS3V3Adapter) {
// getID3 reads up to a quarter of this allowance per MP4 atom.
$id3->memory_limit = min($id3->memory_limit, 128 * 1024 * 1024);
}

return (new \getID3)->analyze($path, $disk->size($path), '', $disk->readStream($path));
return $id3->analyze($path, $size, '', $stream);
} finally {
if (is_resource($stream)) {
fclose($stream);
}
}
}
}
181 changes: 181 additions & 0 deletions src/Assets/S3MetadataStream.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
<?php

namespace Statamic\Assets;

use GuzzleHttp\Psr7\StreamDecoratorTrait;
use GuzzleHttp\Psr7\Utils;
use Illuminate\Filesystem\AwsS3V3Adapter;
use Psr\Http\Message\StreamInterface;
use RuntimeException;

class S3MetadataStream implements StreamInterface
{
use StreamDecoratorTrait;

private const CHUNK_SIZE = 2 * 1024 * 1024;

private StreamInterface $stream;
private int $position = 0;
private int $bufferStart = 0;
private int $requestsCount = 0;
private ?string $etag = null;
private float $deadline;

public function __construct(
private AwsS3V3Adapter $disk,
private string $path,
private int $size,
private int $chunkSize = self::CHUNK_SIZE,
) {
$this->deadline = microtime(true) + 30;
$this->stream = Utils::streamFor('');
}

public function read($length): string
{
if (! $this->isReadable()) {
throw new RuntimeException('Cannot read a closed S3 stream.');
}

if ($length < 0) {
throw new RuntimeException('Read length must not be negative.');
}

if ($length === 0 || $this->eof()) {
return '';
}

if ($this->position < $this->bufferStart || $this->position >= $this->bufferStart + $this->stream->getSize()) {
$this->readRange();
}

$this->stream->seek($this->position - $this->bufferStart);
$data = $this->stream->read($length);
$this->position += strlen($data);

return $data;
}

private function readRange(): void
{
$timeout = $this->deadline - microtime(true);

if (++$this->requestsCount > 128 || $timeout <= 0) {
throw new RuntimeException('S3 metadata extraction exceeded its read limit.');
}

$start = intdiv($this->position, $this->chunkSize) * $this->chunkSize;
$end = min($start + $this->chunkSize, $this->size) - 1;
$config = $this->disk->getConfig();
$options = $config['options'] ?? [];

$params = array_merge($options, [
'Bucket' => $config['bucket'],
'Key' => $this->disk->path($this->path),
'Range' => "bytes={$start}-{$end}",
'@retries' => 0,
'@http' => array_merge($options['@http'] ?? [], [
'stream' => true,
'timeout' => min(10, $timeout),
'read_timeout' => min(10, $timeout),
]),
]);

if ($this->etag !== null) {
$params['IfMatch'] = $this->etag;
}

$result = $this->disk->getClient()->getObject($params);

try {
if (($result['@metadata']['statusCode'] ?? null) !== 206
|| ($result['ContentRange'] ?? null) !== "bytes {$start}-{$end}/{$this->size}") {
throw new RuntimeException('S3 did not return the requested byte range.');
}

if ($this->etag !== null && $result['ETag'] !== $this->etag) {
throw new RuntimeException('The S3 asset changed during metadata extraction.');
}

$data = '';
$length = $end - $start + 1;

while (! $result['Body']->eof() && strlen($data) <= $length) {
if (microtime(true) >= $this->deadline) {
throw new RuntimeException('S3 metadata extraction exceeded its read limit.');
}

$chunk = $result['Body']->read(min(8192, $length - strlen($data) + 1));

if ($chunk === '') {
break;
}

$data .= $chunk;
}

if (strlen($data) !== $length) {
throw new RuntimeException('S3 returned an incomplete or oversized byte range.');
}

$this->etag = $result['ETag'];
$this->bufferStart = $start;
$this->stream->close();
$this->stream = Utils::streamFor($data);
} finally {
$result['Body']->close();
}
}

public function seek($offset, $whence = SEEK_SET): void
{
if (! $this->isReadable()) {
throw new RuntimeException('Cannot seek a closed S3 stream.');
}

$position = match ($whence) {
SEEK_SET => $offset,
SEEK_CUR => $this->position + $offset,
SEEK_END => $this->size + $offset,
default => throw new RuntimeException('Invalid seek mode.'),
};

if ($position < 0) {
throw new RuntimeException('Cannot seek before the beginning of the S3 stream.');
}

$this->position = $position;
}

public function tell(): int
{
return $this->position;
}

public function eof(): bool
{
return $this->position >= $this->size;
}

public function getSize(): ?int
{
return $this->size;
}

public function isWritable(): bool
{
return false;
}

public function write($string): int
{
throw new RuntimeException('The S3 stream is read-only.');
}

public function detach(): mixed
{
$this->close();

return null;
}
}
131 changes: 122 additions & 9 deletions src/Imaging/Attributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,33 @@

namespace Statamic\Imaging;

use GuzzleHttp\Psr7\StreamWrapper;
use Illuminate\Filesystem\AwsS3V3Adapter;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\Local\LocalFilesystemAdapter;
use League\Flysystem\MountManager;
use Statamic\Assets\S3MetadataStream;
use Statamic\Support\Str;

class Attributes
{
private const HEADER_WINDOW = 64 * 1024;
private const HEADER_LIMIT = 2 * 1024 * 1024;
private const S3_CHUNK_SIZE = 256 * 1024;

private $cacheDisk;

public function from(FilesystemAdapter $source, string $path)
{
if ($source->getAdapter() instanceof LocalFilesystemAdapter) {
$svg = Str::endsWith($path, '.svg');
$local = $source->getAdapter() instanceof LocalFilesystemAdapter;

if (! $local && ! $svg && ($attributes = $this->imageAttributesFromHeader($source, $path))) {
return $attributes;
}

if ($local) {
$fullPath = $source->path($path);
} else {
$temporaryPath = Str::random(32).'.'.pathinfo($path, PATHINFO_EXTENSION);
Expand All @@ -25,8 +39,6 @@ public function from(FilesystemAdapter $source, string $path)
$fullPath = $this->cacheDisk()->path($temporaryPath);
}

$svg = Str::endsWith($path, '.svg');

try {
$attributes = $svg ? $this->svgAttributes($fullPath) : $this->imageAttributes($fullPath);
} catch (\Exception $e) {
Expand All @@ -50,20 +62,121 @@ private function imageAttributes(string $path)
return ['width' => 0, 'height' => 0];
}

[$width, $height] = $size;
return $this->orient($size[0], $size[1], $this->orientation($path));
}

/**
* Dimensions and orientation live at the start of an image, so on a remote
* disk only that much is read rather than downloading the whole file.
*
* Returns null when they could not be found, and the file should be copied instead.
*/
private function imageAttributesFromHeader(FilesystemAdapter $source, string $path): ?array
{
try {
$stream = $this->headerStream($source, $path);
} catch (\Throwable $e) {
return null;
}

if (! is_resource($stream)) {
return null;
}

$header = '';
$window = self::HEADER_WINDOW;

try {
while (true) {
$header .= (string) stream_get_contents($stream, $window - strlen($header));

$size = $header !== '' ? @getimagesizefromstring($header) : false;
$orientation = $size ? $this->headerOrientation($header, $size[2]) : null;

if (function_exists('exif_read_data')) {
$exif = @exif_read_data($path);
$orientation = $exif['Orientation'] ?? 1;
// The dimensions can be readable before the orientation is, so keep going until both are.
if ($size && (! is_null($orientation) || feof($stream))) {
return $this->orient($size[0], $size[1], $orientation ?? 1);
}

if (in_array($orientation, [5, 6, 7, 8])) {
[$width, $height] = [$height, $width];
if (! $size && feof($stream)) {
// The whole file has been read, so a copy has nothing more to offer.
return ['width' => 0, 'height' => 0];
}

if (strlen($header) < $window || $window >= self::HEADER_LIMIT) {
return null;
}

$window *= 2;
}
} catch (\Throwable $e) {
return null;
} finally {
is_resource($stream) && fclose($stream);
}
}

/**
* @return resource|null
*/
private function headerStream(FilesystemAdapter $source, string $path)
{
// Laravel buffers S3 reads in full unless told otherwise, so ask for ranges instead.
if ($source instanceof AwsS3V3Adapter) {
return StreamWrapper::getResource(
new S3MetadataStream($source, $path, $source->size($path), self::S3_CHUNK_SIZE)
);
}

return $source->readStream($path);
}

private function orient(int $width, int $height, int $orientation): array
{
if (in_array($orientation, [5, 6, 7, 8])) {
[$width, $height] = [$height, $width];
}

return compact('width', 'height');
}

private function orientation(string $path): int
{
if (! function_exists('exif_read_data')) {
return 1;
}

$exif = @exif_read_data($path);

return $exif['Orientation'] ?? 1;
}

/**
* Returns null when the header stops short of the EXIF data being readable.
*/
private function headerOrientation(string $header, int $type): ?int
{
if (! function_exists('exif_read_data')) {
return 1;
}

$stream = fopen('php://memory', 'r+');
fwrite($stream, $header);
rewind($stream);

try {
$exif = @exif_read_data($stream);
} finally {
fclose($stream);
}

if ($exif === false && in_array($type, [IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM])) {
return null;
}

return $exif['Orientation'] ?? 1;
}

private function svgAttributes(string $path)
{
$svg = simplexml_load_file($path);
Expand Down
Loading
Loading