| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace GuzzleHttp\Psr7; |
| 6 |
|
| 7 |
use Psr\Http\Message\StreamInterface; |
| 8 |
|
| 9 |
/** |
| 10 |
* Stream that when read returns bytes for a streaming multipart or |
| 11 |
* multipart/form-data stream. |
| 12 |
*/ |
| 13 |
final class MultipartStream implements StreamInterface |
| 14 |
{ |
| 15 |
use StreamDecoratorTrait; |
| 16 |
|
| 17 |
/** @var string */ |
| 18 |
private $boundary; |
| 19 |
|
| 20 |
/** @var StreamInterface */ |
| 21 |
private $stream; |
| 22 |
|
| 23 |
private const BOUNDARY_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'()+_,-./:=? "; |
| 24 |
|
| 25 |
/** |
| 26 |
* @param array $elements Array of associative arrays, each containing a |
| 27 |
* required "name" key mapping to the form field, |
| 28 |
* name, a required "contents" key mapping to any |
| 29 |
* non-array value accepted by Utils::streamFor() |
| 30 |
* (non-string scalar field values are cast to |
| 31 |
* string), or an array for nested expansion. |
| 32 |
* Optional keys include "headers" (associative |
| 33 |
* array of custom headers) and "filename" (string |
| 34 |
* to send as the filename in the part). |
| 35 |
* When "contents" is an array, it is recursively |
| 36 |
* expanded into multiple fields using bracket notation |
| 37 |
* (e.g., name[0][key]). Empty arrays produce no fields. |
| 38 |
* The "filename" and "headers" options cannot be used |
| 39 |
* with array contents. |
| 40 |
* @param string|null $boundary You can optionally provide a specific boundary |
| 41 |
* |
| 42 |
* @throws \InvalidArgumentException |
| 43 |
*/ |
| 44 |
public function __construct(array $elements = [], ?string $boundary = null) |
| 45 |
{ |
| 46 |
if ($boundary !== null && !self::isValidBoundary($boundary)) { |
| 47 |
\trigger_deprecation( |
| 48 |
'guzzlehttp/psr7', |
| 49 |
'2.11', |
| 50 |
'Passing an invalid multipart boundary to MultipartStream::__construct() is deprecated; guzzlehttp/psr7 3.0 rejects invalid multipart boundaries.' |
| 51 |
); |
| 52 |
} |
| 53 |
|
| 54 |
$this->boundary = $boundary ?: bin2hex(random_bytes(20)); |
| 55 |
$this->stream = $this->createStream($elements); |
| 56 |
} |
| 57 |
|
| 58 |
public function getBoundary(): string |
| 59 |
{ |
| 60 |
return $this->boundary; |
| 61 |
} |
| 62 |
|
| 63 |
public function isWritable(): bool |
| 64 |
{ |
| 65 |
return false; |
| 66 |
} |
| 67 |
|
| 68 |
/** |
| 69 |
* Get the headers needed before transferring the content of a POST file |
| 70 |
* |
| 71 |
* @param array<array-key, string> $headers |
| 72 |
*/ |
| 73 |
private function getHeaders(array $headers): string |
| 74 |
{ |
| 75 |
$str = ''; |
| 76 |
foreach ($headers as $key => $value) { |
| 77 |
$key = (string) $key; |
| 78 |
$str .= "{$key}: {$value}\r\n"; |
| 79 |
} |
| 80 |
|
| 81 |
return "--{$this->boundary}\r\n".trim($str)."\r\n\r\n"; |
| 82 |
} |
| 83 |
|
| 84 |
/** |
| 85 |
* Create the aggregate stream that will be used to upload the POST data |
| 86 |
*/ |
| 87 |
protected function createStream(array $elements = []): StreamInterface |
| 88 |
{ |
| 89 |
$stream = new AppendStream(); |
| 90 |
|
| 91 |
foreach ($elements as $element) { |
| 92 |
if (!is_array($element)) { |
| 93 |
throw new \UnexpectedValueException('An array is expected'); |
| 94 |
} |
| 95 |
$this->addElement($stream, $element); |
| 96 |
} |
| 97 |
|
| 98 |
// Add the trailing boundary with CRLF |
| 99 |
$stream->addStream(Utils::streamFor("--{$this->boundary}--\r\n")); |
| 100 |
|
| 101 |
return $stream; |
| 102 |
} |
| 103 |
|
| 104 |
private function addElement(AppendStream $stream, array $element): void |
| 105 |
{ |
| 106 |
foreach (['contents', 'name'] as $key) { |
| 107 |
if (!array_key_exists($key, $element)) { |
| 108 |
throw new \InvalidArgumentException("A '{$key}' key is required"); |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
if (!is_string($element['name']) && !is_int($element['name'])) { |
| 113 |
throw new \InvalidArgumentException("The 'name' key must be a string or integer"); |
| 114 |
} |
| 115 |
|
| 116 |
if (is_array($element['contents'])) { |
| 117 |
if (array_key_exists('filename', $element) || array_key_exists('headers', $element)) { |
| 118 |
throw new \InvalidArgumentException( |
| 119 |
"The 'filename' and 'headers' options cannot be used when 'contents' is an array" |
| 120 |
); |
| 121 |
} |
| 122 |
|
| 123 |
$this->addNestedElements($stream, $element['contents'], (string) $element['name']); |
| 124 |
|
| 125 |
return; |
| 126 |
} |
| 127 |
|
| 128 |
$contents = $element['contents']; |
| 129 |
if (is_scalar($contents) && !is_string($contents)) { |
| 130 |
// Multipart field values are byte strings on the wire, so finite |
| 131 |
// numeric and boolean field values are cast to string here rather |
| 132 |
// than tripping streamFor()'s non-string-scalar deprecation. Non-finite |
| 133 |
// floats are deprecated and normalized here too, so the deprecation is |
| 134 |
// reported against MultipartStream instead of transitively through |
| 135 |
// streamFor(). |
| 136 |
if (is_float($contents) && !is_finite($contents)) { |
| 137 |
\trigger_deprecation( |
| 138 |
'guzzlehttp/psr7', |
| 139 |
'2.12', |
| 140 |
'Passing a non-finite float as multipart contents is deprecated; guzzlehttp/psr7 3.0 rejects non-finite floats.' |
| 141 |
); |
| 142 |
|
| 143 |
$contents = is_nan($contents) ? 'NAN' : ($contents > 0 ? 'INF' : '-INF'); |
| 144 |
} |
| 145 |
|
| 146 |
$contents = (string) $contents; |
| 147 |
} |
| 148 |
$element['contents'] = Utils::streamFor($contents); |
| 149 |
|
| 150 |
if (empty($element['filename'])) { |
| 151 |
$uri = $element['contents']->getMetadata('uri'); |
| 152 |
if ($uri && \is_string($uri) && \substr($uri, 0, 6) !== 'php://' && \substr($uri, 0, 7) !== 'data://') { |
| 153 |
$element['filename'] = $uri; |
| 154 |
} |
| 155 |
} |
| 156 |
|
| 157 |
[$body, $headers] = $this->createElement( |
| 158 |
(string) $element['name'], |
| 159 |
$element['contents'], |
| 160 |
$element['filename'] ?? null, |
| 161 |
$element['headers'] ?? [] |
| 162 |
); |
| 163 |
|
| 164 |
$stream->addStream(Utils::streamFor($this->getHeaders($headers))); |
| 165 |
$stream->addStream($body); |
| 166 |
$stream->addStream(Utils::streamFor("\r\n")); |
| 167 |
} |
| 168 |
|
| 169 |
/** |
| 170 |
* Recursively expand array contents into multiple form fields. |
| 171 |
* |
| 172 |
* @param array<array-key, mixed> $contents |
| 173 |
*/ |
| 174 |
private function addNestedElements(AppendStream $stream, array $contents, string $root): void |
| 175 |
{ |
| 176 |
foreach ($contents as $key => $value) { |
| 177 |
$fieldName = $root === '' ? sprintf('[%s]', (string) $key) : sprintf('%s[%s]', $root, (string) $key); |
| 178 |
|
| 179 |
if (is_array($value)) { |
| 180 |
$this->addNestedElements($stream, $value, $fieldName); |
| 181 |
} else { |
| 182 |
$this->addElement($stream, ['name' => $fieldName, 'contents' => $value]); |
| 183 |
} |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
/** |
| 188 |
* @param array<array-key, mixed> $headers |
| 189 |
* |
| 190 |
* @return array{0: StreamInterface, 1: array<array-key, string>} |
| 191 |
*/ |
| 192 |
private function createElement(string $name, StreamInterface $stream, ?string $filename, array $headers): array |
| 193 |
{ |
| 194 |
$headers = self::normalizePartHeaders($headers); |
| 195 |
|
| 196 |
// Set a default content-disposition header if one was no provided |
| 197 |
$disposition = self::getHeader($headers, 'content-disposition'); |
| 198 |
if (!$disposition) { |
| 199 |
$headers['Content-Disposition'] = ($filename === '0' || $filename) |
| 200 |
? sprintf( |
| 201 |
'form-data; name="%s"; filename="%s"', |
| 202 |
$name, |
| 203 |
basename($filename) |
| 204 |
) |
| 205 |
: "form-data; name=\"{$name}\""; |
| 206 |
} |
| 207 |
|
| 208 |
// Set a default content-length header if one was no provided |
| 209 |
$length = self::getHeader($headers, 'content-length'); |
| 210 |
if (!$length) { |
| 211 |
if ($length = $stream->getSize()) { |
| 212 |
$headers['Content-Length'] = (string) $length; |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
// Set a default Content-Type if one was not supplied |
| 217 |
$type = self::getHeader($headers, 'content-type'); |
| 218 |
if (!$type && ($filename === '0' || $filename)) { |
| 219 |
$headers['Content-Type'] = MimeType::fromFilename($filename) ?? 'application/octet-stream'; |
| 220 |
} |
| 221 |
|
| 222 |
return [$stream, $headers]; |
| 223 |
} |
| 224 |
|
| 225 |
/** |
| 226 |
* @param array<array-key, string> $headers |
| 227 |
*/ |
| 228 |
private static function getHeader(array $headers, string $key): ?string |
| 229 |
{ |
| 230 |
$lowercaseHeader = strtolower($key); |
| 231 |
foreach ($headers as $k => $v) { |
| 232 |
if (strtolower((string) $k) === $lowercaseHeader) { |
| 233 |
return $v; |
| 234 |
} |
| 235 |
} |
| 236 |
|
| 237 |
return null; |
| 238 |
} |
| 239 |
|
| 240 |
private static function isValidBoundary(string $boundary): bool |
| 241 |
{ |
| 242 |
$length = strlen($boundary); |
| 243 |
|
| 244 |
if ($length < 1 || $length > 70 || $boundary[$length - 1] === ' ') { |
| 245 |
return false; |
| 246 |
} |
| 247 |
|
| 248 |
return strspn($boundary, self::BOUNDARY_CHARS) === $length; |
| 249 |
} |
| 250 |
|
| 251 |
/** |
| 252 |
* @param array<array-key, mixed> $headers |
| 253 |
* |
| 254 |
* @return array<array-key, string> |
| 255 |
*/ |
| 256 |
private static function normalizePartHeaders(array $headers): array |
| 257 |
{ |
| 258 |
$normalized = []; |
| 259 |
|
| 260 |
foreach ($headers as $key => $value) { |
| 261 |
self::deprecateInvalidPartHeaderName((string) $key); |
| 262 |
|
| 263 |
if (!is_string($value)) { |
| 264 |
if (!is_scalar($value) && $value !== null && !(is_object($value) && method_exists($value, '__toString'))) { |
| 265 |
throw new \InvalidArgumentException(sprintf( |
| 266 |
'Multipart part header value must be a string or stringable value but %s provided.', |
| 267 |
\get_debug_type($value) |
| 268 |
)); |
| 269 |
} |
| 270 |
|
| 271 |
\trigger_deprecation( |
| 272 |
'guzzlehttp/psr7', |
| 273 |
'2.11', |
| 274 |
'Passing %s as a multipart part header value is deprecated; guzzlehttp/psr7 3.0 requires string multipart part header values.', |
| 275 |
\get_debug_type($value) |
| 276 |
); |
| 277 |
} |
| 278 |
|
| 279 |
$value = (string) $value; |
| 280 |
|
| 281 |
self::deprecateInvalidPartHeaderValue($value); |
| 282 |
|
| 283 |
$normalized[$key] = $value; |
| 284 |
} |
| 285 |
|
| 286 |
return $normalized; |
| 287 |
} |
| 288 |
|
| 289 |
private static function deprecateInvalidPartHeaderName(string $name): void |
| 290 |
{ |
| 291 |
if (!preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $name)) { |
| 292 |
\trigger_deprecation( |
| 293 |
'guzzlehttp/psr7', |
| 294 |
'2.11', |
| 295 |
'Passing an invalid multipart part header name to MultipartStream is deprecated; guzzlehttp/psr7 3.0 rejects invalid multipart part header names.' |
| 296 |
); |
| 297 |
} |
| 298 |
} |
| 299 |
|
| 300 |
private static function deprecateInvalidPartHeaderValue(string $value): void |
| 301 |
{ |
| 302 |
if (!preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/D', $value)) { |
| 303 |
\trigger_deprecation( |
| 304 |
'guzzlehttp/psr7', |
| 305 |
'2.11', |
| 306 |
'Passing an invalid multipart part header value to MultipartStream is deprecated; guzzlehttp/psr7 3.0 rejects invalid multipart part header values.' |
| 307 |
); |
| 308 |
} |
| 309 |
} |
| 310 |
} |