mirror of
https://github.com/stylersnico/librenms.git
synced 2026-07-28 00:24:21 +02:00
Initial API release
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
/**
|
||||
* Slim - a micro PHP 5 framework
|
||||
*
|
||||
* @author Josh Lockhart <info@slimframework.com>
|
||||
* @copyright 2011 Josh Lockhart
|
||||
* @link http://www.slimframework.com
|
||||
* @license http://www.slimframework.com/license
|
||||
* @version 2.4.2
|
||||
* @package Slim
|
||||
*
|
||||
* MIT LICENSE
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
namespace Slim\Http;
|
||||
|
||||
class Cookies extends \Slim\Helper\Set
|
||||
{
|
||||
/**
|
||||
* Default cookie settings
|
||||
* @var array
|
||||
*/
|
||||
protected $defaults = array(
|
||||
'value' => '',
|
||||
'domain' => null,
|
||||
'path' => null,
|
||||
'expires' => null,
|
||||
'secure' => false,
|
||||
'httponly' => false
|
||||
);
|
||||
|
||||
/**
|
||||
* Set cookie
|
||||
*
|
||||
* The second argument may be a single scalar value, in which case
|
||||
* it will be merged with the default settings and considered the `value`
|
||||
* of the merged result.
|
||||
*
|
||||
* The second argument may also be an array containing any or all of
|
||||
* the keys shown in the default settings above. This array will be
|
||||
* merged with the defaults shown above.
|
||||
*
|
||||
* @param string $key Cookie name
|
||||
* @param mixed $value Cookie settings
|
||||
*/
|
||||
public function set($key, $value)
|
||||
{
|
||||
if (is_array($value)) {
|
||||
$cookieSettings = array_replace($this->defaults, $value);
|
||||
} else {
|
||||
$cookieSettings = array_replace($this->defaults, array('value' => $value));
|
||||
}
|
||||
parent::set($key, $cookieSettings);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove cookie
|
||||
*
|
||||
* Unlike \Slim\Helper\Set, this will actually *set* a cookie with
|
||||
* an expiration date in the past. This expiration date will force
|
||||
* the client-side cache to remove its cookie with the given name
|
||||
* and settings.
|
||||
*
|
||||
* @param string $key Cookie name
|
||||
* @param array $settings Optional cookie settings
|
||||
*/
|
||||
public function remove($key, $settings = array())
|
||||
{
|
||||
$settings['value'] = '';
|
||||
$settings['expires'] = time() - 86400;
|
||||
$this->set($key, array_replace($this->defaults, $settings));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
/**
|
||||
* Slim - a micro PHP 5 framework
|
||||
*
|
||||
* @author Josh Lockhart <info@slimframework.com>
|
||||
* @copyright 2011 Josh Lockhart
|
||||
* @link http://www.slimframework.com
|
||||
* @license http://www.slimframework.com/license
|
||||
* @version 2.4.2
|
||||
* @package Slim
|
||||
*
|
||||
* MIT LICENSE
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
namespace Slim\Http;
|
||||
|
||||
/**
|
||||
* HTTP Headers
|
||||
*
|
||||
* @package Slim
|
||||
* @author Josh Lockhart
|
||||
* @since 1.6.0
|
||||
*/
|
||||
class Headers extends \Slim\Helper\Set
|
||||
{
|
||||
/********************************************************************************
|
||||
* Static interface
|
||||
*******************************************************************************/
|
||||
|
||||
/**
|
||||
* Special-case HTTP headers that are otherwise unidentifiable as HTTP headers.
|
||||
* Typically, HTTP headers in the $_SERVER array will be prefixed with
|
||||
* `HTTP_` or `X_`. These are not so we list them here for later reference.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected static $special = array(
|
||||
'CONTENT_TYPE',
|
||||
'CONTENT_LENGTH',
|
||||
'PHP_AUTH_USER',
|
||||
'PHP_AUTH_PW',
|
||||
'PHP_AUTH_DIGEST',
|
||||
'AUTH_TYPE'
|
||||
);
|
||||
|
||||
/**
|
||||
* Extract HTTP headers from an array of data (e.g. $_SERVER)
|
||||
* @param array $data
|
||||
* @return array
|
||||
*/
|
||||
public static function extract($data)
|
||||
{
|
||||
$results = array();
|
||||
foreach ($data as $key => $value) {
|
||||
$key = strtoupper($key);
|
||||
if (strpos($key, 'X_') === 0 || strpos($key, 'HTTP_') === 0 || in_array($key, static::$special)) {
|
||||
if ($key === 'HTTP_CONTENT_LENGTH') {
|
||||
continue;
|
||||
}
|
||||
$results[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/********************************************************************************
|
||||
* Instance interface
|
||||
*******************************************************************************/
|
||||
|
||||
/**
|
||||
* Transform header name into canonical form
|
||||
* @param string $key
|
||||
* @return string
|
||||
*/
|
||||
protected function normalizeKey($key)
|
||||
{
|
||||
$key = strtolower($key);
|
||||
$key = str_replace(array('-', '_'), ' ', $key);
|
||||
$key = preg_replace('#^http #', '', $key);
|
||||
$key = ucwords($key);
|
||||
$key = str_replace(' ', '-', $key);
|
||||
|
||||
return $key;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,617 @@
|
||||
<?php
|
||||
/**
|
||||
* Slim - a micro PHP 5 framework
|
||||
*
|
||||
* @author Josh Lockhart <info@slimframework.com>
|
||||
* @copyright 2011 Josh Lockhart
|
||||
* @link http://www.slimframework.com
|
||||
* @license http://www.slimframework.com/license
|
||||
* @version 2.4.2
|
||||
* @package Slim
|
||||
*
|
||||
* MIT LICENSE
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
namespace Slim\Http;
|
||||
|
||||
/**
|
||||
* Slim HTTP Request
|
||||
*
|
||||
* This class provides a human-friendly interface to the Slim environment variables;
|
||||
* environment variables are passed by reference and will be modified directly.
|
||||
*
|
||||
* @package Slim
|
||||
* @author Josh Lockhart
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Request
|
||||
{
|
||||
const METHOD_HEAD = 'HEAD';
|
||||
const METHOD_GET = 'GET';
|
||||
const METHOD_POST = 'POST';
|
||||
const METHOD_PUT = 'PUT';
|
||||
const METHOD_PATCH = 'PATCH';
|
||||
const METHOD_DELETE = 'DELETE';
|
||||
const METHOD_OPTIONS = 'OPTIONS';
|
||||
const METHOD_OVERRIDE = '_METHOD';
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected static $formDataMediaTypes = array('application/x-www-form-urlencoded');
|
||||
|
||||
/**
|
||||
* Application Environment
|
||||
* @var \Slim\Environment
|
||||
*/
|
||||
protected $env;
|
||||
|
||||
/**
|
||||
* HTTP Headers
|
||||
* @var \Slim\Http\Headers
|
||||
*/
|
||||
public $headers;
|
||||
|
||||
/**
|
||||
* HTTP Cookies
|
||||
* @var \Slim\Helper\Set
|
||||
*/
|
||||
public $cookies;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
* @param \Slim\Environment $env
|
||||
*/
|
||||
public function __construct(\Slim\Environment $env)
|
||||
{
|
||||
$this->env = $env;
|
||||
$this->headers = new \Slim\Http\Headers(\Slim\Http\Headers::extract($env));
|
||||
$this->cookies = new \Slim\Helper\Set(\Slim\Http\Util::parseCookieHeader($env['HTTP_COOKIE']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get HTTP method
|
||||
* @return string
|
||||
*/
|
||||
public function getMethod()
|
||||
{
|
||||
return $this->env['REQUEST_METHOD'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this a GET request?
|
||||
* @return bool
|
||||
*/
|
||||
public function isGet()
|
||||
{
|
||||
return $this->getMethod() === self::METHOD_GET;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this a POST request?
|
||||
* @return bool
|
||||
*/
|
||||
public function isPost()
|
||||
{
|
||||
return $this->getMethod() === self::METHOD_POST;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this a PUT request?
|
||||
* @return bool
|
||||
*/
|
||||
public function isPut()
|
||||
{
|
||||
return $this->getMethod() === self::METHOD_PUT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this a PATCH request?
|
||||
* @return bool
|
||||
*/
|
||||
public function isPatch()
|
||||
{
|
||||
return $this->getMethod() === self::METHOD_PATCH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this a DELETE request?
|
||||
* @return bool
|
||||
*/
|
||||
public function isDelete()
|
||||
{
|
||||
return $this->getMethod() === self::METHOD_DELETE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this a HEAD request?
|
||||
* @return bool
|
||||
*/
|
||||
public function isHead()
|
||||
{
|
||||
return $this->getMethod() === self::METHOD_HEAD;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this a OPTIONS request?
|
||||
* @return bool
|
||||
*/
|
||||
public function isOptions()
|
||||
{
|
||||
return $this->getMethod() === self::METHOD_OPTIONS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this an AJAX request?
|
||||
* @return bool
|
||||
*/
|
||||
public function isAjax()
|
||||
{
|
||||
if ($this->params('isajax')) {
|
||||
return true;
|
||||
} elseif (isset($this->headers['X_REQUESTED_WITH']) && $this->headers['X_REQUESTED_WITH'] === 'XMLHttpRequest') {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this an XHR request? (alias of Slim_Http_Request::isAjax)
|
||||
* @return bool
|
||||
*/
|
||||
public function isXhr()
|
||||
{
|
||||
return $this->isAjax();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch GET and POST data
|
||||
*
|
||||
* This method returns a union of GET and POST data as a key-value array, or the value
|
||||
* of the array key if requested; if the array key does not exist, NULL is returned,
|
||||
* unless there is a default value specified.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $default
|
||||
* @return array|mixed|null
|
||||
*/
|
||||
public function params($key = null, $default = null)
|
||||
{
|
||||
$union = array_merge($this->get(), $this->post());
|
||||
if ($key) {
|
||||
return isset($union[$key]) ? $union[$key] : $default;
|
||||
}
|
||||
|
||||
return $union;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch GET data
|
||||
*
|
||||
* This method returns a key-value array of data sent in the HTTP request query string, or
|
||||
* the value of the array key if requested; if the array key does not exist, NULL is returned.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $default Default return value when key does not exist
|
||||
* @return array|mixed|null
|
||||
*/
|
||||
public function get($key = null, $default = null)
|
||||
{
|
||||
if (!isset($this->env['slim.request.query_hash'])) {
|
||||
$output = array();
|
||||
if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) {
|
||||
mb_parse_str($this->env['QUERY_STRING'], $output);
|
||||
} else {
|
||||
parse_str($this->env['QUERY_STRING'], $output);
|
||||
}
|
||||
$this->env['slim.request.query_hash'] = Util::stripSlashesIfMagicQuotes($output);
|
||||
}
|
||||
if ($key) {
|
||||
if (isset($this->env['slim.request.query_hash'][$key])) {
|
||||
return $this->env['slim.request.query_hash'][$key];
|
||||
} else {
|
||||
return $default;
|
||||
}
|
||||
} else {
|
||||
return $this->env['slim.request.query_hash'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch POST data
|
||||
*
|
||||
* This method returns a key-value array of data sent in the HTTP request body, or
|
||||
* the value of a hash key if requested; if the array key does not exist, NULL is returned.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $default Default return value when key does not exist
|
||||
* @return array|mixed|null
|
||||
* @throws \RuntimeException If environment input is not available
|
||||
*/
|
||||
public function post($key = null, $default = null)
|
||||
{
|
||||
if (!isset($this->env['slim.input'])) {
|
||||
throw new \RuntimeException('Missing slim.input in environment variables');
|
||||
}
|
||||
if (!isset($this->env['slim.request.form_hash'])) {
|
||||
$this->env['slim.request.form_hash'] = array();
|
||||
if ($this->isFormData() && is_string($this->env['slim.input'])) {
|
||||
$output = array();
|
||||
if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) {
|
||||
mb_parse_str($this->env['slim.input'], $output);
|
||||
} else {
|
||||
parse_str($this->env['slim.input'], $output);
|
||||
}
|
||||
$this->env['slim.request.form_hash'] = Util::stripSlashesIfMagicQuotes($output);
|
||||
} else {
|
||||
$this->env['slim.request.form_hash'] = Util::stripSlashesIfMagicQuotes($_POST);
|
||||
}
|
||||
}
|
||||
if ($key) {
|
||||
if (isset($this->env['slim.request.form_hash'][$key])) {
|
||||
return $this->env['slim.request.form_hash'][$key];
|
||||
} else {
|
||||
return $default;
|
||||
}
|
||||
} else {
|
||||
return $this->env['slim.request.form_hash'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch PUT data (alias for \Slim\Http\Request::post)
|
||||
* @param string $key
|
||||
* @param mixed $default Default return value when key does not exist
|
||||
* @return array|mixed|null
|
||||
*/
|
||||
public function put($key = null, $default = null)
|
||||
{
|
||||
return $this->post($key, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch PATCH data (alias for \Slim\Http\Request::post)
|
||||
* @param string $key
|
||||
* @param mixed $default Default return value when key does not exist
|
||||
* @return array|mixed|null
|
||||
*/
|
||||
public function patch($key = null, $default = null)
|
||||
{
|
||||
return $this->post($key, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch DELETE data (alias for \Slim\Http\Request::post)
|
||||
* @param string $key
|
||||
* @param mixed $default Default return value when key does not exist
|
||||
* @return array|mixed|null
|
||||
*/
|
||||
public function delete($key = null, $default = null)
|
||||
{
|
||||
return $this->post($key, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch COOKIE data
|
||||
*
|
||||
* This method returns a key-value array of Cookie data sent in the HTTP request, or
|
||||
* the value of a array key if requested; if the array key does not exist, NULL is returned.
|
||||
*
|
||||
* @param string $key
|
||||
* @return array|string|null
|
||||
*/
|
||||
public function cookies($key = null)
|
||||
{
|
||||
if ($key) {
|
||||
return $this->cookies->get($key);
|
||||
}
|
||||
|
||||
return $this->cookies;
|
||||
// if (!isset($this->env['slim.request.cookie_hash'])) {
|
||||
// $cookieHeader = isset($this->env['COOKIE']) ? $this->env['COOKIE'] : '';
|
||||
// $this->env['slim.request.cookie_hash'] = Util::parseCookieHeader($cookieHeader);
|
||||
// }
|
||||
// if ($key) {
|
||||
// if (isset($this->env['slim.request.cookie_hash'][$key])) {
|
||||
// return $this->env['slim.request.cookie_hash'][$key];
|
||||
// } else {
|
||||
// return null;
|
||||
// }
|
||||
// } else {
|
||||
// return $this->env['slim.request.cookie_hash'];
|
||||
// }
|
||||
}
|
||||
|
||||
/**
|
||||
* Does the Request body contain parsed form data?
|
||||
* @return bool
|
||||
*/
|
||||
public function isFormData()
|
||||
{
|
||||
$method = isset($this->env['slim.method_override.original_method']) ? $this->env['slim.method_override.original_method'] : $this->getMethod();
|
||||
|
||||
return ($method === self::METHOD_POST && is_null($this->getContentType())) || in_array($this->getMediaType(), self::$formDataMediaTypes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Headers
|
||||
*
|
||||
* This method returns a key-value array of headers sent in the HTTP request, or
|
||||
* the value of a hash key if requested; if the array key does not exist, NULL is returned.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $default The default value returned if the requested header is not available
|
||||
* @return mixed
|
||||
*/
|
||||
public function headers($key = null, $default = null)
|
||||
{
|
||||
if ($key) {
|
||||
return $this->headers->get($key, $default);
|
||||
}
|
||||
|
||||
return $this->headers;
|
||||
// if ($key) {
|
||||
// $key = strtoupper($key);
|
||||
// $key = str_replace('-', '_', $key);
|
||||
// $key = preg_replace('@^HTTP_@', '', $key);
|
||||
// if (isset($this->env[$key])) {
|
||||
// return $this->env[$key];
|
||||
// } else {
|
||||
// return $default;
|
||||
// }
|
||||
// } else {
|
||||
// $headers = array();
|
||||
// foreach ($this->env as $key => $value) {
|
||||
// if (strpos($key, 'slim.') !== 0) {
|
||||
// $headers[$key] = $value;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// return $headers;
|
||||
// }
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Body
|
||||
* @return string
|
||||
*/
|
||||
public function getBody()
|
||||
{
|
||||
return $this->env['slim.input'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Content Type
|
||||
* @return string|null
|
||||
*/
|
||||
public function getContentType()
|
||||
{
|
||||
return $this->headers->get('CONTENT_TYPE');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Media Type (type/subtype within Content Type header)
|
||||
* @return string|null
|
||||
*/
|
||||
public function getMediaType()
|
||||
{
|
||||
$contentType = $this->getContentType();
|
||||
if ($contentType) {
|
||||
$contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
|
||||
|
||||
return strtolower($contentTypeParts[0]);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Media Type Params
|
||||
* @return array
|
||||
*/
|
||||
public function getMediaTypeParams()
|
||||
{
|
||||
$contentType = $this->getContentType();
|
||||
$contentTypeParams = array();
|
||||
if ($contentType) {
|
||||
$contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
|
||||
$contentTypePartsLength = count($contentTypeParts);
|
||||
for ($i = 1; $i < $contentTypePartsLength; $i++) {
|
||||
$paramParts = explode('=', $contentTypeParts[$i]);
|
||||
$contentTypeParams[strtolower($paramParts[0])] = $paramParts[1];
|
||||
}
|
||||
}
|
||||
|
||||
return $contentTypeParams;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Content Charset
|
||||
* @return string|null
|
||||
*/
|
||||
public function getContentCharset()
|
||||
{
|
||||
$mediaTypeParams = $this->getMediaTypeParams();
|
||||
if (isset($mediaTypeParams['charset'])) {
|
||||
return $mediaTypeParams['charset'];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Content-Length
|
||||
* @return int
|
||||
*/
|
||||
public function getContentLength()
|
||||
{
|
||||
return $this->headers->get('CONTENT_LENGTH', 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Host
|
||||
* @return string
|
||||
*/
|
||||
public function getHost()
|
||||
{
|
||||
if (isset($this->env['HTTP_HOST'])) {
|
||||
if (strpos($this->env['HTTP_HOST'], ':') !== false) {
|
||||
$hostParts = explode(':', $this->env['HTTP_HOST']);
|
||||
|
||||
return $hostParts[0];
|
||||
}
|
||||
|
||||
return $this->env['HTTP_HOST'];
|
||||
}
|
||||
|
||||
return $this->env['SERVER_NAME'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Host with Port
|
||||
* @return string
|
||||
*/
|
||||
public function getHostWithPort()
|
||||
{
|
||||
return sprintf('%s:%s', $this->getHost(), $this->getPort());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Port
|
||||
* @return int
|
||||
*/
|
||||
public function getPort()
|
||||
{
|
||||
return (int)$this->env['SERVER_PORT'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Scheme (https or http)
|
||||
* @return string
|
||||
*/
|
||||
public function getScheme()
|
||||
{
|
||||
return $this->env['slim.url_scheme'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Script Name (physical path)
|
||||
* @return string
|
||||
*/
|
||||
public function getScriptName()
|
||||
{
|
||||
return $this->env['SCRIPT_NAME'];
|
||||
}
|
||||
|
||||
/**
|
||||
* LEGACY: Get Root URI (alias for Slim_Http_Request::getScriptName)
|
||||
* @return string
|
||||
*/
|
||||
public function getRootUri()
|
||||
{
|
||||
return $this->getScriptName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Path (physical path + virtual path)
|
||||
* @return string
|
||||
*/
|
||||
public function getPath()
|
||||
{
|
||||
return $this->getScriptName() . $this->getPathInfo();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Path Info (virtual path)
|
||||
* @return string
|
||||
*/
|
||||
public function getPathInfo()
|
||||
{
|
||||
return $this->env['PATH_INFO'];
|
||||
}
|
||||
|
||||
/**
|
||||
* LEGACY: Get Resource URI (alias for Slim_Http_Request::getPathInfo)
|
||||
* @return string
|
||||
*/
|
||||
public function getResourceUri()
|
||||
{
|
||||
return $this->getPathInfo();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get URL (scheme + host [ + port if non-standard ])
|
||||
* @return string
|
||||
*/
|
||||
public function getUrl()
|
||||
{
|
||||
$url = $this->getScheme() . '://' . $this->getHost();
|
||||
if (($this->getScheme() === 'https' && $this->getPort() !== 443) || ($this->getScheme() === 'http' && $this->getPort() !== 80)) {
|
||||
$url .= sprintf(':%s', $this->getPort());
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get IP
|
||||
* @return string
|
||||
*/
|
||||
public function getIp()
|
||||
{
|
||||
$keys = array('X_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR', 'CLIENT_IP', 'REMOTE_ADDR');
|
||||
foreach ($keys as $key) {
|
||||
if (isset($this->env[$key])) {
|
||||
return $this->env[$key];
|
||||
}
|
||||
}
|
||||
|
||||
return $this->env['REMOTE_ADDR'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Referrer
|
||||
* @return string|null
|
||||
*/
|
||||
public function getReferrer()
|
||||
{
|
||||
return $this->headers->get('HTTP_REFERER');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Referer (for those who can't spell)
|
||||
* @return string|null
|
||||
*/
|
||||
public function getReferer()
|
||||
{
|
||||
return $this->getReferrer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get User Agent
|
||||
* @return string|null
|
||||
*/
|
||||
public function getUserAgent()
|
||||
{
|
||||
return $this->headers->get('HTTP_USER_AGENT');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
<?php
|
||||
/**
|
||||
* Slim - a micro PHP 5 framework
|
||||
*
|
||||
* @author Josh Lockhart <info@slimframework.com>
|
||||
* @copyright 2011 Josh Lockhart
|
||||
* @link http://www.slimframework.com
|
||||
* @license http://www.slimframework.com/license
|
||||
* @version 2.4.2
|
||||
* @package Slim
|
||||
*
|
||||
* MIT LICENSE
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
namespace Slim\Http;
|
||||
|
||||
/**
|
||||
* Response
|
||||
*
|
||||
* This is a simple abstraction over top an HTTP response. This
|
||||
* provides methods to set the HTTP status, the HTTP headers,
|
||||
* and the HTTP body.
|
||||
*
|
||||
* @package Slim
|
||||
* @author Josh Lockhart
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Response implements \ArrayAccess, \Countable, \IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* @var int HTTP status code
|
||||
*/
|
||||
protected $status;
|
||||
|
||||
/**
|
||||
* @var \Slim\Http\Headers
|
||||
*/
|
||||
public $headers;
|
||||
|
||||
/**
|
||||
* @var \Slim\Http\Cookies
|
||||
*/
|
||||
public $cookies;
|
||||
|
||||
/**
|
||||
* @var string HTTP response body
|
||||
*/
|
||||
protected $body;
|
||||
|
||||
/**
|
||||
* @var int Length of HTTP response body
|
||||
*/
|
||||
protected $length;
|
||||
|
||||
/**
|
||||
* @var array HTTP response codes and messages
|
||||
*/
|
||||
protected static $messages = array(
|
||||
//Informational 1xx
|
||||
100 => '100 Continue',
|
||||
101 => '101 Switching Protocols',
|
||||
//Successful 2xx
|
||||
200 => '200 OK',
|
||||
201 => '201 Created',
|
||||
202 => '202 Accepted',
|
||||
203 => '203 Non-Authoritative Information',
|
||||
204 => '204 No Content',
|
||||
205 => '205 Reset Content',
|
||||
206 => '206 Partial Content',
|
||||
//Redirection 3xx
|
||||
300 => '300 Multiple Choices',
|
||||
301 => '301 Moved Permanently',
|
||||
302 => '302 Found',
|
||||
303 => '303 See Other',
|
||||
304 => '304 Not Modified',
|
||||
305 => '305 Use Proxy',
|
||||
306 => '306 (Unused)',
|
||||
307 => '307 Temporary Redirect',
|
||||
//Client Error 4xx
|
||||
400 => '400 Bad Request',
|
||||
401 => '401 Unauthorized',
|
||||
402 => '402 Payment Required',
|
||||
403 => '403 Forbidden',
|
||||
404 => '404 Not Found',
|
||||
405 => '405 Method Not Allowed',
|
||||
406 => '406 Not Acceptable',
|
||||
407 => '407 Proxy Authentication Required',
|
||||
408 => '408 Request Timeout',
|
||||
409 => '409 Conflict',
|
||||
410 => '410 Gone',
|
||||
411 => '411 Length Required',
|
||||
412 => '412 Precondition Failed',
|
||||
413 => '413 Request Entity Too Large',
|
||||
414 => '414 Request-URI Too Long',
|
||||
415 => '415 Unsupported Media Type',
|
||||
416 => '416 Requested Range Not Satisfiable',
|
||||
417 => '417 Expectation Failed',
|
||||
418 => '418 I\'m a teapot',
|
||||
422 => '422 Unprocessable Entity',
|
||||
423 => '423 Locked',
|
||||
//Server Error 5xx
|
||||
500 => '500 Internal Server Error',
|
||||
501 => '501 Not Implemented',
|
||||
502 => '502 Bad Gateway',
|
||||
503 => '503 Service Unavailable',
|
||||
504 => '504 Gateway Timeout',
|
||||
505 => '505 HTTP Version Not Supported'
|
||||
);
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
* @param string $body The HTTP response body
|
||||
* @param int $status The HTTP response status
|
||||
* @param \Slim\Http\Headers|array $headers The HTTP response headers
|
||||
*/
|
||||
public function __construct($body = '', $status = 200, $headers = array())
|
||||
{
|
||||
$this->setStatus($status);
|
||||
$this->headers = new \Slim\Http\Headers(array('Content-Type' => 'text/html'));
|
||||
$this->headers->replace($headers);
|
||||
$this->cookies = new \Slim\Http\Cookies();
|
||||
$this->write($body);
|
||||
}
|
||||
|
||||
public function getStatus()
|
||||
{
|
||||
return $this->status;
|
||||
}
|
||||
|
||||
public function setStatus($status)
|
||||
{
|
||||
$this->status = (int)$status;
|
||||
}
|
||||
|
||||
/**
|
||||
* DEPRECATION WARNING! Use `getStatus` or `setStatus` instead.
|
||||
*
|
||||
* Get and set status
|
||||
* @param int|null $status
|
||||
* @return int
|
||||
*/
|
||||
public function status($status = null)
|
||||
{
|
||||
if (!is_null($status)) {
|
||||
$this->status = (int) $status;
|
||||
}
|
||||
|
||||
return $this->status;
|
||||
}
|
||||
|
||||
/**
|
||||
* DEPRECATION WARNING! Access `headers` property directly.
|
||||
*
|
||||
* Get and set header
|
||||
* @param string $name Header name
|
||||
* @param string|null $value Header value
|
||||
* @return string Header value
|
||||
*/
|
||||
public function header($name, $value = null)
|
||||
{
|
||||
if (!is_null($value)) {
|
||||
$this->headers->set($name, $value);
|
||||
}
|
||||
|
||||
return $this->headers->get($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* DEPRECATION WARNING! Access `headers` property directly.
|
||||
*
|
||||
* Get headers
|
||||
* @return \Slim\Http\Headers
|
||||
*/
|
||||
public function headers()
|
||||
{
|
||||
return $this->headers;
|
||||
}
|
||||
|
||||
public function getBody()
|
||||
{
|
||||
return $this->body;
|
||||
}
|
||||
|
||||
public function setBody($content)
|
||||
{
|
||||
$this->write($content, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* DEPRECATION WARNING! use `getBody` or `setBody` instead.
|
||||
*
|
||||
* Get and set body
|
||||
* @param string|null $body Content of HTTP response body
|
||||
* @return string
|
||||
*/
|
||||
public function body($body = null)
|
||||
{
|
||||
if (!is_null($body)) {
|
||||
$this->write($body, true);
|
||||
}
|
||||
|
||||
return $this->body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Append HTTP response body
|
||||
* @param string $body Content to append to the current HTTP response body
|
||||
* @param bool $replace Overwrite existing response body?
|
||||
* @return string The updated HTTP response body
|
||||
*/
|
||||
public function write($body, $replace = false)
|
||||
{
|
||||
if ($replace) {
|
||||
$this->body = $body;
|
||||
} else {
|
||||
$this->body .= (string)$body;
|
||||
}
|
||||
$this->length = strlen($this->body);
|
||||
|
||||
return $this->body;
|
||||
}
|
||||
|
||||
public function getLength()
|
||||
{
|
||||
return $this->length;
|
||||
}
|
||||
|
||||
/**
|
||||
* DEPRECATION WARNING! Use `getLength` or `write` or `body` instead.
|
||||
*
|
||||
* Get and set length
|
||||
* @param int|null $length
|
||||
* @return int
|
||||
*/
|
||||
public function length($length = null)
|
||||
{
|
||||
if (!is_null($length)) {
|
||||
$this->length = (int) $length;
|
||||
}
|
||||
|
||||
return $this->length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finalize
|
||||
*
|
||||
* This prepares this response and returns an array
|
||||
* of [status, headers, body]. This array is passed to outer middleware
|
||||
* if available or directly to the Slim run method.
|
||||
*
|
||||
* @return array[int status, array headers, string body]
|
||||
*/
|
||||
public function finalize()
|
||||
{
|
||||
// Prepare response
|
||||
if (in_array($this->status, array(204, 304))) {
|
||||
$this->headers->remove('Content-Type');
|
||||
$this->headers->remove('Content-Length');
|
||||
$this->setBody('');
|
||||
}
|
||||
|
||||
return array($this->status, $this->headers, $this->body);
|
||||
}
|
||||
|
||||
/**
|
||||
* DEPRECATION WARNING! Access `cookies` property directly.
|
||||
*
|
||||
* Set cookie
|
||||
*
|
||||
* Instead of using PHP's `setcookie()` function, Slim manually constructs the HTTP `Set-Cookie`
|
||||
* header on its own and delegates this responsibility to the `Slim_Http_Util` class. This
|
||||
* response's header is passed by reference to the utility class and is directly modified. By not
|
||||
* relying on PHP's native implementation, Slim allows middleware the opportunity to massage or
|
||||
* analyze the raw header before the response is ultimately delivered to the HTTP client.
|
||||
*
|
||||
* @param string $name The name of the cookie
|
||||
* @param string|array $value If string, the value of cookie; if array, properties for
|
||||
* cookie including: value, expire, path, domain, secure, httponly
|
||||
*/
|
||||
public function setCookie($name, $value)
|
||||
{
|
||||
// Util::setCookieHeader($this->header, $name, $value);
|
||||
$this->cookies->set($name, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* DEPRECATION WARNING! Access `cookies` property directly.
|
||||
*
|
||||
* Delete cookie
|
||||
*
|
||||
* Instead of using PHP's `setcookie()` function, Slim manually constructs the HTTP `Set-Cookie`
|
||||
* header on its own and delegates this responsibility to the `Slim_Http_Util` class. This
|
||||
* response's header is passed by reference to the utility class and is directly modified. By not
|
||||
* relying on PHP's native implementation, Slim allows middleware the opportunity to massage or
|
||||
* analyze the raw header before the response is ultimately delivered to the HTTP client.
|
||||
*
|
||||
* This method will set a cookie with the given name that has an expiration time in the past; this will
|
||||
* prompt the HTTP client to invalidate and remove the client-side cookie. Optionally, you may
|
||||
* also pass a key/value array as the second argument. If the "domain" key is present in this
|
||||
* array, only the Cookie with the given name AND domain will be removed. The invalidating cookie
|
||||
* sent with this response will adopt all properties of the second argument.
|
||||
*
|
||||
* @param string $name The name of the cookie
|
||||
* @param array $settings Properties for cookie including: value, expire, path, domain, secure, httponly
|
||||
*/
|
||||
public function deleteCookie($name, $settings = array())
|
||||
{
|
||||
$this->cookies->remove($name, $settings);
|
||||
// Util::deleteCookieHeader($this->header, $name, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect
|
||||
*
|
||||
* This method prepares this response to return an HTTP Redirect response
|
||||
* to the HTTP client.
|
||||
*
|
||||
* @param string $url The redirect destination
|
||||
* @param int $status The redirect HTTP status code
|
||||
*/
|
||||
public function redirect ($url, $status = 302)
|
||||
{
|
||||
$this->setStatus($status);
|
||||
$this->headers->set('Location', $url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helpers: Empty?
|
||||
* @return bool
|
||||
*/
|
||||
public function isEmpty()
|
||||
{
|
||||
return in_array($this->status, array(201, 204, 304));
|
||||
}
|
||||
|
||||
/**
|
||||
* Helpers: Informational?
|
||||
* @return bool
|
||||
*/
|
||||
public function isInformational()
|
||||
{
|
||||
return $this->status >= 100 && $this->status < 200;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helpers: OK?
|
||||
* @return bool
|
||||
*/
|
||||
public function isOk()
|
||||
{
|
||||
return $this->status === 200;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helpers: Successful?
|
||||
* @return bool
|
||||
*/
|
||||
public function isSuccessful()
|
||||
{
|
||||
return $this->status >= 200 && $this->status < 300;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helpers: Redirect?
|
||||
* @return bool
|
||||
*/
|
||||
public function isRedirect()
|
||||
{
|
||||
return in_array($this->status, array(301, 302, 303, 307));
|
||||
}
|
||||
|
||||
/**
|
||||
* Helpers: Redirection?
|
||||
* @return bool
|
||||
*/
|
||||
public function isRedirection()
|
||||
{
|
||||
return $this->status >= 300 && $this->status < 400;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helpers: Forbidden?
|
||||
* @return bool
|
||||
*/
|
||||
public function isForbidden()
|
||||
{
|
||||
return $this->status === 403;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helpers: Not Found?
|
||||
* @return bool
|
||||
*/
|
||||
public function isNotFound()
|
||||
{
|
||||
return $this->status === 404;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helpers: Client error?
|
||||
* @return bool
|
||||
*/
|
||||
public function isClientError()
|
||||
{
|
||||
return $this->status >= 400 && $this->status < 500;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helpers: Server Error?
|
||||
* @return bool
|
||||
*/
|
||||
public function isServerError()
|
||||
{
|
||||
return $this->status >= 500 && $this->status < 600;
|
||||
}
|
||||
|
||||
/**
|
||||
* DEPRECATION WARNING! ArrayAccess interface will be removed from \Slim\Http\Response.
|
||||
* Iterate `headers` or `cookies` properties directly.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Array Access: Offset Exists
|
||||
*/
|
||||
public function offsetExists($offset)
|
||||
{
|
||||
return isset($this->headers[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Array Access: Offset Get
|
||||
*/
|
||||
public function offsetGet($offset)
|
||||
{
|
||||
return $this->headers[$offset];
|
||||
}
|
||||
|
||||
/**
|
||||
* Array Access: Offset Set
|
||||
*/
|
||||
public function offsetSet($offset, $value)
|
||||
{
|
||||
$this->headers[$offset] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Array Access: Offset Unset
|
||||
*/
|
||||
public function offsetUnset($offset)
|
||||
{
|
||||
unset($this->headers[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* DEPRECATION WARNING! Countable interface will be removed from \Slim\Http\Response.
|
||||
* Call `count` on `headers` or `cookies` properties directly.
|
||||
*
|
||||
* Countable: Count
|
||||
*/
|
||||
public function count()
|
||||
{
|
||||
return count($this->headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* DEPRECATION WARNING! IteratorAggregate interface will be removed from \Slim\Http\Response.
|
||||
* Iterate `headers` or `cookies` properties directly.
|
||||
*
|
||||
* Get Iterator
|
||||
*
|
||||
* This returns the contained `\Slim\Http\Headers` instance which
|
||||
* is itself iterable.
|
||||
*
|
||||
* @return \Slim\Http\Headers
|
||||
*/
|
||||
public function getIterator()
|
||||
{
|
||||
return $this->headers->getIterator();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get message for HTTP status code
|
||||
* @param int $status
|
||||
* @return string|null
|
||||
*/
|
||||
public static function getMessageForCode($status)
|
||||
{
|
||||
if (isset(self::$messages[$status])) {
|
||||
return self::$messages[$status];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
<?php
|
||||
/**
|
||||
* Slim - a micro PHP 5 framework
|
||||
*
|
||||
* @author Josh Lockhart <info@slimframework.com>
|
||||
* @copyright 2011 Josh Lockhart
|
||||
* @link http://www.slimframework.com
|
||||
* @license http://www.slimframework.com/license
|
||||
* @version 2.4.2
|
||||
* @package Slim
|
||||
*
|
||||
* MIT LICENSE
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
namespace Slim\Http;
|
||||
|
||||
/**
|
||||
* Slim HTTP Utilities
|
||||
*
|
||||
* This class provides useful methods for handling HTTP requests.
|
||||
*
|
||||
* @package Slim
|
||||
* @author Josh Lockhart
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Util
|
||||
{
|
||||
/**
|
||||
* Strip slashes from string or array
|
||||
*
|
||||
* This method strips slashes from its input. By default, this method will only
|
||||
* strip slashes from its input if magic quotes are enabled. Otherwise, you may
|
||||
* override the magic quotes setting with either TRUE or FALSE as the send argument
|
||||
* to force this method to strip or not strip slashes from its input.
|
||||
*
|
||||
* @param array|string $rawData
|
||||
* @param bool $overrideStripSlashes
|
||||
* @return array|string
|
||||
*/
|
||||
public static function stripSlashesIfMagicQuotes($rawData, $overrideStripSlashes = null)
|
||||
{
|
||||
$strip = is_null($overrideStripSlashes) ? get_magic_quotes_gpc() : $overrideStripSlashes;
|
||||
if ($strip) {
|
||||
return self::stripSlashes($rawData);
|
||||
} else {
|
||||
return $rawData;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip slashes from string or array
|
||||
* @param array|string $rawData
|
||||
* @return array|string
|
||||
*/
|
||||
protected static function stripSlashes($rawData)
|
||||
{
|
||||
return is_array($rawData) ? array_map(array('self', 'stripSlashes'), $rawData) : stripslashes($rawData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt data
|
||||
*
|
||||
* This method will encrypt data using a given key, vector, and cipher.
|
||||
* By default, this will encrypt data using the RIJNDAEL/AES 256 bit cipher. You
|
||||
* may override the default cipher and cipher mode by passing your own desired
|
||||
* cipher and cipher mode as the final key-value array argument.
|
||||
*
|
||||
* @param string $data The unencrypted data
|
||||
* @param string $key The encryption key
|
||||
* @param string $iv The encryption initialization vector
|
||||
* @param array $settings Optional key-value array with custom algorithm and mode
|
||||
* @return string
|
||||
*/
|
||||
public static function encrypt($data, $key, $iv, $settings = array())
|
||||
{
|
||||
if ($data === '' || !extension_loaded('mcrypt')) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
//Merge settings with defaults
|
||||
$defaults = array(
|
||||
'algorithm' => MCRYPT_RIJNDAEL_256,
|
||||
'mode' => MCRYPT_MODE_CBC
|
||||
);
|
||||
$settings = array_merge($defaults, $settings);
|
||||
|
||||
//Get module
|
||||
$module = mcrypt_module_open($settings['algorithm'], '', $settings['mode'], '');
|
||||
|
||||
//Validate IV
|
||||
$ivSize = mcrypt_enc_get_iv_size($module);
|
||||
if (strlen($iv) > $ivSize) {
|
||||
$iv = substr($iv, 0, $ivSize);
|
||||
}
|
||||
|
||||
//Validate key
|
||||
$keySize = mcrypt_enc_get_key_size($module);
|
||||
if (strlen($key) > $keySize) {
|
||||
$key = substr($key, 0, $keySize);
|
||||
}
|
||||
|
||||
//Encrypt value
|
||||
mcrypt_generic_init($module, $key, $iv);
|
||||
$res = @mcrypt_generic($module, $data);
|
||||
mcrypt_generic_deinit($module);
|
||||
|
||||
return $res;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt data
|
||||
*
|
||||
* This method will decrypt data using a given key, vector, and cipher.
|
||||
* By default, this will decrypt data using the RIJNDAEL/AES 256 bit cipher. You
|
||||
* may override the default cipher and cipher mode by passing your own desired
|
||||
* cipher and cipher mode as the final key-value array argument.
|
||||
*
|
||||
* @param string $data The encrypted data
|
||||
* @param string $key The encryption key
|
||||
* @param string $iv The encryption initialization vector
|
||||
* @param array $settings Optional key-value array with custom algorithm and mode
|
||||
* @return string
|
||||
*/
|
||||
public static function decrypt($data, $key, $iv, $settings = array())
|
||||
{
|
||||
if ($data === '' || !extension_loaded('mcrypt')) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
//Merge settings with defaults
|
||||
$defaults = array(
|
||||
'algorithm' => MCRYPT_RIJNDAEL_256,
|
||||
'mode' => MCRYPT_MODE_CBC
|
||||
);
|
||||
$settings = array_merge($defaults, $settings);
|
||||
|
||||
//Get module
|
||||
$module = mcrypt_module_open($settings['algorithm'], '', $settings['mode'], '');
|
||||
|
||||
//Validate IV
|
||||
$ivSize = mcrypt_enc_get_iv_size($module);
|
||||
if (strlen($iv) > $ivSize) {
|
||||
$iv = substr($iv, 0, $ivSize);
|
||||
}
|
||||
|
||||
//Validate key
|
||||
$keySize = mcrypt_enc_get_key_size($module);
|
||||
if (strlen($key) > $keySize) {
|
||||
$key = substr($key, 0, $keySize);
|
||||
}
|
||||
|
||||
//Decrypt value
|
||||
mcrypt_generic_init($module, $key, $iv);
|
||||
$decryptedData = @mdecrypt_generic($module, $data);
|
||||
$res = rtrim($decryptedData, "\0");
|
||||
mcrypt_generic_deinit($module);
|
||||
|
||||
return $res;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize Response cookies into raw HTTP header
|
||||
* @param \Slim\Http\Headers $headers The Response headers
|
||||
* @param \Slim\Http\Cookies $cookies The Response cookies
|
||||
* @param array $config The Slim app settings
|
||||
*/
|
||||
public static function serializeCookies(\Slim\Http\Headers &$headers, \Slim\Http\Cookies $cookies, array $config)
|
||||
{
|
||||
if ($config['cookies.encrypt']) {
|
||||
foreach ($cookies as $name => $settings) {
|
||||
if (is_string($settings['expires'])) {
|
||||
$expires = strtotime($settings['expires']);
|
||||
} else {
|
||||
$expires = (int) $settings['expires'];
|
||||
}
|
||||
|
||||
$settings['value'] = static::encodeSecureCookie(
|
||||
$settings['value'],
|
||||
$expires,
|
||||
$config['cookies.secret_key'],
|
||||
$config['cookies.cipher'],
|
||||
$config['cookies.cipher_mode']
|
||||
);
|
||||
static::setCookieHeader($headers, $name, $settings);
|
||||
}
|
||||
} else {
|
||||
foreach ($cookies as $name => $settings) {
|
||||
static::setCookieHeader($headers, $name, $settings);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode secure cookie value
|
||||
*
|
||||
* This method will create the secure value of an HTTP cookie. The
|
||||
* cookie value is encrypted and hashed so that its value is
|
||||
* secure and checked for integrity when read in subsequent requests.
|
||||
*
|
||||
* @param string $value The insecure HTTP cookie value
|
||||
* @param int $expires The UNIX timestamp at which this cookie will expire
|
||||
* @param string $secret The secret key used to hash the cookie value
|
||||
* @param int $algorithm The algorithm to use for encryption
|
||||
* @param int $mode The algorithm mode to use for encryption
|
||||
* @return string
|
||||
*/
|
||||
public static function encodeSecureCookie($value, $expires, $secret, $algorithm, $mode)
|
||||
{
|
||||
$key = hash_hmac('sha1', (string) $expires, $secret);
|
||||
$iv = self::getIv($expires, $secret);
|
||||
$secureString = base64_encode(
|
||||
self::encrypt(
|
||||
$value,
|
||||
$key,
|
||||
$iv,
|
||||
array(
|
||||
'algorithm' => $algorithm,
|
||||
'mode' => $mode
|
||||
)
|
||||
)
|
||||
);
|
||||
$verificationString = hash_hmac('sha1', $expires . $value, $key);
|
||||
|
||||
return implode('|', array($expires, $secureString, $verificationString));
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode secure cookie value
|
||||
*
|
||||
* This method will decode the secure value of an HTTP cookie. The
|
||||
* cookie value is encrypted and hashed so that its value is
|
||||
* secure and checked for integrity when read in subsequent requests.
|
||||
*
|
||||
* @param string $value The secure HTTP cookie value
|
||||
* @param string $secret The secret key used to hash the cookie value
|
||||
* @param int $algorithm The algorithm to use for encryption
|
||||
* @param int $mode The algorithm mode to use for encryption
|
||||
* @return bool|string
|
||||
*/
|
||||
public static function decodeSecureCookie($value, $secret, $algorithm, $mode)
|
||||
{
|
||||
if ($value) {
|
||||
$value = explode('|', $value);
|
||||
if (count($value) === 3 && ((int) $value[0] === 0 || (int) $value[0] > time())) {
|
||||
$key = hash_hmac('sha1', $value[0], $secret);
|
||||
$iv = self::getIv($value[0], $secret);
|
||||
$data = self::decrypt(
|
||||
base64_decode($value[1]),
|
||||
$key,
|
||||
$iv,
|
||||
array(
|
||||
'algorithm' => $algorithm,
|
||||
'mode' => $mode
|
||||
)
|
||||
);
|
||||
$verificationString = hash_hmac('sha1', $value[0] . $data, $key);
|
||||
if ($verificationString === $value[2]) {
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set HTTP cookie header
|
||||
*
|
||||
* This method will construct and set the HTTP `Set-Cookie` header. Slim
|
||||
* uses this method instead of PHP's native `setcookie` method. This allows
|
||||
* more control of the HTTP header irrespective of the native implementation's
|
||||
* dependency on PHP versions.
|
||||
*
|
||||
* This method accepts the Slim_Http_Headers object by reference as its
|
||||
* first argument; this method directly modifies this object instead of
|
||||
* returning a value.
|
||||
*
|
||||
* @param array $header
|
||||
* @param string $name
|
||||
* @param string $value
|
||||
*/
|
||||
public static function setCookieHeader(&$header, $name, $value)
|
||||
{
|
||||
//Build cookie header
|
||||
if (is_array($value)) {
|
||||
$domain = '';
|
||||
$path = '';
|
||||
$expires = '';
|
||||
$secure = '';
|
||||
$httponly = '';
|
||||
if (isset($value['domain']) && $value['domain']) {
|
||||
$domain = '; domain=' . $value['domain'];
|
||||
}
|
||||
if (isset($value['path']) && $value['path']) {
|
||||
$path = '; path=' . $value['path'];
|
||||
}
|
||||
if (isset($value['expires'])) {
|
||||
if (is_string($value['expires'])) {
|
||||
$timestamp = strtotime($value['expires']);
|
||||
} else {
|
||||
$timestamp = (int) $value['expires'];
|
||||
}
|
||||
if ($timestamp !== 0) {
|
||||
$expires = '; expires=' . gmdate('D, d-M-Y H:i:s e', $timestamp);
|
||||
}
|
||||
}
|
||||
if (isset($value['secure']) && $value['secure']) {
|
||||
$secure = '; secure';
|
||||
}
|
||||
if (isset($value['httponly']) && $value['httponly']) {
|
||||
$httponly = '; HttpOnly';
|
||||
}
|
||||
$cookie = sprintf('%s=%s%s', urlencode($name), urlencode((string) $value['value']), $domain . $path . $expires . $secure . $httponly);
|
||||
} else {
|
||||
$cookie = sprintf('%s=%s', urlencode($name), urlencode((string) $value));
|
||||
}
|
||||
|
||||
//Set cookie header
|
||||
if (!isset($header['Set-Cookie']) || $header['Set-Cookie'] === '') {
|
||||
$header['Set-Cookie'] = $cookie;
|
||||
} else {
|
||||
$header['Set-Cookie'] = implode("\n", array($header['Set-Cookie'], $cookie));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete HTTP cookie header
|
||||
*
|
||||
* This method will construct and set the HTTP `Set-Cookie` header to invalidate
|
||||
* a client-side HTTP cookie. If a cookie with the same name (and, optionally, domain)
|
||||
* is already set in the HTTP response, it will also be removed. Slim uses this method
|
||||
* instead of PHP's native `setcookie` method. This allows more control of the HTTP header
|
||||
* irrespective of PHP's native implementation's dependency on PHP versions.
|
||||
*
|
||||
* This method accepts the Slim_Http_Headers object by reference as its
|
||||
* first argument; this method directly modifies this object instead of
|
||||
* returning a value.
|
||||
*
|
||||
* @param array $header
|
||||
* @param string $name
|
||||
* @param array $value
|
||||
*/
|
||||
public static function deleteCookieHeader(&$header, $name, $value = array())
|
||||
{
|
||||
//Remove affected cookies from current response header
|
||||
$cookiesOld = array();
|
||||
$cookiesNew = array();
|
||||
if (isset($header['Set-Cookie'])) {
|
||||
$cookiesOld = explode("\n", $header['Set-Cookie']);
|
||||
}
|
||||
foreach ($cookiesOld as $c) {
|
||||
if (isset($value['domain']) && $value['domain']) {
|
||||
$regex = sprintf('@%s=.*domain=%s@', urlencode($name), preg_quote($value['domain']));
|
||||
} else {
|
||||
$regex = sprintf('@%s=@', urlencode($name));
|
||||
}
|
||||
if (preg_match($regex, $c) === 0) {
|
||||
$cookiesNew[] = $c;
|
||||
}
|
||||
}
|
||||
if ($cookiesNew) {
|
||||
$header['Set-Cookie'] = implode("\n", $cookiesNew);
|
||||
} else {
|
||||
unset($header['Set-Cookie']);
|
||||
}
|
||||
|
||||
//Set invalidating cookie to clear client-side cookie
|
||||
self::setCookieHeader($header, $name, array_merge(array('value' => '', 'path' => null, 'domain' => null, 'expires' => time() - 100), $value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse cookie header
|
||||
*
|
||||
* This method will parse the HTTP request's `Cookie` header
|
||||
* and extract cookies into an associative array.
|
||||
*
|
||||
* @param string
|
||||
* @return array
|
||||
*/
|
||||
public static function parseCookieHeader($header)
|
||||
{
|
||||
$cookies = array();
|
||||
$header = rtrim($header, "\r\n");
|
||||
$headerPieces = preg_split('@\s*[;,]\s*@', $header);
|
||||
foreach ($headerPieces as $c) {
|
||||
$cParts = explode('=', $c, 2);
|
||||
if (count($cParts) === 2) {
|
||||
$key = urldecode($cParts[0]);
|
||||
$value = urldecode($cParts[1]);
|
||||
if (!isset($cookies[$key])) {
|
||||
$cookies[$key] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a random IV
|
||||
*
|
||||
* This method will generate a non-predictable IV for use with
|
||||
* the cookie encryption
|
||||
*
|
||||
* @param int $expires The UNIX timestamp at which this cookie will expire
|
||||
* @param string $secret The secret key used to hash the cookie value
|
||||
* @return string Hash
|
||||
*/
|
||||
private static function getIv($expires, $secret)
|
||||
{
|
||||
$data1 = hash_hmac('sha1', 'a'.$expires.'b', $secret);
|
||||
$data2 = hash_hmac('sha1', 'z'.$expires.'y', $secret);
|
||||
|
||||
return pack("h*", $data1.$data2);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user