| 1 | <?php
|
|---|
| 2 | namespace GuzzleHttp\Psr7;
|
|---|
| 3 |
|
|---|
| 4 | use Psr\Http\Message\MessageInterface;
|
|---|
| 5 | use Psr\Http\Message\RequestInterface;
|
|---|
| 6 | use Psr\Http\Message\ResponseInterface;
|
|---|
| 7 | use Psr\Http\Message\StreamInterface;
|
|---|
| 8 | use Psr\Http\Message\UriInterface;
|
|---|
| 9 |
|
|---|
| 10 | /**
|
|---|
| 11 | * Returns the string representation of an HTTP message.
|
|---|
| 12 | *
|
|---|
| 13 | * @param MessageInterface $message Message to convert to a string.
|
|---|
| 14 | *
|
|---|
| 15 | * @return string
|
|---|
| 16 | */
|
|---|
| 17 | function str(MessageInterface $message)
|
|---|
| 18 | {
|
|---|
| 19 | if ($message instanceof RequestInterface) {
|
|---|
| 20 | $msg = trim($message->getMethod() . ' '
|
|---|
| 21 | . $message->getRequestTarget())
|
|---|
| 22 | . ' HTTP/' . $message->getProtocolVersion();
|
|---|
| 23 | if (!$message->hasHeader('host')) {
|
|---|
| 24 | $msg .= "\r\nHost: " . $message->getUri()->getHost();
|
|---|
| 25 | }
|
|---|
| 26 | } elseif ($message instanceof ResponseInterface) {
|
|---|
| 27 | $msg = 'HTTP/' . $message->getProtocolVersion() . ' '
|
|---|
| 28 | . $message->getStatusCode() . ' '
|
|---|
| 29 | . $message->getReasonPhrase();
|
|---|
| 30 | } else {
|
|---|
| 31 | throw new \InvalidArgumentException('Unknown message type');
|
|---|
| 32 | }
|
|---|
| 33 |
|
|---|
| 34 | foreach ($message->getHeaders() as $name => $values) {
|
|---|
| 35 | $msg .= "\r\n{$name}: " . implode(', ', $values);
|
|---|
| 36 | }
|
|---|
| 37 |
|
|---|
| 38 | return "{$msg}\r\n\r\n" . $message->getBody();
|
|---|
| 39 | }
|
|---|
| 40 |
|
|---|
| 41 | /**
|
|---|
| 42 | * Returns a UriInterface for the given value.
|
|---|
| 43 | *
|
|---|
| 44 | * This function accepts a string or {@see Psr\Http\Message\UriInterface} and
|
|---|
| 45 | * returns a UriInterface for the given value. If the value is already a
|
|---|
| 46 | * `UriInterface`, it is returned as-is.
|
|---|
| 47 | *
|
|---|
| 48 | * @param string|UriInterface $uri
|
|---|
| 49 | *
|
|---|
| 50 | * @return UriInterface
|
|---|
| 51 | * @throws \InvalidArgumentException
|
|---|
| 52 | */
|
|---|
| 53 | function uri_for($uri)
|
|---|
| 54 | {
|
|---|
| 55 | if ($uri instanceof UriInterface) {
|
|---|
| 56 | return $uri;
|
|---|
| 57 | } elseif (is_string($uri)) {
|
|---|
| 58 | return new Uri($uri);
|
|---|
| 59 | }
|
|---|
| 60 |
|
|---|
| 61 | throw new \InvalidArgumentException('URI must be a string or UriInterface');
|
|---|
| 62 | }
|
|---|
| 63 |
|
|---|
| 64 | /**
|
|---|
| 65 | * Create a new stream based on the input type.
|
|---|
| 66 | *
|
|---|
| 67 | * Options is an associative array that can contain the following keys:
|
|---|
| 68 | * - metadata: Array of custom metadata.
|
|---|
| 69 | * - size: Size of the stream.
|
|---|
| 70 | *
|
|---|
| 71 | * @param resource|string|StreamInterface $resource Entity body data
|
|---|
| 72 | * @param array $options Additional options
|
|---|
| 73 | *
|
|---|
| 74 | * @return Stream
|
|---|
| 75 | * @throws \InvalidArgumentException if the $resource arg is not valid.
|
|---|
| 76 | */
|
|---|
| 77 | function stream_for($resource = '', array $options = [])
|
|---|
| 78 | {
|
|---|
| 79 | switch (gettype($resource)) {
|
|---|
| 80 | case 'string':
|
|---|
| 81 | $stream = fopen('php://temp', 'r+');
|
|---|
| 82 | if ($resource !== '') {
|
|---|
| 83 | fwrite($stream, $resource);
|
|---|
| 84 | fseek($stream, 0);
|
|---|
| 85 | }
|
|---|
| 86 | return new Stream($stream, $options);
|
|---|
| 87 | case 'resource':
|
|---|
| 88 | return new Stream($resource, $options);
|
|---|
| 89 | case 'object':
|
|---|
| 90 | if ($resource instanceof StreamInterface) {
|
|---|
| 91 | return $resource;
|
|---|
| 92 | } elseif ($resource instanceof \Iterator) {
|
|---|
| 93 | return new PumpStream(function () use ($resource) {
|
|---|
| 94 | if (!$resource->valid()) {
|
|---|
| 95 | return false;
|
|---|
| 96 | }
|
|---|
| 97 | $result = $resource->current();
|
|---|
| 98 | $resource->next();
|
|---|
| 99 | return $result;
|
|---|
| 100 | }, $options);
|
|---|
| 101 | } elseif (method_exists($resource, '__toString')) {
|
|---|
| 102 | return stream_for((string) $resource, $options);
|
|---|
| 103 | }
|
|---|
| 104 | break;
|
|---|
| 105 | case 'NULL':
|
|---|
| 106 | return new Stream(fopen('php://temp', 'r+'), $options);
|
|---|
| 107 | }
|
|---|
| 108 |
|
|---|
| 109 | if (is_callable($resource)) {
|
|---|
| 110 | return new PumpStream($resource, $options);
|
|---|
| 111 | }
|
|---|
| 112 |
|
|---|
| 113 | throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource));
|
|---|
| 114 | }
|
|---|
| 115 |
|
|---|
| 116 | /**
|
|---|
| 117 | * Parse an array of header values containing ";" separated data into an
|
|---|
| 118 | * array of associative arrays representing the header key value pair
|
|---|
| 119 | * data of the header. When a parameter does not contain a value, but just
|
|---|
| 120 | * contains a key, this function will inject a key with a '' string value.
|
|---|
| 121 | *
|
|---|
| 122 | * @param string|array $header Header to parse into components.
|
|---|
| 123 | *
|
|---|
| 124 | * @return array Returns the parsed header values.
|
|---|
| 125 | */
|
|---|
| 126 | function parse_header($header)
|
|---|
| 127 | {
|
|---|
| 128 | static $trimmed = "\"' \n\t\r";
|
|---|
| 129 | $params = $matches = [];
|
|---|
| 130 |
|
|---|
| 131 | foreach (normalize_header($header) as $val) {
|
|---|
| 132 | $part = [];
|
|---|
| 133 | foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) {
|
|---|
| 134 | if (preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) {
|
|---|
| 135 | $m = $matches[0];
|
|---|
| 136 | if (isset($m[1])) {
|
|---|
| 137 | $part[trim($m[0], $trimmed)] = trim($m[1], $trimmed);
|
|---|
| 138 | } else {
|
|---|
| 139 | $part[] = trim($m[0], $trimmed);
|
|---|
| 140 | }
|
|---|
| 141 | }
|
|---|
| 142 | }
|
|---|
| 143 | if ($part) {
|
|---|
| 144 | $params[] = $part;
|
|---|
| 145 | }
|
|---|
| 146 | }
|
|---|
| 147 |
|
|---|
| 148 | return $params;
|
|---|
| 149 | }
|
|---|
| 150 |
|
|---|
| 151 | /**
|
|---|
| 152 | * Converts an array of header values that may contain comma separated
|
|---|
| 153 | * headers into an array of headers with no comma separated values.
|
|---|
| 154 | *
|
|---|
| 155 | * @param string|array $header Header to normalize.
|
|---|
| 156 | *
|
|---|
| 157 | * @return array Returns the normalized header field values.
|
|---|
| 158 | */
|
|---|
| 159 | function normalize_header($header)
|
|---|
| 160 | {
|
|---|
| 161 | if (!is_array($header)) {
|
|---|
| 162 | return array_map('trim', explode(',', $header));
|
|---|
| 163 | }
|
|---|
| 164 |
|
|---|
| 165 | $result = [];
|
|---|
| 166 | foreach ($header as $value) {
|
|---|
| 167 | foreach ((array) $value as $v) {
|
|---|
| 168 | if (strpos($v, ',') === false) {
|
|---|
| 169 | $result[] = $v;
|
|---|
| 170 | continue;
|
|---|
| 171 | }
|
|---|
| 172 | foreach (preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $v) as $vv) {
|
|---|
| 173 | $result[] = trim($vv);
|
|---|
| 174 | }
|
|---|
| 175 | }
|
|---|
| 176 | }
|
|---|
| 177 |
|
|---|
| 178 | return $result;
|
|---|
| 179 | }
|
|---|
| 180 |
|
|---|
| 181 | /**
|
|---|
| 182 | * Clone and modify a request with the given changes.
|
|---|
| 183 | *
|
|---|
| 184 | * The changes can be one of:
|
|---|
| 185 | * - method: (string) Changes the HTTP method.
|
|---|
| 186 | * - set_headers: (array) Sets the given headers.
|
|---|
| 187 | * - remove_headers: (array) Remove the given headers.
|
|---|
| 188 | * - body: (mixed) Sets the given body.
|
|---|
| 189 | * - uri: (UriInterface) Set the URI.
|
|---|
| 190 | * - query: (string) Set the query string value of the URI.
|
|---|
| 191 | * - version: (string) Set the protocol version.
|
|---|
| 192 | *
|
|---|
| 193 | * @param RequestInterface $request Request to clone and modify.
|
|---|
| 194 | * @param array $changes Changes to apply.
|
|---|
| 195 | *
|
|---|
| 196 | * @return RequestInterface
|
|---|
| 197 | */
|
|---|
| 198 | function modify_request(RequestInterface $request, array $changes)
|
|---|
| 199 | {
|
|---|
| 200 | if (!$changes) {
|
|---|
| 201 | return $request;
|
|---|
| 202 | }
|
|---|
| 203 |
|
|---|
| 204 | $headers = $request->getHeaders();
|
|---|
| 205 |
|
|---|
| 206 | if (!isset($changes['uri'])) {
|
|---|
| 207 | $uri = $request->getUri();
|
|---|
| 208 | } else {
|
|---|
| 209 | // Remove the host header if one is on the URI
|
|---|
| 210 | if ($host = $changes['uri']->getHost()) {
|
|---|
| 211 | $changes['set_headers']['Host'] = $host;
|
|---|
| 212 | }
|
|---|
| 213 | $uri = $changes['uri'];
|
|---|
| 214 | }
|
|---|
| 215 |
|
|---|
| 216 | if (!empty($changes['remove_headers'])) {
|
|---|
| 217 | $headers = _caseless_remove($changes['remove_headers'], $headers);
|
|---|
| 218 | }
|
|---|
| 219 |
|
|---|
| 220 | if (!empty($changes['set_headers'])) {
|
|---|
| 221 | $headers = _caseless_remove(array_keys($changes['set_headers']), $headers);
|
|---|
| 222 | $headers = $changes['set_headers'] + $headers;
|
|---|
| 223 | }
|
|---|
| 224 |
|
|---|
| 225 | if (isset($changes['query'])) {
|
|---|
| 226 | $uri = $uri->withQuery($changes['query']);
|
|---|
| 227 | }
|
|---|
| 228 |
|
|---|
| 229 | return new Request(
|
|---|
| 230 | isset($changes['method']) ? $changes['method'] : $request->getMethod(),
|
|---|
| 231 | $uri,
|
|---|
| 232 | $headers,
|
|---|
| 233 | isset($changes['body']) ? $changes['body'] : $request->getBody(),
|
|---|
| 234 | isset($changes['version'])
|
|---|
| 235 | ? $changes['version']
|
|---|
| 236 | : $request->getProtocolVersion()
|
|---|
| 237 | );
|
|---|
| 238 | }
|
|---|
| 239 |
|
|---|
| 240 | /**
|
|---|
| 241 | * Attempts to rewind a message body and throws an exception on failure.
|
|---|
| 242 | *
|
|---|
| 243 | * The body of the message will only be rewound if a call to `tell()` returns a
|
|---|
| 244 | * value other than `0`.
|
|---|
| 245 | *
|
|---|
| 246 | * @param MessageInterface $message Message to rewind
|
|---|
| 247 | *
|
|---|
| 248 | * @throws \RuntimeException
|
|---|
| 249 | */
|
|---|
| 250 | function rewind_body(MessageInterface $message)
|
|---|
| 251 | {
|
|---|
| 252 | $body = $message->getBody();
|
|---|
| 253 |
|
|---|
| 254 | if ($body->tell()) {
|
|---|
| 255 | $body->rewind();
|
|---|
| 256 | }
|
|---|
| 257 | }
|
|---|
| 258 |
|
|---|
| 259 | /**
|
|---|
| 260 | * Safely opens a PHP stream resource using a filename.
|
|---|
| 261 | *
|
|---|
| 262 | * When fopen fails, PHP normally raises a warning. This function adds an
|
|---|
| 263 | * error handler that checks for errors and throws an exception instead.
|
|---|
| 264 | *
|
|---|
| 265 | * @param string $filename File to open
|
|---|
| 266 | * @param string $mode Mode used to open the file
|
|---|
| 267 | *
|
|---|
| 268 | * @return resource
|
|---|
| 269 | * @throws \RuntimeException if the file cannot be opened
|
|---|
| 270 | */
|
|---|
| 271 | function try_fopen($filename, $mode)
|
|---|
| 272 | {
|
|---|
| 273 | $ex = null;
|
|---|
| 274 | set_error_handler(function () use ($filename, $mode, &$ex) {
|
|---|
| 275 | $ex = new \RuntimeException(sprintf(
|
|---|
| 276 | 'Unable to open %s using mode %s: %s',
|
|---|
| 277 | $filename,
|
|---|
| 278 | $mode,
|
|---|
| 279 | func_get_args()[1]
|
|---|
| 280 | ));
|
|---|
| 281 | });
|
|---|
| 282 |
|
|---|
| 283 | $handle = fopen($filename, $mode);
|
|---|
| 284 | restore_error_handler();
|
|---|
| 285 |
|
|---|
| 286 | if ($ex) {
|
|---|
| 287 | /** @var $ex \RuntimeException */
|
|---|
| 288 | throw $ex;
|
|---|
| 289 | }
|
|---|
| 290 |
|
|---|
| 291 | return $handle;
|
|---|
| 292 | }
|
|---|
| 293 |
|
|---|
| 294 | /**
|
|---|
| 295 | * Copy the contents of a stream into a string until the given number of
|
|---|
| 296 | * bytes have been read.
|
|---|
| 297 | *
|
|---|
| 298 | * @param StreamInterface $stream Stream to read
|
|---|
| 299 | * @param int $maxLen Maximum number of bytes to read. Pass -1
|
|---|
| 300 | * to read the entire stream.
|
|---|
| 301 | * @return string
|
|---|
| 302 | * @throws \RuntimeException on error.
|
|---|
| 303 | */
|
|---|
| 304 | function copy_to_string(StreamInterface $stream, $maxLen = -1)
|
|---|
| 305 | {
|
|---|
| 306 | $buffer = '';
|
|---|
| 307 |
|
|---|
| 308 | if ($maxLen === -1) {
|
|---|
| 309 | while (!$stream->eof()) {
|
|---|
| 310 | $buf = $stream->read(1048576);
|
|---|
| 311 | // Using a loose equality here to match on '' and false.
|
|---|
| 312 | if ($buf == null) {
|
|---|
| 313 | break;
|
|---|
| 314 | }
|
|---|
| 315 | $buffer .= $buf;
|
|---|
| 316 | }
|
|---|
| 317 | return $buffer;
|
|---|
| 318 | }
|
|---|
| 319 |
|
|---|
| 320 | $len = 0;
|
|---|
| 321 | while (!$stream->eof() && $len < $maxLen) {
|
|---|
| 322 | $buf = $stream->read($maxLen - $len);
|
|---|
| 323 | // Using a loose equality here to match on '' and false.
|
|---|
| 324 | if ($buf == null) {
|
|---|
| 325 | break;
|
|---|
| 326 | }
|
|---|
| 327 | $buffer .= $buf;
|
|---|
| 328 | $len = strlen($buffer);
|
|---|
| 329 | }
|
|---|
| 330 |
|
|---|
| 331 | return $buffer;
|
|---|
| 332 | }
|
|---|
| 333 |
|
|---|
| 334 | /**
|
|---|
| 335 | * Copy the contents of a stream into another stream until the given number
|
|---|
| 336 | * of bytes have been read.
|
|---|
| 337 | *
|
|---|
| 338 | * @param StreamInterface $source Stream to read from
|
|---|
| 339 | * @param StreamInterface $dest Stream to write to
|
|---|
| 340 | * @param int $maxLen Maximum number of bytes to read. Pass -1
|
|---|
| 341 | * to read the entire stream.
|
|---|
| 342 | *
|
|---|
| 343 | * @throws \RuntimeException on error.
|
|---|
| 344 | */
|
|---|
| 345 | function copy_to_stream(
|
|---|
| 346 | StreamInterface $source,
|
|---|
| 347 | StreamInterface $dest,
|
|---|
| 348 | $maxLen = -1
|
|---|
| 349 | ) {
|
|---|
| 350 | if ($maxLen === -1) {
|
|---|
| 351 | while (!$source->eof()) {
|
|---|
| 352 | if (!$dest->write($source->read(1048576))) {
|
|---|
| 353 | break;
|
|---|
| 354 | }
|
|---|
| 355 | }
|
|---|
| 356 | return;
|
|---|
| 357 | }
|
|---|
| 358 |
|
|---|
| 359 | $bytes = 0;
|
|---|
| 360 | while (!$source->eof()) {
|
|---|
| 361 | $buf = $source->read($maxLen - $bytes);
|
|---|
| 362 | if (!($len = strlen($buf))) {
|
|---|
| 363 | break;
|
|---|
| 364 | }
|
|---|
| 365 | $bytes += $len;
|
|---|
| 366 | $dest->write($buf);
|
|---|
| 367 | if ($bytes == $maxLen) {
|
|---|
| 368 | break;
|
|---|
| 369 | }
|
|---|
| 370 | }
|
|---|
| 371 | }
|
|---|
| 372 |
|
|---|
| 373 | /**
|
|---|
| 374 | * Calculate a hash of a Stream
|
|---|
| 375 | *
|
|---|
| 376 | * @param StreamInterface $stream Stream to calculate the hash for
|
|---|
| 377 | * @param string $algo Hash algorithm (e.g. md5, crc32, etc)
|
|---|
| 378 | * @param bool $rawOutput Whether or not to use raw output
|
|---|
| 379 | *
|
|---|
| 380 | * @return string Returns the hash of the stream
|
|---|
| 381 | * @throws \RuntimeException on error.
|
|---|
| 382 | */
|
|---|
| 383 | function hash(
|
|---|
| 384 | StreamInterface $stream,
|
|---|
| 385 | $algo,
|
|---|
| 386 | $rawOutput = false
|
|---|
| 387 | ) {
|
|---|
| 388 | $pos = $stream->tell();
|
|---|
| 389 |
|
|---|
| 390 | if ($pos > 0) {
|
|---|
| 391 | $stream->rewind();
|
|---|
| 392 | }
|
|---|
| 393 |
|
|---|
| 394 | $ctx = hash_init($algo);
|
|---|
| 395 | while (!$stream->eof()) {
|
|---|
| 396 | hash_update($ctx, $stream->read(1048576));
|
|---|
| 397 | }
|
|---|
| 398 |
|
|---|
| 399 | $out = hash_final($ctx, (bool) $rawOutput);
|
|---|
| 400 | $stream->seek($pos);
|
|---|
| 401 |
|
|---|
| 402 | return $out;
|
|---|
| 403 | }
|
|---|
| 404 |
|
|---|
| 405 | /**
|
|---|
| 406 | * Read a line from the stream up to the maximum allowed buffer length
|
|---|
| 407 | *
|
|---|
| 408 | * @param StreamInterface $stream Stream to read from
|
|---|
| 409 | * @param int $maxLength Maximum buffer length
|
|---|
| 410 | *
|
|---|
| 411 | * @return string|bool
|
|---|
| 412 | */
|
|---|
| 413 | function readline(StreamInterface $stream, $maxLength = null)
|
|---|
| 414 | {
|
|---|
| 415 | $buffer = '';
|
|---|
| 416 | $size = 0;
|
|---|
| 417 |
|
|---|
| 418 | while (!$stream->eof()) {
|
|---|
| 419 | // Using a loose equality here to match on '' and false.
|
|---|
| 420 | if (null == ($byte = $stream->read(1))) {
|
|---|
| 421 | return $buffer;
|
|---|
| 422 | }
|
|---|
| 423 | $buffer .= $byte;
|
|---|
| 424 | // Break when a new line is found or the max length - 1 is reached
|
|---|
| 425 | if ($byte == PHP_EOL || ++$size == $maxLength - 1) {
|
|---|
| 426 | break;
|
|---|
| 427 | }
|
|---|
| 428 | }
|
|---|
| 429 |
|
|---|
| 430 | return $buffer;
|
|---|
| 431 | }
|
|---|
| 432 |
|
|---|
| 433 | /**
|
|---|
| 434 | * Parses a request message string into a request object.
|
|---|
| 435 | *
|
|---|
| 436 | * @param string $message Request message string.
|
|---|
| 437 | *
|
|---|
| 438 | * @return Request
|
|---|
| 439 | */
|
|---|
| 440 | function parse_request($message)
|
|---|
| 441 | {
|
|---|
| 442 | $data = _parse_message($message);
|
|---|
| 443 | $matches = [];
|
|---|
| 444 | if (!preg_match('/^[a-zA-Z]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) {
|
|---|
| 445 | throw new \InvalidArgumentException('Invalid request string');
|
|---|
| 446 | }
|
|---|
| 447 | $parts = explode(' ', $data['start-line'], 3);
|
|---|
| 448 | $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1';
|
|---|
| 449 |
|
|---|
| 450 | $request = new Request(
|
|---|
| 451 | $parts[0],
|
|---|
| 452 | $matches[1] === '/' ? _parse_request_uri($parts[1], $data['headers']) : $parts[1],
|
|---|
| 453 | $data['headers'],
|
|---|
| 454 | $data['body'],
|
|---|
| 455 | $version
|
|---|
| 456 | );
|
|---|
| 457 |
|
|---|
| 458 | return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);
|
|---|
| 459 | }
|
|---|
| 460 |
|
|---|
| 461 | /**
|
|---|
| 462 | * Parses a response message string into a response object.
|
|---|
| 463 | *
|
|---|
| 464 | * @param string $message Response message string.
|
|---|
| 465 | *
|
|---|
| 466 | * @return Response
|
|---|
| 467 | */
|
|---|
| 468 | function parse_response($message)
|
|---|
| 469 | {
|
|---|
| 470 | $data = _parse_message($message);
|
|---|
| 471 | if (!preg_match('/^HTTP\/.* [0-9]{3} .*/', $data['start-line'])) {
|
|---|
| 472 | throw new \InvalidArgumentException('Invalid response string');
|
|---|
| 473 | }
|
|---|
| 474 | $parts = explode(' ', $data['start-line'], 3);
|
|---|
| 475 |
|
|---|
| 476 | return new Response(
|
|---|
| 477 | $parts[1],
|
|---|
| 478 | $data['headers'],
|
|---|
| 479 | $data['body'],
|
|---|
| 480 | explode('/', $parts[0])[1],
|
|---|
| 481 | isset($parts[2]) ? $parts[2] : null
|
|---|
| 482 | );
|
|---|
| 483 | }
|
|---|
| 484 |
|
|---|
| 485 | /**
|
|---|
| 486 | * Parse a query string into an associative array.
|
|---|
| 487 | *
|
|---|
| 488 | * If multiple values are found for the same key, the value of that key
|
|---|
| 489 | * value pair will become an array. This function does not parse nested
|
|---|
| 490 | * PHP style arrays into an associative array (e.g., foo[a]=1&foo[b]=2 will
|
|---|
| 491 | * be parsed into ['foo[a]' => '1', 'foo[b]' => '2']).
|
|---|
| 492 | *
|
|---|
| 493 | * @param string $str Query string to parse
|
|---|
| 494 | * @param bool|string $urlEncoding How the query string is encoded
|
|---|
| 495 | *
|
|---|
| 496 | * @return array
|
|---|
| 497 | */
|
|---|
| 498 | function parse_query($str, $urlEncoding = true)
|
|---|
| 499 | {
|
|---|
| 500 | $result = [];
|
|---|
| 501 |
|
|---|
| 502 | if ($str === '') {
|
|---|
| 503 | return $result;
|
|---|
| 504 | }
|
|---|
| 505 |
|
|---|
| 506 | if ($urlEncoding === true) {
|
|---|
| 507 | $decoder = function ($value) {
|
|---|
| 508 | return rawurldecode(str_replace('+', ' ', $value));
|
|---|
| 509 | };
|
|---|
| 510 | } elseif ($urlEncoding == PHP_QUERY_RFC3986) {
|
|---|
| 511 | $decoder = 'rawurldecode';
|
|---|
| 512 | } elseif ($urlEncoding == PHP_QUERY_RFC1738) {
|
|---|
| 513 | $decoder = 'urldecode';
|
|---|
| 514 | } else {
|
|---|
| 515 | $decoder = function ($str) { return $str; };
|
|---|
| 516 | }
|
|---|
| 517 |
|
|---|
| 518 | foreach (explode('&', $str) as $kvp) {
|
|---|
| 519 | $parts = explode('=', $kvp, 2);
|
|---|
| 520 | $key = $decoder($parts[0]);
|
|---|
| 521 | $value = isset($parts[1]) ? $decoder($parts[1]) : null;
|
|---|
| 522 | if (!isset($result[$key])) {
|
|---|
| 523 | $result[$key] = $value;
|
|---|
| 524 | } else {
|
|---|
| 525 | if (!is_array($result[$key])) {
|
|---|
| 526 | $result[$key] = [$result[$key]];
|
|---|
| 527 | }
|
|---|
| 528 | $result[$key][] = $value;
|
|---|
| 529 | }
|
|---|
| 530 | }
|
|---|
| 531 |
|
|---|
| 532 | return $result;
|
|---|
| 533 | }
|
|---|
| 534 |
|
|---|
| 535 | /**
|
|---|
| 536 | * Build a query string from an array of key value pairs.
|
|---|
| 537 | *
|
|---|
| 538 | * This function can use the return value of parseQuery() to build a query
|
|---|
| 539 | * string. This function does not modify the provided keys when an array is
|
|---|
| 540 | * encountered (like http_build_query would).
|
|---|
| 541 | *
|
|---|
| 542 | * @param array $params Query string parameters.
|
|---|
| 543 | * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986
|
|---|
| 544 | * to encode using RFC3986, or PHP_QUERY_RFC1738
|
|---|
| 545 | * to encode using RFC1738.
|
|---|
| 546 | * @return string
|
|---|
| 547 | */
|
|---|
| 548 | function build_query(array $params, $encoding = PHP_QUERY_RFC3986)
|
|---|
| 549 | {
|
|---|
| 550 | if (!$params) {
|
|---|
| 551 | return '';
|
|---|
| 552 | }
|
|---|
| 553 |
|
|---|
| 554 | if ($encoding === false) {
|
|---|
| 555 | $encoder = function ($str) { return $str; };
|
|---|
| 556 | } elseif ($encoding == PHP_QUERY_RFC3986) {
|
|---|
| 557 | $encoder = 'rawurlencode';
|
|---|
| 558 | } elseif ($encoding == PHP_QUERY_RFC1738) {
|
|---|
| 559 | $encoder = 'urlencode';
|
|---|
| 560 | } else {
|
|---|
| 561 | throw new \InvalidArgumentException('Invalid type');
|
|---|
| 562 | }
|
|---|
| 563 |
|
|---|
| 564 | $qs = '';
|
|---|
| 565 | foreach ($params as $k => $v) {
|
|---|
| 566 | $k = $encoder($k);
|
|---|
| 567 | if (!is_array($v)) {
|
|---|
| 568 | $qs .= $k;
|
|---|
| 569 | if ($v !== null) {
|
|---|
| 570 | $qs .= '=' . $encoder($v);
|
|---|
| 571 | }
|
|---|
| 572 | $qs .= '&';
|
|---|
| 573 | } else {
|
|---|
| 574 | foreach ($v as $vv) {
|
|---|
| 575 | $qs .= $k;
|
|---|
| 576 | if ($vv !== null) {
|
|---|
| 577 | $qs .= '=' . $encoder($vv);
|
|---|
| 578 | }
|
|---|
| 579 | $qs .= '&';
|
|---|
| 580 | }
|
|---|
| 581 | }
|
|---|
| 582 | }
|
|---|
| 583 |
|
|---|
| 584 | return $qs ? (string) substr($qs, 0, -1) : '';
|
|---|
| 585 | }
|
|---|
| 586 |
|
|---|
| 587 | /**
|
|---|
| 588 | * Determines the mimetype of a file by looking at its extension.
|
|---|
| 589 | *
|
|---|
| 590 | * @param $filename
|
|---|
| 591 | *
|
|---|
| 592 | * @return null|string
|
|---|
| 593 | */
|
|---|
| 594 | function mimetype_from_filename($filename)
|
|---|
| 595 | {
|
|---|
| 596 | return mimetype_from_extension(pathinfo($filename, PATHINFO_EXTENSION));
|
|---|
| 597 | }
|
|---|
| 598 |
|
|---|
| 599 | /**
|
|---|
| 600 | * Maps a file extensions to a mimetype.
|
|---|
| 601 | *
|
|---|
| 602 | * @param $extension string The file extension.
|
|---|
| 603 | *
|
|---|
| 604 | * @return string|null
|
|---|
| 605 | * @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types
|
|---|
| 606 | */
|
|---|
| 607 | function mimetype_from_extension($extension)
|
|---|
| 608 | {
|
|---|
| 609 | static $mimetypes = [
|
|---|
| 610 | '7z' => 'application/x-7z-compressed',
|
|---|
| 611 | 'aac' => 'audio/x-aac',
|
|---|
| 612 | 'ai' => 'application/postscript',
|
|---|
| 613 | 'aif' => 'audio/x-aiff',
|
|---|
| 614 | 'asc' => 'text/plain',
|
|---|
| 615 | 'asf' => 'video/x-ms-asf',
|
|---|
| 616 | 'atom' => 'application/atom+xml',
|
|---|
| 617 | 'avi' => 'video/x-msvideo',
|
|---|
| 618 | 'bmp' => 'image/bmp',
|
|---|
| 619 | 'bz2' => 'application/x-bzip2',
|
|---|
| 620 | 'cer' => 'application/pkix-cert',
|
|---|
| 621 | 'crl' => 'application/pkix-crl',
|
|---|
| 622 | 'crt' => 'application/x-x509-ca-cert',
|
|---|
| 623 | 'css' => 'text/css',
|
|---|
| 624 | 'csv' => 'text/csv',
|
|---|
| 625 | 'cu' => 'application/cu-seeme',
|
|---|
| 626 | 'deb' => 'application/x-debian-package',
|
|---|
| 627 | 'doc' => 'application/msword',
|
|---|
| 628 | 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|---|
| 629 | 'dvi' => 'application/x-dvi',
|
|---|
| 630 | 'eot' => 'application/vnd.ms-fontobject',
|
|---|
| 631 | 'eps' => 'application/postscript',
|
|---|
| 632 | 'epub' => 'application/epub+zip',
|
|---|
| 633 | 'etx' => 'text/x-setext',
|
|---|
| 634 | 'flac' => 'audio/flac',
|
|---|
| 635 | 'flv' => 'video/x-flv',
|
|---|
| 636 | 'gif' => 'image/gif',
|
|---|
| 637 | 'gz' => 'application/gzip',
|
|---|
| 638 | 'htm' => 'text/html',
|
|---|
| 639 | 'html' => 'text/html',
|
|---|
| 640 | 'ico' => 'image/x-icon',
|
|---|
| 641 | 'ics' => 'text/calendar',
|
|---|
| 642 | 'ini' => 'text/plain',
|
|---|
| 643 | 'iso' => 'application/x-iso9660-image',
|
|---|
| 644 | 'jar' => 'application/java-archive',
|
|---|
| 645 | 'jpe' => 'image/jpeg',
|
|---|
| 646 | 'jpeg' => 'image/jpeg',
|
|---|
| 647 | 'jpg' => 'image/jpeg',
|
|---|
| 648 | 'js' => 'text/javascript',
|
|---|
| 649 | 'json' => 'application/json',
|
|---|
| 650 | 'latex' => 'application/x-latex',
|
|---|
| 651 | 'log' => 'text/plain',
|
|---|
| 652 | 'm4a' => 'audio/mp4',
|
|---|
| 653 | 'm4v' => 'video/mp4',
|
|---|
| 654 | 'mid' => 'audio/midi',
|
|---|
| 655 | 'midi' => 'audio/midi',
|
|---|
| 656 | 'mov' => 'video/quicktime',
|
|---|
| 657 | 'mp3' => 'audio/mpeg',
|
|---|
| 658 | 'mp4' => 'video/mp4',
|
|---|
| 659 | 'mp4a' => 'audio/mp4',
|
|---|
| 660 | 'mp4v' => 'video/mp4',
|
|---|
| 661 | 'mpe' => 'video/mpeg',
|
|---|
| 662 | 'mpeg' => 'video/mpeg',
|
|---|
| 663 | 'mpg' => 'video/mpeg',
|
|---|
| 664 | 'mpg4' => 'video/mp4',
|
|---|
| 665 | 'oga' => 'audio/ogg',
|
|---|
| 666 | 'ogg' => 'audio/ogg',
|
|---|
| 667 | 'ogv' => 'video/ogg',
|
|---|
| 668 | 'ogx' => 'application/ogg',
|
|---|
| 669 | 'pbm' => 'image/x-portable-bitmap',
|
|---|
| 670 | 'pdf' => 'application/pdf',
|
|---|
| 671 | 'pgm' => 'image/x-portable-graymap',
|
|---|
| 672 | 'png' => 'image/png',
|
|---|
| 673 | 'pnm' => 'image/x-portable-anymap',
|
|---|
| 674 | 'ppm' => 'image/x-portable-pixmap',
|
|---|
| 675 | 'ppt' => 'application/vnd.ms-powerpoint',
|
|---|
| 676 | 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|---|
| 677 | 'ps' => 'application/postscript',
|
|---|
| 678 | 'qt' => 'video/quicktime',
|
|---|
| 679 | 'rar' => 'application/x-rar-compressed',
|
|---|
| 680 | 'ras' => 'image/x-cmu-raster',
|
|---|
| 681 | 'rss' => 'application/rss+xml',
|
|---|
| 682 | 'rtf' => 'application/rtf',
|
|---|
| 683 | 'sgm' => 'text/sgml',
|
|---|
| 684 | 'sgml' => 'text/sgml',
|
|---|
| 685 | 'svg' => 'image/svg+xml',
|
|---|
| 686 | 'swf' => 'application/x-shockwave-flash',
|
|---|
| 687 | 'tar' => 'application/x-tar',
|
|---|
| 688 | 'tif' => 'image/tiff',
|
|---|
| 689 | 'tiff' => 'image/tiff',
|
|---|
| 690 | 'torrent' => 'application/x-bittorrent',
|
|---|
| 691 | 'ttf' => 'application/x-font-ttf',
|
|---|
| 692 | 'txt' => 'text/plain',
|
|---|
| 693 | 'wav' => 'audio/x-wav',
|
|---|
| 694 | 'webm' => 'video/webm',
|
|---|
| 695 | 'wma' => 'audio/x-ms-wma',
|
|---|
| 696 | 'wmv' => 'video/x-ms-wmv',
|
|---|
| 697 | 'woff' => 'application/x-font-woff',
|
|---|
| 698 | 'wsdl' => 'application/wsdl+xml',
|
|---|
| 699 | 'xbm' => 'image/x-xbitmap',
|
|---|
| 700 | 'xls' => 'application/vnd.ms-excel',
|
|---|
| 701 | 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|---|
| 702 | 'xml' => 'application/xml',
|
|---|
| 703 | 'xpm' => 'image/x-xpixmap',
|
|---|
| 704 | 'xwd' => 'image/x-xwindowdump',
|
|---|
| 705 | 'yaml' => 'text/yaml',
|
|---|
| 706 | 'yml' => 'text/yaml',
|
|---|
| 707 | 'zip' => 'application/zip',
|
|---|
| 708 | ];
|
|---|
| 709 |
|
|---|
| 710 | $extension = strtolower($extension);
|
|---|
| 711 |
|
|---|
| 712 | return isset($mimetypes[$extension])
|
|---|
| 713 | ? $mimetypes[$extension]
|
|---|
| 714 | : null;
|
|---|
| 715 | }
|
|---|
| 716 |
|
|---|
| 717 | /**
|
|---|
| 718 | * Parses an HTTP message into an associative array.
|
|---|
| 719 | *
|
|---|
| 720 | * The array contains the "start-line" key containing the start line of
|
|---|
| 721 | * the message, "headers" key containing an associative array of header
|
|---|
| 722 | * array values, and a "body" key containing the body of the message.
|
|---|
| 723 | *
|
|---|
| 724 | * @param string $message HTTP request or response to parse.
|
|---|
| 725 | *
|
|---|
| 726 | * @return array
|
|---|
| 727 | * @internal
|
|---|
| 728 | */
|
|---|
| 729 | function _parse_message($message)
|
|---|
| 730 | {
|
|---|
| 731 | if (!$message) {
|
|---|
| 732 | throw new \InvalidArgumentException('Invalid message');
|
|---|
| 733 | }
|
|---|
| 734 |
|
|---|
| 735 | // Iterate over each line in the message, accounting for line endings
|
|---|
| 736 | $lines = preg_split('/(\\r?\\n)/', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
|
|---|
| 737 | $result = ['start-line' => array_shift($lines), 'headers' => [], 'body' => ''];
|
|---|
| 738 | array_shift($lines);
|
|---|
| 739 |
|
|---|
| 740 | for ($i = 0, $totalLines = count($lines); $i < $totalLines; $i += 2) {
|
|---|
| 741 | $line = $lines[$i];
|
|---|
| 742 | // If two line breaks were encountered, then this is the end of body
|
|---|
| 743 | if (empty($line)) {
|
|---|
| 744 | if ($i < $totalLines - 1) {
|
|---|
| 745 | $result['body'] = implode('', array_slice($lines, $i + 2));
|
|---|
| 746 | }
|
|---|
| 747 | break;
|
|---|
| 748 | }
|
|---|
| 749 | if (strpos($line, ':')) {
|
|---|
| 750 | $parts = explode(':', $line, 2);
|
|---|
| 751 | $key = trim($parts[0]);
|
|---|
| 752 | $value = isset($parts[1]) ? trim($parts[1]) : '';
|
|---|
| 753 | $result['headers'][$key][] = $value;
|
|---|
| 754 | }
|
|---|
| 755 | }
|
|---|
| 756 |
|
|---|
| 757 | return $result;
|
|---|
| 758 | }
|
|---|
| 759 |
|
|---|
| 760 | /**
|
|---|
| 761 | * Constructs a URI for an HTTP request message.
|
|---|
| 762 | *
|
|---|
| 763 | * @param string $path Path from the start-line
|
|---|
| 764 | * @param array $headers Array of headers (each value an array).
|
|---|
| 765 | *
|
|---|
| 766 | * @return string
|
|---|
| 767 | * @internal
|
|---|
| 768 | */
|
|---|
| 769 | function _parse_request_uri($path, array $headers)
|
|---|
| 770 | {
|
|---|
| 771 | $hostKey = array_filter(array_keys($headers), function ($k) {
|
|---|
| 772 | return strtolower($k) === 'host';
|
|---|
| 773 | });
|
|---|
| 774 |
|
|---|
| 775 | // If no host is found, then a full URI cannot be constructed.
|
|---|
| 776 | if (!$hostKey) {
|
|---|
| 777 | return $path;
|
|---|
| 778 | }
|
|---|
| 779 |
|
|---|
| 780 | $host = $headers[reset($hostKey)][0];
|
|---|
| 781 | $scheme = substr($host, -4) === ':443' ? 'https' : 'http';
|
|---|
| 782 |
|
|---|
| 783 | return $scheme . '://' . $host . '/' . ltrim($path, '/');
|
|---|
| 784 | }
|
|---|
| 785 |
|
|---|
| 786 | /** @internal */
|
|---|
| 787 | function _caseless_remove($keys, array $data)
|
|---|
| 788 | {
|
|---|
| 789 | $result = [];
|
|---|
| 790 |
|
|---|
| 791 | foreach ($keys as &$key) {
|
|---|
| 792 | $key = strtolower($key);
|
|---|
| 793 | }
|
|---|
| 794 |
|
|---|
| 795 | foreach ($data as $k => $v) {
|
|---|
| 796 | if (!in_array(strtolower($k), $keys)) {
|
|---|
| 797 | $result[$k] = $v;
|
|---|
| 798 | }
|
|---|
| 799 | }
|
|---|
| 800 |
|
|---|
| 801 | return $result;
|
|---|
| 802 | }
|
|---|