PK GfcJ(j9J J
CONDUCT.mdnu W+A # Contributor Code of Conduct
The Zend Framework project adheres to [The Code Manifesto](http://codemanifesto.com)
as its guidelines for contributor interactions.
## The Code Manifesto
We want to work in an ecosystem that empowers developers to reach their
potential — one that encourages growth and effective collaboration. A space that
is safe for all.
A space such as this benefits everyone that participates in it. It encourages
new developers to enter our field. It is through discussion and collaboration
that we grow, and through growth that we improve.
In the effort to create such a place, we hold to these values:
1. **Discrimination limits us.** This includes discrimination on the basis of
race, gender, sexual orientation, gender identity, age, nationality, technology
and any other arbitrary exclusion of a group of people.
2. **Boundaries honor us.** Your comfort levels are not everyone’s comfort
levels. Remember that, and if brought to your attention, heed it.
3. **We are our biggest assets.** None of us were born masters of our trade.
Each of us has been helped along the way. Return that favor, when and where
you can.
4. **We are resources for the future.** As an extension of #3, share what you
know. Make yourself a resource to help those that come after you.
5. **Respect defines us.** Treat others as you wish to be treated. Make your
discussions, criticisms and debates from a position of respectfulness. Ask
yourself, is it true? Is it necessary? Is it constructive? Anything less is
unacceptable.
6. **Reactions require grace.** Angry responses are valid, but abusive language
and vindictive actions are toxic. When something happens that offends you,
handle it assertively, but be respectful. Escalate reasonably, and try to
allow the offender an opportunity to explain themselves, and possibly correct
the issue.
7. **Opinions are just that: opinions.** Each and every one of us, due to our
background and upbringing, have varying opinions. The fact of the matter, is
that is perfectly acceptable. Remember this: if you respect your own
opinions, you should respect the opinions of others.
8. **To err is human.** You might not intend it, but mistakes do happen and
contribute to build experience. Tolerate honest mistakes, and don't hesitate
to apologize if you make one yourself.
PK GfcJB ?
LICENSE.mdnu W+A Copyright (c) 2005-2015, Zend Technologies USA, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of Zend Technologies USA, Inc. nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
PK GfcJɶH phpcs.xmlnu W+A
src
test
*/_files/*
PK GfcJqQ Q README.mdnu W+A # zend-http
[![Build Status](https://secure.travis-ci.org/zendframework/zend-http.svg?branch=master)](https://secure.travis-ci.org/zendframework/zend-http)
[![Coverage Status](https://coveralls.io/repos/zendframework/zend-http/badge.svg?branch=master)](https://coveralls.io/r/zendframework/zend-http?branch=master)
zend-http provides the HTTP message abstraction used by
[zend-mvc](https://zendframework.github.io/zend-mvc/), and also provides an
extensible, adapter-driven HTTP client library.
This library **does not** support [PSR-7](http://www.php-fig.org/psr/psr-7), as
it predates that specification. For PSR-7 support, please see our
[Diactoros component](https://zendframework.github.io/zend-diactoros/).
- File issues at https://github.com/zendframework/zend-http/issues
- Documentation is at https://zendframework.github.io/zend-http/
PK GfcJjh| | CONTRIBUTING.mdnu W+A # CONTRIBUTING
## RESOURCES
If you wish to contribute to Zend Framework, please be sure to
read/subscribe to the following resources:
- [Coding Standards](https://github.com/zendframework/zf2/wiki/Coding-Standards)
- [Contributor's Guide](http://framework.zend.com/participate/contributor-guide)
- ZF Contributor's mailing list:
Archives: http://zend-framework-community.634137.n4.nabble.com/ZF-Contributor-f680267.html
Subscribe: zf-contributors-subscribe@lists.zend.com
- ZF Contributor's IRC channel:
#zftalk.dev on Freenode.net
If you are working on new features or refactoring [create a proposal](https://github.com/zendframework/zend-http/issues/new).
## Reporting Potential Security Issues
If you have encountered a potential security vulnerability, please **DO NOT** report it on the public
issue tracker: send it to us at [zf-security@zend.com](mailto:zf-security@zend.com) instead.
We will work with you to verify the vulnerability and patch it as soon as possible.
When reporting issues, please provide the following information:
- Component(s) affected
- A description indicating how to reproduce the issue
- A summary of the security vulnerability and impact
We request that you contact us via the email address above and give the project
contributors a chance to resolve the vulnerability and issue a new release prior
to any public exposure; this helps protect users and provides them with a chance
to upgrade and/or update in order to protect their applications.
For sensitive email communications, please use [our PGP key](http://framework.zend.com/zf-security-pgp-key.asc).
## RUNNING TESTS
> ### Note: testing versions prior to 2.4
>
> This component originates with Zend Framework 2. During the lifetime of ZF2,
> testing infrastructure migrated from PHPUnit 3 to PHPUnit 4. In most cases, no
> changes were necessary. However, due to the migration, tests may not run on
> versions < 2.4. As such, you may need to change the PHPUnit dependency if
> attempting a fix on such a version.
To run tests:
- Clone the repository:
```console
$ git clone git@github.com:zendframework/zend-http.git
$ cd
```
- Install dependencies via composer:
```console
$ curl -sS https://getcomposer.org/installer | php --
$ ./composer.phar install
```
If you don't have `curl` installed, you can also download `composer.phar` from https://getcomposer.org/
- Run the tests via `phpunit` and the provided PHPUnit config, like in this example:
```console
$ ./vendor/bin/phpunit
```
You can turn on conditional tests with the phpunit.xml file.
To do so:
- Copy `phpunit.xml.dist` file to `phpunit.xml`
- Edit `phpunit.xml` to enable any specific functionality you
want to test, as well as to provide test values to utilize.
## Running Coding Standards Checks
This component uses [phpcs](https://github.com/squizlabs/PHP_CodeSniffer) for coding
standards checks, and provides configuration for our selected checks.
`phpcs` is installed by default via Composer.
To run checks only:
```console
$ composer cs-check
```
`phpcs` also includes a tool for fixing most CS violations, `phpcbf`:
```console
$ composer cs-fix
```
If you allow `phpcbf` to fix CS issues, please re-run the tests to ensure
they pass, and make sure you add and commit the changes after verification.
## Recommended Workflow for Contributions
Your first step is to establish a public repository from which we can
pull your work into the master repository. We recommend using
[GitHub](https://github.com), as that is where the component is already hosted.
1. Setup a [GitHub account](http://github.com/), if you haven't yet
2. Fork the repository (http://github.com/zendframework/zend-http)
3. Clone the canonical repository locally and enter it.
```console
$ git clone git://github.com:zendframework/zend-http.git
$ cd zend-http
```
4. Add a remote to your fork; substitute your GitHub username in the command
below.
```console
$ git remote add {username} git@github.com:{username}/zend-http.git
$ git fetch {username}
```
### Keeping Up-to-Date
Periodically, you should update your fork or personal repository to
match the canonical ZF repository. Assuming you have setup your local repository
per the instructions above, you can do the following:
```console
$ git checkout master
$ git fetch origin
$ git rebase origin/master
# OPTIONALLY, to keep your remote up-to-date -
$ git push {username} master:master
```
If you're tracking other branches -- for example, the "develop" branch, where
new feature development occurs -- you'll want to do the same operations for that
branch; simply substitute "develop" for "master".
### Working on a patch
We recommend you do each new feature or bugfix in a new branch. This simplifies
the task of code review as well as the task of merging your changes into the
canonical repository.
A typical workflow will then consist of the following:
1. Create a new local branch based off either your master or develop branch.
2. Switch to your new local branch. (This step can be combined with the
previous step with the use of `git checkout -b`.)
3. Do some work, commit, repeat as necessary.
4. Push the local branch to your remote repository.
5. Send a pull request.
The mechanics of this process are actually quite trivial. Below, we will
create a branch for fixing an issue in the tracker.
```console
$ git checkout -b hotfix/9295
Switched to a new branch 'hotfix/9295'
```
... do some work ...
```console
$ git commit
```
... write your log message ...
```console
$ git push {username} hotfix/9295:hotfix/9295
Counting objects: 38, done.
Delta compression using up to 2 threads.
Compression objects: 100% (18/18), done.
Writing objects: 100% (20/20), 8.19KiB, done.
Total 20 (delta 12), reused 0 (delta 0)
To ssh://git@github.com/{username}/zend-http.git
b5583aa..4f51698 HEAD -> master
```
To send a pull request, you have two options.
If using GitHub, you can do the pull request from there. Navigate to
your repository, select the branch you just created, and then select the
"Pull Request" button in the upper right. Select the user/organization
"zendframework" as the recipient.
If using your own repository - or even if using GitHub - you can use `git
format-patch` to create a patchset for us to apply; in fact, this is
**recommended** for security-related patches. If you use `format-patch`, please
send the patches as attachments to:
- zf-devteam@zend.com for patches without security implications
- zf-security@zend.com for security patches
#### What branch to issue the pull request against?
Which branch should you issue a pull request against?
- For fixes against the stable release, issue the pull request against the
"master" branch.
- For new features, or fixes that introduce new elements to the public API (such
as new public methods or properties), issue the pull request against the
"develop" branch.
### Branch Cleanup
As you might imagine, if you are a frequent contributor, you'll start to
get a ton of branches both locally and on your remote.
Once you know that your changes have been accepted to the master
repository, we suggest doing some cleanup of these branches.
- Local branch cleanup
```console
$ git branch -d
```
- Remote branch removal
```console
$ git push {username} :
```
## Conduct
Please see our [CONDUCT.md](CONDUCT.md) to understand expected behavior when interacting with others in the project.
PK GfcJM&?7 ?7 src/Headers.phpnu W+A 2) {
throw new Exception\RuntimeException('Malformed header detected');
}
continue;
}
if ($emptyLine) {
throw new Exception\RuntimeException('Malformed header detected');
}
// check if a header name is present
if (preg_match('/^(?P[^()><@,;:\"\\/\[\]?={} \t]+):.*$/', $line, $matches)) {
if ($current) {
// a header name was present, then store the current complete line
$headers->headersKeys[] = static::createKey($current['name']);
$headers->headers[] = $current;
}
$current = [
'name' => $matches['name'],
'line' => trim($line)
];
continue;
}
if (preg_match("/^[ \t][^\r\n]*$/", $line, $matches)) {
// continuation: append to current line
$current['line'] .= trim($line);
continue;
}
// Line does not match header format!
throw new Exception\RuntimeException(sprintf(
'Line "%s" does not match header format!',
$line
));
}
if ($current) {
$headers->headersKeys[] = static::createKey($current['name']);
$headers->headers[] = $current;
}
return $headers;
}
/**
* Set an alternate implementation for the PluginClassLoader
*
* @param \Zend\Loader\PluginClassLocator $pluginClassLoader
* @return Headers
*/
public function setPluginClassLoader(PluginClassLocator $pluginClassLoader)
{
$this->pluginClassLoader = $pluginClassLoader;
return $this;
}
/**
* Return an instance of a PluginClassLocator, lazyload and inject map if necessary
*
* @return PluginClassLocator
*/
public function getPluginClassLoader()
{
if ($this->pluginClassLoader === null) {
$this->pluginClassLoader = new HeaderLoader();
}
return $this->pluginClassLoader;
}
/**
* Add many headers at once
*
* Expects an array (or Traversable object) of type/value pairs.
*
* @param array|Traversable $headers
* @return Headers
* @throws Exception\InvalidArgumentException
*/
public function addHeaders($headers)
{
if (! is_array($headers) && ! $headers instanceof Traversable) {
throw new Exception\InvalidArgumentException(sprintf(
'Expected array or Traversable; received "%s"',
(is_object($headers) ? get_class($headers) : gettype($headers))
));
}
foreach ($headers as $name => $value) {
if (is_int($name)) {
if (is_string($value)) {
$this->addHeaderLine($value);
} elseif (is_array($value) && count($value) == 1) {
$this->addHeaderLine(key($value), current($value));
} elseif (is_array($value) && count($value) == 2) {
$this->addHeaderLine($value[0], $value[1]);
} elseif ($value instanceof Header\HeaderInterface) {
$this->addHeader($value);
}
} elseif (is_string($name)) {
$this->addHeaderLine($name, $value);
}
}
return $this;
}
/**
* Add a raw header line, either in name => value, or as a single string 'name: value'
*
* This method allows for lazy-loading in that the parsing and instantiation of Header object
* will be delayed until they are retrieved by either get() or current()
*
* @throws Exception\InvalidArgumentException
* @param string $headerFieldNameOrLine
* @param string $fieldValue optional
* @return Headers
*/
public function addHeaderLine($headerFieldNameOrLine, $fieldValue = null)
{
$matches = null;
if (preg_match('/^(?P[^()><@,;:\"\\/\[\]?=}{ \t]+):.*$/', $headerFieldNameOrLine, $matches)
&& $fieldValue === null) {
// is a header
$headerName = $matches['name'];
$headerKey = static::createKey($matches['name']);
$line = $headerFieldNameOrLine;
} elseif ($fieldValue === null) {
throw new Exception\InvalidArgumentException('A field name was provided without a field value');
} else {
$headerName = $headerFieldNameOrLine;
$headerKey = static::createKey($headerFieldNameOrLine);
if (is_array($fieldValue)) {
$fieldValue = implode(', ', $fieldValue);
}
$line = $headerFieldNameOrLine . ': ' . $fieldValue;
}
$this->headersKeys[] = $headerKey;
$this->headers[] = ['name' => $headerName, 'line' => $line];
return $this;
}
/**
* Add a Header to this container, for raw values @see addHeaderLine() and addHeaders()
*
* @param Header\HeaderInterface $header
* @return Headers
*/
public function addHeader(Header\HeaderInterface $header)
{
$this->headersKeys[] = static::createKey($header->getFieldName());
$this->headers[] = $header;
return $this;
}
/**
* Remove a Header from the container
*
* @param Header\HeaderInterface $header
* @return bool
*/
public function removeHeader(Header\HeaderInterface $header)
{
$index = array_search($header, $this->headers, true);
if ($index !== false) {
unset($this->headersKeys[$index]);
unset($this->headers[$index]);
return true;
}
return false;
}
/**
* Clear all headers
*
* Removes all headers from queue
*
* @return Headers
*/
public function clearHeaders()
{
$this->headers = $this->headersKeys = [];
return $this;
}
/**
* Get all headers of a certain name/type
*
* @param string $name
* @return bool|Header\HeaderInterface|ArrayIterator
*/
public function get($name)
{
$key = static::createKey($name);
if (! in_array($key, $this->headersKeys)) {
return false;
}
$class = ($this->getPluginClassLoader()->load($key)) ?: 'Zend\Http\Header\GenericHeader';
if (in_array('Zend\Http\Header\MultipleHeaderInterface', class_implements($class, true))) {
$headers = [];
foreach (array_keys($this->headersKeys, $key) as $index) {
if (is_array($this->headers[$index])) {
$this->lazyLoadHeader($index);
}
}
foreach (array_keys($this->headersKeys, $key) as $index) {
$headers[] = $this->headers[$index];
}
return new ArrayIterator($headers);
}
$index = array_search($key, $this->headersKeys);
if ($index === false) {
return false;
}
if (is_array($this->headers[$index])) {
return $this->lazyLoadHeader($index);
}
return $this->headers[$index];
}
/**
* Test for existence of a type of header
*
* @param string $name
* @return bool
*/
public function has($name)
{
return (in_array(static::createKey($name), $this->headersKeys));
}
/**
* Advance the pointer for this object as an iterator
*
* @return void
*/
public function next()
{
next($this->headers);
}
/**
* Return the current key for this object as an iterator
*
* @return mixed
*/
public function key()
{
return (key($this->headers));
}
/**
* Is this iterator still valid?
*
* @return bool
*/
public function valid()
{
return (current($this->headers) !== false);
}
/**
* Reset the internal pointer for this object as an iterator
*
* @return void
*/
public function rewind()
{
reset($this->headers);
}
/**
* Return the current value for this iterator, lazy loading it if need be
*
* @return array|Header\HeaderInterface
*/
public function current()
{
$current = current($this->headers);
if (is_array($current)) {
$current = $this->lazyLoadHeader(key($this->headers));
}
return $current;
}
/**
* Return the number of headers in this contain, if all headers have not been parsed, actual count could
* increase if MultipleHeader objects exist in the Request/Response. If you need an exact count, iterate
*
* @return int count of currently known headers
*/
public function count()
{
return count($this->headers);
}
/**
* Render all headers at once
*
* This method handles the normal iteration of headers; it is up to the
* concrete classes to prepend with the appropriate status/request line.
*
* @return string
*/
public function toString()
{
$headers = '';
foreach ($this->toArray() as $fieldName => $fieldValue) {
if (is_array($fieldValue)) {
// Handle multi-value headers
foreach ($fieldValue as $value) {
$headers .= $fieldName . ': ' . $value . "\r\n";
}
continue;
}
// Handle single-value headers
$headers .= $fieldName . ': ' . $fieldValue . "\r\n";
}
return $headers;
}
/**
* Return the headers container as an array
*
* @todo determine how to produce single line headers, if they are supported
* @return array
*/
public function toArray()
{
$headers = [];
/* @var $header Header\HeaderInterface */
foreach ($this->headers as $header) {
if ($header instanceof Header\MultipleHeaderInterface) {
$name = $header->getFieldName();
if (! isset($headers[$name])) {
$headers[$name] = [];
}
$headers[$name][] = $header->getFieldValue();
} elseif ($header instanceof Header\HeaderInterface) {
$headers[$header->getFieldName()] = $header->getFieldValue();
} else {
$matches = null;
preg_match('/^(?P[^()><@,;:\"\\/\[\]?=}{ \t]+):\s*(?P.*)$/', $header['line'], $matches);
if ($matches) {
$headers[$matches['name']] = $matches['value'];
}
}
}
return $headers;
}
/**
* By calling this, it will force parsing and loading of all headers, after this count() will be accurate
*
* @return bool
*/
public function forceLoading()
{
foreach ($this as $item) {
// $item should now be loaded
}
return true;
}
/**
* @param $index
* @return mixed|void
*/
protected function lazyLoadHeader($index)
{
$current = $this->headers[$index];
$key = $this->headersKeys[$index];
/* @var $class Header\HeaderInterface */
$class = ($this->getPluginClassLoader()->load($key)) ?: 'Zend\Http\Header\GenericHeader';
$headers = $class::fromString($current['line']);
if (is_array($headers)) {
$this->headers[$index] = $current = array_shift($headers);
foreach ($headers as $header) {
$this->headersKeys[] = $key;
$this->headers[] = $header;
}
return $current;
}
$this->headers[$index] = $current = $headers;
return $current;
}
/**
* Create array key from header name
*
* @param string $name
* @return string
*/
protected static function createKey($name)
{
return str_replace(['-', '_', ' ', '.'], '', strtolower($name));
}
}
PK GfcJd % src/Exception/OutOfRangeException.phpnu W+A 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
// SUCCESS CODES
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-status',
208 => 'Already Reported',
// REDIRECTION CODES
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => 'Switch Proxy', // Deprecated
307 => 'Temporary Redirect',
// CLIENT ERROR
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
418 => 'I\'m a teapot',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
425 => 'Unordered Collection',
426 => 'Upgrade Required',
428 => 'Precondition Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',
451 => 'Unavailable For Legal Reasons',
// SERVER ERROR
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
508 => 'Loop Detected',
511 => 'Network Authentication Required',
];
/**
* @var int Status code
*/
protected $statusCode = 200;
/**
* @var string|null Null means it will be looked up from the $reasonPhrase list above
*/
protected $reasonPhrase = null;
/**
* Populate object from string
*
* @param string $string
* @return self
* @throws Exception\InvalidArgumentException
*/
public static function fromString($string)
{
$lines = explode("\r\n", $string);
if (! is_array($lines) || count($lines) === 1) {
$lines = explode("\n", $string);
}
$firstLine = array_shift($lines);
$response = new static();
$regex = '/^HTTP\/(?P1\.[01]) (?P\d{3})(?:[ ]+(?P.*))?$/';
$matches = [];
if (! preg_match($regex, $firstLine, $matches)) {
throw new Exception\InvalidArgumentException(
'A valid response status line was not found in the provided string'
);
}
$response->version = $matches['version'];
$response->setStatusCode($matches['status']);
$response->setReasonPhrase((isset($matches['reason']) ? $matches['reason'] : ''));
if (count($lines) === 0) {
return $response;
}
$isHeader = true;
$headers = $content = [];
foreach ($lines as $line) {
if ($isHeader && $line === '') {
$isHeader = false;
continue;
}
if ($isHeader) {
if (preg_match("/[\r\n]/", $line)) {
throw new Exception\RuntimeException('CRLF injection detected');
}
$headers[] = $line;
continue;
}
if (empty($content)
&& preg_match('/^[a-z0-9!#$%&\'*+.^_`|~-]+:$/i', $line)
) {
throw new Exception\RuntimeException('CRLF injection detected');
}
$content[] = $line;
}
if ($headers) {
$response->headers = implode("\r\n", $headers);
}
if ($content) {
$response->setContent(implode("\r\n", $content));
}
return $response;
}
/**
* @return Header\SetCookie[]
*/
public function getCookie()
{
return $this->getHeaders()->get('Set-Cookie');
}
/**
* Set HTTP status code and (optionally) message
*
* @param int $code
* @throws Exception\InvalidArgumentException
* @return self
*/
public function setStatusCode($code)
{
$const = get_class($this) . '::STATUS_CODE_' . $code;
if (! is_numeric($code) || ! defined($const)) {
$code = is_scalar($code) ? $code : gettype($code);
throw new Exception\InvalidArgumentException(sprintf(
'Invalid status code provided: "%s"',
$code
));
}
return $this->saveStatusCode($code);
}
/**
* Retrieve HTTP status code
*
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* Set custom HTTP status code
*
* @param int $code
* @throws Exception\InvalidArgumentException
* @return self
*/
public function setCustomStatusCode($code)
{
if (! is_numeric($code)) {
$code = is_scalar($code) ? $code : gettype($code);
throw new Exception\InvalidArgumentException(sprintf(
'Invalid status code provided: "%s"',
$code
));
}
return $this->saveStatusCode($code);
}
/**
* Assign status code
*
* @param int $code
* @return self
*/
protected function saveStatusCode($code)
{
$this->reasonPhrase = null;
$this->statusCode = (int) $code;
return $this;
}
/**
* @param string $reasonPhrase
* @return self
*/
public function setReasonPhrase($reasonPhrase)
{
$this->reasonPhrase = trim($reasonPhrase);
return $this;
}
/**
* Get HTTP status message
*
* @return string
*/
public function getReasonPhrase()
{
if (null == $this->reasonPhrase and isset($this->recommendedReasonPhrases[$this->statusCode])) {
$this->reasonPhrase = $this->recommendedReasonPhrases[$this->statusCode];
}
return $this->reasonPhrase;
}
/**
* Get the body of the response
*
* @return string
*/
public function getBody()
{
$body = (string) $this->getContent();
$transferEncoding = $this->getHeaders()->get('Transfer-Encoding');
if (! empty($transferEncoding)) {
if (strtolower($transferEncoding->getFieldValue()) === 'chunked') {
$body = $this->decodeChunkedBody($body);
}
}
$contentEncoding = $this->getHeaders()->get('Content-Encoding');
if (! empty($contentEncoding)) {
$contentEncoding = $contentEncoding->getFieldValue();
if ($contentEncoding === 'gzip') {
$body = $this->decodeGzip($body);
} elseif ($contentEncoding === 'deflate') {
$body = $this->decodeDeflate($body);
}
}
return $body;
}
/**
* Does the status code indicate a client error?
*
* @return bool
*/
public function isClientError()
{
$code = $this->getStatusCode();
return ($code < 500 && $code >= 400);
}
/**
* Is the request forbidden due to ACLs?
*
* @return bool
*/
public function isForbidden()
{
return (403 === $this->getStatusCode());
}
/**
* Is the current status "informational"?
*
* @return bool
*/
public function isInformational()
{
$code = $this->getStatusCode();
return ($code >= 100 && $code < 200);
}
/**
* Does the status code indicate the resource is not found?
*
* @return bool
*/
public function isNotFound()
{
return (404 === $this->getStatusCode());
}
/**
* Does the status code indicate the resource is gone?
*
* @return bool
*/
public function isGone()
{
return (410 === $this->getStatusCode());
}
/**
* Do we have a normal, OK response?
*
* @return bool
*/
public function isOk()
{
return (200 === $this->getStatusCode());
}
/**
* Does the status code reflect a server error?
*
* @return bool
*/
public function isServerError()
{
$code = $this->getStatusCode();
return (500 <= $code && 600 > $code);
}
/**
* Do we have a redirect?
*
* @return bool
*/
public function isRedirect()
{
$code = $this->getStatusCode();
return (300 <= $code && 400 > $code);
}
/**
* Was the response successful?
*
* @return bool
*/
public function isSuccess()
{
$code = $this->getStatusCode();
return (200 <= $code && 300 > $code);
}
/**
* Render the status line header
*
* @return string
*/
public function renderStatusLine()
{
$status = sprintf(
'HTTP/%s %d %s',
$this->getVersion(),
$this->getStatusCode(),
$this->getReasonPhrase()
);
return trim($status);
}
/**
* Render entire response as HTTP response string
*
* @return string
*/
public function toString()
{
$str = $this->renderStatusLine() . "\r\n";
$str .= $this->getHeaders()->toString();
$str .= "\r\n";
$str .= $this->getContent();
return $str;
}
/**
* Decode a "chunked" transfer-encoded body and return the decoded text
*
* @param string $body
* @return string
* @throws Exception\RuntimeException
*/
protected function decodeChunkedBody($body)
{
$decBody = '';
while (trim($body)) {
if (! preg_match("/^([\da-fA-F]+)[^\r\n]*\r\n/sm", $body, $m)) {
throw new Exception\RuntimeException(
"Error parsing body - doesn't seem to be a chunked message"
);
}
$length = hexdec(trim($m[1]));
$cut = strlen($m[0]);
$decBody .= substr($body, $cut, $length);
$body = substr($body, $cut + $length + 2);
}
return $decBody;
}
/**
* Decode a gzip encoded message (when Content-encoding = gzip)
*
* Currently requires PHP with zlib support
*
* @param string $body
* @return string
* @throws Exception\RuntimeException
*/
protected function decodeGzip($body)
{
if (! function_exists('gzinflate')) {
throw new Exception\RuntimeException(
'zlib extension is required in order to decode "gzip" encoding'
);
}
ErrorHandler::start();
$return = gzinflate(substr($body, 10));
$test = ErrorHandler::stop();
if ($test) {
throw new Exception\RuntimeException(
'Error occurred during gzip inflation',
0,
$test
);
}
return $return;
}
/**
* Decode a zlib deflated message (when Content-encoding = deflate)
*
* Currently requires PHP with zlib support
*
* @param string $body
* @return string
* @throws Exception\RuntimeException
*/
protected function decodeDeflate($body)
{
if (! function_exists('gzuncompress')) {
throw new Exception\RuntimeException(
'zlib extension is required in order to decode "deflate" encoding'
);
}
/**
* Some servers (IIS ?) send a broken deflate response, without the
* RFC-required zlib header.
*
* We try to detect the zlib header, and if it does not exist we
* teat the body is plain DEFLATE content.
*
* This method was adapted from PEAR HTTP_Request2 by (c) Alexey Borzov
*
* @link http://framework.zend.com/issues/browse/ZF-6040
*/
$zlibHeader = unpack('n', substr($body, 0, 2));
if ($zlibHeader[1] % 31 === 0) {
return gzuncompress($body);
}
return gzinflate($body);
}
}
PK GfcJ`= src/Response/Stream.phpnu W+A contentLength = $contentLength;
}
/**
* Get content length
*
* @return int|null
*/
public function getContentLength()
{
return $this->contentLength;
}
/**
* Get the response as stream
*
* @return resource
*/
public function getStream()
{
return $this->stream;
}
/**
* Set the response stream
*
* @param resource $stream
* @return Stream
*/
public function setStream($stream)
{
$this->stream = $stream;
return $this;
}
/**
* Get the cleanup trigger
*
* @return bool
*/
public function getCleanup()
{
return $this->cleanup;
}
/**
* Set the cleanup trigger
*
* @param bool $cleanup
*/
public function setCleanup($cleanup = true)
{
$this->cleanup = $cleanup;
}
/**
* Get file name associated with the stream
*
* @return string
*/
public function getStreamName()
{
return $this->streamName;
}
/**
* Set file name associated with the stream
*
* @param string $streamName Name to set
* @return Stream
*/
public function setStreamName($streamName)
{
$this->streamName = $streamName;
return $this;
}
/**
* Create a new Zend\Http\Response\Stream object from a stream
*
* @param string $responseString
* @param resource $stream
* @return Stream
* @throws Exception\InvalidArgumentException
* @throws Exception\OutOfRangeException
*/
public static function fromStream($responseString, $stream)
{
if (! is_resource($stream) || get_resource_type($stream) !== 'stream') {
throw new Exception\InvalidArgumentException('A valid stream is required');
}
$headerComplete = false;
$headersString = '';
$responseArray = [];
if ($responseString) {
$responseArray = explode("\n", $responseString);
}
while (count($responseArray)) {
$nextLine = array_shift($responseArray);
$headersString .= $nextLine."\n";
$nextLineTrimmed = trim($nextLine);
if ($nextLineTrimmed == '') {
$headerComplete = true;
break;
}
}
if (! $headerComplete) {
while (false !== ($nextLine = fgets($stream))) {
$headersString .= trim($nextLine)."\r\n";
if ($nextLine == "\r\n" || $nextLine == "\n") {
$headerComplete = true;
break;
}
}
}
if (! $headerComplete) {
throw new Exception\OutOfRangeException('End of header not found');
}
/** @var Stream $response */
$response = static::fromString($headersString);
if (is_resource($stream)) {
$response->setStream($stream);
}
if (count($responseArray)) {
$response->content = implode("\n", $responseArray);
}
$headers = $response->getHeaders();
foreach ($headers as $header) {
if ($header instanceof \Zend\Http\Header\ContentLength) {
$response->setContentLength((int) $header->getFieldValue());
$contentLength = $response->getContentLength();
if (strlen($response->content) > $contentLength) {
throw new Exception\OutOfRangeException(sprintf(
'Too much content was extracted from the stream (%d instead of %d bytes)',
strlen($response->content),
$contentLength
));
}
break;
}
}
return $response;
}
/**
* Get the response body as string
*
* This method returns the body of the HTTP response (the content), as it
* should be in it's readable version - that is, after decoding it (if it
* was decoded), deflating it (if it was gzip compressed), etc.
*
* If you want to get the raw body (as transferred on wire) use
* $this->getRawBody() instead.
*
* @return string
*/
public function getBody()
{
if ($this->stream !== null) {
$this->readStream();
}
return parent::getBody();
}
/**
* Get the raw response body (as transferred "on wire") as string
*
* If the body is encoded (with Transfer-Encoding, not content-encoding -
* IE "chunked" body), gzip compressed, etc. it will not be decoded.
*
* @return string
*/
public function getRawBody()
{
if ($this->stream) {
$this->readStream();
}
return $this->content;
}
/**
* Read stream content and return it as string
*
* Function reads the remainder of the body from the stream and closes the stream.
*
* @return string
*/
protected function readStream()
{
$contentLength = $this->getContentLength();
if (null !== $contentLength) {
$bytes = $contentLength - $this->contentStreamed;
} else {
$bytes = -1; // Read the whole buffer
}
if (! is_resource($this->stream) || $bytes == 0) {
return '';
}
$this->content .= stream_get_contents($this->stream, $bytes);
$this->contentStreamed += strlen($this->content);
if ($this->getContentLength() == $this->contentStreamed) {
$this->stream = null;
}
}
/**
* Destructor
*/
public function __destruct()
{
if (is_resource($this->stream)) {
$this->stream = null; //Could be listened by others
}
if ($this->cleanup) {
ErrorHandler::start(E_WARNING);
unlink($this->streamName);
ErrorHandler::stop();
}
}
}
PK GfcJTWou
src/PhpEnvironment/Response.phpnu W+A version) {
$this->version = $this->detectVersion();
}
return $this->version;
}
/**
* Detect the current used protocol version.
* If detection failed it falls back to version 1.0.
*
* @return string
*/
protected function detectVersion()
{
if (isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.1') {
return self::VERSION_11;
}
return self::VERSION_10;
}
/**
* @return bool
*/
public function headersSent()
{
return headers_sent();
}
/**
* @return bool
*/
public function contentSent()
{
return $this->contentSent;
}
/**
* Send HTTP headers
*
* @return Response
*/
public function sendHeaders()
{
if ($this->headersSent()) {
return $this;
}
$status = $this->renderStatusLine();
header($status);
/** @var \Zend\Http\Header\HeaderInterface $header */
foreach ($this->getHeaders() as $header) {
if ($header instanceof MultipleHeaderInterface) {
header($header->toString(), false);
continue;
}
header($header->toString());
}
$this->headersSent = true;
return $this;
}
/**
* Send content
*
* @return Response
*/
public function sendContent()
{
if ($this->contentSent()) {
return $this;
}
echo $this->getContent();
$this->contentSent = true;
return $this;
}
/**
* Send HTTP response
*
* @return Response
*/
public function send()
{
$this->sendHeaders()
->sendContent();
return $this;
}
}
PK GfcJ^0 $ src/PhpEnvironment/RemoteAddress.phpnu W+A useProxy = $useProxy;
return $this;
}
/**
* Checks proxy handling setting.
*
* @return bool Current setting value.
*/
public function getUseProxy()
{
return $this->useProxy;
}
/**
* Set list of trusted proxy addresses
*
* @param array $trustedProxies
* @return RemoteAddress
*/
public function setTrustedProxies(array $trustedProxies)
{
$this->trustedProxies = $trustedProxies;
return $this;
}
/**
* Set the header to introspect for proxy IPs
*
* @param string $header
* @return RemoteAddress
*/
public function setProxyHeader($header = 'X-Forwarded-For')
{
$this->proxyHeader = $this->normalizeProxyHeader($header);
return $this;
}
/**
* Returns client IP address.
*
* @return string IP address.
*/
public function getIpAddress()
{
$ip = $this->getIpAddressFromProxy();
if ($ip) {
return $ip;
}
// direct IP address
if (isset($_SERVER['REMOTE_ADDR'])) {
return $_SERVER['REMOTE_ADDR'];
}
return '';
}
/**
* Attempt to get the IP address for a proxied client
*
* @see http://tools.ietf.org/html/draft-ietf-appsawg-http-forwarded-10#section-5.2
* @return false|string
*/
protected function getIpAddressFromProxy()
{
if (! $this->useProxy
|| (isset($_SERVER['REMOTE_ADDR']) && ! in_array($_SERVER['REMOTE_ADDR'], $this->trustedProxies))
) {
return false;
}
$header = $this->proxyHeader;
if (! isset($_SERVER[$header]) || empty($_SERVER[$header])) {
return false;
}
// Extract IPs
$ips = explode(',', $_SERVER[$header]);
// trim, so we can compare against trusted proxies properly
$ips = array_map('trim', $ips);
// remove trusted proxy IPs
$ips = array_diff($ips, $this->trustedProxies);
// Any left?
if (empty($ips)) {
return false;
}
// Since we've removed any known, trusted proxy servers, the right-most
// address represents the first IP we do not know about -- i.e., we do
// not know if it is a proxy server, or a client. As such, we treat it
// as the originating IP.
// @see http://en.wikipedia.org/wiki/X-Forwarded-For
$ip = array_pop($ips);
return $ip;
}
/**
* Normalize a header string
*
* Normalizes a header string to a format that is compatible with
* $_SERVER
*
* @param string $header
* @return string
*/
protected function normalizeProxyHeader($header)
{
$header = strtoupper($header);
$header = str_replace('-', '_', $header);
if (0 !== strpos($header, 'HTTP_')) {
$header = 'HTTP_' . $header;
}
return $header;
}
}
PK GfcJ