Chris@0: getMethod() . ' ' Chris@0: . $message->getRequestTarget()) Chris@0: . ' HTTP/' . $message->getProtocolVersion(); Chris@0: if (!$message->hasHeader('host')) { Chris@0: $msg .= "\r\nHost: " . $message->getUri()->getHost(); Chris@0: } Chris@0: } elseif ($message instanceof ResponseInterface) { Chris@0: $msg = 'HTTP/' . $message->getProtocolVersion() . ' ' Chris@0: . $message->getStatusCode() . ' ' Chris@0: . $message->getReasonPhrase(); Chris@0: } else { Chris@0: throw new \InvalidArgumentException('Unknown message type'); Chris@0: } Chris@0: Chris@0: foreach ($message->getHeaders() as $name => $values) { Chris@0: $msg .= "\r\n{$name}: " . implode(', ', $values); Chris@0: } Chris@0: Chris@0: return "{$msg}\r\n\r\n" . $message->getBody(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns a UriInterface for the given value. Chris@0: * Chris@0: * This function accepts a string or {@see Psr\Http\Message\UriInterface} and Chris@0: * returns a UriInterface for the given value. If the value is already a Chris@0: * `UriInterface`, it is returned as-is. Chris@0: * Chris@0: * @param string|UriInterface $uri Chris@0: * Chris@0: * @return UriInterface Chris@0: * @throws \InvalidArgumentException Chris@0: */ Chris@0: function uri_for($uri) Chris@0: { Chris@0: if ($uri instanceof UriInterface) { Chris@0: return $uri; Chris@0: } elseif (is_string($uri)) { Chris@0: return new Uri($uri); Chris@0: } Chris@0: Chris@0: throw new \InvalidArgumentException('URI must be a string or UriInterface'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Create a new stream based on the input type. Chris@0: * Chris@0: * Options is an associative array that can contain the following keys: Chris@0: * - metadata: Array of custom metadata. Chris@0: * - size: Size of the stream. Chris@0: * Chris@17: * @param resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource Entity body data Chris@17: * @param array $options Additional options Chris@0: * Chris@17: * @return StreamInterface Chris@0: * @throws \InvalidArgumentException if the $resource arg is not valid. Chris@0: */ Chris@0: function stream_for($resource = '', array $options = []) Chris@0: { Chris@0: if (is_scalar($resource)) { Chris@0: $stream = fopen('php://temp', 'r+'); Chris@0: if ($resource !== '') { Chris@0: fwrite($stream, $resource); Chris@0: fseek($stream, 0); Chris@0: } Chris@0: return new Stream($stream, $options); Chris@0: } Chris@0: Chris@0: switch (gettype($resource)) { Chris@0: case 'resource': Chris@0: return new Stream($resource, $options); Chris@0: case 'object': Chris@0: if ($resource instanceof StreamInterface) { Chris@0: return $resource; Chris@0: } elseif ($resource instanceof \Iterator) { Chris@0: return new PumpStream(function () use ($resource) { Chris@0: if (!$resource->valid()) { Chris@0: return false; Chris@0: } Chris@0: $result = $resource->current(); Chris@0: $resource->next(); Chris@0: return $result; Chris@0: }, $options); Chris@0: } elseif (method_exists($resource, '__toString')) { Chris@0: return stream_for((string) $resource, $options); Chris@0: } Chris@0: break; Chris@0: case 'NULL': Chris@0: return new Stream(fopen('php://temp', 'r+'), $options); Chris@0: } Chris@0: Chris@0: if (is_callable($resource)) { Chris@0: return new PumpStream($resource, $options); Chris@0: } Chris@0: Chris@0: throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Parse an array of header values containing ";" separated data into an Chris@0: * array of associative arrays representing the header key value pair Chris@0: * data of the header. When a parameter does not contain a value, but just Chris@0: * contains a key, this function will inject a key with a '' string value. Chris@0: * Chris@0: * @param string|array $header Header to parse into components. Chris@0: * Chris@0: * @return array Returns the parsed header values. Chris@0: */ Chris@0: function parse_header($header) Chris@0: { Chris@0: static $trimmed = "\"' \n\t\r"; Chris@0: $params = $matches = []; Chris@0: Chris@0: foreach (normalize_header($header) as $val) { Chris@0: $part = []; Chris@0: foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) { Chris@0: if (preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) { Chris@0: $m = $matches[0]; Chris@0: if (isset($m[1])) { Chris@0: $part[trim($m[0], $trimmed)] = trim($m[1], $trimmed); Chris@0: } else { Chris@0: $part[] = trim($m[0], $trimmed); Chris@0: } Chris@0: } Chris@0: } Chris@0: if ($part) { Chris@0: $params[] = $part; Chris@0: } Chris@0: } Chris@0: Chris@0: return $params; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Converts an array of header values that may contain comma separated Chris@0: * headers into an array of headers with no comma separated values. Chris@0: * Chris@0: * @param string|array $header Header to normalize. Chris@0: * Chris@0: * @return array Returns the normalized header field values. Chris@0: */ Chris@0: function normalize_header($header) Chris@0: { Chris@0: if (!is_array($header)) { Chris@0: return array_map('trim', explode(',', $header)); Chris@0: } Chris@0: Chris@0: $result = []; Chris@0: foreach ($header as $value) { Chris@0: foreach ((array) $value as $v) { Chris@0: if (strpos($v, ',') === false) { Chris@0: $result[] = $v; Chris@0: continue; Chris@0: } Chris@0: foreach (preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $v) as $vv) { Chris@0: $result[] = trim($vv); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: return $result; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Clone and modify a request with the given changes. Chris@0: * Chris@0: * The changes can be one of: Chris@0: * - method: (string) Changes the HTTP method. Chris@0: * - set_headers: (array) Sets the given headers. Chris@0: * - remove_headers: (array) Remove the given headers. Chris@0: * - body: (mixed) Sets the given body. Chris@0: * - uri: (UriInterface) Set the URI. Chris@0: * - query: (string) Set the query string value of the URI. Chris@0: * - version: (string) Set the protocol version. Chris@0: * Chris@0: * @param RequestInterface $request Request to clone and modify. Chris@0: * @param array $changes Changes to apply. Chris@0: * Chris@0: * @return RequestInterface Chris@0: */ Chris@0: function modify_request(RequestInterface $request, array $changes) Chris@0: { Chris@0: if (!$changes) { Chris@0: return $request; Chris@0: } Chris@0: Chris@0: $headers = $request->getHeaders(); Chris@0: Chris@0: if (!isset($changes['uri'])) { Chris@0: $uri = $request->getUri(); Chris@0: } else { Chris@0: // Remove the host header if one is on the URI Chris@0: if ($host = $changes['uri']->getHost()) { Chris@0: $changes['set_headers']['Host'] = $host; Chris@0: Chris@0: if ($port = $changes['uri']->getPort()) { Chris@0: $standardPorts = ['http' => 80, 'https' => 443]; Chris@0: $scheme = $changes['uri']->getScheme(); Chris@0: if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) { Chris@0: $changes['set_headers']['Host'] .= ':'.$port; Chris@0: } Chris@0: } Chris@0: } Chris@0: $uri = $changes['uri']; Chris@0: } Chris@0: Chris@0: if (!empty($changes['remove_headers'])) { Chris@0: $headers = _caseless_remove($changes['remove_headers'], $headers); Chris@0: } Chris@0: Chris@0: if (!empty($changes['set_headers'])) { Chris@0: $headers = _caseless_remove(array_keys($changes['set_headers']), $headers); Chris@0: $headers = $changes['set_headers'] + $headers; Chris@0: } Chris@0: Chris@0: if (isset($changes['query'])) { Chris@0: $uri = $uri->withQuery($changes['query']); Chris@0: } Chris@0: Chris@0: if ($request instanceof ServerRequestInterface) { Chris@17: return (new ServerRequest( Chris@0: isset($changes['method']) ? $changes['method'] : $request->getMethod(), Chris@0: $uri, Chris@0: $headers, Chris@0: isset($changes['body']) ? $changes['body'] : $request->getBody(), Chris@0: isset($changes['version']) Chris@0: ? $changes['version'] Chris@0: : $request->getProtocolVersion(), Chris@0: $request->getServerParams() Chris@17: )) Chris@17: ->withParsedBody($request->getParsedBody()) Chris@17: ->withQueryParams($request->getQueryParams()) Chris@17: ->withCookieParams($request->getCookieParams()) Chris@17: ->withUploadedFiles($request->getUploadedFiles()); Chris@0: } Chris@0: Chris@0: return new Request( Chris@0: isset($changes['method']) ? $changes['method'] : $request->getMethod(), Chris@0: $uri, Chris@0: $headers, Chris@0: isset($changes['body']) ? $changes['body'] : $request->getBody(), Chris@0: isset($changes['version']) Chris@0: ? $changes['version'] Chris@0: : $request->getProtocolVersion() Chris@0: ); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Attempts to rewind a message body and throws an exception on failure. Chris@0: * Chris@0: * The body of the message will only be rewound if a call to `tell()` returns a Chris@0: * value other than `0`. Chris@0: * Chris@0: * @param MessageInterface $message Message to rewind Chris@0: * Chris@0: * @throws \RuntimeException Chris@0: */ Chris@0: function rewind_body(MessageInterface $message) Chris@0: { Chris@0: $body = $message->getBody(); Chris@0: Chris@0: if ($body->tell()) { Chris@0: $body->rewind(); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Safely opens a PHP stream resource using a filename. Chris@0: * Chris@0: * When fopen fails, PHP normally raises a warning. This function adds an Chris@0: * error handler that checks for errors and throws an exception instead. Chris@0: * Chris@0: * @param string $filename File to open Chris@0: * @param string $mode Mode used to open the file Chris@0: * Chris@0: * @return resource Chris@0: * @throws \RuntimeException if the file cannot be opened Chris@0: */ Chris@0: function try_fopen($filename, $mode) Chris@0: { Chris@0: $ex = null; Chris@0: set_error_handler(function () use ($filename, $mode, &$ex) { Chris@0: $ex = new \RuntimeException(sprintf( Chris@0: 'Unable to open %s using mode %s: %s', Chris@0: $filename, Chris@0: $mode, Chris@0: func_get_args()[1] Chris@0: )); Chris@0: }); Chris@0: Chris@0: $handle = fopen($filename, $mode); Chris@0: restore_error_handler(); Chris@0: Chris@0: if ($ex) { Chris@0: /** @var $ex \RuntimeException */ Chris@0: throw $ex; Chris@0: } Chris@0: Chris@0: return $handle; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Copy the contents of a stream into a string until the given number of Chris@0: * bytes have been read. Chris@0: * Chris@0: * @param StreamInterface $stream Stream to read Chris@0: * @param int $maxLen Maximum number of bytes to read. Pass -1 Chris@0: * to read the entire stream. Chris@0: * @return string Chris@0: * @throws \RuntimeException on error. Chris@0: */ Chris@0: function copy_to_string(StreamInterface $stream, $maxLen = -1) Chris@0: { Chris@0: $buffer = ''; Chris@0: Chris@0: if ($maxLen === -1) { Chris@0: while (!$stream->eof()) { Chris@0: $buf = $stream->read(1048576); Chris@0: // Using a loose equality here to match on '' and false. Chris@0: if ($buf == null) { Chris@0: break; Chris@0: } Chris@0: $buffer .= $buf; Chris@0: } Chris@0: return $buffer; Chris@0: } Chris@0: Chris@0: $len = 0; Chris@0: while (!$stream->eof() && $len < $maxLen) { Chris@0: $buf = $stream->read($maxLen - $len); Chris@0: // Using a loose equality here to match on '' and false. Chris@0: if ($buf == null) { Chris@0: break; Chris@0: } Chris@0: $buffer .= $buf; Chris@0: $len = strlen($buffer); Chris@0: } Chris@0: Chris@0: return $buffer; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Copy the contents of a stream into another stream until the given number Chris@0: * of bytes have been read. Chris@0: * Chris@0: * @param StreamInterface $source Stream to read from Chris@0: * @param StreamInterface $dest Stream to write to Chris@0: * @param int $maxLen Maximum number of bytes to read. Pass -1 Chris@0: * to read the entire stream. Chris@0: * Chris@0: * @throws \RuntimeException on error. Chris@0: */ Chris@0: function copy_to_stream( Chris@0: StreamInterface $source, Chris@0: StreamInterface $dest, Chris@0: $maxLen = -1 Chris@0: ) { Chris@0: $bufferSize = 8192; Chris@0: Chris@0: if ($maxLen === -1) { Chris@0: while (!$source->eof()) { Chris@0: if (!$dest->write($source->read($bufferSize))) { Chris@0: break; Chris@0: } Chris@0: } Chris@0: } else { Chris@0: $remaining = $maxLen; Chris@0: while ($remaining > 0 && !$source->eof()) { Chris@0: $buf = $source->read(min($bufferSize, $remaining)); Chris@0: $len = strlen($buf); Chris@0: if (!$len) { Chris@0: break; Chris@0: } Chris@0: $remaining -= $len; Chris@0: $dest->write($buf); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Calculate a hash of a Stream Chris@0: * Chris@0: * @param StreamInterface $stream Stream to calculate the hash for Chris@0: * @param string $algo Hash algorithm (e.g. md5, crc32, etc) Chris@0: * @param bool $rawOutput Whether or not to use raw output Chris@0: * Chris@0: * @return string Returns the hash of the stream Chris@0: * @throws \RuntimeException on error. Chris@0: */ Chris@0: function hash( Chris@0: StreamInterface $stream, Chris@0: $algo, Chris@0: $rawOutput = false Chris@0: ) { Chris@0: $pos = $stream->tell(); Chris@0: Chris@0: if ($pos > 0) { Chris@0: $stream->rewind(); Chris@0: } Chris@0: Chris@0: $ctx = hash_init($algo); Chris@0: while (!$stream->eof()) { Chris@0: hash_update($ctx, $stream->read(1048576)); Chris@0: } Chris@0: Chris@0: $out = hash_final($ctx, (bool) $rawOutput); Chris@0: $stream->seek($pos); Chris@0: Chris@0: return $out; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Read a line from the stream up to the maximum allowed buffer length Chris@0: * Chris@0: * @param StreamInterface $stream Stream to read from Chris@0: * @param int $maxLength Maximum buffer length Chris@0: * Chris@17: * @return string Chris@0: */ Chris@0: function readline(StreamInterface $stream, $maxLength = null) Chris@0: { Chris@0: $buffer = ''; Chris@0: $size = 0; Chris@0: Chris@0: while (!$stream->eof()) { Chris@0: // Using a loose equality here to match on '' and false. Chris@0: if (null == ($byte = $stream->read(1))) { Chris@0: return $buffer; Chris@0: } Chris@0: $buffer .= $byte; Chris@0: // Break when a new line is found or the max length - 1 is reached Chris@0: if ($byte === "\n" || ++$size === $maxLength - 1) { Chris@0: break; Chris@0: } Chris@0: } Chris@0: Chris@0: return $buffer; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Parses a request message string into a request object. Chris@0: * Chris@0: * @param string $message Request message string. Chris@0: * Chris@0: * @return Request Chris@0: */ Chris@0: function parse_request($message) Chris@0: { Chris@0: $data = _parse_message($message); Chris@0: $matches = []; Chris@0: if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) { Chris@0: throw new \InvalidArgumentException('Invalid request string'); Chris@0: } Chris@0: $parts = explode(' ', $data['start-line'], 3); Chris@0: $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1'; Chris@0: Chris@0: $request = new Request( Chris@0: $parts[0], Chris@0: $matches[1] === '/' ? _parse_request_uri($parts[1], $data['headers']) : $parts[1], Chris@0: $data['headers'], Chris@0: $data['body'], Chris@0: $version Chris@0: ); Chris@0: Chris@0: return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Parses a response message string into a response object. Chris@0: * Chris@0: * @param string $message Response message string. Chris@0: * Chris@0: * @return Response Chris@0: */ Chris@0: function parse_response($message) Chris@0: { Chris@0: $data = _parse_message($message); Chris@0: // According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space Chris@0: // between status-code and reason-phrase is required. But browsers accept Chris@0: // responses without space and reason as well. Chris@0: if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) { Chris@17: throw new \InvalidArgumentException('Invalid response string: ' . $data['start-line']); Chris@0: } Chris@0: $parts = explode(' ', $data['start-line'], 3); Chris@0: Chris@0: return new Response( Chris@0: $parts[1], Chris@0: $data['headers'], Chris@0: $data['body'], Chris@0: explode('/', $parts[0])[1], Chris@0: isset($parts[2]) ? $parts[2] : null Chris@0: ); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Parse a query string into an associative array. Chris@0: * Chris@0: * If multiple values are found for the same key, the value of that key Chris@0: * value pair will become an array. This function does not parse nested Chris@0: * PHP style arrays into an associative array (e.g., foo[a]=1&foo[b]=2 will Chris@0: * be parsed into ['foo[a]' => '1', 'foo[b]' => '2']). Chris@0: * Chris@17: * @param string $str Query string to parse Chris@17: * @param int|bool $urlEncoding How the query string is encoded Chris@0: * Chris@0: * @return array Chris@0: */ Chris@0: function parse_query($str, $urlEncoding = true) Chris@0: { Chris@0: $result = []; Chris@0: Chris@0: if ($str === '') { Chris@0: return $result; Chris@0: } Chris@0: Chris@0: if ($urlEncoding === true) { Chris@0: $decoder = function ($value) { Chris@0: return rawurldecode(str_replace('+', ' ', $value)); Chris@0: }; Chris@17: } elseif ($urlEncoding === PHP_QUERY_RFC3986) { Chris@0: $decoder = 'rawurldecode'; Chris@17: } elseif ($urlEncoding === PHP_QUERY_RFC1738) { Chris@0: $decoder = 'urldecode'; Chris@0: } else { Chris@0: $decoder = function ($str) { return $str; }; Chris@0: } Chris@0: Chris@0: foreach (explode('&', $str) as $kvp) { Chris@0: $parts = explode('=', $kvp, 2); Chris@0: $key = $decoder($parts[0]); Chris@0: $value = isset($parts[1]) ? $decoder($parts[1]) : null; Chris@0: if (!isset($result[$key])) { Chris@0: $result[$key] = $value; Chris@0: } else { Chris@0: if (!is_array($result[$key])) { Chris@0: $result[$key] = [$result[$key]]; Chris@0: } Chris@0: $result[$key][] = $value; Chris@0: } Chris@0: } Chris@0: Chris@0: return $result; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Build a query string from an array of key value pairs. Chris@0: * Chris@0: * This function can use the return value of parse_query() to build a query Chris@0: * string. This function does not modify the provided keys when an array is Chris@0: * encountered (like http_build_query would). Chris@0: * Chris@0: * @param array $params Query string parameters. Chris@0: * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 Chris@0: * to encode using RFC3986, or PHP_QUERY_RFC1738 Chris@0: * to encode using RFC1738. Chris@0: * @return string Chris@0: */ Chris@0: function build_query(array $params, $encoding = PHP_QUERY_RFC3986) Chris@0: { Chris@0: if (!$params) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: if ($encoding === false) { Chris@0: $encoder = function ($str) { return $str; }; Chris@0: } elseif ($encoding === PHP_QUERY_RFC3986) { Chris@0: $encoder = 'rawurlencode'; Chris@0: } elseif ($encoding === PHP_QUERY_RFC1738) { Chris@0: $encoder = 'urlencode'; Chris@0: } else { Chris@0: throw new \InvalidArgumentException('Invalid type'); Chris@0: } Chris@0: Chris@0: $qs = ''; Chris@0: foreach ($params as $k => $v) { Chris@0: $k = $encoder($k); Chris@0: if (!is_array($v)) { Chris@0: $qs .= $k; Chris@0: if ($v !== null) { Chris@0: $qs .= '=' . $encoder($v); Chris@0: } Chris@0: $qs .= '&'; Chris@0: } else { Chris@0: foreach ($v as $vv) { Chris@0: $qs .= $k; Chris@0: if ($vv !== null) { Chris@0: $qs .= '=' . $encoder($vv); Chris@0: } Chris@0: $qs .= '&'; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: return $qs ? (string) substr($qs, 0, -1) : ''; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Determines the mimetype of a file by looking at its extension. Chris@0: * Chris@0: * @param $filename Chris@0: * Chris@0: * @return null|string Chris@0: */ Chris@0: function mimetype_from_filename($filename) Chris@0: { Chris@0: return mimetype_from_extension(pathinfo($filename, PATHINFO_EXTENSION)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Maps a file extensions to a mimetype. Chris@0: * Chris@0: * @param $extension string The file extension. Chris@0: * Chris@0: * @return string|null Chris@0: * @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types Chris@0: */ Chris@0: function mimetype_from_extension($extension) Chris@0: { Chris@0: static $mimetypes = [ Chris@17: '3gp' => 'video/3gpp', Chris@0: '7z' => 'application/x-7z-compressed', Chris@0: 'aac' => 'audio/x-aac', Chris@0: 'ai' => 'application/postscript', Chris@0: 'aif' => 'audio/x-aiff', Chris@0: 'asc' => 'text/plain', Chris@0: 'asf' => 'video/x-ms-asf', Chris@0: 'atom' => 'application/atom+xml', Chris@0: 'avi' => 'video/x-msvideo', Chris@0: 'bmp' => 'image/bmp', Chris@0: 'bz2' => 'application/x-bzip2', Chris@0: 'cer' => 'application/pkix-cert', Chris@0: 'crl' => 'application/pkix-crl', Chris@0: 'crt' => 'application/x-x509-ca-cert', Chris@0: 'css' => 'text/css', Chris@0: 'csv' => 'text/csv', Chris@0: 'cu' => 'application/cu-seeme', Chris@0: 'deb' => 'application/x-debian-package', Chris@0: 'doc' => 'application/msword', Chris@0: 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', Chris@0: 'dvi' => 'application/x-dvi', Chris@0: 'eot' => 'application/vnd.ms-fontobject', Chris@0: 'eps' => 'application/postscript', Chris@0: 'epub' => 'application/epub+zip', Chris@0: 'etx' => 'text/x-setext', Chris@0: 'flac' => 'audio/flac', Chris@0: 'flv' => 'video/x-flv', Chris@0: 'gif' => 'image/gif', Chris@0: 'gz' => 'application/gzip', Chris@0: 'htm' => 'text/html', Chris@0: 'html' => 'text/html', Chris@0: 'ico' => 'image/x-icon', Chris@0: 'ics' => 'text/calendar', Chris@0: 'ini' => 'text/plain', Chris@0: 'iso' => 'application/x-iso9660-image', Chris@0: 'jar' => 'application/java-archive', Chris@0: 'jpe' => 'image/jpeg', Chris@0: 'jpeg' => 'image/jpeg', Chris@0: 'jpg' => 'image/jpeg', Chris@0: 'js' => 'text/javascript', Chris@0: 'json' => 'application/json', Chris@0: 'latex' => 'application/x-latex', Chris@0: 'log' => 'text/plain', Chris@0: 'm4a' => 'audio/mp4', Chris@0: 'm4v' => 'video/mp4', Chris@0: 'mid' => 'audio/midi', Chris@0: 'midi' => 'audio/midi', Chris@0: 'mov' => 'video/quicktime', Chris@17: 'mkv' => 'video/x-matroska', Chris@0: 'mp3' => 'audio/mpeg', Chris@0: 'mp4' => 'video/mp4', Chris@0: 'mp4a' => 'audio/mp4', Chris@0: 'mp4v' => 'video/mp4', Chris@0: 'mpe' => 'video/mpeg', Chris@0: 'mpeg' => 'video/mpeg', Chris@0: 'mpg' => 'video/mpeg', Chris@0: 'mpg4' => 'video/mp4', Chris@0: 'oga' => 'audio/ogg', Chris@0: 'ogg' => 'audio/ogg', Chris@0: 'ogv' => 'video/ogg', Chris@0: 'ogx' => 'application/ogg', Chris@0: 'pbm' => 'image/x-portable-bitmap', Chris@0: 'pdf' => 'application/pdf', Chris@0: 'pgm' => 'image/x-portable-graymap', Chris@0: 'png' => 'image/png', Chris@0: 'pnm' => 'image/x-portable-anymap', Chris@0: 'ppm' => 'image/x-portable-pixmap', Chris@0: 'ppt' => 'application/vnd.ms-powerpoint', Chris@0: 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', Chris@0: 'ps' => 'application/postscript', Chris@0: 'qt' => 'video/quicktime', Chris@0: 'rar' => 'application/x-rar-compressed', Chris@0: 'ras' => 'image/x-cmu-raster', Chris@0: 'rss' => 'application/rss+xml', Chris@0: 'rtf' => 'application/rtf', Chris@0: 'sgm' => 'text/sgml', Chris@0: 'sgml' => 'text/sgml', Chris@0: 'svg' => 'image/svg+xml', Chris@0: 'swf' => 'application/x-shockwave-flash', Chris@0: 'tar' => 'application/x-tar', Chris@0: 'tif' => 'image/tiff', Chris@0: 'tiff' => 'image/tiff', Chris@0: 'torrent' => 'application/x-bittorrent', Chris@0: 'ttf' => 'application/x-font-ttf', Chris@0: 'txt' => 'text/plain', Chris@0: 'wav' => 'audio/x-wav', Chris@0: 'webm' => 'video/webm', Chris@0: 'wma' => 'audio/x-ms-wma', Chris@0: 'wmv' => 'video/x-ms-wmv', Chris@0: 'woff' => 'application/x-font-woff', Chris@0: 'wsdl' => 'application/wsdl+xml', Chris@0: 'xbm' => 'image/x-xbitmap', Chris@0: 'xls' => 'application/vnd.ms-excel', Chris@0: 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', Chris@0: 'xml' => 'application/xml', Chris@0: 'xpm' => 'image/x-xpixmap', Chris@0: 'xwd' => 'image/x-xwindowdump', Chris@0: 'yaml' => 'text/yaml', Chris@0: 'yml' => 'text/yaml', Chris@0: 'zip' => 'application/zip', Chris@0: ]; Chris@0: Chris@0: $extension = strtolower($extension); Chris@0: Chris@0: return isset($mimetypes[$extension]) Chris@0: ? $mimetypes[$extension] Chris@0: : null; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Parses an HTTP message into an associative array. Chris@0: * Chris@0: * The array contains the "start-line" key containing the start line of Chris@0: * the message, "headers" key containing an associative array of header Chris@0: * array values, and a "body" key containing the body of the message. Chris@0: * Chris@0: * @param string $message HTTP request or response to parse. Chris@0: * Chris@0: * @return array Chris@0: * @internal Chris@0: */ Chris@0: function _parse_message($message) Chris@0: { Chris@0: if (!$message) { Chris@0: throw new \InvalidArgumentException('Invalid message'); Chris@0: } Chris@0: Chris@17: $message = ltrim($message, "\r\n"); Chris@0: Chris@17: $messageParts = preg_split("/\r?\n\r?\n/", $message, 2); Chris@17: Chris@17: if ($messageParts === false || count($messageParts) !== 2) { Chris@17: throw new \InvalidArgumentException('Invalid message: Missing header delimiter'); Chris@0: } Chris@0: Chris@17: list($rawHeaders, $body) = $messageParts; Chris@17: $rawHeaders .= "\r\n"; // Put back the delimiter we split previously Chris@17: $headerParts = preg_split("/\r?\n/", $rawHeaders, 2); Chris@17: Chris@17: if ($headerParts === false || count($headerParts) !== 2) { Chris@17: throw new \InvalidArgumentException('Invalid message: Missing status line'); Chris@17: } Chris@17: Chris@17: list($startLine, $rawHeaders) = $headerParts; Chris@17: Chris@17: if (preg_match("/(?:^HTTP\/|^[A-Z]+ \S+ HTTP\/)(\d+(?:\.\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') { Chris@17: // Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0 Chris@17: $rawHeaders = preg_replace(Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders); Chris@17: } Chris@17: Chris@17: /** @var array[] $headerLines */ Chris@17: $count = preg_match_all(Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER); Chris@17: Chris@17: // If these aren't the same, then one line didn't match and there's an invalid header. Chris@17: if ($count !== substr_count($rawHeaders, "\n")) { Chris@17: // Folding is deprecated, see https://tools.ietf.org/html/rfc7230#section-3.2.4 Chris@17: if (preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) { Chris@17: throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding'); Chris@17: } Chris@17: Chris@17: throw new \InvalidArgumentException('Invalid header syntax'); Chris@17: } Chris@17: Chris@17: $headers = []; Chris@17: Chris@17: foreach ($headerLines as $headerLine) { Chris@17: $headers[$headerLine[1]][] = $headerLine[2]; Chris@17: } Chris@17: Chris@17: return [ Chris@17: 'start-line' => $startLine, Chris@17: 'headers' => $headers, Chris@17: 'body' => $body, Chris@17: ]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Constructs a URI for an HTTP request message. Chris@0: * Chris@0: * @param string $path Path from the start-line Chris@0: * @param array $headers Array of headers (each value an array). Chris@0: * Chris@0: * @return string Chris@0: * @internal Chris@0: */ Chris@0: function _parse_request_uri($path, array $headers) Chris@0: { Chris@0: $hostKey = array_filter(array_keys($headers), function ($k) { Chris@0: return strtolower($k) === 'host'; Chris@0: }); Chris@0: Chris@0: // If no host is found, then a full URI cannot be constructed. Chris@0: if (!$hostKey) { Chris@0: return $path; Chris@0: } Chris@0: Chris@0: $host = $headers[reset($hostKey)][0]; Chris@0: $scheme = substr($host, -4) === ':443' ? 'https' : 'http'; Chris@0: Chris@0: return $scheme . '://' . $host . '/' . ltrim($path, '/'); Chris@0: } Chris@0: Chris@17: /** Chris@17: * Get a short summary of the message body Chris@17: * Chris@17: * Will return `null` if the response is not printable. Chris@17: * Chris@17: * @param MessageInterface $message The message to get the body summary Chris@17: * @param int $truncateAt The maximum allowed size of the summary Chris@17: * Chris@17: * @return null|string Chris@17: */ Chris@17: function get_message_body_summary(MessageInterface $message, $truncateAt = 120) Chris@17: { Chris@17: $body = $message->getBody(); Chris@17: Chris@17: if (!$body->isSeekable() || !$body->isReadable()) { Chris@17: return null; Chris@17: } Chris@17: Chris@17: $size = $body->getSize(); Chris@17: Chris@17: if ($size === 0) { Chris@17: return null; Chris@17: } Chris@17: Chris@17: $summary = $body->read($truncateAt); Chris@17: $body->rewind(); Chris@17: Chris@17: if ($size > $truncateAt) { Chris@17: $summary .= ' (truncated...)'; Chris@17: } Chris@17: Chris@17: // Matches any printable character, including unicode characters: Chris@17: // letters, marks, numbers, punctuation, spacing, and separators. Chris@17: if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/', $summary)) { Chris@17: return null; Chris@17: } Chris@17: Chris@17: return $summary; Chris@17: } Chris@17: Chris@0: /** @internal */ Chris@0: function _caseless_remove($keys, array $data) Chris@0: { Chris@0: $result = []; Chris@0: Chris@0: foreach ($keys as &$key) { Chris@0: $key = strtolower($key); Chris@0: } Chris@0: Chris@0: foreach ($data as $k => $v) { Chris@0: if (!in_array(strtolower($k), $keys)) { Chris@0: $result[$k] = $v; Chris@0: } Chris@0: } Chris@0: Chris@0: return $result; Chris@0: }