pax_global_header 0000666 0000000 0000000 00000000064 12634026554 0014521 g ustar 00root root 0000000 0000000 52 comment=8fbf2263732793916fbba6c90a4f13a2ec5d156b
DEEP.git/ 0000775 0000000 0000000 00000000000 12634026554 0012364 5 ustar 00root root 0000000 0000000 DEEP.git/.htaccess 0000775 0000000 0000000 00000000124 12634026554 0014162 0 ustar 00root root 0000000 0000000 RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L] DEEP.git/DEEP.php 0000775 0000000 0000000 00000012231 12634026554 0013614 0 ustar 00root root 0000000 0000000 app = new \Slim\Slim();
$this->loadRepositoryUrl("configuration.xml");
$this->all_datalets = $this->loadServices("datalets.xml", $this->datalet_repository_url);
$this->app->get('/datalets-list', function(){
$this->app->response()->header("Content-Type", "application/json");
$this->app->response()->header("Access-Control-Allow-Origin", "*");
echo json_encode($this->all_datalets);
});
$this->all_controllets = $this->loadServices("controllets.xml", $this->controllet_repository_url);
$this->app->get('/controllets-list', function(){
$this->app->response()->header("Content-Type", "application/json");
$this->app->response()->header("Access-Control-Allow-Origin", "*");
echo json_encode($this->all_controllets);
});
//main service
$this->app->get('/', function(){
echo "Hello from web compoments RESTful service, call /datalets-list to get datalets list";
});
}
public function loadRepositoryUrl($source)
{
$handler_configuration = simplexml_load_file($source) or die("ERROR: cant read Components configuration \n");
$this->datalet_repository_url = $handler_configuration->deep_datalet_configuration->components_repository_url_reference;
$this->controllet_repository_url = $handler_configuration->deep_controllets_configuration->components_repository_url_reference;
}
/**
* @param $source
* @return array
*/
public function loadServices($source, $repository_url){
$components_array = array();
$handler_configuration = simplexml_load_file($source) or die("ERROR: cant read Components configuration \n");
foreach($handler_configuration->components->children() as $component){
//array_push($components_array, $component->name."");
$component->url = $repository_url . $component->name . "/";
array_push($components_array, $component);
$this->app->get('/'.$component->name, function() use($component, $repository_url){
$response = array(
"name" => $component->name."",
"type" => $component->type."",
"bridge_link" => $repository_url."",
"component_link" => $component->name."/".$component->name.".html",
"idm" => $component->idm
);
if(isset($component->attributes)) {
$response['attributes'] = array();
foreach ($component->attributes->children() as $attribute) {
array_push($response['attributes'], $attribute->name."");
}
}
$this->app->response()->header("Content-Type", "application/json");
$this->app->response()->header("Access-Control-Allow-Origin", "*");
echo json_encode($response);
});
}
return $components_array;
}
public function run(){
//run the Slim app
$this->app->run();
}
} DEEP.git/README.md 0000775 0000000 0000000 00000002472 12634026554 0013653 0 ustar 00root root 0000000 0000000 # DatalEts Ecosystem Provider (DEEP)
The DatalEts Ecosystem Provider (DEEP) is a RESTful web service written in PHP. It make available a public discovery service that retrieve all the Datalet available into the system and a service call that provide a specific Datalet.
Developed by the [UNISA TEAM](http://www.isislab.it/) for the [ROUTE-TO-PA PROJECT](http://www.routetopa.eu/).
## Table of contents
* [Quick start](#quick-start)
* [Bugs and feature requests](#bugs-and-feature-requests)
* [Usage](#usage)
* [Versioning](#versioning)
* [Creators](#creators)
* [Copyright and license](#copyright-and-license)
## Quick start
Clone the repo: `git clone http://service.routetopa.eu:7480/admin/projects/isislab/DEEP.git`
### What's included
Within the download you'll find the following directories and files. You'll see something like this:
```
DEEPCLIENT/
├── Slim/
│ ├── ...
├── DEEP.php
├── controllets.xml
├── datalets.xml
├── index.php
└── .htaccess
```
## Bugs and feature requests
Have a bug or a feature request?
Send a mail to developers@routetopa.eu
## Versioning
v0.1
## Creators
UNISA Team - Dipartimento di Informatica - Università degli studi di Salerno - Italy
## Copyright and license
Code released under [the MIT license](https://opensource.org/licenses/MIT). DEEP.git/Slim/ 0000775 0000000 0000000 00000000000 12634026554 0013270 5 ustar 00root root 0000000 0000000 DEEP.git/Slim/.gitignore 0000775 0000000 0000000 00000000006 12634026554 0015257 0 ustar 00root root 0000000 0000000 .idea
DEEP.git/Slim/.htaccess 0000775 0000000 0000000 00000000535 12634026554 0015074 0 ustar 00root root 0000000 0000000 RewriteEngine On
# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
DEEP.git/Slim/.travis.yml 0000775 0000000 0000000 00000000146 12634026554 0015405 0 ustar 00root root 0000000 0000000 language: php
php:
- 5.3
- 5.4
- 5.5
- 5.6
- 7.0
- hhvm
script: phpunit --coverage-text
DEEP.git/Slim/CONTRIBUTING.md 0000775 0000000 0000000 00000001451 12634026554 0015525 0 ustar 00root root 0000000 0000000 # How to Contribute
## Pull Requests
1. Fork the Slim Framework repository
2. Create a new branch for each feature or improvement
3. Send a pull request from each feature branch to the **develop** branch
It is very important to separate new features or improvements into separate feature branches, and to send a
pull request for each branch. This allows me to review and pull in new features or improvements individually.
## Style Guide
All pull requests must adhere to the [PSR-2 standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md).
## Unit Testing
All pull requests must be accompanied by passing unit tests and complete code coverage. The Slim Framework uses phpunit for testing.
[Learn about PHPUnit](https://github.com/sebastianbergmann/phpunit/)
DEEP.git/Slim/Environment.php 0000775 0000000 0000000 00000016571 12634026554 0016322 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
/**
* Environment
*
* This class creates and returns a key/value array of common
* environment variables for the current HTTP request.
*
* This is a singleton class; derived environment variables will
* be common across multiple Slim applications.
*
* This class matches the Rack (Ruby) specification as closely
* as possible. More information available below.
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
class Environment implements \ArrayAccess, \IteratorAggregate
{
/**
* @var array
*/
protected $properties;
/**
* @var \Slim\Environment
*/
protected static $environment;
/**
* Get environment instance (singleton)
*
* This creates and/or returns an environment instance (singleton)
* derived from $_SERVER variables. You may override the global server
* variables by using `\Slim\Environment::mock()` instead.
*
* @param bool $refresh Refresh properties using global server variables?
* @return \Slim\Environment
*/
public static function getInstance($refresh = false)
{
if (is_null(self::$environment) || $refresh) {
self::$environment = new self();
}
return self::$environment;
}
/**
* Get mock environment instance
*
* @param array $userSettings
* @return \Slim\Environment
*/
public static function mock($userSettings = array())
{
$defaults = array(
'REQUEST_METHOD' => 'GET',
'SCRIPT_NAME' => '',
'PATH_INFO' => '',
'QUERY_STRING' => '',
'SERVER_NAME' => 'localhost',
'SERVER_PORT' => 80,
'ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'ACCEPT_LANGUAGE' => 'en-US,en;q=0.8',
'ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'USER_AGENT' => 'Slim Framework',
'REMOTE_ADDR' => '127.0.0.1',
'slim.url_scheme' => 'http',
'slim.input' => '',
'slim.errors' => @fopen('php://stderr', 'w')
);
self::$environment = new self(array_merge($defaults, $userSettings));
return self::$environment;
}
/**
* Constructor (private access)
*
* @param array|null $settings If present, these are used instead of global server variables
*/
private function __construct($settings = null)
{
if ($settings) {
$this->properties = $settings;
} else {
$env = array();
//The HTTP request method
$env['REQUEST_METHOD'] = $_SERVER['REQUEST_METHOD'];
//The IP
$env['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
// Server params
$scriptName = $_SERVER['SCRIPT_NAME']; // <-- "/foo/index.php"
$requestUri = $_SERVER['REQUEST_URI']; // <-- "/foo/bar?test=abc" or "/foo/index.php/bar?test=abc"
$queryString = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''; // <-- "test=abc" or ""
// Physical path
if (strpos($requestUri, $scriptName) !== false) {
$physicalPath = $scriptName; // <-- Without rewriting
} else {
$physicalPath = str_replace('\\', '', dirname($scriptName)); // <-- With rewriting
}
$env['SCRIPT_NAME'] = rtrim($physicalPath, '/'); // <-- Remove trailing slashes
// Virtual path
$env['PATH_INFO'] = $requestUri;
if (substr($requestUri, 0, strlen($physicalPath)) == $physicalPath) {
$env['PATH_INFO'] = substr($requestUri, strlen($physicalPath)); // <-- Remove physical path
}
$env['PATH_INFO'] = str_replace('?' . $queryString, '', $env['PATH_INFO']); // <-- Remove query string
$env['PATH_INFO'] = '/' . ltrim($env['PATH_INFO'], '/'); // <-- Ensure leading slash
// Query string (without leading "?")
$env['QUERY_STRING'] = $queryString;
//Name of server host that is running the script
$env['SERVER_NAME'] = $_SERVER['SERVER_NAME'];
//Number of server port that is running the script
//Fixes: https://github.com/slimphp/Slim/issues/962
$env['SERVER_PORT'] = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
//HTTP request headers (retains HTTP_ prefix to match $_SERVER)
$headers = \Slim\Http\Headers::extract($_SERVER);
foreach ($headers as $key => $value) {
$env[$key] = $value;
}
//Is the application running under HTTPS or HTTP protocol?
$env['slim.url_scheme'] = empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' ? 'http' : 'https';
//Input stream (readable one time only; not available for multipart/form-data requests)
$rawInput = @file_get_contents('php://input');
if (!$rawInput) {
$rawInput = '';
}
$env['slim.input'] = $rawInput;
//Error stream
$env['slim.errors'] = @fopen('php://stderr', 'w');
$this->properties = $env;
}
}
/**
* Array Access: Offset Exists
*/
public function offsetExists($offset)
{
return isset($this->properties[$offset]);
}
/**
* Array Access: Offset Get
*/
public function offsetGet($offset)
{
if (isset($this->properties[$offset])) {
return $this->properties[$offset];
}
return null;
}
/**
* Array Access: Offset Set
*/
public function offsetSet($offset, $value)
{
$this->properties[$offset] = $value;
}
/**
* Array Access: Offset Unset
*/
public function offsetUnset($offset)
{
unset($this->properties[$offset]);
}
/**
* IteratorAggregate
*
* @return \ArrayIterator
*/
public function getIterator()
{
return new \ArrayIterator($this->properties);
}
}
DEEP.git/Slim/Exception/ 0000775 0000000 0000000 00000000000 12634026554 0015226 5 ustar 00root root 0000000 0000000 DEEP.git/Slim/Exception/Pass.php 0000775 0000000 0000000 00000003347 12634026554 0016657 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Exception;
/**
* Pass Exception
*
* This Exception will cause the Router::dispatch method
* to skip the current matching route and continue to the next
* matching route. If no subsequent routes are found, a
* HTTP 404 Not Found response will be sent to the client.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class Pass extends \Exception
{
}
DEEP.git/Slim/Exception/Stop.php 0000775 0000000 0000000 00000003200 12634026554 0016662 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Exception;
/**
* Stop Exception
*
* This Exception is thrown when the Slim application needs to abort
* processing and return control flow to the outer PHP script.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class Stop extends \Exception
{
}
DEEP.git/Slim/Helper/ 0000775 0000000 0000000 00000000000 12634026554 0014507 5 ustar 00root root 0000000 0000000 DEEP.git/Slim/Helper/Set.php 0000775 0000000 0000000 00000013574 12634026554 0015770 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Helper;
class Set implements \ArrayAccess, \Countable, \IteratorAggregate
{
/**
* Key-value array of arbitrary data
* @var array
*/
protected $data = array();
/**
* Constructor
* @param array $items Pre-populate set with this key-value array
*/
public function __construct($items = array())
{
$this->replace($items);
}
/**
* Normalize data key
*
* Used to transform data key into the necessary
* key format for this set. Used in subclasses
* like \Slim\Http\Headers.
*
* @param string $key The data key
* @return mixed The transformed/normalized data key
*/
protected function normalizeKey($key)
{
return $key;
}
/**
* Set data key to value
* @param string $key The data key
* @param mixed $value The data value
*/
public function set($key, $value)
{
$this->data[$this->normalizeKey($key)] = $value;
}
/**
* Get data value with key
* @param string $key The data key
* @param mixed $default The value to return if data key does not exist
* @return mixed The data value, or the default value
*/
public function get($key, $default = null)
{
if ($this->has($key)) {
$isInvokable = is_object($this->data[$this->normalizeKey($key)]) && method_exists($this->data[$this->normalizeKey($key)], '__invoke');
return $isInvokable ? $this->data[$this->normalizeKey($key)]($this) : $this->data[$this->normalizeKey($key)];
}
return $default;
}
/**
* Add data to set
* @param array $items Key-value array of data to append to this set
*/
public function replace($items)
{
foreach ($items as $key => $value) {
$this->set($key, $value); // Ensure keys are normalized
}
}
/**
* Fetch set data
* @return array This set's key-value data array
*/
public function all()
{
return $this->data;
}
/**
* Fetch set data keys
* @return array This set's key-value data array keys
*/
public function keys()
{
return array_keys($this->data);
}
/**
* Does this set contain a key?
* @param string $key The data key
* @return boolean
*/
public function has($key)
{
return array_key_exists($this->normalizeKey($key), $this->data);
}
/**
* Remove value with key from this set
* @param string $key The data key
*/
public function remove($key)
{
unset($this->data[$this->normalizeKey($key)]);
}
/**
* Property Overloading
*/
public function __get($key)
{
return $this->get($key);
}
public function __set($key, $value)
{
$this->set($key, $value);
}
public function __isset($key)
{
return $this->has($key);
}
public function __unset($key)
{
$this->remove($key);
}
/**
* Clear all values
*/
public function clear()
{
$this->data = array();
}
/**
* Array Access
*/
public function offsetExists($offset)
{
return $this->has($offset);
}
public function offsetGet($offset)
{
return $this->get($offset);
}
public function offsetSet($offset, $value)
{
$this->set($offset, $value);
}
public function offsetUnset($offset)
{
$this->remove($offset);
}
/**
* Countable
*/
public function count()
{
return count($this->data);
}
/**
* IteratorAggregate
*/
public function getIterator()
{
return new \ArrayIterator($this->data);
}
/**
* Ensure a value or object will remain globally unique
* @param string $key The value or object name
* @param \Closure $value The closure that defines the object
* @return mixed
*/
public function singleton($key, $value)
{
$this->set($key, function ($c) use ($value) {
static $object;
if (null === $object) {
$object = $value($c);
}
return $object;
});
}
/**
* Protect closure from being directly invoked
* @param \Closure $callable A closure to keep from being invoked and evaluated
* @return \Closure
*/
public function protect(\Closure $callable)
{
return function () use ($callable) {
return $callable;
};
}
}
DEEP.git/Slim/Http/ 0000775 0000000 0000000 00000000000 12634026554 0014207 5 ustar 00root root 0000000 0000000 DEEP.git/Slim/Http/Cookies.php 0000775 0000000 0000000 00000006063 12634026554 0016324 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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));
}
}
DEEP.git/Slim/Http/Headers.php 0000775 0000000 0000000 00000006514 12634026554 0016304 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
}
}
DEEP.git/Slim/Http/Request.php 0000775 0000000 0000000 00000041001 12634026554 0016347 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
}
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');
}
}
DEEP.git/Slim/Http/Response.php 0000775 0000000 0000000 00000034321 12634026554 0016524 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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',
226 => '226 IM Used',
//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',
426 => '426 Upgrade Required',
428 => '428 Precondition Required',
429 => '429 Too Many Requests',
431 => '431 Request Header Fields Too Large',
//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',
506 => '506 Variant Also Negotiates',
510 => '510 Not Extended',
511 => '511 Network Authentication Required'
);
/**
* 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;
}
}
}
DEEP.git/Slim/Http/Util.php 0000775 0000000 0000000 00000036637 12634026554 0015657 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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);
}
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);
}
}
DEEP.git/Slim/LICENSE 0000775 0000000 0000000 00000002041 12634026554 0014275 0 ustar 00root root 0000000 0000000 Copyright (c) 2012 Josh Lockhart
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.
DEEP.git/Slim/Log.php 0000775 0000000 0000000 00000023731 12634026554 0014533 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
/**
* Log
*
* This is the primary logger for a Slim application. You may provide
* a Log Writer in conjunction with this Log to write to various output
* destinations (e.g. a file). This class provides this interface:
*
* debug( mixed $object, array $context )
* info( mixed $object, array $context )
* notice( mixed $object, array $context )
* warning( mixed $object, array $context )
* error( mixed $object, array $context )
* critical( mixed $object, array $context )
* alert( mixed $object, array $context )
* emergency( mixed $object, array $context )
* log( mixed $level, mixed $object, array $context )
*
* This class assumes only that your Log Writer has a public `write()` method
* that accepts any object as its one and only argument. The Log Writer
* class may write or send its argument anywhere: a file, STDERR,
* a remote web API, etc. The possibilities are endless.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class Log
{
const EMERGENCY = 1;
const ALERT = 2;
const CRITICAL = 3;
const FATAL = 3; //DEPRECATED replace with CRITICAL
const ERROR = 4;
const WARN = 5;
const NOTICE = 6;
const INFO = 7;
const DEBUG = 8;
/**
* @var array
*/
protected static $levels = array(
self::EMERGENCY => 'EMERGENCY',
self::ALERT => 'ALERT',
self::CRITICAL => 'CRITICAL',
self::ERROR => 'ERROR',
self::WARN => 'WARNING',
self::NOTICE => 'NOTICE',
self::INFO => 'INFO',
self::DEBUG => 'DEBUG'
);
/**
* @var mixed
*/
protected $writer;
/**
* @var bool
*/
protected $enabled;
/**
* @var int
*/
protected $level;
/**
* Constructor
* @param mixed $writer
*/
public function __construct($writer)
{
$this->writer = $writer;
$this->enabled = true;
$this->level = self::DEBUG;
}
/**
* Is logging enabled?
* @return bool
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Enable or disable logging
* @param bool $enabled
*/
public function setEnabled($enabled)
{
if ($enabled) {
$this->enabled = true;
} else {
$this->enabled = false;
}
}
/**
* Set level
* @param int $level
* @throws \InvalidArgumentException If invalid log level specified
*/
public function setLevel($level)
{
if (!isset(self::$levels[$level])) {
throw new \InvalidArgumentException('Invalid log level');
}
$this->level = $level;
}
/**
* Get level
* @return int
*/
public function getLevel()
{
return $this->level;
}
/**
* Set writer
* @param mixed $writer
*/
public function setWriter($writer)
{
$this->writer = $writer;
}
/**
* Get writer
* @return mixed
*/
public function getWriter()
{
return $this->writer;
}
/**
* Is logging enabled?
* @return bool
*/
public function isEnabled()
{
return $this->enabled;
}
/**
* Log debug message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function debug($object, $context = array())
{
return $this->log(self::DEBUG, $object, $context);
}
/**
* Log info message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function info($object, $context = array())
{
return $this->log(self::INFO, $object, $context);
}
/**
* Log notice message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function notice($object, $context = array())
{
return $this->log(self::NOTICE, $object, $context);
}
/**
* Log warning message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function warning($object, $context = array())
{
return $this->log(self::WARN, $object, $context);
}
/**
* DEPRECATED for function warning
* Log warning message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function warn($object, $context = array())
{
return $this->log(self::WARN, $object, $context);
}
/**
* Log error message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function error($object, $context = array())
{
return $this->log(self::ERROR, $object, $context);
}
/**
* Log critical message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function critical($object, $context = array())
{
return $this->log(self::CRITICAL, $object, $context);
}
/**
* DEPRECATED for function critical
* Log fatal message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function fatal($object, $context = array())
{
return $this->log(self::CRITICAL, $object, $context);
}
/**
* Log alert message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function alert($object, $context = array())
{
return $this->log(self::ALERT, $object, $context);
}
/**
* Log emergency message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function emergency($object, $context = array())
{
return $this->log(self::EMERGENCY, $object, $context);
}
/**
* Log message
* @param mixed $level
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
* @throws \InvalidArgumentException If invalid log level
*/
public function log($level, $object, $context = array())
{
if (!isset(self::$levels[$level])) {
throw new \InvalidArgumentException('Invalid log level supplied to function');
} else if ($this->enabled && $this->writer && $level <= $this->level) {
if (is_array($object) || (is_object($object) && !method_exists($object, "__toString"))) {
$message = print_r($object, true);
} else {
$message = (string) $object;
}
if (count($context) > 0) {
if (isset($context['exception']) && $context['exception'] instanceof \Exception) {
$message .= ' - ' . $context['exception'];
unset($context['exception']);
}
$message = $this->interpolate($message, $context);
}
return $this->writer->write($message, $level);
} else {
return false;
}
}
/**
* DEPRECATED for function log
* Log message
* @param mixed $object The object to log
* @param int $level The message level
* @return int|bool
*/
protected function write($object, $level)
{
return $this->log($level, $object);
}
/**
* Interpolate log message
* @param mixed $message The log message
* @param array $context An array of placeholder values
* @return string The processed string
*/
protected function interpolate($message, $context = array())
{
$replace = array();
foreach ($context as $key => $value) {
$replace['{' . $key . '}'] = $value;
}
return strtr($message, $replace);
}
}
DEEP.git/Slim/LogWriter.php 0000775 0000000 0000000 00000004442 12634026554 0015726 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
/**
* Log Writer
*
* This class is used by Slim_Log to write log messages to a valid, writable
* resource handle (e.g. a file or STDERR).
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
class LogWriter
{
/**
* @var resource
*/
protected $resource;
/**
* Constructor
* @param resource $resource
* @throws \InvalidArgumentException If invalid resource
*/
public function __construct($resource)
{
if (!is_resource($resource)) {
throw new \InvalidArgumentException('Cannot create LogWriter. Invalid resource handle.');
}
$this->resource = $resource;
}
/**
* Write message
* @param mixed $message
* @param int $level
* @return int|bool
*/
public function write($message, $level = null)
{
return fwrite($this->resource, (string) $message . PHP_EOL);
}
}
DEEP.git/Slim/Middleware.php 0000775 0000000 0000000 00000006026 12634026554 0016065 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
/**
* Middleware
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
abstract class Middleware
{
/**
* @var \Slim\Slim Reference to the primary application instance
*/
protected $app;
/**
* @var mixed Reference to the next downstream middleware
*/
protected $next;
/**
* Set application
*
* This method injects the primary Slim application instance into
* this middleware.
*
* @param \Slim\Slim $application
*/
final public function setApplication($application)
{
$this->app = $application;
}
/**
* Get application
*
* This method retrieves the application previously injected
* into this middleware.
*
* @return \Slim\Slim
*/
final public function getApplication()
{
return $this->app;
}
/**
* Set next middleware
*
* This method injects the next downstream middleware into
* this middleware so that it may optionally be called
* when appropriate.
*
* @param \Slim|\Slim\Middleware
*/
final public function setNextMiddleware($nextMiddleware)
{
$this->next = $nextMiddleware;
}
/**
* Get next middleware
*
* This method retrieves the next downstream middleware
* previously injected into this middleware.
*
* @return \Slim\Slim|\Slim\Middleware
*/
final public function getNextMiddleware()
{
return $this->next;
}
/**
* Call
*
* Perform actions specific to this middleware and optionally
* call the next downstream middleware.
*/
abstract public function call();
}
DEEP.git/Slim/Middleware/ 0000775 0000000 0000000 00000000000 12634026554 0015345 5 ustar 00root root 0000000 0000000 DEEP.git/Slim/Middleware/ContentTypes.php 0000775 0000000 0000000 00000011750 12634026554 0020524 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Middleware;
/**
* Content Types
*
* This is middleware for a Slim application that intercepts
* the HTTP request body and parses it into the appropriate
* PHP data structure if possible; else it returns the HTTP
* request body unchanged. This is particularly useful
* for preparing the HTTP request body for an XML or JSON API.
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
class ContentTypes extends \Slim\Middleware
{
/**
* @var array
*/
protected $contentTypes;
/**
* Constructor
* @param array $settings
*/
public function __construct($settings = array())
{
$defaults = array(
'application/json' => array($this, 'parseJson'),
'application/xml' => array($this, 'parseXml'),
'text/xml' => array($this, 'parseXml'),
'text/csv' => array($this, 'parseCsv')
);
$this->contentTypes = array_merge($defaults, $settings);
}
/**
* Call
*/
public function call()
{
$mediaType = $this->app->request()->getMediaType();
if ($mediaType) {
$env = $this->app->environment();
$env['slim.input_original'] = $env['slim.input'];
$env['slim.input'] = $this->parse($env['slim.input'], $mediaType);
}
$this->next->call();
}
/**
* Parse input
*
* This method will attempt to parse the request body
* based on its content type if available.
*
* @param string $input
* @param string $contentType
* @return mixed
*/
protected function parse ($input, $contentType)
{
if (isset($this->contentTypes[$contentType]) && is_callable($this->contentTypes[$contentType])) {
$result = call_user_func($this->contentTypes[$contentType], $input);
if ($result) {
return $result;
}
}
return $input;
}
/**
* Parse JSON
*
* This method converts the raw JSON input
* into an associative array.
*
* @param string $input
* @return array|string
*/
protected function parseJson($input)
{
if (function_exists('json_decode')) {
$result = json_decode($input, true);
if(json_last_error() === JSON_ERROR_NONE) {
return $result;
}
}
}
/**
* Parse XML
*
* This method creates a SimpleXMLElement
* based upon the XML input. If the SimpleXML
* extension is not available, the raw input
* will be returned unchanged.
*
* @param string $input
* @return \SimpleXMLElement|string
*/
protected function parseXml($input)
{
if (class_exists('SimpleXMLElement')) {
try {
$backup = libxml_disable_entity_loader(true);
$result = new \SimpleXMLElement($input);
libxml_disable_entity_loader($backup);
return $result;
} catch (\Exception $e) {
// Do nothing
}
}
return $input;
}
/**
* Parse CSV
*
* This method parses CSV content into a numeric array
* containing an array of data for each CSV line.
*
* @param string $input
* @return array
*/
protected function parseCsv($input)
{
$temp = fopen('php://memory', 'rw');
fwrite($temp, $input);
fseek($temp, 0);
$res = array();
while (($data = fgetcsv($temp)) !== false) {
$res[] = $data;
}
fclose($temp);
return $res;
}
}
DEEP.git/Slim/Middleware/Flash.php 0000775 0000000 0000000 00000012426 12634026554 0017123 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Middleware;
/**
* Flash
*
* This is middleware for a Slim application that enables
* Flash messaging between HTTP requests. This allows you
* set Flash messages for the current request, for the next request,
* or to retain messages from the previous request through to
* the next request.
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
class Flash extends \Slim\Middleware implements \ArrayAccess, \IteratorAggregate, \Countable
{
/**
* @var array
*/
protected $settings;
/**
* @var array
*/
protected $messages;
/**
* Constructor
* @param array $settings
*/
public function __construct($settings = array())
{
$this->settings = array_merge(array('key' => 'slim.flash'), $settings);
$this->messages = array(
'prev' => array(), //flash messages from prev request (loaded when middleware called)
'next' => array(), //flash messages for next request
'now' => array() //flash messages for current request
);
}
/**
* Call
*/
public function call()
{
//Read flash messaging from previous request if available
$this->loadMessages();
//Prepare flash messaging for current request
$env = $this->app->environment();
$env['slim.flash'] = $this;
$this->next->call();
$this->save();
}
/**
* Now
*
* Specify a flash message for a given key to be shown for the current request
*
* @param string $key
* @param string $value
*/
public function now($key, $value)
{
$this->messages['now'][(string) $key] = $value;
}
/**
* Set
*
* Specify a flash message for a given key to be shown for the next request
*
* @param string $key
* @param string $value
*/
public function set($key, $value)
{
$this->messages['next'][(string) $key] = $value;
}
/**
* Keep
*
* Retain flash messages from the previous request for the next request
*/
public function keep()
{
foreach ($this->messages['prev'] as $key => $val) {
$this->messages['next'][$key] = $val;
}
}
/**
* Save
*/
public function save()
{
$_SESSION[$this->settings['key']] = $this->messages['next'];
}
/**
* Load messages from previous request if available
*/
public function loadMessages()
{
if (isset($_SESSION[$this->settings['key']])) {
$this->messages['prev'] = $_SESSION[$this->settings['key']];
}
}
/**
* Return array of flash messages to be shown for the current request
*
* @return array
*/
public function getMessages()
{
return array_merge($this->messages['prev'], $this->messages['now']);
}
/**
* Array Access: Offset Exists
*/
public function offsetExists($offset)
{
$messages = $this->getMessages();
return isset($messages[$offset]);
}
/**
* Array Access: Offset Get
*/
public function offsetGet($offset)
{
$messages = $this->getMessages();
return isset($messages[$offset]) ? $messages[$offset] : null;
}
/**
* Array Access: Offset Set
*/
public function offsetSet($offset, $value)
{
$this->now($offset, $value);
}
/**
* Array Access: Offset Unset
*/
public function offsetUnset($offset)
{
unset($this->messages['prev'][$offset], $this->messages['now'][$offset]);
}
/**
* Iterator Aggregate: Get Iterator
* @return \ArrayIterator
*/
public function getIterator()
{
$messages = $this->getMessages();
return new \ArrayIterator($messages);
}
/**
* Countable: Count
*/
public function count()
{
return count($this->getMessages());
}
}
DEEP.git/Slim/Middleware/MethodOverride.php 0000775 0000000 0000000 00000006634 12634026554 0021012 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Middleware;
/**
* HTTP Method Override
*
* This is middleware for a Slim application that allows traditional
* desktop browsers to submit pseudo PUT and DELETE requests by relying
* on a pre-determined request parameter. Without this middleware,
* desktop browsers are only able to submit GET and POST requests.
*
* This middleware is included automatically!
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
class MethodOverride extends \Slim\Middleware
{
/**
* @var array
*/
protected $settings;
/**
* Constructor
* @param array $settings
*/
public function __construct($settings = array())
{
$this->settings = array_merge(array('key' => '_METHOD'), $settings);
}
/**
* Call
*
* Implements Slim middleware interface. This method is invoked and passed
* an array of environment variables. This middleware inspects the environment
* variables for the HTTP method override parameter; if found, this middleware
* modifies the environment settings so downstream middleware and/or the Slim
* application will treat the request with the desired HTTP method.
*
* @return array[status, header, body]
*/
public function call()
{
$env = $this->app->environment();
if (isset($env['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
// Header commonly used by Backbone.js and others
$env['slim.method_override.original_method'] = $env['REQUEST_METHOD'];
$env['REQUEST_METHOD'] = strtoupper($env['HTTP_X_HTTP_METHOD_OVERRIDE']);
} elseif (isset($env['REQUEST_METHOD']) && $env['REQUEST_METHOD'] === 'POST') {
// HTML Form Override
$req = new \Slim\Http\Request($env);
$method = $req->post($this->settings['key']);
if ($method) {
$env['slim.method_override.original_method'] = $env['REQUEST_METHOD'];
$env['REQUEST_METHOD'] = strtoupper($method);
}
}
$this->next->call();
}
}
DEEP.git/Slim/Middleware/PrettyExceptions.php 0000775 0000000 0000000 00000010047 12634026554 0021414 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Middleware;
/**
* Pretty Exceptions
*
* This middleware catches any Exception thrown by the surrounded
* application and displays a developer-friendly diagnostic screen.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class PrettyExceptions extends \Slim\Middleware
{
/**
* @var array
*/
protected $settings;
/**
* Constructor
* @param array $settings
*/
public function __construct($settings = array())
{
$this->settings = $settings;
}
/**
* Call
*/
public function call()
{
try {
$this->next->call();
} catch (\Exception $e) {
$log = $this->app->getLog(); // Force Slim to append log to env if not already
$env = $this->app->environment();
$env['slim.log'] = $log;
$env['slim.log']->error($e);
$this->app->contentType('text/html');
$this->app->response()->status(500);
$this->app->response()->body($this->renderBody($env, $e));
}
}
/**
* Render response body
* @param array $env
* @param \Exception $exception
* @return string
*/
protected function renderBody(&$env, $exception)
{
$title = 'Slim Application Error';
$code = $exception->getCode();
$message = htmlspecialchars($exception->getMessage());
$file = $exception->getFile();
$line = $exception->getLine();
$trace = str_replace(array('#', "\n"), array('
#', '
'), htmlspecialchars($exception->getTraceAsString()));
$html = sprintf('%s
', $title);
$html .= 'The application could not run because of the following error:
';
$html .= 'Details
';
$html .= sprintf('Type: %s
', get_class($exception));
if ($code) {
$html .= sprintf('Code: %s
', $code);
}
if ($message) {
$html .= sprintf('Message: %s
', $message);
}
if ($file) {
$html .= sprintf('File: %s
', $file);
}
if ($line) {
$html .= sprintf('Line: %s
', $line);
}
if ($trace) {
$html .= 'Trace
';
$html .= sprintf('%s
', $trace);
}
return sprintf("%s%s", $title, $html);
}
}
DEEP.git/Slim/Middleware/SessionCookie.php 0000775 0000000 0000000 00000013247 12634026554 0020645 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Middleware;
/**
* Session Cookie
*
* This class provides an HTTP cookie storage mechanism
* for session data. This class avoids using a PHP session
* and instead serializes/unserializes the $_SESSION global
* variable to/from an HTTP cookie.
*
* You should NEVER store sensitive data in a client-side cookie
* in any format, encrypted (with cookies.encrypt) or not. If you
* need to store sensitive user information in a session, you should
* rely on PHP's native session implementation, or use other middleware
* to store session data in a database or alternative server-side cache.
*
* Because this class stores serialized session data in an HTTP cookie,
* you are inherently limited to 4 Kb. If you attempt to store
* more than this amount, serialization will fail.
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
class SessionCookie extends \Slim\Middleware
{
/**
* @var array
*/
protected $settings;
/**
* Constructor
*
* @param array $settings
*/
public function __construct($settings = array())
{
$defaults = array(
'expires' => '20 minutes',
'path' => '/',
'domain' => null,
'secure' => false,
'httponly' => false,
'name' => 'slim_session',
);
$this->settings = array_merge($defaults, $settings);
if (is_string($this->settings['expires'])) {
$this->settings['expires'] = strtotime($this->settings['expires']);
}
/**
* Session
*
* We must start a native PHP session to initialize the $_SESSION superglobal.
* However, we won't be using the native session store for persistence, so we
* disable the session cookie and cache limiter. We also set the session
* handler to this class instance to avoid PHP's native session file locking.
*/
ini_set('session.use_cookies', 0);
session_cache_limiter(false);
session_set_save_handler(
array($this, 'open'),
array($this, 'close'),
array($this, 'read'),
array($this, 'write'),
array($this, 'destroy'),
array($this, 'gc')
);
}
/**
* Call
*/
public function call()
{
$this->loadSession();
$this->next->call();
$this->saveSession();
}
/**
* Load session
*/
protected function loadSession()
{
if (session_id() === '') {
session_start();
}
$value = $this->app->getCookie($this->settings['name']);
if ($value) {
$value = json_decode($value, true);
$_SESSION = is_array($value) ? $value : array();
} else {
$_SESSION = array();
}
}
/**
* Save session
*/
protected function saveSession()
{
$value = json_encode($_SESSION);
if (strlen($value) > 4096) {
$this->app->getLog()->error('WARNING! Slim\Middleware\SessionCookie data size is larger than 4KB. Content save failed.');
} else {
$this->app->setCookie(
$this->settings['name'],
$value,
$this->settings['expires'],
$this->settings['path'],
$this->settings['domain'],
$this->settings['secure'],
$this->settings['httponly']
);
}
// session_destroy();
}
/********************************************************************************
* Session Handler
*******************************************************************************/
/**
* @codeCoverageIgnore
*/
public function open($savePath, $sessionName)
{
return true;
}
/**
* @codeCoverageIgnore
*/
public function close()
{
return true;
}
/**
* @codeCoverageIgnore
*/
public function read($id)
{
return '';
}
/**
* @codeCoverageIgnore
*/
public function write($id, $data)
{
return true;
}
/**
* @codeCoverageIgnore
*/
public function destroy($id)
{
return true;
}
/**
* @codeCoverageIgnore
*/
public function gc($maxlifetime)
{
return true;
}
}
DEEP.git/Slim/README.markdown 0000775 0000000 0000000 00000014473 12634026554 0016005 0 ustar 00root root 0000000 0000000 # Slim Framework
[![Build Status](https://travis-ci.org/slimphp/Slim.svg?branch=master)](https://travis-ci.org/slimphp/Slim)
Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.
Slim is easy to use for both beginners and professionals. Slim favors cleanliness over terseness and common cases
over edge cases. Its interface is simple, intuitive, and extensively documented — both online and in the code itself.
Thank you for choosing the Slim Framework for your next project. I think you're going to love it.
## Features
* Powerful router
* Standard and custom HTTP methods
* Route parameters with wildcards and conditions
* Route redirect, halt, and pass
* Route middleware
* Resource Locator and DI container
* Template rendering with custom views
* Flash messages
* Encrypt cookie data
* HTTP caching
* Logging with custom log writers
* Error handling and debugging
* Middleware and hook architecture
* Simple configuration
## Getting Started
### Install
You may install the Slim Framework with Composer (recommended) or manually.
[Read how to install Slim](http://docs.slimframework.com/#Installation)
### System Requirements
You need **PHP >= 5.3.0**. If you use encrypted cookies, you'll also need the `mcrypt` extension.
### Hello World Tutorial
Instantiate a Slim application:
$app = new \Slim\Slim();
Define a HTTP GET route:
$app->get('/hello/:name', function ($name) {
echo "Hello, $name";
});
Run the Slim application:
$app->run();
### Setup your web server
#### Apache
Ensure the `.htaccess` and `index.php` files are in the same public-accessible directory. The `.htaccess` file
should contain this code:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
Additionally, make sure your virtual host is configured with the AllowOverride option so that the .htaccess rewrite rules can be used:
AllowOverride All
#### Nginx
The nginx configuration file should contain this code (along with other settings you may need) in your `location` block:
try_files $uri $uri/ /index.php?$args;
This assumes that Slim's `index.php` is in the root folder of your project (www root).
#### HipHop Virtual Machine for PHP
Your HipHop Virtual Machine configuration file should contain this code (along with other settings you may need).
Be sure you change the `ServerRoot` setting to point to your Slim app's document root directory.
Server {
SourceRoot = /path/to/public/directory
}
ServerVariables {
SCRIPT_NAME = /index.php
}
VirtualHost {
* {
Pattern = .*
RewriteRules {
* {
pattern = ^(.*)$
to = index.php/$1
qsa = true
}
}
}
}
#### lighttpd ####
Your lighttpd configuration file should contain this code (along with other settings you may need). This code requires
lighttpd >= 1.4.24.
url.rewrite-if-not-file = ("(.*)" => "/index.php/$0")
This assumes that Slim's `index.php` is in the root folder of your project (www root).
#### IIS
Ensure the `Web.config` and `index.php` files are in the same public-accessible directory. The `Web.config` file should contain this code:
#### Google App Engine
Two steps are required to successfully run your Slim application on Google App Engine. First, ensure the `app.yaml` file includes a default handler to `index.php`:
application: your-app-name
version: 1
runtime: php
api_version: 1
handlers:
# ...
- url: /.*
script: public_html/index.php
Next, edit your `index.php` file so Slim knows about the incoming URI:
$app = new Slim();
// Google App Engine doesn't set $_SERVER['PATH_INFO']
$app->environment['PATH_INFO'] = $_SERVER['REQUEST_URI'];
// ...
$app->run();
## Documentation
## How to Contribute
### Pull Requests
1. Fork the Slim Framework repository
2. Create a new branch for each feature or improvement
3. Send a pull request from each feature branch to the **develop** branch
It is very important to separate new features or improvements into separate feature branches, and to send a pull
request for each branch. This allows me to review and pull in new features or improvements individually.
### Style Guide
All pull requests must adhere to the [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) standard.
### Unit Testing
All pull requests must be accompanied by passing unit tests and complete code coverage. The Slim Framework uses
`phpunit` for testing.
[Learn about PHPUnit](https://github.com/sebastianbergmann/phpunit/)
## Community
### Forum and Knowledgebase
Visit Slim's official forum and knowledge base at where you can find announcements,
chat with fellow Slim users, ask questions, help others, or show off your cool Slim Framework apps.
### Twitter
Follow [@slimphp](http://www.twitter.com/slimphp) on Twitter to receive news and updates about the framework.
## Author
The Slim Framework is created and maintained by [Josh Lockhart](http://www.joshlockhart.com). Josh is a senior
web developer at [New Media Campaigns](http://www.newmediacampaigns.com/). Josh also created and maintains
[PHP: The Right Way](http://www.phptherightway.com/), a popular movement in the PHP community to introduce new
PHP programmers to best practices and good information.
## License
The Slim Framework is released under the MIT public license.
DEEP.git/Slim/Route.php 0000775 0000000 0000000 00000030767 12634026554 0015117 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
/**
* Route
* @package Slim
* @author Josh Lockhart, Thomas Bley
* @since 1.0.0
*/
class Route
{
/**
* @var string The route pattern (e.g. "/books/:id")
*/
protected $pattern;
/**
* @var mixed The route callable
*/
protected $callable;
/**
* @var array Conditions for this route's URL parameters
*/
protected $conditions = array();
/**
* @var array Default conditions applied to all route instances
*/
protected static $defaultConditions = array();
/**
* @var string The name of this route (optional)
*/
protected $name;
/**
* @var array Key-value array of URL parameters
*/
protected $params = array();
/**
* @var array value array of URL parameter names
*/
protected $paramNames = array();
/**
* @var array key array of URL parameter names with + at the end
*/
protected $paramNamesPath = array();
/**
* @var array HTTP methods supported by this Route
*/
protected $methods = array();
/**
* @var array[Callable] Middleware to be run before only this route instance
*/
protected $middleware = array();
/**
* @var bool Whether or not this route should be matched in a case-sensitive manner
*/
protected $caseSensitive;
/**
* Constructor
* @param string $pattern The URL pattern (e.g. "/books/:id")
* @param mixed $callable Anything that returns TRUE for is_callable()
* @param bool $caseSensitive Whether or not this route should be matched in a case-sensitive manner
*/
public function __construct($pattern, $callable, $caseSensitive = true)
{
$this->setPattern($pattern);
$this->setCallable($callable);
$this->setConditions(self::getDefaultConditions());
$this->caseSensitive = $caseSensitive;
}
/**
* Set default route conditions for all instances
* @param array $defaultConditions
*/
public static function setDefaultConditions(array $defaultConditions)
{
self::$defaultConditions = $defaultConditions;
}
/**
* Get default route conditions for all instances
* @return array
*/
public static function getDefaultConditions()
{
return self::$defaultConditions;
}
/**
* Get route pattern
* @return string
*/
public function getPattern()
{
return $this->pattern;
}
/**
* Set route pattern
* @param string $pattern
*/
public function setPattern($pattern)
{
$this->pattern = $pattern;
}
/**
* Get route callable
* @return mixed
*/
public function getCallable()
{
return $this->callable;
}
/**
* Set route callable
* @param mixed $callable
* @throws \InvalidArgumentException If argument is not callable
*/
public function setCallable($callable)
{
$matches = array();
if (is_string($callable) && preg_match('!^([^\:]+)\:([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$!', $callable, $matches)) {
$class = $matches[1];
$method = $matches[2];
$callable = function() use ($class, $method) {
static $obj = null;
if ($obj === null) {
$obj = new $class;
}
return call_user_func_array(array($obj, $method), func_get_args());
};
}
if (!is_callable($callable)) {
throw new \InvalidArgumentException('Route callable must be callable');
}
$this->callable = $callable;
}
/**
* Get route conditions
* @return array
*/
public function getConditions()
{
return $this->conditions;
}
/**
* Set route conditions
* @param array $conditions
*/
public function setConditions(array $conditions)
{
$this->conditions = $conditions;
}
/**
* Get route name
* @return string|null
*/
public function getName()
{
return $this->name;
}
/**
* Set route name
* @param string $name
*/
public function setName($name)
{
$this->name = (string)$name;
}
/**
* Get route parameters
* @return array
*/
public function getParams()
{
return $this->params;
}
/**
* Set route parameters
* @param array $params
*/
public function setParams($params)
{
$this->params = $params;
}
/**
* Get route parameter value
* @param string $index Name of URL parameter
* @return string
* @throws \InvalidArgumentException If route parameter does not exist at index
*/
public function getParam($index)
{
if (!isset($this->params[$index])) {
throw new \InvalidArgumentException('Route parameter does not exist at specified index');
}
return $this->params[$index];
}
/**
* Set route parameter value
* @param string $index Name of URL parameter
* @param mixed $value The new parameter value
* @throws \InvalidArgumentException If route parameter does not exist at index
*/
public function setParam($index, $value)
{
if (!isset($this->params[$index])) {
throw new \InvalidArgumentException('Route parameter does not exist at specified index');
}
$this->params[$index] = $value;
}
/**
* Add supported HTTP method(s)
*/
public function setHttpMethods()
{
$args = func_get_args();
$this->methods = $args;
}
/**
* Get supported HTTP methods
* @return array
*/
public function getHttpMethods()
{
return $this->methods;
}
/**
* Append supported HTTP methods
*/
public function appendHttpMethods()
{
$args = func_get_args();
if(count($args) && is_array($args[0])){
$args = $args[0];
}
$this->methods = array_merge($this->methods, $args);
}
/**
* Append supported HTTP methods (alias for Route::appendHttpMethods)
* @return \Slim\Route
*/
public function via()
{
$args = func_get_args();
if(count($args) && is_array($args[0])){
$args = $args[0];
}
$this->methods = array_merge($this->methods, $args);
return $this;
}
/**
* Detect support for an HTTP method
* @param string $method
* @return bool
*/
public function supportsHttpMethod($method)
{
return in_array($method, $this->methods);
}
/**
* Get middleware
* @return array[Callable]
*/
public function getMiddleware()
{
return $this->middleware;
}
/**
* Set middleware
*
* This method allows middleware to be assigned to a specific Route.
* If the method argument `is_callable` (including callable arrays!),
* we directly append the argument to `$this->middleware`. Else, we
* assume the argument is an array of callables and merge the array
* with `$this->middleware`. Each middleware is checked for is_callable()
* and an InvalidArgumentException is thrown immediately if it isn't.
*
* @param Callable|array[Callable]
* @return \Slim\Route
* @throws \InvalidArgumentException If argument is not callable or not an array of callables.
*/
public function setMiddleware($middleware)
{
if (is_callable($middleware)) {
$this->middleware[] = $middleware;
} elseif (is_array($middleware)) {
foreach ($middleware as $callable) {
if (!is_callable($callable)) {
throw new \InvalidArgumentException('All Route middleware must be callable');
}
}
$this->middleware = array_merge($this->middleware, $middleware);
} else {
throw new \InvalidArgumentException('Route middleware must be callable or an array of callables');
}
return $this;
}
/**
* Matches URI?
*
* Parse this route's pattern, and then compare it to an HTTP resource URI
* This method was modeled after the techniques demonstrated by Dan Sosedoff at:
*
* http://blog.sosedoff.com/2009/09/20/rails-like-php-url-router/
*
* @param string $resourceUri A Request URI
* @return bool
*/
public function matches($resourceUri)
{
//Convert URL params into regex patterns, construct a regex for this route, init params
$patternAsRegex = preg_replace_callback(
'#:([\w]+)\+?#',
array($this, 'matchesCallback'),
str_replace(')', ')?', (string)$this->pattern)
);
if (substr($this->pattern, -1) === '/') {
$patternAsRegex .= '?';
}
$regex = '#^' . $patternAsRegex . '$#';
if ($this->caseSensitive === false) {
$regex .= 'i';
}
//Cache URL params' names and values if this route matches the current HTTP request
if (!preg_match($regex, $resourceUri, $paramValues)) {
return false;
}
foreach ($this->paramNames as $name) {
if (isset($paramValues[$name])) {
if (isset($this->paramNamesPath[$name])) {
$this->params[$name] = explode('/', urldecode($paramValues[$name]));
} else {
$this->params[$name] = urldecode($paramValues[$name]);
}
}
}
return true;
}
/**
* Convert a URL parameter (e.g. ":id", ":id+") into a regular expression
* @param array $m URL parameters
* @return string Regular expression for URL parameter
*/
protected function matchesCallback($m)
{
$this->paramNames[] = $m[1];
if (isset($this->conditions[$m[1]])) {
return '(?P<' . $m[1] . '>' . $this->conditions[$m[1]] . ')';
}
if (substr($m[0], -1) === '+') {
$this->paramNamesPath[$m[1]] = 1;
return '(?P<' . $m[1] . '>.+)';
}
return '(?P<' . $m[1] . '>[^/]+)';
}
/**
* Set route name
* @param string $name The name of the route
* @return \Slim\Route
*/
public function name($name)
{
$this->setName($name);
return $this;
}
/**
* Merge route conditions
* @param array $conditions Key-value array of URL parameter conditions
* @return \Slim\Route
*/
public function conditions(array $conditions)
{
$this->conditions = array_merge($this->conditions, $conditions);
return $this;
}
/**
* Dispatch route
*
* This method invokes the route object's callable. If middleware is
* registered for the route, each callable middleware is invoked in
* the order specified.
*
* @return bool
*/
public function dispatch()
{
foreach ($this->middleware as $mw) {
call_user_func_array($mw, array($this));
}
$return = call_user_func_array($this->getCallable(), array_values($this->getParams()));
return ($return === false) ? false : true;
}
}
DEEP.git/Slim/Router.php 0000775 0000000 0000000 00000017352 12634026554 0015274 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
/**
* Router
*
* This class organizes, iterates, and dispatches \Slim\Route objects.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class Router
{
/**
* @var Route The current route (most recently dispatched)
*/
protected $currentRoute;
/**
* @var array Lookup hash of all route objects
*/
protected $routes;
/**
* @var array Lookup hash of named route objects, keyed by route name (lazy-loaded)
*/
protected $namedRoutes;
/**
* @var array Array of route objects that match the request URI (lazy-loaded)
*/
protected $matchedRoutes;
/**
* @var array Array containing all route groups
*/
protected $routeGroups;
/**
* Constructor
*/
public function __construct()
{
$this->routes = array();
$this->routeGroups = array();
}
/**
* Get Current Route object or the first matched one if matching has been performed
* @return \Slim\Route|null
*/
public function getCurrentRoute()
{
if ($this->currentRoute !== null) {
return $this->currentRoute;
}
if (is_array($this->matchedRoutes) && count($this->matchedRoutes) > 0) {
return $this->matchedRoutes[0];
}
return null;
}
/**
* Return route objects that match the given HTTP method and URI
* @param string $httpMethod The HTTP method to match against
* @param string $resourceUri The resource URI to match against
* @param bool $reload Should matching routes be re-parsed?
* @return array[\Slim\Route]
*/
public function getMatchedRoutes($httpMethod, $resourceUri, $reload = false)
{
if ($reload || is_null($this->matchedRoutes)) {
$this->matchedRoutes = array();
foreach ($this->routes as $route) {
if (!$route->supportsHttpMethod($httpMethod) && !$route->supportsHttpMethod("ANY")) {
continue;
}
if ($route->matches($resourceUri)) {
$this->matchedRoutes[] = $route;
}
}
}
return $this->matchedRoutes;
}
/**
* Add a route object to the router
* @param \Slim\Route $route The Slim Route
*/
public function map(\Slim\Route $route)
{
list($groupPattern, $groupMiddleware) = $this->processGroups();
$route->setPattern($groupPattern . $route->getPattern());
$this->routes[] = $route;
foreach ($groupMiddleware as $middleware) {
$route->setMiddleware($middleware);
}
}
/**
* A helper function for processing the group's pattern and middleware
* @return array Returns an array with the elements: pattern, middlewareArr
*/
protected function processGroups()
{
$pattern = "";
$middleware = array();
foreach ($this->routeGroups as $group) {
$k = key($group);
$pattern .= $k;
if (is_array($group[$k])) {
$middleware = array_merge($middleware, $group[$k]);
}
}
return array($pattern, $middleware);
}
/**
* Add a route group to the array
* @param string $group The group pattern (ie. "/books/:id")
* @param array|null $middleware Optional parameter array of middleware
* @return int The index of the new group
*/
public function pushGroup($group, $middleware = array())
{
return array_push($this->routeGroups, array($group => $middleware));
}
/**
* Removes the last route group from the array
* @return bool True if successful, else False
*/
public function popGroup()
{
return (array_pop($this->routeGroups) !== null);
}
/**
* Get URL for named route
* @param string $name The name of the route
* @param array $params Associative array of URL parameter names and replacement values
* @throws \RuntimeException If named route not found
* @return string The URL for the given route populated with provided replacement values
*/
public function urlFor($name, $params = array())
{
if (!$this->hasNamedRoute($name)) {
throw new \RuntimeException('Named route not found for name: ' . $name);
}
$search = array();
foreach ($params as $key => $value) {
$search[] = '#:' . preg_quote($key, '#') . '\+?(?!\w)#';
}
$pattern = preg_replace($search, $params, $this->getNamedRoute($name)->getPattern());
//Remove remnants of unpopulated, trailing optional pattern segments, escaped special characters
return preg_replace('#\(/?:.+\)|\(|\)|\\\\#', '', $pattern);
}
/**
* Add named route
* @param string $name The route name
* @param \Slim\Route $route The route object
* @throws \RuntimeException If a named route already exists with the same name
*/
public function addNamedRoute($name, \Slim\Route $route)
{
if ($this->hasNamedRoute($name)) {
throw new \RuntimeException('Named route already exists with name: ' . $name);
}
$this->namedRoutes[(string) $name] = $route;
}
/**
* Has named route
* @param string $name The route name
* @return bool
*/
public function hasNamedRoute($name)
{
$this->getNamedRoutes();
return isset($this->namedRoutes[(string) $name]);
}
/**
* Get named route
* @param string $name
* @return \Slim\Route|null
*/
public function getNamedRoute($name)
{
$this->getNamedRoutes();
if ($this->hasNamedRoute($name)) {
return $this->namedRoutes[(string) $name];
}
return null;
}
/**
* Get named routes
* @return \ArrayIterator
*/
public function getNamedRoutes()
{
if (is_null($this->namedRoutes)) {
$this->namedRoutes = array();
foreach ($this->routes as $route) {
if ($route->getName() !== null) {
$this->addNamedRoute($route->getName(), $route);
}
}
}
return new \ArrayIterator($this->namedRoutes);
}
}
DEEP.git/Slim/Slim.php 0000775 0000000 0000000 00000137251 12634026554 0014721 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
// Ensure mcrypt constants are defined even if mcrypt extension is not loaded
if (!extension_loaded('mcrypt')) {
define('MCRYPT_MODE_CBC', 0);
define('MCRYPT_RIJNDAEL_256', 0);
}
/**
* Slim
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*
* @property \Slim\Environment $environment
* @property \Slim\Http\Response $response
* @property \Slim\Http\Request $request
* @property \Slim\Router $router
*/
class Slim
{
/**
* @const string
*/
const VERSION = '2.6.1';
/**
* @var \Slim\Helper\Set
*/
public $container;
/**
* @var array[\Slim]
*/
protected static $apps = array();
/**
* @var string
*/
protected $name;
/**
* @var array
*/
protected $middleware;
/**
* @var mixed Callable to be invoked if application error
*/
protected $error;
/**
* @var mixed Callable to be invoked if no matching routes are found
*/
protected $notFound;
/**
* @var array
*/
protected $hooks = array(
'slim.before' => array(array()),
'slim.before.router' => array(array()),
'slim.before.dispatch' => array(array()),
'slim.after.dispatch' => array(array()),
'slim.after.router' => array(array()),
'slim.after' => array(array())
);
/********************************************************************************
* PSR-0 Autoloader
*
* Do not use if you are using Composer to autoload dependencies.
*******************************************************************************/
/**
* Slim PSR-0 autoloader
*/
public static function autoload($className)
{
$thisClass = str_replace(__NAMESPACE__.'\\', '', __CLASS__);
$baseDir = __DIR__;
if (substr($baseDir, -strlen($thisClass)) === $thisClass) {
$baseDir = substr($baseDir, 0, -strlen($thisClass));
}
$className = ltrim($className, '\\');
$fileName = $baseDir;
$namespace = '';
if ($lastNsPos = strripos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
if (file_exists($fileName)) {
require $fileName;
}
}
/**
* Register Slim's PSR-0 autoloader
*/
public static function registerAutoloader()
{
spl_autoload_register(__NAMESPACE__ . "\\Slim::autoload");
}
/********************************************************************************
* Instantiation and Configuration
*******************************************************************************/
/**
* Constructor
* @param array $userSettings Associative array of application settings
*/
public function __construct(array $userSettings = array())
{
// Setup IoC container
$this->container = new \Slim\Helper\Set();
$this->container['settings'] = array_merge(static::getDefaultSettings(), $userSettings);
// Default environment
$this->container->singleton('environment', function ($c) {
return \Slim\Environment::getInstance();
});
// Default request
$this->container->singleton('request', function ($c) {
return new \Slim\Http\Request($c['environment']);
});
// Default response
$this->container->singleton('response', function ($c) {
return new \Slim\Http\Response();
});
// Default router
$this->container->singleton('router', function ($c) {
return new \Slim\Router();
});
// Default view
$this->container->singleton('view', function ($c) {
$viewClass = $c['settings']['view'];
$templatesPath = $c['settings']['templates.path'];
$view = ($viewClass instanceOf \Slim\View) ? $viewClass : new $viewClass;
$view->setTemplatesDirectory($templatesPath);
return $view;
});
// Default log writer
$this->container->singleton('logWriter', function ($c) {
$logWriter = $c['settings']['log.writer'];
return is_object($logWriter) ? $logWriter : new \Slim\LogWriter($c['environment']['slim.errors']);
});
// Default log
$this->container->singleton('log', function ($c) {
$log = new \Slim\Log($c['logWriter']);
$log->setEnabled($c['settings']['log.enabled']);
$log->setLevel($c['settings']['log.level']);
$env = $c['environment'];
$env['slim.log'] = $log;
return $log;
});
// Default mode
$this->container['mode'] = function ($c) {
$mode = $c['settings']['mode'];
if (isset($_ENV['SLIM_MODE'])) {
$mode = $_ENV['SLIM_MODE'];
} else {
$envMode = getenv('SLIM_MODE');
if ($envMode !== false) {
$mode = $envMode;
}
}
return $mode;
};
// Define default middleware stack
$this->middleware = array($this);
$this->add(new \Slim\Middleware\Flash());
$this->add(new \Slim\Middleware\MethodOverride());
// Make default if first instance
if (is_null(static::getInstance())) {
$this->setName('default');
}
}
public function __get($name)
{
return $this->container->get($name);
}
public function __set($name, $value)
{
$this->container->set($name, $value);
}
public function __isset($name)
{
return $this->container->has($name);
}
public function __unset($name)
{
$this->container->remove($name);
}
/**
* Get application instance by name
* @param string $name The name of the Slim application
* @return \Slim\Slim|null
*/
public static function getInstance($name = 'default')
{
return isset(static::$apps[$name]) ? static::$apps[$name] : null;
}
/**
* Set Slim application name
* @param string $name The name of this Slim application
*/
public function setName($name)
{
$this->name = $name;
static::$apps[$name] = $this;
}
/**
* Get Slim application name
* @return string|null
*/
public function getName()
{
return $this->name;
}
/**
* Get default application settings
* @return array
*/
public static function getDefaultSettings()
{
return array(
// Application
'mode' => 'development',
// Debugging
'debug' => true,
// Logging
'log.writer' => null,
'log.level' => \Slim\Log::DEBUG,
'log.enabled' => true,
// View
'templates.path' => './templates',
'view' => '\Slim\View',
// Cookies
'cookies.encrypt' => false,
'cookies.lifetime' => '20 minutes',
'cookies.path' => '/',
'cookies.domain' => null,
'cookies.secure' => false,
'cookies.httponly' => false,
// Encryption
'cookies.secret_key' => 'CHANGE_ME',
'cookies.cipher' => MCRYPT_RIJNDAEL_256,
'cookies.cipher_mode' => MCRYPT_MODE_CBC,
// HTTP
'http.version' => '1.1',
// Routing
'routes.case_sensitive' => true
);
}
/**
* Configure Slim Settings
*
* This method defines application settings and acts as a setter and a getter.
*
* If only one argument is specified and that argument is a string, the value
* of the setting identified by the first argument will be returned, or NULL if
* that setting does not exist.
*
* If only one argument is specified and that argument is an associative array,
* the array will be merged into the existing application settings.
*
* If two arguments are provided, the first argument is the name of the setting
* to be created or updated, and the second argument is the setting value.
*
* @param string|array $name If a string, the name of the setting to set or retrieve. Else an associated array of setting names and values
* @param mixed $value If name is a string, the value of the setting identified by $name
* @return mixed The value of a setting if only one argument is a string
*/
public function config($name, $value = null)
{
$c = $this->container;
if (is_array($name)) {
if (true === $value) {
$c['settings'] = array_merge_recursive($c['settings'], $name);
} else {
$c['settings'] = array_merge($c['settings'], $name);
}
} elseif (func_num_args() === 1) {
return isset($c['settings'][$name]) ? $c['settings'][$name] : null;
} else {
$settings = $c['settings'];
$settings[$name] = $value;
$c['settings'] = $settings;
}
}
/********************************************************************************
* Application Modes
*******************************************************************************/
/**
* Get application mode
*
* This method determines the application mode. It first inspects the $_ENV
* superglobal for key `SLIM_MODE`. If that is not found, it queries
* the `getenv` function. Else, it uses the application `mode` setting.
*
* @return string
*/
public function getMode()
{
return $this->mode;
}
/**
* Configure Slim for a given mode
*
* This method will immediately invoke the callable if
* the specified mode matches the current application mode.
* Otherwise, the callable is ignored. This should be called
* only _after_ you initialize your Slim app.
*
* @param string $mode
* @param mixed $callable
* @return void
*/
public function configureMode($mode, $callable)
{
if ($mode === $this->getMode() && is_callable($callable)) {
call_user_func($callable);
}
}
/********************************************************************************
* Logging
*******************************************************************************/
/**
* Get application log
* @return \Slim\Log
*/
public function getLog()
{
return $this->log;
}
/********************************************************************************
* Routing
*******************************************************************************/
/**
* Add GET|POST|PUT|PATCH|DELETE route
*
* Adds a new route to the router with associated callable. This
* route will only be invoked when the HTTP request's method matches
* this route's method.
*
* ARGUMENTS:
*
* First: string The URL pattern (REQUIRED)
* In-Between: mixed Anything that returns TRUE for `is_callable` (OPTIONAL)
* Last: mixed Anything that returns TRUE for `is_callable` (REQUIRED)
*
* The first argument is required and must always be the
* route pattern (ie. '/books/:id').
*
* The last argument is required and must always be the callable object
* to be invoked when the route matches an HTTP request.
*
* You may also provide an unlimited number of in-between arguments;
* each interior argument must be callable and will be invoked in the
* order specified before the route's callable is invoked.
*
* USAGE:
*
* Slim::get('/foo'[, middleware, middleware, ...], callable);
*
* @param array (See notes above)
* @return \Slim\Route
*/
protected function mapRoute($args)
{
$pattern = array_shift($args);
$callable = array_pop($args);
$route = new \Slim\Route($pattern, $callable, $this->settings['routes.case_sensitive']);
$this->router->map($route);
if (count($args) > 0) {
$route->setMiddleware($args);
}
return $route;
}
/**
* Add generic route without associated HTTP method
* @see mapRoute()
* @return \Slim\Route
*/
public function map()
{
$args = func_get_args();
return $this->mapRoute($args);
}
/**
* Add GET route
* @see mapRoute()
* @return \Slim\Route
*/
public function get()
{
$args = func_get_args();
return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_GET, \Slim\Http\Request::METHOD_HEAD);
}
/**
* Add POST route
* @see mapRoute()
* @return \Slim\Route
*/
public function post()
{
$args = func_get_args();
return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_POST);
}
/**
* Add PUT route
* @see mapRoute()
* @return \Slim\Route
*/
public function put()
{
$args = func_get_args();
return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_PUT);
}
/**
* Add PATCH route
* @see mapRoute()
* @return \Slim\Route
*/
public function patch()
{
$args = func_get_args();
return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_PATCH);
}
/**
* Add DELETE route
* @see mapRoute()
* @return \Slim\Route
*/
public function delete()
{
$args = func_get_args();
return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_DELETE);
}
/**
* Add OPTIONS route
* @see mapRoute()
* @return \Slim\Route
*/
public function options()
{
$args = func_get_args();
return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_OPTIONS);
}
/**
* Route Groups
*
* This method accepts a route pattern and a callback all Route
* declarations in the callback will be prepended by the group(s)
* that it is in
*
* Accepts the same parameters as a standard route so:
* (pattern, middleware1, middleware2, ..., $callback)
*/
public function group()
{
$args = func_get_args();
$pattern = array_shift($args);
$callable = array_pop($args);
$this->router->pushGroup($pattern, $args);
if (is_callable($callable)) {
call_user_func($callable);
}
$this->router->popGroup();
}
/*
* Add route for any HTTP method
* @see mapRoute()
* @return \Slim\Route
*/
public function any()
{
$args = func_get_args();
return $this->mapRoute($args)->via("ANY");
}
/**
* Not Found Handler
*
* This method defines or invokes the application-wide Not Found handler.
* There are two contexts in which this method may be invoked:
*
* 1. When declaring the handler:
*
* If the $callable parameter is not null and is callable, this
* method will register the callable to be invoked when no
* routes match the current HTTP request. It WILL NOT invoke the callable.
*
* 2. When invoking the handler:
*
* If the $callable parameter is null, Slim assumes you want
* to invoke an already-registered handler. If the handler has been
* registered and is callable, it is invoked and sends a 404 HTTP Response
* whose body is the output of the Not Found handler.
*
* @param mixed $callable Anything that returns true for is_callable()
*/
public function notFound ($callable = null)
{
if (is_callable($callable)) {
$this->notFound = $callable;
} else {
ob_start();
if (is_callable($this->notFound)) {
call_user_func($this->notFound);
} else {
call_user_func(array($this, 'defaultNotFound'));
}
$this->halt(404, ob_get_clean());
}
}
/**
* Error Handler
*
* This method defines or invokes the application-wide Error handler.
* There are two contexts in which this method may be invoked:
*
* 1. When declaring the handler:
*
* If the $argument parameter is callable, this
* method will register the callable to be invoked when an uncaught
* Exception is detected, or when otherwise explicitly invoked.
* The handler WILL NOT be invoked in this context.
*
* 2. When invoking the handler:
*
* If the $argument parameter is not callable, Slim assumes you want
* to invoke an already-registered handler. If the handler has been
* registered and is callable, it is invoked and passed the caught Exception
* as its one and only argument. The error handler's output is captured
* into an output buffer and sent as the body of a 500 HTTP Response.
*
* @param mixed $argument Callable|\Exception
*/
public function error($argument = null)
{
if (is_callable($argument)) {
//Register error handler
$this->error = $argument;
} else {
//Invoke error handler
$this->response->status(500);
$this->response->body('');
$this->response->write($this->callErrorHandler($argument));
$this->stop();
}
}
/**
* Call error handler
*
* This will invoke the custom or default error handler
* and RETURN its output.
*
* @param \Exception|null $argument
* @return string
*/
protected function callErrorHandler($argument = null)
{
ob_start();
if (is_callable($this->error)) {
call_user_func_array($this->error, array($argument));
} else {
call_user_func_array(array($this, 'defaultError'), array($argument));
}
return ob_get_clean();
}
/********************************************************************************
* Application Accessors
*******************************************************************************/
/**
* Get a reference to the Environment object
* @return \Slim\Environment
*/
public function environment()
{
return $this->environment;
}
/**
* Get the Request object
* @return \Slim\Http\Request
*/
public function request()
{
return $this->request;
}
/**
* Get the Response object
* @return \Slim\Http\Response
*/
public function response()
{
return $this->response;
}
/**
* Get the Router object
* @return \Slim\Router
*/
public function router()
{
return $this->router;
}
/**
* Get and/or set the View
*
* This method declares the View to be used by the Slim application.
* If the argument is a string, Slim will instantiate a new object
* of the same class. If the argument is an instance of View or a subclass
* of View, Slim will use the argument as the View.
*
* If a View already exists and this method is called to create a
* new View, data already set in the existing View will be
* transferred to the new View.
*
* @param string|\Slim\View $viewClass The name or instance of a \Slim\View subclass
* @return \Slim\View
*/
public function view($viewClass = null)
{
if (!is_null($viewClass)) {
$existingData = is_null($this->view) ? array() : $this->view->getData();
if ($viewClass instanceOf \Slim\View) {
$this->view = $viewClass;
} else {
$this->view = new $viewClass();
}
$this->view->appendData($existingData);
$this->view->setTemplatesDirectory($this->config('templates.path'));
}
return $this->view;
}
/********************************************************************************
* Rendering
*******************************************************************************/
/**
* Render a template
*
* Call this method within a GET, POST, PUT, PATCH, DELETE, NOT FOUND, or ERROR
* callable to render a template whose output is appended to the
* current HTTP response body. How the template is rendered is
* delegated to the current View.
*
* @param string $template The name of the template passed into the view's render() method
* @param array $data Associative array of data made available to the view
* @param int $status The HTTP response status code to use (optional)
*/
public function render($template, $data = array(), $status = null)
{
if (!is_null($status)) {
$this->response->status($status);
}
$this->view->appendData($data);
$this->view->display($template);
}
/********************************************************************************
* HTTP Caching
*******************************************************************************/
/**
* Set Last-Modified HTTP Response Header
*
* Set the HTTP 'Last-Modified' header and stop if a conditional
* GET request's `If-Modified-Since` header matches the last modified time
* of the resource. The `time` argument is a UNIX timestamp integer value.
* When the current request includes an 'If-Modified-Since' header that
* matches the specified last modified time, the application will stop
* and send a '304 Not Modified' response to the client.
*
* @param int $time The last modified UNIX timestamp
* @throws \InvalidArgumentException If provided timestamp is not an integer
*/
public function lastModified($time)
{
if (is_integer($time)) {
$this->response->headers->set('Last-Modified', gmdate('D, d M Y H:i:s T', $time));
if ($time === strtotime($this->request->headers->get('IF_MODIFIED_SINCE'))) {
$this->halt(304);
}
} else {
throw new \InvalidArgumentException('Slim::lastModified only accepts an integer UNIX timestamp value.');
}
}
/**
* Set ETag HTTP Response Header
*
* Set the etag header and stop if the conditional GET request matches.
* The `value` argument is a unique identifier for the current resource.
* The `type` argument indicates whether the etag should be used as a strong or
* weak cache validator.
*
* When the current request includes an 'If-None-Match' header with
* a matching etag, execution is immediately stopped. If the request
* method is GET or HEAD, a '304 Not Modified' response is sent.
*
* @param string $value The etag value
* @param string $type The type of etag to create; either "strong" or "weak"
* @throws \InvalidArgumentException If provided type is invalid
*/
public function etag($value, $type = 'strong')
{
//Ensure type is correct
if (!in_array($type, array('strong', 'weak'))) {
throw new \InvalidArgumentException('Invalid Slim::etag type. Expected "strong" or "weak".');
}
//Set etag value
$value = '"' . $value . '"';
if ($type === 'weak') {
$value = 'W/'.$value;
}
$this->response['ETag'] = $value;
//Check conditional GET
if ($etagsHeader = $this->request->headers->get('IF_NONE_MATCH')) {
$etags = preg_split('@\s*,\s*@', $etagsHeader);
if (in_array($value, $etags) || in_array('*', $etags)) {
$this->halt(304);
}
}
}
/**
* Set Expires HTTP response header
*
* The `Expires` header tells the HTTP client the time at which
* the current resource should be considered stale. At that time the HTTP
* client will send a conditional GET request to the server; the server
* may return a 200 OK if the resource has changed, else a 304 Not Modified
* if the resource has not changed. The `Expires` header should be used in
* conjunction with the `etag()` or `lastModified()` methods above.
*
* @param string|int $time If string, a time to be parsed by `strtotime()`;
* If int, a UNIX timestamp;
*/
public function expires($time)
{
if (is_string($time)) {
$time = strtotime($time);
}
$this->response->headers->set('Expires', gmdate('D, d M Y H:i:s T', $time));
}
/********************************************************************************
* HTTP Cookies
*******************************************************************************/
/**
* Set HTTP cookie to be sent with the HTTP response
*
* @param string $name The cookie name
* @param string $value The cookie value
* @param int|string $time The duration of the cookie;
* If integer, should be UNIX timestamp;
* If string, converted to UNIX timestamp with `strtotime`;
* @param string $path The path on the server in which the cookie will be available on
* @param string $domain The domain that the cookie is available to
* @param bool $secure Indicates that the cookie should only be transmitted over a secure
* HTTPS connection to/from the client
* @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
*/
public function setCookie($name, $value, $time = null, $path = null, $domain = null, $secure = null, $httponly = null)
{
$settings = array(
'value' => $value,
'expires' => is_null($time) ? $this->config('cookies.lifetime') : $time,
'path' => is_null($path) ? $this->config('cookies.path') : $path,
'domain' => is_null($domain) ? $this->config('cookies.domain') : $domain,
'secure' => is_null($secure) ? $this->config('cookies.secure') : $secure,
'httponly' => is_null($httponly) ? $this->config('cookies.httponly') : $httponly
);
$this->response->cookies->set($name, $settings);
}
/**
* Get value of HTTP cookie from the current HTTP request
*
* Return the value of a cookie from the current HTTP request,
* or return NULL if cookie does not exist. Cookies created during
* the current request will not be available until the next request.
*
* @param string $name
* @param bool $deleteIfInvalid
* @return string|null
*/
public function getCookie($name, $deleteIfInvalid = true)
{
// Get cookie value
$value = $this->request->cookies->get($name);
// Decode if encrypted
if ($this->config('cookies.encrypt')) {
$value = \Slim\Http\Util::decodeSecureCookie(
$value,
$this->config('cookies.secret_key'),
$this->config('cookies.cipher'),
$this->config('cookies.cipher_mode')
);
if ($value === false && $deleteIfInvalid) {
$this->deleteCookie($name);
}
}
/*
* transform $value to @return doc requirement.
* \Slim\Http\Util::decodeSecureCookie - is able
* to return false and we have to cast it to null.
*/
return $value === false ? null : $value;
}
/**
* DEPRECATION WARNING! Use `setCookie` with the `cookies.encrypt` app setting set to `true`.
*
* Set encrypted HTTP cookie
*
* @param string $name The cookie name
* @param mixed $value The cookie value
* @param mixed $expires The duration of the cookie;
* If integer, should be UNIX timestamp;
* If string, converted to UNIX timestamp with `strtotime`;
* @param string $path The path on the server in which the cookie will be available on
* @param string $domain The domain that the cookie is available to
* @param bool $secure Indicates that the cookie should only be transmitted over a secure
* HTTPS connection from the client
* @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
*/
public function setEncryptedCookie($name, $value, $expires = null, $path = null, $domain = null, $secure = false, $httponly = false)
{
$this->setCookie($name, $value, $expires, $path, $domain, $secure, $httponly);
}
/**
* DEPRECATION WARNING! Use `getCookie` with the `cookies.encrypt` app setting set to `true`.
*
* Get value of encrypted HTTP cookie
*
* Return the value of an encrypted cookie from the current HTTP request,
* or return NULL if cookie does not exist. Encrypted cookies created during
* the current request will not be available until the next request.
*
* @param string $name
* @param bool $deleteIfInvalid
* @return string|bool
*/
public function getEncryptedCookie($name, $deleteIfInvalid = true)
{
return $this->getCookie($name, $deleteIfInvalid);
}
/**
* Delete HTTP cookie (encrypted or unencrypted)
*
* Remove a Cookie from the client. This method will overwrite an existing Cookie
* with a new, empty, auto-expiring Cookie. This method's arguments must match
* the original Cookie's respective arguments for the original Cookie to be
* removed. If any of this method's arguments are omitted or set to NULL, the
* default Cookie setting values (set during Slim::init) will be used instead.
*
* @param string $name The cookie name
* @param string $path The path on the server in which the cookie will be available on
* @param string $domain The domain that the cookie is available to
* @param bool $secure Indicates that the cookie should only be transmitted over a secure
* HTTPS connection from the client
* @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
*/
public function deleteCookie($name, $path = null, $domain = null, $secure = null, $httponly = null)
{
$settings = array(
'domain' => is_null($domain) ? $this->config('cookies.domain') : $domain,
'path' => is_null($path) ? $this->config('cookies.path') : $path,
'secure' => is_null($secure) ? $this->config('cookies.secure') : $secure,
'httponly' => is_null($httponly) ? $this->config('cookies.httponly') : $httponly
);
$this->response->cookies->remove($name, $settings);
}
/********************************************************************************
* Helper Methods
*******************************************************************************/
/**
* Get the absolute path to this Slim application's root directory
*
* This method returns the absolute path to the Slim application's
* directory. If the Slim application is installed in a public-accessible
* sub-directory, the sub-directory path will be included. This method
* will always return an absolute path WITH a trailing slash.
*
* @return string
*/
public function root()
{
return rtrim($_SERVER['DOCUMENT_ROOT'], '/') . rtrim($this->request->getRootUri(), '/') . '/';
}
/**
* Clean current output buffer
*/
protected function cleanBuffer()
{
if (ob_get_level() !== 0) {
ob_clean();
}
}
/**
* Stop
*
* The thrown exception will be caught in application's `call()` method
* and the response will be sent as is to the HTTP client.
*
* @throws \Slim\Exception\Stop
*/
public function stop()
{
throw new \Slim\Exception\Stop();
}
/**
* Halt
*
* Stop the application and immediately send the response with a
* specific status and body to the HTTP client. This may send any
* type of response: info, success, redirect, client error, or server error.
* If you need to render a template AND customize the response status,
* use the application's `render()` method instead.
*
* @param int $status The HTTP response status
* @param string $message The HTTP response body
*/
public function halt($status, $message = '')
{
$this->cleanBuffer();
$this->response->status($status);
$this->response->body($message);
$this->stop();
}
/**
* Pass
*
* The thrown exception is caught in the application's `call()` method causing
* the router's current iteration to stop and continue to the subsequent route if available.
* If no subsequent matching routes are found, a 404 response will be sent to the client.
*
* @throws \Slim\Exception\Pass
*/
public function pass()
{
$this->cleanBuffer();
throw new \Slim\Exception\Pass();
}
/**
* Set the HTTP response Content-Type
* @param string $type The Content-Type for the Response (ie. text/html)
*/
public function contentType($type)
{
$this->response->headers->set('Content-Type', $type);
}
/**
* Set the HTTP response status code
* @param int $code The HTTP response status code
*/
public function status($code)
{
$this->response->setStatus($code);
}
/**
* Get the URL for a named route
* @param string $name The route name
* @param array $params Associative array of URL parameters and replacement values
* @throws \RuntimeException If named route does not exist
* @return string
*/
public function urlFor($name, $params = array())
{
return $this->request->getRootUri() . $this->router->urlFor($name, $params);
}
/**
* Redirect
*
* This method immediately redirects to a new URL. By default,
* this issues a 302 Found response; this is considered the default
* generic redirect response. You may also specify another valid
* 3xx status code if you want. This method will automatically set the
* HTTP Location header for you using the URL parameter.
*
* @param string $url The destination URL
* @param int $status The HTTP redirect status code (optional)
*/
public function redirect($url, $status = 302)
{
$this->response->redirect($url, $status);
$this->halt($status);
}
/**
* RedirectTo
*
* Redirects to a specific named route
*
* @param string $route The route name
* @param array $params Associative array of URL parameters and replacement values
*/
public function redirectTo($route, $params = array(), $status = 302){
$this->redirect($this->urlFor($route, $params), $status);
}
/********************************************************************************
* Flash Messages
*******************************************************************************/
/**
* Set flash message for subsequent request
* @param string $key
* @param mixed $value
*/
public function flash($key, $value)
{
if (isset($this->environment['slim.flash'])) {
$this->environment['slim.flash']->set($key, $value);
}
}
/**
* Set flash message for current request
* @param string $key
* @param mixed $value
*/
public function flashNow($key, $value)
{
if (isset($this->environment['slim.flash'])) {
$this->environment['slim.flash']->now($key, $value);
}
}
/**
* Keep flash messages from previous request for subsequent request
*/
public function flashKeep()
{
if (isset($this->environment['slim.flash'])) {
$this->environment['slim.flash']->keep();
}
}
/**
* Get all flash messages
*/
public function flashData()
{
if (isset($this->environment['slim.flash'])) {
return $this->environment['slim.flash']->getMessages();
}
}
/********************************************************************************
* Hooks
*******************************************************************************/
/**
* Assign hook
* @param string $name The hook name
* @param mixed $callable A callable object
* @param int $priority The hook priority; 0 = high, 10 = low
*/
public function hook($name, $callable, $priority = 10)
{
if (!isset($this->hooks[$name])) {
$this->hooks[$name] = array(array());
}
if (is_callable($callable)) {
$this->hooks[$name][(int) $priority][] = $callable;
}
}
/**
* Invoke hook
* @param string $name The hook name
* @param mixed ... (Optional) Argument(s) for hooked functions, can specify multiple arguments
*/
public function applyHook($name)
{
if (!isset($this->hooks[$name])) {
$this->hooks[$name] = array(array());
}
if (!empty($this->hooks[$name])) {
// Sort by priority, low to high, if there's more than one priority
if (count($this->hooks[$name]) > 1) {
ksort($this->hooks[$name]);
}
$args = func_get_args();
array_shift($args);
foreach ($this->hooks[$name] as $priority) {
if (!empty($priority)) {
foreach ($priority as $callable) {
call_user_func_array($callable, $args);
}
}
}
}
}
/**
* Get hook listeners
*
* Return an array of registered hooks. If `$name` is a valid
* hook name, only the listeners attached to that hook are returned.
* Else, all listeners are returned as an associative array whose
* keys are hook names and whose values are arrays of listeners.
*
* @param string $name A hook name (Optional)
* @return array|null
*/
public function getHooks($name = null)
{
if (!is_null($name)) {
return isset($this->hooks[(string) $name]) ? $this->hooks[(string) $name] : null;
} else {
return $this->hooks;
}
}
/**
* Clear hook listeners
*
* Clear all listeners for all hooks. If `$name` is
* a valid hook name, only the listeners attached
* to that hook will be cleared.
*
* @param string $name A hook name (Optional)
*/
public function clearHooks($name = null)
{
if (!is_null($name) && isset($this->hooks[(string) $name])) {
$this->hooks[(string) $name] = array(array());
} else {
foreach ($this->hooks as $key => $value) {
$this->hooks[$key] = array(array());
}
}
}
/********************************************************************************
* Middleware
*******************************************************************************/
/**
* Add middleware
*
* This method prepends new middleware to the application middleware stack.
* The argument must be an instance that subclasses Slim_Middleware.
*
* @param \Slim\Middleware
*/
public function add(\Slim\Middleware $newMiddleware)
{
if(in_array($newMiddleware, $this->middleware)) {
$middleware_class = get_class($newMiddleware);
throw new \RuntimeException("Circular Middleware setup detected. Tried to queue the same Middleware instance ({$middleware_class}) twice.");
}
$newMiddleware->setApplication($this);
$newMiddleware->setNextMiddleware($this->middleware[0]);
array_unshift($this->middleware, $newMiddleware);
}
/********************************************************************************
* Runner
*******************************************************************************/
/**
* Run
*
* This method invokes the middleware stack, including the core Slim application;
* the result is an array of HTTP status, header, and body. These three items
* are returned to the HTTP client.
*/
public function run()
{
set_error_handler(array('\Slim\Slim', 'handleErrors'));
//Apply final outer middleware layers
if ($this->config('debug')) {
//Apply pretty exceptions only in debug to avoid accidental information leakage in production
$this->add(new \Slim\Middleware\PrettyExceptions());
}
//Invoke middleware and application stack
$this->middleware[0]->call();
//Fetch status, header, and body
list($status, $headers, $body) = $this->response->finalize();
// Serialize cookies (with optional encryption)
\Slim\Http\Util::serializeCookies($headers, $this->response->cookies, $this->settings);
//Send headers
if (headers_sent() === false) {
//Send status
if (strpos(PHP_SAPI, 'cgi') === 0) {
header(sprintf('Status: %s', \Slim\Http\Response::getMessageForCode($status)));
} else {
header(sprintf('HTTP/%s %s', $this->config('http.version'), \Slim\Http\Response::getMessageForCode($status)));
}
//Send headers
foreach ($headers as $name => $value) {
$hValues = explode("\n", $value);
foreach ($hValues as $hVal) {
header("$name: $hVal", false);
}
}
}
//Send body, but only if it isn't a HEAD request
if (!$this->request->isHead()) {
echo $body;
}
$this->applyHook('slim.after');
restore_error_handler();
}
/**
* Call
*
* This method finds and iterates all route objects that match the current request URI.
*/
public function call()
{
try {
if (isset($this->environment['slim.flash'])) {
$this->view()->setData('flash', $this->environment['slim.flash']);
}
$this->applyHook('slim.before');
ob_start();
$this->applyHook('slim.before.router');
$dispatched = false;
$matchedRoutes = $this->router->getMatchedRoutes($this->request->getMethod(), $this->request->getResourceUri());
foreach ($matchedRoutes as $route) {
try {
$this->applyHook('slim.before.dispatch');
$dispatched = $route->dispatch();
$this->applyHook('slim.after.dispatch');
if ($dispatched) {
break;
}
} catch (\Slim\Exception\Pass $e) {
continue;
}
}
if (!$dispatched) {
$this->notFound();
}
$this->applyHook('slim.after.router');
$this->stop();
} catch (\Slim\Exception\Stop $e) {
$this->response()->write(ob_get_clean());
} catch (\Exception $e) {
if ($this->config('debug')) {
throw $e;
} else {
try {
$this->response()->write(ob_get_clean());
$this->error($e);
} catch (\Slim\Exception\Stop $e) {
// Do nothing
}
}
}
}
/********************************************************************************
* Error Handling and Debugging
*******************************************************************************/
/**
* Convert errors into ErrorException objects
*
* This method catches PHP errors and converts them into \ErrorException objects;
* these \ErrorException objects are then thrown and caught by Slim's
* built-in or custom error handlers.
*
* @param int $errno The numeric type of the Error
* @param string $errstr The error message
* @param string $errfile The absolute path to the affected file
* @param int $errline The line number of the error in the affected file
* @return bool
* @throws \ErrorException
*/
public static function handleErrors($errno, $errstr = '', $errfile = '', $errline = '')
{
if (!($errno & error_reporting())) {
return;
}
throw new \ErrorException($errstr, $errno, 0, $errfile, $errline);
}
/**
* Generate diagnostic template markup
*
* This method accepts a title and body content to generate an HTML document layout.
*
* @param string $title The title of the HTML template
* @param string $body The body content of the HTML template
* @return string
*/
protected static function generateTemplateMarkup($title, $body)
{
return sprintf("%s%s
%s", $title, $title, $body);
}
/**
* Default Not Found handler
*/
protected function defaultNotFound()
{
echo static::generateTemplateMarkup('404 Page Not Found', 'The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.
Visit the Home Page');
}
/**
* Default Error handler
*/
protected function defaultError($e)
{
$this->getLog()->error($e);
echo self::generateTemplateMarkup('Error', 'A website error has occurred. The website administrator has been notified of the issue. Sorry for the temporary inconvenience.
');
}
}
DEEP.git/Slim/Slim/ 0000775 0000000 0000000 00000000000 12634026554 0014174 5 ustar 00root root 0000000 0000000 DEEP.git/Slim/Slim/Environment.php 0000775 0000000 0000000 00000016571 12634026554 0017226 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
/**
* Environment
*
* This class creates and returns a key/value array of common
* environment variables for the current HTTP request.
*
* This is a singleton class; derived environment variables will
* be common across multiple Slim applications.
*
* This class matches the Rack (Ruby) specification as closely
* as possible. More information available below.
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
class Environment implements \ArrayAccess, \IteratorAggregate
{
/**
* @var array
*/
protected $properties;
/**
* @var \Slim\Environment
*/
protected static $environment;
/**
* Get environment instance (singleton)
*
* This creates and/or returns an environment instance (singleton)
* derived from $_SERVER variables. You may override the global server
* variables by using `\Slim\Environment::mock()` instead.
*
* @param bool $refresh Refresh properties using global server variables?
* @return \Slim\Environment
*/
public static function getInstance($refresh = false)
{
if (is_null(self::$environment) || $refresh) {
self::$environment = new self();
}
return self::$environment;
}
/**
* Get mock environment instance
*
* @param array $userSettings
* @return \Slim\Environment
*/
public static function mock($userSettings = array())
{
$defaults = array(
'REQUEST_METHOD' => 'GET',
'SCRIPT_NAME' => '',
'PATH_INFO' => '',
'QUERY_STRING' => '',
'SERVER_NAME' => 'localhost',
'SERVER_PORT' => 80,
'ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'ACCEPT_LANGUAGE' => 'en-US,en;q=0.8',
'ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'USER_AGENT' => 'Slim Framework',
'REMOTE_ADDR' => '127.0.0.1',
'slim.url_scheme' => 'http',
'slim.input' => '',
'slim.errors' => @fopen('php://stderr', 'w')
);
self::$environment = new self(array_merge($defaults, $userSettings));
return self::$environment;
}
/**
* Constructor (private access)
*
* @param array|null $settings If present, these are used instead of global server variables
*/
private function __construct($settings = null)
{
if ($settings) {
$this->properties = $settings;
} else {
$env = array();
//The HTTP request method
$env['REQUEST_METHOD'] = $_SERVER['REQUEST_METHOD'];
//The IP
$env['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
// Server params
$scriptName = $_SERVER['SCRIPT_NAME']; // <-- "/foo/index.php"
$requestUri = $_SERVER['REQUEST_URI']; // <-- "/foo/bar?test=abc" or "/foo/index.php/bar?test=abc"
$queryString = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''; // <-- "test=abc" or ""
// Physical path
if (strpos($requestUri, $scriptName) !== false) {
$physicalPath = $scriptName; // <-- Without rewriting
} else {
$physicalPath = str_replace('\\', '', dirname($scriptName)); // <-- With rewriting
}
$env['SCRIPT_NAME'] = rtrim($physicalPath, '/'); // <-- Remove trailing slashes
// Virtual path
$env['PATH_INFO'] = $requestUri;
if (substr($requestUri, 0, strlen($physicalPath)) == $physicalPath) {
$env['PATH_INFO'] = substr($requestUri, strlen($physicalPath)); // <-- Remove physical path
}
$env['PATH_INFO'] = str_replace('?' . $queryString, '', $env['PATH_INFO']); // <-- Remove query string
$env['PATH_INFO'] = '/' . ltrim($env['PATH_INFO'], '/'); // <-- Ensure leading slash
// Query string (without leading "?")
$env['QUERY_STRING'] = $queryString;
//Name of server host that is running the script
$env['SERVER_NAME'] = $_SERVER['SERVER_NAME'];
//Number of server port that is running the script
//Fixes: https://github.com/slimphp/Slim/issues/962
$env['SERVER_PORT'] = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
//HTTP request headers (retains HTTP_ prefix to match $_SERVER)
$headers = \Slim\Http\Headers::extract($_SERVER);
foreach ($headers as $key => $value) {
$env[$key] = $value;
}
//Is the application running under HTTPS or HTTP protocol?
$env['slim.url_scheme'] = empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' ? 'http' : 'https';
//Input stream (readable one time only; not available for multipart/form-data requests)
$rawInput = @file_get_contents('php://input');
if (!$rawInput) {
$rawInput = '';
}
$env['slim.input'] = $rawInput;
//Error stream
$env['slim.errors'] = @fopen('php://stderr', 'w');
$this->properties = $env;
}
}
/**
* Array Access: Offset Exists
*/
public function offsetExists($offset)
{
return isset($this->properties[$offset]);
}
/**
* Array Access: Offset Get
*/
public function offsetGet($offset)
{
if (isset($this->properties[$offset])) {
return $this->properties[$offset];
}
return null;
}
/**
* Array Access: Offset Set
*/
public function offsetSet($offset, $value)
{
$this->properties[$offset] = $value;
}
/**
* Array Access: Offset Unset
*/
public function offsetUnset($offset)
{
unset($this->properties[$offset]);
}
/**
* IteratorAggregate
*
* @return \ArrayIterator
*/
public function getIterator()
{
return new \ArrayIterator($this->properties);
}
}
DEEP.git/Slim/Slim/Exception/ 0000775 0000000 0000000 00000000000 12634026554 0016132 5 ustar 00root root 0000000 0000000 DEEP.git/Slim/Slim/Exception/Pass.php 0000775 0000000 0000000 00000003347 12634026554 0017563 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Exception;
/**
* Pass Exception
*
* This Exception will cause the Router::dispatch method
* to skip the current matching route and continue to the next
* matching route. If no subsequent routes are found, a
* HTTP 404 Not Found response will be sent to the client.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class Pass extends \Exception
{
}
DEEP.git/Slim/Slim/Exception/Stop.php 0000775 0000000 0000000 00000003200 12634026554 0017566 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Exception;
/**
* Stop Exception
*
* This Exception is thrown when the Slim application needs to abort
* processing and return control flow to the outer PHP script.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class Stop extends \Exception
{
}
DEEP.git/Slim/Slim/Helper/ 0000775 0000000 0000000 00000000000 12634026554 0015413 5 ustar 00root root 0000000 0000000 DEEP.git/Slim/Slim/Helper/Set.php 0000775 0000000 0000000 00000013574 12634026554 0016674 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Helper;
class Set implements \ArrayAccess, \Countable, \IteratorAggregate
{
/**
* Key-value array of arbitrary data
* @var array
*/
protected $data = array();
/**
* Constructor
* @param array $items Pre-populate set with this key-value array
*/
public function __construct($items = array())
{
$this->replace($items);
}
/**
* Normalize data key
*
* Used to transform data key into the necessary
* key format for this set. Used in subclasses
* like \Slim\Http\Headers.
*
* @param string $key The data key
* @return mixed The transformed/normalized data key
*/
protected function normalizeKey($key)
{
return $key;
}
/**
* Set data key to value
* @param string $key The data key
* @param mixed $value The data value
*/
public function set($key, $value)
{
$this->data[$this->normalizeKey($key)] = $value;
}
/**
* Get data value with key
* @param string $key The data key
* @param mixed $default The value to return if data key does not exist
* @return mixed The data value, or the default value
*/
public function get($key, $default = null)
{
if ($this->has($key)) {
$isInvokable = is_object($this->data[$this->normalizeKey($key)]) && method_exists($this->data[$this->normalizeKey($key)], '__invoke');
return $isInvokable ? $this->data[$this->normalizeKey($key)]($this) : $this->data[$this->normalizeKey($key)];
}
return $default;
}
/**
* Add data to set
* @param array $items Key-value array of data to append to this set
*/
public function replace($items)
{
foreach ($items as $key => $value) {
$this->set($key, $value); // Ensure keys are normalized
}
}
/**
* Fetch set data
* @return array This set's key-value data array
*/
public function all()
{
return $this->data;
}
/**
* Fetch set data keys
* @return array This set's key-value data array keys
*/
public function keys()
{
return array_keys($this->data);
}
/**
* Does this set contain a key?
* @param string $key The data key
* @return boolean
*/
public function has($key)
{
return array_key_exists($this->normalizeKey($key), $this->data);
}
/**
* Remove value with key from this set
* @param string $key The data key
*/
public function remove($key)
{
unset($this->data[$this->normalizeKey($key)]);
}
/**
* Property Overloading
*/
public function __get($key)
{
return $this->get($key);
}
public function __set($key, $value)
{
$this->set($key, $value);
}
public function __isset($key)
{
return $this->has($key);
}
public function __unset($key)
{
$this->remove($key);
}
/**
* Clear all values
*/
public function clear()
{
$this->data = array();
}
/**
* Array Access
*/
public function offsetExists($offset)
{
return $this->has($offset);
}
public function offsetGet($offset)
{
return $this->get($offset);
}
public function offsetSet($offset, $value)
{
$this->set($offset, $value);
}
public function offsetUnset($offset)
{
$this->remove($offset);
}
/**
* Countable
*/
public function count()
{
return count($this->data);
}
/**
* IteratorAggregate
*/
public function getIterator()
{
return new \ArrayIterator($this->data);
}
/**
* Ensure a value or object will remain globally unique
* @param string $key The value or object name
* @param \Closure $value The closure that defines the object
* @return mixed
*/
public function singleton($key, $value)
{
$this->set($key, function ($c) use ($value) {
static $object;
if (null === $object) {
$object = $value($c);
}
return $object;
});
}
/**
* Protect closure from being directly invoked
* @param \Closure $callable A closure to keep from being invoked and evaluated
* @return \Closure
*/
public function protect(\Closure $callable)
{
return function () use ($callable) {
return $callable;
};
}
}
DEEP.git/Slim/Slim/Http/ 0000775 0000000 0000000 00000000000 12634026554 0015113 5 ustar 00root root 0000000 0000000 DEEP.git/Slim/Slim/Http/Cookies.php 0000775 0000000 0000000 00000006063 12634026554 0017230 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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));
}
}
DEEP.git/Slim/Slim/Http/Headers.php 0000775 0000000 0000000 00000006514 12634026554 0017210 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
}
}
DEEP.git/Slim/Slim/Http/Request.php 0000775 0000000 0000000 00000041001 12634026554 0017253 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
}
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');
}
}
DEEP.git/Slim/Slim/Http/Response.php 0000775 0000000 0000000 00000034321 12634026554 0017430 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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',
226 => '226 IM Used',
//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',
426 => '426 Upgrade Required',
428 => '428 Precondition Required',
429 => '429 Too Many Requests',
431 => '431 Request Header Fields Too Large',
//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',
506 => '506 Variant Also Negotiates',
510 => '510 Not Extended',
511 => '511 Network Authentication Required'
);
/**
* 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;
}
}
}
DEEP.git/Slim/Slim/Http/Util.php 0000775 0000000 0000000 00000036637 12634026554 0016563 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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);
}
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);
}
}
DEEP.git/Slim/Slim/Log.php 0000775 0000000 0000000 00000023731 12634026554 0015437 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
/**
* Log
*
* This is the primary logger for a Slim application. You may provide
* a Log Writer in conjunction with this Log to write to various output
* destinations (e.g. a file). This class provides this interface:
*
* debug( mixed $object, array $context )
* info( mixed $object, array $context )
* notice( mixed $object, array $context )
* warning( mixed $object, array $context )
* error( mixed $object, array $context )
* critical( mixed $object, array $context )
* alert( mixed $object, array $context )
* emergency( mixed $object, array $context )
* log( mixed $level, mixed $object, array $context )
*
* This class assumes only that your Log Writer has a public `write()` method
* that accepts any object as its one and only argument. The Log Writer
* class may write or send its argument anywhere: a file, STDERR,
* a remote web API, etc. The possibilities are endless.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class Log
{
const EMERGENCY = 1;
const ALERT = 2;
const CRITICAL = 3;
const FATAL = 3; //DEPRECATED replace with CRITICAL
const ERROR = 4;
const WARN = 5;
const NOTICE = 6;
const INFO = 7;
const DEBUG = 8;
/**
* @var array
*/
protected static $levels = array(
self::EMERGENCY => 'EMERGENCY',
self::ALERT => 'ALERT',
self::CRITICAL => 'CRITICAL',
self::ERROR => 'ERROR',
self::WARN => 'WARNING',
self::NOTICE => 'NOTICE',
self::INFO => 'INFO',
self::DEBUG => 'DEBUG'
);
/**
* @var mixed
*/
protected $writer;
/**
* @var bool
*/
protected $enabled;
/**
* @var int
*/
protected $level;
/**
* Constructor
* @param mixed $writer
*/
public function __construct($writer)
{
$this->writer = $writer;
$this->enabled = true;
$this->level = self::DEBUG;
}
/**
* Is logging enabled?
* @return bool
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Enable or disable logging
* @param bool $enabled
*/
public function setEnabled($enabled)
{
if ($enabled) {
$this->enabled = true;
} else {
$this->enabled = false;
}
}
/**
* Set level
* @param int $level
* @throws \InvalidArgumentException If invalid log level specified
*/
public function setLevel($level)
{
if (!isset(self::$levels[$level])) {
throw new \InvalidArgumentException('Invalid log level');
}
$this->level = $level;
}
/**
* Get level
* @return int
*/
public function getLevel()
{
return $this->level;
}
/**
* Set writer
* @param mixed $writer
*/
public function setWriter($writer)
{
$this->writer = $writer;
}
/**
* Get writer
* @return mixed
*/
public function getWriter()
{
return $this->writer;
}
/**
* Is logging enabled?
* @return bool
*/
public function isEnabled()
{
return $this->enabled;
}
/**
* Log debug message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function debug($object, $context = array())
{
return $this->log(self::DEBUG, $object, $context);
}
/**
* Log info message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function info($object, $context = array())
{
return $this->log(self::INFO, $object, $context);
}
/**
* Log notice message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function notice($object, $context = array())
{
return $this->log(self::NOTICE, $object, $context);
}
/**
* Log warning message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function warning($object, $context = array())
{
return $this->log(self::WARN, $object, $context);
}
/**
* DEPRECATED for function warning
* Log warning message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function warn($object, $context = array())
{
return $this->log(self::WARN, $object, $context);
}
/**
* Log error message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function error($object, $context = array())
{
return $this->log(self::ERROR, $object, $context);
}
/**
* Log critical message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function critical($object, $context = array())
{
return $this->log(self::CRITICAL, $object, $context);
}
/**
* DEPRECATED for function critical
* Log fatal message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function fatal($object, $context = array())
{
return $this->log(self::CRITICAL, $object, $context);
}
/**
* Log alert message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function alert($object, $context = array())
{
return $this->log(self::ALERT, $object, $context);
}
/**
* Log emergency message
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
*/
public function emergency($object, $context = array())
{
return $this->log(self::EMERGENCY, $object, $context);
}
/**
* Log message
* @param mixed $level
* @param mixed $object
* @param array $context
* @return mixed|bool What the Logger returns, or false if Logger not set or not enabled
* @throws \InvalidArgumentException If invalid log level
*/
public function log($level, $object, $context = array())
{
if (!isset(self::$levels[$level])) {
throw new \InvalidArgumentException('Invalid log level supplied to function');
} else if ($this->enabled && $this->writer && $level <= $this->level) {
if (is_array($object) || (is_object($object) && !method_exists($object, "__toString"))) {
$message = print_r($object, true);
} else {
$message = (string) $object;
}
if (count($context) > 0) {
if (isset($context['exception']) && $context['exception'] instanceof \Exception) {
$message .= ' - ' . $context['exception'];
unset($context['exception']);
}
$message = $this->interpolate($message, $context);
}
return $this->writer->write($message, $level);
} else {
return false;
}
}
/**
* DEPRECATED for function log
* Log message
* @param mixed $object The object to log
* @param int $level The message level
* @return int|bool
*/
protected function write($object, $level)
{
return $this->log($level, $object);
}
/**
* Interpolate log message
* @param mixed $message The log message
* @param array $context An array of placeholder values
* @return string The processed string
*/
protected function interpolate($message, $context = array())
{
$replace = array();
foreach ($context as $key => $value) {
$replace['{' . $key . '}'] = $value;
}
return strtr($message, $replace);
}
}
DEEP.git/Slim/Slim/LogWriter.php 0000775 0000000 0000000 00000004442 12634026554 0016632 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
/**
* Log Writer
*
* This class is used by Slim_Log to write log messages to a valid, writable
* resource handle (e.g. a file or STDERR).
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
class LogWriter
{
/**
* @var resource
*/
protected $resource;
/**
* Constructor
* @param resource $resource
* @throws \InvalidArgumentException If invalid resource
*/
public function __construct($resource)
{
if (!is_resource($resource)) {
throw new \InvalidArgumentException('Cannot create LogWriter. Invalid resource handle.');
}
$this->resource = $resource;
}
/**
* Write message
* @param mixed $message
* @param int $level
* @return int|bool
*/
public function write($message, $level = null)
{
return fwrite($this->resource, (string) $message . PHP_EOL);
}
}
DEEP.git/Slim/Slim/Middleware.php 0000775 0000000 0000000 00000006026 12634026554 0016771 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
/**
* Middleware
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
abstract class Middleware
{
/**
* @var \Slim\Slim Reference to the primary application instance
*/
protected $app;
/**
* @var mixed Reference to the next downstream middleware
*/
protected $next;
/**
* Set application
*
* This method injects the primary Slim application instance into
* this middleware.
*
* @param \Slim\Slim $application
*/
final public function setApplication($application)
{
$this->app = $application;
}
/**
* Get application
*
* This method retrieves the application previously injected
* into this middleware.
*
* @return \Slim\Slim
*/
final public function getApplication()
{
return $this->app;
}
/**
* Set next middleware
*
* This method injects the next downstream middleware into
* this middleware so that it may optionally be called
* when appropriate.
*
* @param \Slim|\Slim\Middleware
*/
final public function setNextMiddleware($nextMiddleware)
{
$this->next = $nextMiddleware;
}
/**
* Get next middleware
*
* This method retrieves the next downstream middleware
* previously injected into this middleware.
*
* @return \Slim\Slim|\Slim\Middleware
*/
final public function getNextMiddleware()
{
return $this->next;
}
/**
* Call
*
* Perform actions specific to this middleware and optionally
* call the next downstream middleware.
*/
abstract public function call();
}
DEEP.git/Slim/Slim/Middleware/ 0000775 0000000 0000000 00000000000 12634026554 0016251 5 ustar 00root root 0000000 0000000 DEEP.git/Slim/Slim/Middleware/ContentTypes.php 0000775 0000000 0000000 00000011750 12634026554 0021430 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Middleware;
/**
* Content Types
*
* This is middleware for a Slim application that intercepts
* the HTTP request body and parses it into the appropriate
* PHP data structure if possible; else it returns the HTTP
* request body unchanged. This is particularly useful
* for preparing the HTTP request body for an XML or JSON API.
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
class ContentTypes extends \Slim\Middleware
{
/**
* @var array
*/
protected $contentTypes;
/**
* Constructor
* @param array $settings
*/
public function __construct($settings = array())
{
$defaults = array(
'application/json' => array($this, 'parseJson'),
'application/xml' => array($this, 'parseXml'),
'text/xml' => array($this, 'parseXml'),
'text/csv' => array($this, 'parseCsv')
);
$this->contentTypes = array_merge($defaults, $settings);
}
/**
* Call
*/
public function call()
{
$mediaType = $this->app->request()->getMediaType();
if ($mediaType) {
$env = $this->app->environment();
$env['slim.input_original'] = $env['slim.input'];
$env['slim.input'] = $this->parse($env['slim.input'], $mediaType);
}
$this->next->call();
}
/**
* Parse input
*
* This method will attempt to parse the request body
* based on its content type if available.
*
* @param string $input
* @param string $contentType
* @return mixed
*/
protected function parse ($input, $contentType)
{
if (isset($this->contentTypes[$contentType]) && is_callable($this->contentTypes[$contentType])) {
$result = call_user_func($this->contentTypes[$contentType], $input);
if ($result) {
return $result;
}
}
return $input;
}
/**
* Parse JSON
*
* This method converts the raw JSON input
* into an associative array.
*
* @param string $input
* @return array|string
*/
protected function parseJson($input)
{
if (function_exists('json_decode')) {
$result = json_decode($input, true);
if(json_last_error() === JSON_ERROR_NONE) {
return $result;
}
}
}
/**
* Parse XML
*
* This method creates a SimpleXMLElement
* based upon the XML input. If the SimpleXML
* extension is not available, the raw input
* will be returned unchanged.
*
* @param string $input
* @return \SimpleXMLElement|string
*/
protected function parseXml($input)
{
if (class_exists('SimpleXMLElement')) {
try {
$backup = libxml_disable_entity_loader(true);
$result = new \SimpleXMLElement($input);
libxml_disable_entity_loader($backup);
return $result;
} catch (\Exception $e) {
// Do nothing
}
}
return $input;
}
/**
* Parse CSV
*
* This method parses CSV content into a numeric array
* containing an array of data for each CSV line.
*
* @param string $input
* @return array
*/
protected function parseCsv($input)
{
$temp = fopen('php://memory', 'rw');
fwrite($temp, $input);
fseek($temp, 0);
$res = array();
while (($data = fgetcsv($temp)) !== false) {
$res[] = $data;
}
fclose($temp);
return $res;
}
}
DEEP.git/Slim/Slim/Middleware/Flash.php 0000775 0000000 0000000 00000012426 12634026554 0020027 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Middleware;
/**
* Flash
*
* This is middleware for a Slim application that enables
* Flash messaging between HTTP requests. This allows you
* set Flash messages for the current request, for the next request,
* or to retain messages from the previous request through to
* the next request.
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
class Flash extends \Slim\Middleware implements \ArrayAccess, \IteratorAggregate, \Countable
{
/**
* @var array
*/
protected $settings;
/**
* @var array
*/
protected $messages;
/**
* Constructor
* @param array $settings
*/
public function __construct($settings = array())
{
$this->settings = array_merge(array('key' => 'slim.flash'), $settings);
$this->messages = array(
'prev' => array(), //flash messages from prev request (loaded when middleware called)
'next' => array(), //flash messages for next request
'now' => array() //flash messages for current request
);
}
/**
* Call
*/
public function call()
{
//Read flash messaging from previous request if available
$this->loadMessages();
//Prepare flash messaging for current request
$env = $this->app->environment();
$env['slim.flash'] = $this;
$this->next->call();
$this->save();
}
/**
* Now
*
* Specify a flash message for a given key to be shown for the current request
*
* @param string $key
* @param string $value
*/
public function now($key, $value)
{
$this->messages['now'][(string) $key] = $value;
}
/**
* Set
*
* Specify a flash message for a given key to be shown for the next request
*
* @param string $key
* @param string $value
*/
public function set($key, $value)
{
$this->messages['next'][(string) $key] = $value;
}
/**
* Keep
*
* Retain flash messages from the previous request for the next request
*/
public function keep()
{
foreach ($this->messages['prev'] as $key => $val) {
$this->messages['next'][$key] = $val;
}
}
/**
* Save
*/
public function save()
{
$_SESSION[$this->settings['key']] = $this->messages['next'];
}
/**
* Load messages from previous request if available
*/
public function loadMessages()
{
if (isset($_SESSION[$this->settings['key']])) {
$this->messages['prev'] = $_SESSION[$this->settings['key']];
}
}
/**
* Return array of flash messages to be shown for the current request
*
* @return array
*/
public function getMessages()
{
return array_merge($this->messages['prev'], $this->messages['now']);
}
/**
* Array Access: Offset Exists
*/
public function offsetExists($offset)
{
$messages = $this->getMessages();
return isset($messages[$offset]);
}
/**
* Array Access: Offset Get
*/
public function offsetGet($offset)
{
$messages = $this->getMessages();
return isset($messages[$offset]) ? $messages[$offset] : null;
}
/**
* Array Access: Offset Set
*/
public function offsetSet($offset, $value)
{
$this->now($offset, $value);
}
/**
* Array Access: Offset Unset
*/
public function offsetUnset($offset)
{
unset($this->messages['prev'][$offset], $this->messages['now'][$offset]);
}
/**
* Iterator Aggregate: Get Iterator
* @return \ArrayIterator
*/
public function getIterator()
{
$messages = $this->getMessages();
return new \ArrayIterator($messages);
}
/**
* Countable: Count
*/
public function count()
{
return count($this->getMessages());
}
}
DEEP.git/Slim/Slim/Middleware/MethodOverride.php 0000775 0000000 0000000 00000006634 12634026554 0021716 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Middleware;
/**
* HTTP Method Override
*
* This is middleware for a Slim application that allows traditional
* desktop browsers to submit pseudo PUT and DELETE requests by relying
* on a pre-determined request parameter. Without this middleware,
* desktop browsers are only able to submit GET and POST requests.
*
* This middleware is included automatically!
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
class MethodOverride extends \Slim\Middleware
{
/**
* @var array
*/
protected $settings;
/**
* Constructor
* @param array $settings
*/
public function __construct($settings = array())
{
$this->settings = array_merge(array('key' => '_METHOD'), $settings);
}
/**
* Call
*
* Implements Slim middleware interface. This method is invoked and passed
* an array of environment variables. This middleware inspects the environment
* variables for the HTTP method override parameter; if found, this middleware
* modifies the environment settings so downstream middleware and/or the Slim
* application will treat the request with the desired HTTP method.
*
* @return array[status, header, body]
*/
public function call()
{
$env = $this->app->environment();
if (isset($env['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
// Header commonly used by Backbone.js and others
$env['slim.method_override.original_method'] = $env['REQUEST_METHOD'];
$env['REQUEST_METHOD'] = strtoupper($env['HTTP_X_HTTP_METHOD_OVERRIDE']);
} elseif (isset($env['REQUEST_METHOD']) && $env['REQUEST_METHOD'] === 'POST') {
// HTML Form Override
$req = new \Slim\Http\Request($env);
$method = $req->post($this->settings['key']);
if ($method) {
$env['slim.method_override.original_method'] = $env['REQUEST_METHOD'];
$env['REQUEST_METHOD'] = strtoupper($method);
}
}
$this->next->call();
}
}
DEEP.git/Slim/Slim/Middleware/PrettyExceptions.php 0000775 0000000 0000000 00000010047 12634026554 0022320 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Middleware;
/**
* Pretty Exceptions
*
* This middleware catches any Exception thrown by the surrounded
* application and displays a developer-friendly diagnostic screen.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class PrettyExceptions extends \Slim\Middleware
{
/**
* @var array
*/
protected $settings;
/**
* Constructor
* @param array $settings
*/
public function __construct($settings = array())
{
$this->settings = $settings;
}
/**
* Call
*/
public function call()
{
try {
$this->next->call();
} catch (\Exception $e) {
$log = $this->app->getLog(); // Force Slim to append log to env if not already
$env = $this->app->environment();
$env['slim.log'] = $log;
$env['slim.log']->error($e);
$this->app->contentType('text/html');
$this->app->response()->status(500);
$this->app->response()->body($this->renderBody($env, $e));
}
}
/**
* Render response body
* @param array $env
* @param \Exception $exception
* @return string
*/
protected function renderBody(&$env, $exception)
{
$title = 'Slim Application Error';
$code = $exception->getCode();
$message = htmlspecialchars($exception->getMessage());
$file = $exception->getFile();
$line = $exception->getLine();
$trace = str_replace(array('#', "\n"), array('#', '
'), htmlspecialchars($exception->getTraceAsString()));
$html = sprintf('%s
', $title);
$html .= 'The application could not run because of the following error:
';
$html .= 'Details
';
$html .= sprintf('Type: %s
', get_class($exception));
if ($code) {
$html .= sprintf('Code: %s
', $code);
}
if ($message) {
$html .= sprintf('Message: %s
', $message);
}
if ($file) {
$html .= sprintf('File: %s
', $file);
}
if ($line) {
$html .= sprintf('Line: %s
', $line);
}
if ($trace) {
$html .= 'Trace
';
$html .= sprintf('%s
', $trace);
}
return sprintf("%s%s", $title, $html);
}
}
DEEP.git/Slim/Slim/Middleware/SessionCookie.php 0000775 0000000 0000000 00000013247 12634026554 0021551 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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\Middleware;
/**
* Session Cookie
*
* This class provides an HTTP cookie storage mechanism
* for session data. This class avoids using a PHP session
* and instead serializes/unserializes the $_SESSION global
* variable to/from an HTTP cookie.
*
* You should NEVER store sensitive data in a client-side cookie
* in any format, encrypted (with cookies.encrypt) or not. If you
* need to store sensitive user information in a session, you should
* rely on PHP's native session implementation, or use other middleware
* to store session data in a database or alternative server-side cache.
*
* Because this class stores serialized session data in an HTTP cookie,
* you are inherently limited to 4 Kb. If you attempt to store
* more than this amount, serialization will fail.
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
class SessionCookie extends \Slim\Middleware
{
/**
* @var array
*/
protected $settings;
/**
* Constructor
*
* @param array $settings
*/
public function __construct($settings = array())
{
$defaults = array(
'expires' => '20 minutes',
'path' => '/',
'domain' => null,
'secure' => false,
'httponly' => false,
'name' => 'slim_session',
);
$this->settings = array_merge($defaults, $settings);
if (is_string($this->settings['expires'])) {
$this->settings['expires'] = strtotime($this->settings['expires']);
}
/**
* Session
*
* We must start a native PHP session to initialize the $_SESSION superglobal.
* However, we won't be using the native session store for persistence, so we
* disable the session cookie and cache limiter. We also set the session
* handler to this class instance to avoid PHP's native session file locking.
*/
ini_set('session.use_cookies', 0);
session_cache_limiter(false);
session_set_save_handler(
array($this, 'open'),
array($this, 'close'),
array($this, 'read'),
array($this, 'write'),
array($this, 'destroy'),
array($this, 'gc')
);
}
/**
* Call
*/
public function call()
{
$this->loadSession();
$this->next->call();
$this->saveSession();
}
/**
* Load session
*/
protected function loadSession()
{
if (session_id() === '') {
session_start();
}
$value = $this->app->getCookie($this->settings['name']);
if ($value) {
$value = json_decode($value, true);
$_SESSION = is_array($value) ? $value : array();
} else {
$_SESSION = array();
}
}
/**
* Save session
*/
protected function saveSession()
{
$value = json_encode($_SESSION);
if (strlen($value) > 4096) {
$this->app->getLog()->error('WARNING! Slim\Middleware\SessionCookie data size is larger than 4KB. Content save failed.');
} else {
$this->app->setCookie(
$this->settings['name'],
$value,
$this->settings['expires'],
$this->settings['path'],
$this->settings['domain'],
$this->settings['secure'],
$this->settings['httponly']
);
}
// session_destroy();
}
/********************************************************************************
* Session Handler
*******************************************************************************/
/**
* @codeCoverageIgnore
*/
public function open($savePath, $sessionName)
{
return true;
}
/**
* @codeCoverageIgnore
*/
public function close()
{
return true;
}
/**
* @codeCoverageIgnore
*/
public function read($id)
{
return '';
}
/**
* @codeCoverageIgnore
*/
public function write($id, $data)
{
return true;
}
/**
* @codeCoverageIgnore
*/
public function destroy($id)
{
return true;
}
/**
* @codeCoverageIgnore
*/
public function gc($maxlifetime)
{
return true;
}
}
DEEP.git/Slim/Slim/Route.php 0000775 0000000 0000000 00000030767 12634026554 0016023 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
/**
* Route
* @package Slim
* @author Josh Lockhart, Thomas Bley
* @since 1.0.0
*/
class Route
{
/**
* @var string The route pattern (e.g. "/books/:id")
*/
protected $pattern;
/**
* @var mixed The route callable
*/
protected $callable;
/**
* @var array Conditions for this route's URL parameters
*/
protected $conditions = array();
/**
* @var array Default conditions applied to all route instances
*/
protected static $defaultConditions = array();
/**
* @var string The name of this route (optional)
*/
protected $name;
/**
* @var array Key-value array of URL parameters
*/
protected $params = array();
/**
* @var array value array of URL parameter names
*/
protected $paramNames = array();
/**
* @var array key array of URL parameter names with + at the end
*/
protected $paramNamesPath = array();
/**
* @var array HTTP methods supported by this Route
*/
protected $methods = array();
/**
* @var array[Callable] Middleware to be run before only this route instance
*/
protected $middleware = array();
/**
* @var bool Whether or not this route should be matched in a case-sensitive manner
*/
protected $caseSensitive;
/**
* Constructor
* @param string $pattern The URL pattern (e.g. "/books/:id")
* @param mixed $callable Anything that returns TRUE for is_callable()
* @param bool $caseSensitive Whether or not this route should be matched in a case-sensitive manner
*/
public function __construct($pattern, $callable, $caseSensitive = true)
{
$this->setPattern($pattern);
$this->setCallable($callable);
$this->setConditions(self::getDefaultConditions());
$this->caseSensitive = $caseSensitive;
}
/**
* Set default route conditions for all instances
* @param array $defaultConditions
*/
public static function setDefaultConditions(array $defaultConditions)
{
self::$defaultConditions = $defaultConditions;
}
/**
* Get default route conditions for all instances
* @return array
*/
public static function getDefaultConditions()
{
return self::$defaultConditions;
}
/**
* Get route pattern
* @return string
*/
public function getPattern()
{
return $this->pattern;
}
/**
* Set route pattern
* @param string $pattern
*/
public function setPattern($pattern)
{
$this->pattern = $pattern;
}
/**
* Get route callable
* @return mixed
*/
public function getCallable()
{
return $this->callable;
}
/**
* Set route callable
* @param mixed $callable
* @throws \InvalidArgumentException If argument is not callable
*/
public function setCallable($callable)
{
$matches = array();
if (is_string($callable) && preg_match('!^([^\:]+)\:([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$!', $callable, $matches)) {
$class = $matches[1];
$method = $matches[2];
$callable = function() use ($class, $method) {
static $obj = null;
if ($obj === null) {
$obj = new $class;
}
return call_user_func_array(array($obj, $method), func_get_args());
};
}
if (!is_callable($callable)) {
throw new \InvalidArgumentException('Route callable must be callable');
}
$this->callable = $callable;
}
/**
* Get route conditions
* @return array
*/
public function getConditions()
{
return $this->conditions;
}
/**
* Set route conditions
* @param array $conditions
*/
public function setConditions(array $conditions)
{
$this->conditions = $conditions;
}
/**
* Get route name
* @return string|null
*/
public function getName()
{
return $this->name;
}
/**
* Set route name
* @param string $name
*/
public function setName($name)
{
$this->name = (string)$name;
}
/**
* Get route parameters
* @return array
*/
public function getParams()
{
return $this->params;
}
/**
* Set route parameters
* @param array $params
*/
public function setParams($params)
{
$this->params = $params;
}
/**
* Get route parameter value
* @param string $index Name of URL parameter
* @return string
* @throws \InvalidArgumentException If route parameter does not exist at index
*/
public function getParam($index)
{
if (!isset($this->params[$index])) {
throw new \InvalidArgumentException('Route parameter does not exist at specified index');
}
return $this->params[$index];
}
/**
* Set route parameter value
* @param string $index Name of URL parameter
* @param mixed $value The new parameter value
* @throws \InvalidArgumentException If route parameter does not exist at index
*/
public function setParam($index, $value)
{
if (!isset($this->params[$index])) {
throw new \InvalidArgumentException('Route parameter does not exist at specified index');
}
$this->params[$index] = $value;
}
/**
* Add supported HTTP method(s)
*/
public function setHttpMethods()
{
$args = func_get_args();
$this->methods = $args;
}
/**
* Get supported HTTP methods
* @return array
*/
public function getHttpMethods()
{
return $this->methods;
}
/**
* Append supported HTTP methods
*/
public function appendHttpMethods()
{
$args = func_get_args();
if(count($args) && is_array($args[0])){
$args = $args[0];
}
$this->methods = array_merge($this->methods, $args);
}
/**
* Append supported HTTP methods (alias for Route::appendHttpMethods)
* @return \Slim\Route
*/
public function via()
{
$args = func_get_args();
if(count($args) && is_array($args[0])){
$args = $args[0];
}
$this->methods = array_merge($this->methods, $args);
return $this;
}
/**
* Detect support for an HTTP method
* @param string $method
* @return bool
*/
public function supportsHttpMethod($method)
{
return in_array($method, $this->methods);
}
/**
* Get middleware
* @return array[Callable]
*/
public function getMiddleware()
{
return $this->middleware;
}
/**
* Set middleware
*
* This method allows middleware to be assigned to a specific Route.
* If the method argument `is_callable` (including callable arrays!),
* we directly append the argument to `$this->middleware`. Else, we
* assume the argument is an array of callables and merge the array
* with `$this->middleware`. Each middleware is checked for is_callable()
* and an InvalidArgumentException is thrown immediately if it isn't.
*
* @param Callable|array[Callable]
* @return \Slim\Route
* @throws \InvalidArgumentException If argument is not callable or not an array of callables.
*/
public function setMiddleware($middleware)
{
if (is_callable($middleware)) {
$this->middleware[] = $middleware;
} elseif (is_array($middleware)) {
foreach ($middleware as $callable) {
if (!is_callable($callable)) {
throw new \InvalidArgumentException('All Route middleware must be callable');
}
}
$this->middleware = array_merge($this->middleware, $middleware);
} else {
throw new \InvalidArgumentException('Route middleware must be callable or an array of callables');
}
return $this;
}
/**
* Matches URI?
*
* Parse this route's pattern, and then compare it to an HTTP resource URI
* This method was modeled after the techniques demonstrated by Dan Sosedoff at:
*
* http://blog.sosedoff.com/2009/09/20/rails-like-php-url-router/
*
* @param string $resourceUri A Request URI
* @return bool
*/
public function matches($resourceUri)
{
//Convert URL params into regex patterns, construct a regex for this route, init params
$patternAsRegex = preg_replace_callback(
'#:([\w]+)\+?#',
array($this, 'matchesCallback'),
str_replace(')', ')?', (string)$this->pattern)
);
if (substr($this->pattern, -1) === '/') {
$patternAsRegex .= '?';
}
$regex = '#^' . $patternAsRegex . '$#';
if ($this->caseSensitive === false) {
$regex .= 'i';
}
//Cache URL params' names and values if this route matches the current HTTP request
if (!preg_match($regex, $resourceUri, $paramValues)) {
return false;
}
foreach ($this->paramNames as $name) {
if (isset($paramValues[$name])) {
if (isset($this->paramNamesPath[$name])) {
$this->params[$name] = explode('/', urldecode($paramValues[$name]));
} else {
$this->params[$name] = urldecode($paramValues[$name]);
}
}
}
return true;
}
/**
* Convert a URL parameter (e.g. ":id", ":id+") into a regular expression
* @param array $m URL parameters
* @return string Regular expression for URL parameter
*/
protected function matchesCallback($m)
{
$this->paramNames[] = $m[1];
if (isset($this->conditions[$m[1]])) {
return '(?P<' . $m[1] . '>' . $this->conditions[$m[1]] . ')';
}
if (substr($m[0], -1) === '+') {
$this->paramNamesPath[$m[1]] = 1;
return '(?P<' . $m[1] . '>.+)';
}
return '(?P<' . $m[1] . '>[^/]+)';
}
/**
* Set route name
* @param string $name The name of the route
* @return \Slim\Route
*/
public function name($name)
{
$this->setName($name);
return $this;
}
/**
* Merge route conditions
* @param array $conditions Key-value array of URL parameter conditions
* @return \Slim\Route
*/
public function conditions(array $conditions)
{
$this->conditions = array_merge($this->conditions, $conditions);
return $this;
}
/**
* Dispatch route
*
* This method invokes the route object's callable. If middleware is
* registered for the route, each callable middleware is invoked in
* the order specified.
*
* @return bool
*/
public function dispatch()
{
foreach ($this->middleware as $mw) {
call_user_func_array($mw, array($this));
}
$return = call_user_func_array($this->getCallable(), array_values($this->getParams()));
return ($return === false) ? false : true;
}
}
DEEP.git/Slim/Slim/Router.php 0000775 0000000 0000000 00000017352 12634026554 0016200 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
/**
* Router
*
* This class organizes, iterates, and dispatches \Slim\Route objects.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class Router
{
/**
* @var Route The current route (most recently dispatched)
*/
protected $currentRoute;
/**
* @var array Lookup hash of all route objects
*/
protected $routes;
/**
* @var array Lookup hash of named route objects, keyed by route name (lazy-loaded)
*/
protected $namedRoutes;
/**
* @var array Array of route objects that match the request URI (lazy-loaded)
*/
protected $matchedRoutes;
/**
* @var array Array containing all route groups
*/
protected $routeGroups;
/**
* Constructor
*/
public function __construct()
{
$this->routes = array();
$this->routeGroups = array();
}
/**
* Get Current Route object or the first matched one if matching has been performed
* @return \Slim\Route|null
*/
public function getCurrentRoute()
{
if ($this->currentRoute !== null) {
return $this->currentRoute;
}
if (is_array($this->matchedRoutes) && count($this->matchedRoutes) > 0) {
return $this->matchedRoutes[0];
}
return null;
}
/**
* Return route objects that match the given HTTP method and URI
* @param string $httpMethod The HTTP method to match against
* @param string $resourceUri The resource URI to match against
* @param bool $reload Should matching routes be re-parsed?
* @return array[\Slim\Route]
*/
public function getMatchedRoutes($httpMethod, $resourceUri, $reload = false)
{
if ($reload || is_null($this->matchedRoutes)) {
$this->matchedRoutes = array();
foreach ($this->routes as $route) {
if (!$route->supportsHttpMethod($httpMethod) && !$route->supportsHttpMethod("ANY")) {
continue;
}
if ($route->matches($resourceUri)) {
$this->matchedRoutes[] = $route;
}
}
}
return $this->matchedRoutes;
}
/**
* Add a route object to the router
* @param \Slim\Route $route The Slim Route
*/
public function map(\Slim\Route $route)
{
list($groupPattern, $groupMiddleware) = $this->processGroups();
$route->setPattern($groupPattern . $route->getPattern());
$this->routes[] = $route;
foreach ($groupMiddleware as $middleware) {
$route->setMiddleware($middleware);
}
}
/**
* A helper function for processing the group's pattern and middleware
* @return array Returns an array with the elements: pattern, middlewareArr
*/
protected function processGroups()
{
$pattern = "";
$middleware = array();
foreach ($this->routeGroups as $group) {
$k = key($group);
$pattern .= $k;
if (is_array($group[$k])) {
$middleware = array_merge($middleware, $group[$k]);
}
}
return array($pattern, $middleware);
}
/**
* Add a route group to the array
* @param string $group The group pattern (ie. "/books/:id")
* @param array|null $middleware Optional parameter array of middleware
* @return int The index of the new group
*/
public function pushGroup($group, $middleware = array())
{
return array_push($this->routeGroups, array($group => $middleware));
}
/**
* Removes the last route group from the array
* @return bool True if successful, else False
*/
public function popGroup()
{
return (array_pop($this->routeGroups) !== null);
}
/**
* Get URL for named route
* @param string $name The name of the route
* @param array $params Associative array of URL parameter names and replacement values
* @throws \RuntimeException If named route not found
* @return string The URL for the given route populated with provided replacement values
*/
public function urlFor($name, $params = array())
{
if (!$this->hasNamedRoute($name)) {
throw new \RuntimeException('Named route not found for name: ' . $name);
}
$search = array();
foreach ($params as $key => $value) {
$search[] = '#:' . preg_quote($key, '#') . '\+?(?!\w)#';
}
$pattern = preg_replace($search, $params, $this->getNamedRoute($name)->getPattern());
//Remove remnants of unpopulated, trailing optional pattern segments, escaped special characters
return preg_replace('#\(/?:.+\)|\(|\)|\\\\#', '', $pattern);
}
/**
* Add named route
* @param string $name The route name
* @param \Slim\Route $route The route object
* @throws \RuntimeException If a named route already exists with the same name
*/
public function addNamedRoute($name, \Slim\Route $route)
{
if ($this->hasNamedRoute($name)) {
throw new \RuntimeException('Named route already exists with name: ' . $name);
}
$this->namedRoutes[(string) $name] = $route;
}
/**
* Has named route
* @param string $name The route name
* @return bool
*/
public function hasNamedRoute($name)
{
$this->getNamedRoutes();
return isset($this->namedRoutes[(string) $name]);
}
/**
* Get named route
* @param string $name
* @return \Slim\Route|null
*/
public function getNamedRoute($name)
{
$this->getNamedRoutes();
if ($this->hasNamedRoute($name)) {
return $this->namedRoutes[(string) $name];
}
return null;
}
/**
* Get named routes
* @return \ArrayIterator
*/
public function getNamedRoutes()
{
if (is_null($this->namedRoutes)) {
$this->namedRoutes = array();
foreach ($this->routes as $route) {
if ($route->getName() !== null) {
$this->addNamedRoute($route->getName(), $route);
}
}
}
return new \ArrayIterator($this->namedRoutes);
}
}
DEEP.git/Slim/Slim/Slim.php 0000775 0000000 0000000 00000137251 12634026554 0015625 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
// Ensure mcrypt constants are defined even if mcrypt extension is not loaded
if (!extension_loaded('mcrypt')) {
define('MCRYPT_MODE_CBC', 0);
define('MCRYPT_RIJNDAEL_256', 0);
}
/**
* Slim
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*
* @property \Slim\Environment $environment
* @property \Slim\Http\Response $response
* @property \Slim\Http\Request $request
* @property \Slim\Router $router
*/
class Slim
{
/**
* @const string
*/
const VERSION = '2.6.1';
/**
* @var \Slim\Helper\Set
*/
public $container;
/**
* @var array[\Slim]
*/
protected static $apps = array();
/**
* @var string
*/
protected $name;
/**
* @var array
*/
protected $middleware;
/**
* @var mixed Callable to be invoked if application error
*/
protected $error;
/**
* @var mixed Callable to be invoked if no matching routes are found
*/
protected $notFound;
/**
* @var array
*/
protected $hooks = array(
'slim.before' => array(array()),
'slim.before.router' => array(array()),
'slim.before.dispatch' => array(array()),
'slim.after.dispatch' => array(array()),
'slim.after.router' => array(array()),
'slim.after' => array(array())
);
/********************************************************************************
* PSR-0 Autoloader
*
* Do not use if you are using Composer to autoload dependencies.
*******************************************************************************/
/**
* Slim PSR-0 autoloader
*/
public static function autoload($className)
{
$thisClass = str_replace(__NAMESPACE__.'\\', '', __CLASS__);
$baseDir = __DIR__;
if (substr($baseDir, -strlen($thisClass)) === $thisClass) {
$baseDir = substr($baseDir, 0, -strlen($thisClass));
}
$className = ltrim($className, '\\');
$fileName = $baseDir;
$namespace = '';
if ($lastNsPos = strripos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
if (file_exists($fileName)) {
require $fileName;
}
}
/**
* Register Slim's PSR-0 autoloader
*/
public static function registerAutoloader()
{
spl_autoload_register(__NAMESPACE__ . "\\Slim::autoload");
}
/********************************************************************************
* Instantiation and Configuration
*******************************************************************************/
/**
* Constructor
* @param array $userSettings Associative array of application settings
*/
public function __construct(array $userSettings = array())
{
// Setup IoC container
$this->container = new \Slim\Helper\Set();
$this->container['settings'] = array_merge(static::getDefaultSettings(), $userSettings);
// Default environment
$this->container->singleton('environment', function ($c) {
return \Slim\Environment::getInstance();
});
// Default request
$this->container->singleton('request', function ($c) {
return new \Slim\Http\Request($c['environment']);
});
// Default response
$this->container->singleton('response', function ($c) {
return new \Slim\Http\Response();
});
// Default router
$this->container->singleton('router', function ($c) {
return new \Slim\Router();
});
// Default view
$this->container->singleton('view', function ($c) {
$viewClass = $c['settings']['view'];
$templatesPath = $c['settings']['templates.path'];
$view = ($viewClass instanceOf \Slim\View) ? $viewClass : new $viewClass;
$view->setTemplatesDirectory($templatesPath);
return $view;
});
// Default log writer
$this->container->singleton('logWriter', function ($c) {
$logWriter = $c['settings']['log.writer'];
return is_object($logWriter) ? $logWriter : new \Slim\LogWriter($c['environment']['slim.errors']);
});
// Default log
$this->container->singleton('log', function ($c) {
$log = new \Slim\Log($c['logWriter']);
$log->setEnabled($c['settings']['log.enabled']);
$log->setLevel($c['settings']['log.level']);
$env = $c['environment'];
$env['slim.log'] = $log;
return $log;
});
// Default mode
$this->container['mode'] = function ($c) {
$mode = $c['settings']['mode'];
if (isset($_ENV['SLIM_MODE'])) {
$mode = $_ENV['SLIM_MODE'];
} else {
$envMode = getenv('SLIM_MODE');
if ($envMode !== false) {
$mode = $envMode;
}
}
return $mode;
};
// Define default middleware stack
$this->middleware = array($this);
$this->add(new \Slim\Middleware\Flash());
$this->add(new \Slim\Middleware\MethodOverride());
// Make default if first instance
if (is_null(static::getInstance())) {
$this->setName('default');
}
}
public function __get($name)
{
return $this->container->get($name);
}
public function __set($name, $value)
{
$this->container->set($name, $value);
}
public function __isset($name)
{
return $this->container->has($name);
}
public function __unset($name)
{
$this->container->remove($name);
}
/**
* Get application instance by name
* @param string $name The name of the Slim application
* @return \Slim\Slim|null
*/
public static function getInstance($name = 'default')
{
return isset(static::$apps[$name]) ? static::$apps[$name] : null;
}
/**
* Set Slim application name
* @param string $name The name of this Slim application
*/
public function setName($name)
{
$this->name = $name;
static::$apps[$name] = $this;
}
/**
* Get Slim application name
* @return string|null
*/
public function getName()
{
return $this->name;
}
/**
* Get default application settings
* @return array
*/
public static function getDefaultSettings()
{
return array(
// Application
'mode' => 'development',
// Debugging
'debug' => true,
// Logging
'log.writer' => null,
'log.level' => \Slim\Log::DEBUG,
'log.enabled' => true,
// View
'templates.path' => './templates',
'view' => '\Slim\View',
// Cookies
'cookies.encrypt' => false,
'cookies.lifetime' => '20 minutes',
'cookies.path' => '/',
'cookies.domain' => null,
'cookies.secure' => false,
'cookies.httponly' => false,
// Encryption
'cookies.secret_key' => 'CHANGE_ME',
'cookies.cipher' => MCRYPT_RIJNDAEL_256,
'cookies.cipher_mode' => MCRYPT_MODE_CBC,
// HTTP
'http.version' => '1.1',
// Routing
'routes.case_sensitive' => true
);
}
/**
* Configure Slim Settings
*
* This method defines application settings and acts as a setter and a getter.
*
* If only one argument is specified and that argument is a string, the value
* of the setting identified by the first argument will be returned, or NULL if
* that setting does not exist.
*
* If only one argument is specified and that argument is an associative array,
* the array will be merged into the existing application settings.
*
* If two arguments are provided, the first argument is the name of the setting
* to be created or updated, and the second argument is the setting value.
*
* @param string|array $name If a string, the name of the setting to set or retrieve. Else an associated array of setting names and values
* @param mixed $value If name is a string, the value of the setting identified by $name
* @return mixed The value of a setting if only one argument is a string
*/
public function config($name, $value = null)
{
$c = $this->container;
if (is_array($name)) {
if (true === $value) {
$c['settings'] = array_merge_recursive($c['settings'], $name);
} else {
$c['settings'] = array_merge($c['settings'], $name);
}
} elseif (func_num_args() === 1) {
return isset($c['settings'][$name]) ? $c['settings'][$name] : null;
} else {
$settings = $c['settings'];
$settings[$name] = $value;
$c['settings'] = $settings;
}
}
/********************************************************************************
* Application Modes
*******************************************************************************/
/**
* Get application mode
*
* This method determines the application mode. It first inspects the $_ENV
* superglobal for key `SLIM_MODE`. If that is not found, it queries
* the `getenv` function. Else, it uses the application `mode` setting.
*
* @return string
*/
public function getMode()
{
return $this->mode;
}
/**
* Configure Slim for a given mode
*
* This method will immediately invoke the callable if
* the specified mode matches the current application mode.
* Otherwise, the callable is ignored. This should be called
* only _after_ you initialize your Slim app.
*
* @param string $mode
* @param mixed $callable
* @return void
*/
public function configureMode($mode, $callable)
{
if ($mode === $this->getMode() && is_callable($callable)) {
call_user_func($callable);
}
}
/********************************************************************************
* Logging
*******************************************************************************/
/**
* Get application log
* @return \Slim\Log
*/
public function getLog()
{
return $this->log;
}
/********************************************************************************
* Routing
*******************************************************************************/
/**
* Add GET|POST|PUT|PATCH|DELETE route
*
* Adds a new route to the router with associated callable. This
* route will only be invoked when the HTTP request's method matches
* this route's method.
*
* ARGUMENTS:
*
* First: string The URL pattern (REQUIRED)
* In-Between: mixed Anything that returns TRUE for `is_callable` (OPTIONAL)
* Last: mixed Anything that returns TRUE for `is_callable` (REQUIRED)
*
* The first argument is required and must always be the
* route pattern (ie. '/books/:id').
*
* The last argument is required and must always be the callable object
* to be invoked when the route matches an HTTP request.
*
* You may also provide an unlimited number of in-between arguments;
* each interior argument must be callable and will be invoked in the
* order specified before the route's callable is invoked.
*
* USAGE:
*
* Slim::get('/foo'[, middleware, middleware, ...], callable);
*
* @param array (See notes above)
* @return \Slim\Route
*/
protected function mapRoute($args)
{
$pattern = array_shift($args);
$callable = array_pop($args);
$route = new \Slim\Route($pattern, $callable, $this->settings['routes.case_sensitive']);
$this->router->map($route);
if (count($args) > 0) {
$route->setMiddleware($args);
}
return $route;
}
/**
* Add generic route without associated HTTP method
* @see mapRoute()
* @return \Slim\Route
*/
public function map()
{
$args = func_get_args();
return $this->mapRoute($args);
}
/**
* Add GET route
* @see mapRoute()
* @return \Slim\Route
*/
public function get()
{
$args = func_get_args();
return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_GET, \Slim\Http\Request::METHOD_HEAD);
}
/**
* Add POST route
* @see mapRoute()
* @return \Slim\Route
*/
public function post()
{
$args = func_get_args();
return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_POST);
}
/**
* Add PUT route
* @see mapRoute()
* @return \Slim\Route
*/
public function put()
{
$args = func_get_args();
return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_PUT);
}
/**
* Add PATCH route
* @see mapRoute()
* @return \Slim\Route
*/
public function patch()
{
$args = func_get_args();
return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_PATCH);
}
/**
* Add DELETE route
* @see mapRoute()
* @return \Slim\Route
*/
public function delete()
{
$args = func_get_args();
return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_DELETE);
}
/**
* Add OPTIONS route
* @see mapRoute()
* @return \Slim\Route
*/
public function options()
{
$args = func_get_args();
return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_OPTIONS);
}
/**
* Route Groups
*
* This method accepts a route pattern and a callback all Route
* declarations in the callback will be prepended by the group(s)
* that it is in
*
* Accepts the same parameters as a standard route so:
* (pattern, middleware1, middleware2, ..., $callback)
*/
public function group()
{
$args = func_get_args();
$pattern = array_shift($args);
$callable = array_pop($args);
$this->router->pushGroup($pattern, $args);
if (is_callable($callable)) {
call_user_func($callable);
}
$this->router->popGroup();
}
/*
* Add route for any HTTP method
* @see mapRoute()
* @return \Slim\Route
*/
public function any()
{
$args = func_get_args();
return $this->mapRoute($args)->via("ANY");
}
/**
* Not Found Handler
*
* This method defines or invokes the application-wide Not Found handler.
* There are two contexts in which this method may be invoked:
*
* 1. When declaring the handler:
*
* If the $callable parameter is not null and is callable, this
* method will register the callable to be invoked when no
* routes match the current HTTP request. It WILL NOT invoke the callable.
*
* 2. When invoking the handler:
*
* If the $callable parameter is null, Slim assumes you want
* to invoke an already-registered handler. If the handler has been
* registered and is callable, it is invoked and sends a 404 HTTP Response
* whose body is the output of the Not Found handler.
*
* @param mixed $callable Anything that returns true for is_callable()
*/
public function notFound ($callable = null)
{
if (is_callable($callable)) {
$this->notFound = $callable;
} else {
ob_start();
if (is_callable($this->notFound)) {
call_user_func($this->notFound);
} else {
call_user_func(array($this, 'defaultNotFound'));
}
$this->halt(404, ob_get_clean());
}
}
/**
* Error Handler
*
* This method defines or invokes the application-wide Error handler.
* There are two contexts in which this method may be invoked:
*
* 1. When declaring the handler:
*
* If the $argument parameter is callable, this
* method will register the callable to be invoked when an uncaught
* Exception is detected, or when otherwise explicitly invoked.
* The handler WILL NOT be invoked in this context.
*
* 2. When invoking the handler:
*
* If the $argument parameter is not callable, Slim assumes you want
* to invoke an already-registered handler. If the handler has been
* registered and is callable, it is invoked and passed the caught Exception
* as its one and only argument. The error handler's output is captured
* into an output buffer and sent as the body of a 500 HTTP Response.
*
* @param mixed $argument Callable|\Exception
*/
public function error($argument = null)
{
if (is_callable($argument)) {
//Register error handler
$this->error = $argument;
} else {
//Invoke error handler
$this->response->status(500);
$this->response->body('');
$this->response->write($this->callErrorHandler($argument));
$this->stop();
}
}
/**
* Call error handler
*
* This will invoke the custom or default error handler
* and RETURN its output.
*
* @param \Exception|null $argument
* @return string
*/
protected function callErrorHandler($argument = null)
{
ob_start();
if (is_callable($this->error)) {
call_user_func_array($this->error, array($argument));
} else {
call_user_func_array(array($this, 'defaultError'), array($argument));
}
return ob_get_clean();
}
/********************************************************************************
* Application Accessors
*******************************************************************************/
/**
* Get a reference to the Environment object
* @return \Slim\Environment
*/
public function environment()
{
return $this->environment;
}
/**
* Get the Request object
* @return \Slim\Http\Request
*/
public function request()
{
return $this->request;
}
/**
* Get the Response object
* @return \Slim\Http\Response
*/
public function response()
{
return $this->response;
}
/**
* Get the Router object
* @return \Slim\Router
*/
public function router()
{
return $this->router;
}
/**
* Get and/or set the View
*
* This method declares the View to be used by the Slim application.
* If the argument is a string, Slim will instantiate a new object
* of the same class. If the argument is an instance of View or a subclass
* of View, Slim will use the argument as the View.
*
* If a View already exists and this method is called to create a
* new View, data already set in the existing View will be
* transferred to the new View.
*
* @param string|\Slim\View $viewClass The name or instance of a \Slim\View subclass
* @return \Slim\View
*/
public function view($viewClass = null)
{
if (!is_null($viewClass)) {
$existingData = is_null($this->view) ? array() : $this->view->getData();
if ($viewClass instanceOf \Slim\View) {
$this->view = $viewClass;
} else {
$this->view = new $viewClass();
}
$this->view->appendData($existingData);
$this->view->setTemplatesDirectory($this->config('templates.path'));
}
return $this->view;
}
/********************************************************************************
* Rendering
*******************************************************************************/
/**
* Render a template
*
* Call this method within a GET, POST, PUT, PATCH, DELETE, NOT FOUND, or ERROR
* callable to render a template whose output is appended to the
* current HTTP response body. How the template is rendered is
* delegated to the current View.
*
* @param string $template The name of the template passed into the view's render() method
* @param array $data Associative array of data made available to the view
* @param int $status The HTTP response status code to use (optional)
*/
public function render($template, $data = array(), $status = null)
{
if (!is_null($status)) {
$this->response->status($status);
}
$this->view->appendData($data);
$this->view->display($template);
}
/********************************************************************************
* HTTP Caching
*******************************************************************************/
/**
* Set Last-Modified HTTP Response Header
*
* Set the HTTP 'Last-Modified' header and stop if a conditional
* GET request's `If-Modified-Since` header matches the last modified time
* of the resource. The `time` argument is a UNIX timestamp integer value.
* When the current request includes an 'If-Modified-Since' header that
* matches the specified last modified time, the application will stop
* and send a '304 Not Modified' response to the client.
*
* @param int $time The last modified UNIX timestamp
* @throws \InvalidArgumentException If provided timestamp is not an integer
*/
public function lastModified($time)
{
if (is_integer($time)) {
$this->response->headers->set('Last-Modified', gmdate('D, d M Y H:i:s T', $time));
if ($time === strtotime($this->request->headers->get('IF_MODIFIED_SINCE'))) {
$this->halt(304);
}
} else {
throw new \InvalidArgumentException('Slim::lastModified only accepts an integer UNIX timestamp value.');
}
}
/**
* Set ETag HTTP Response Header
*
* Set the etag header and stop if the conditional GET request matches.
* The `value` argument is a unique identifier for the current resource.
* The `type` argument indicates whether the etag should be used as a strong or
* weak cache validator.
*
* When the current request includes an 'If-None-Match' header with
* a matching etag, execution is immediately stopped. If the request
* method is GET or HEAD, a '304 Not Modified' response is sent.
*
* @param string $value The etag value
* @param string $type The type of etag to create; either "strong" or "weak"
* @throws \InvalidArgumentException If provided type is invalid
*/
public function etag($value, $type = 'strong')
{
//Ensure type is correct
if (!in_array($type, array('strong', 'weak'))) {
throw new \InvalidArgumentException('Invalid Slim::etag type. Expected "strong" or "weak".');
}
//Set etag value
$value = '"' . $value . '"';
if ($type === 'weak') {
$value = 'W/'.$value;
}
$this->response['ETag'] = $value;
//Check conditional GET
if ($etagsHeader = $this->request->headers->get('IF_NONE_MATCH')) {
$etags = preg_split('@\s*,\s*@', $etagsHeader);
if (in_array($value, $etags) || in_array('*', $etags)) {
$this->halt(304);
}
}
}
/**
* Set Expires HTTP response header
*
* The `Expires` header tells the HTTP client the time at which
* the current resource should be considered stale. At that time the HTTP
* client will send a conditional GET request to the server; the server
* may return a 200 OK if the resource has changed, else a 304 Not Modified
* if the resource has not changed. The `Expires` header should be used in
* conjunction with the `etag()` or `lastModified()` methods above.
*
* @param string|int $time If string, a time to be parsed by `strtotime()`;
* If int, a UNIX timestamp;
*/
public function expires($time)
{
if (is_string($time)) {
$time = strtotime($time);
}
$this->response->headers->set('Expires', gmdate('D, d M Y H:i:s T', $time));
}
/********************************************************************************
* HTTP Cookies
*******************************************************************************/
/**
* Set HTTP cookie to be sent with the HTTP response
*
* @param string $name The cookie name
* @param string $value The cookie value
* @param int|string $time The duration of the cookie;
* If integer, should be UNIX timestamp;
* If string, converted to UNIX timestamp with `strtotime`;
* @param string $path The path on the server in which the cookie will be available on
* @param string $domain The domain that the cookie is available to
* @param bool $secure Indicates that the cookie should only be transmitted over a secure
* HTTPS connection to/from the client
* @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
*/
public function setCookie($name, $value, $time = null, $path = null, $domain = null, $secure = null, $httponly = null)
{
$settings = array(
'value' => $value,
'expires' => is_null($time) ? $this->config('cookies.lifetime') : $time,
'path' => is_null($path) ? $this->config('cookies.path') : $path,
'domain' => is_null($domain) ? $this->config('cookies.domain') : $domain,
'secure' => is_null($secure) ? $this->config('cookies.secure') : $secure,
'httponly' => is_null($httponly) ? $this->config('cookies.httponly') : $httponly
);
$this->response->cookies->set($name, $settings);
}
/**
* Get value of HTTP cookie from the current HTTP request
*
* Return the value of a cookie from the current HTTP request,
* or return NULL if cookie does not exist. Cookies created during
* the current request will not be available until the next request.
*
* @param string $name
* @param bool $deleteIfInvalid
* @return string|null
*/
public function getCookie($name, $deleteIfInvalid = true)
{
// Get cookie value
$value = $this->request->cookies->get($name);
// Decode if encrypted
if ($this->config('cookies.encrypt')) {
$value = \Slim\Http\Util::decodeSecureCookie(
$value,
$this->config('cookies.secret_key'),
$this->config('cookies.cipher'),
$this->config('cookies.cipher_mode')
);
if ($value === false && $deleteIfInvalid) {
$this->deleteCookie($name);
}
}
/*
* transform $value to @return doc requirement.
* \Slim\Http\Util::decodeSecureCookie - is able
* to return false and we have to cast it to null.
*/
return $value === false ? null : $value;
}
/**
* DEPRECATION WARNING! Use `setCookie` with the `cookies.encrypt` app setting set to `true`.
*
* Set encrypted HTTP cookie
*
* @param string $name The cookie name
* @param mixed $value The cookie value
* @param mixed $expires The duration of the cookie;
* If integer, should be UNIX timestamp;
* If string, converted to UNIX timestamp with `strtotime`;
* @param string $path The path on the server in which the cookie will be available on
* @param string $domain The domain that the cookie is available to
* @param bool $secure Indicates that the cookie should only be transmitted over a secure
* HTTPS connection from the client
* @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
*/
public function setEncryptedCookie($name, $value, $expires = null, $path = null, $domain = null, $secure = false, $httponly = false)
{
$this->setCookie($name, $value, $expires, $path, $domain, $secure, $httponly);
}
/**
* DEPRECATION WARNING! Use `getCookie` with the `cookies.encrypt` app setting set to `true`.
*
* Get value of encrypted HTTP cookie
*
* Return the value of an encrypted cookie from the current HTTP request,
* or return NULL if cookie does not exist. Encrypted cookies created during
* the current request will not be available until the next request.
*
* @param string $name
* @param bool $deleteIfInvalid
* @return string|bool
*/
public function getEncryptedCookie($name, $deleteIfInvalid = true)
{
return $this->getCookie($name, $deleteIfInvalid);
}
/**
* Delete HTTP cookie (encrypted or unencrypted)
*
* Remove a Cookie from the client. This method will overwrite an existing Cookie
* with a new, empty, auto-expiring Cookie. This method's arguments must match
* the original Cookie's respective arguments for the original Cookie to be
* removed. If any of this method's arguments are omitted or set to NULL, the
* default Cookie setting values (set during Slim::init) will be used instead.
*
* @param string $name The cookie name
* @param string $path The path on the server in which the cookie will be available on
* @param string $domain The domain that the cookie is available to
* @param bool $secure Indicates that the cookie should only be transmitted over a secure
* HTTPS connection from the client
* @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
*/
public function deleteCookie($name, $path = null, $domain = null, $secure = null, $httponly = null)
{
$settings = array(
'domain' => is_null($domain) ? $this->config('cookies.domain') : $domain,
'path' => is_null($path) ? $this->config('cookies.path') : $path,
'secure' => is_null($secure) ? $this->config('cookies.secure') : $secure,
'httponly' => is_null($httponly) ? $this->config('cookies.httponly') : $httponly
);
$this->response->cookies->remove($name, $settings);
}
/********************************************************************************
* Helper Methods
*******************************************************************************/
/**
* Get the absolute path to this Slim application's root directory
*
* This method returns the absolute path to the Slim application's
* directory. If the Slim application is installed in a public-accessible
* sub-directory, the sub-directory path will be included. This method
* will always return an absolute path WITH a trailing slash.
*
* @return string
*/
public function root()
{
return rtrim($_SERVER['DOCUMENT_ROOT'], '/') . rtrim($this->request->getRootUri(), '/') . '/';
}
/**
* Clean current output buffer
*/
protected function cleanBuffer()
{
if (ob_get_level() !== 0) {
ob_clean();
}
}
/**
* Stop
*
* The thrown exception will be caught in application's `call()` method
* and the response will be sent as is to the HTTP client.
*
* @throws \Slim\Exception\Stop
*/
public function stop()
{
throw new \Slim\Exception\Stop();
}
/**
* Halt
*
* Stop the application and immediately send the response with a
* specific status and body to the HTTP client. This may send any
* type of response: info, success, redirect, client error, or server error.
* If you need to render a template AND customize the response status,
* use the application's `render()` method instead.
*
* @param int $status The HTTP response status
* @param string $message The HTTP response body
*/
public function halt($status, $message = '')
{
$this->cleanBuffer();
$this->response->status($status);
$this->response->body($message);
$this->stop();
}
/**
* Pass
*
* The thrown exception is caught in the application's `call()` method causing
* the router's current iteration to stop and continue to the subsequent route if available.
* If no subsequent matching routes are found, a 404 response will be sent to the client.
*
* @throws \Slim\Exception\Pass
*/
public function pass()
{
$this->cleanBuffer();
throw new \Slim\Exception\Pass();
}
/**
* Set the HTTP response Content-Type
* @param string $type The Content-Type for the Response (ie. text/html)
*/
public function contentType($type)
{
$this->response->headers->set('Content-Type', $type);
}
/**
* Set the HTTP response status code
* @param int $code The HTTP response status code
*/
public function status($code)
{
$this->response->setStatus($code);
}
/**
* Get the URL for a named route
* @param string $name The route name
* @param array $params Associative array of URL parameters and replacement values
* @throws \RuntimeException If named route does not exist
* @return string
*/
public function urlFor($name, $params = array())
{
return $this->request->getRootUri() . $this->router->urlFor($name, $params);
}
/**
* Redirect
*
* This method immediately redirects to a new URL. By default,
* this issues a 302 Found response; this is considered the default
* generic redirect response. You may also specify another valid
* 3xx status code if you want. This method will automatically set the
* HTTP Location header for you using the URL parameter.
*
* @param string $url The destination URL
* @param int $status The HTTP redirect status code (optional)
*/
public function redirect($url, $status = 302)
{
$this->response->redirect($url, $status);
$this->halt($status);
}
/**
* RedirectTo
*
* Redirects to a specific named route
*
* @param string $route The route name
* @param array $params Associative array of URL parameters and replacement values
*/
public function redirectTo($route, $params = array(), $status = 302){
$this->redirect($this->urlFor($route, $params), $status);
}
/********************************************************************************
* Flash Messages
*******************************************************************************/
/**
* Set flash message for subsequent request
* @param string $key
* @param mixed $value
*/
public function flash($key, $value)
{
if (isset($this->environment['slim.flash'])) {
$this->environment['slim.flash']->set($key, $value);
}
}
/**
* Set flash message for current request
* @param string $key
* @param mixed $value
*/
public function flashNow($key, $value)
{
if (isset($this->environment['slim.flash'])) {
$this->environment['slim.flash']->now($key, $value);
}
}
/**
* Keep flash messages from previous request for subsequent request
*/
public function flashKeep()
{
if (isset($this->environment['slim.flash'])) {
$this->environment['slim.flash']->keep();
}
}
/**
* Get all flash messages
*/
public function flashData()
{
if (isset($this->environment['slim.flash'])) {
return $this->environment['slim.flash']->getMessages();
}
}
/********************************************************************************
* Hooks
*******************************************************************************/
/**
* Assign hook
* @param string $name The hook name
* @param mixed $callable A callable object
* @param int $priority The hook priority; 0 = high, 10 = low
*/
public function hook($name, $callable, $priority = 10)
{
if (!isset($this->hooks[$name])) {
$this->hooks[$name] = array(array());
}
if (is_callable($callable)) {
$this->hooks[$name][(int) $priority][] = $callable;
}
}
/**
* Invoke hook
* @param string $name The hook name
* @param mixed ... (Optional) Argument(s) for hooked functions, can specify multiple arguments
*/
public function applyHook($name)
{
if (!isset($this->hooks[$name])) {
$this->hooks[$name] = array(array());
}
if (!empty($this->hooks[$name])) {
// Sort by priority, low to high, if there's more than one priority
if (count($this->hooks[$name]) > 1) {
ksort($this->hooks[$name]);
}
$args = func_get_args();
array_shift($args);
foreach ($this->hooks[$name] as $priority) {
if (!empty($priority)) {
foreach ($priority as $callable) {
call_user_func_array($callable, $args);
}
}
}
}
}
/**
* Get hook listeners
*
* Return an array of registered hooks. If `$name` is a valid
* hook name, only the listeners attached to that hook are returned.
* Else, all listeners are returned as an associative array whose
* keys are hook names and whose values are arrays of listeners.
*
* @param string $name A hook name (Optional)
* @return array|null
*/
public function getHooks($name = null)
{
if (!is_null($name)) {
return isset($this->hooks[(string) $name]) ? $this->hooks[(string) $name] : null;
} else {
return $this->hooks;
}
}
/**
* Clear hook listeners
*
* Clear all listeners for all hooks. If `$name` is
* a valid hook name, only the listeners attached
* to that hook will be cleared.
*
* @param string $name A hook name (Optional)
*/
public function clearHooks($name = null)
{
if (!is_null($name) && isset($this->hooks[(string) $name])) {
$this->hooks[(string) $name] = array(array());
} else {
foreach ($this->hooks as $key => $value) {
$this->hooks[$key] = array(array());
}
}
}
/********************************************************************************
* Middleware
*******************************************************************************/
/**
* Add middleware
*
* This method prepends new middleware to the application middleware stack.
* The argument must be an instance that subclasses Slim_Middleware.
*
* @param \Slim\Middleware
*/
public function add(\Slim\Middleware $newMiddleware)
{
if(in_array($newMiddleware, $this->middleware)) {
$middleware_class = get_class($newMiddleware);
throw new \RuntimeException("Circular Middleware setup detected. Tried to queue the same Middleware instance ({$middleware_class}) twice.");
}
$newMiddleware->setApplication($this);
$newMiddleware->setNextMiddleware($this->middleware[0]);
array_unshift($this->middleware, $newMiddleware);
}
/********************************************************************************
* Runner
*******************************************************************************/
/**
* Run
*
* This method invokes the middleware stack, including the core Slim application;
* the result is an array of HTTP status, header, and body. These three items
* are returned to the HTTP client.
*/
public function run()
{
set_error_handler(array('\Slim\Slim', 'handleErrors'));
//Apply final outer middleware layers
if ($this->config('debug')) {
//Apply pretty exceptions only in debug to avoid accidental information leakage in production
$this->add(new \Slim\Middleware\PrettyExceptions());
}
//Invoke middleware and application stack
$this->middleware[0]->call();
//Fetch status, header, and body
list($status, $headers, $body) = $this->response->finalize();
// Serialize cookies (with optional encryption)
\Slim\Http\Util::serializeCookies($headers, $this->response->cookies, $this->settings);
//Send headers
if (headers_sent() === false) {
//Send status
if (strpos(PHP_SAPI, 'cgi') === 0) {
header(sprintf('Status: %s', \Slim\Http\Response::getMessageForCode($status)));
} else {
header(sprintf('HTTP/%s %s', $this->config('http.version'), \Slim\Http\Response::getMessageForCode($status)));
}
//Send headers
foreach ($headers as $name => $value) {
$hValues = explode("\n", $value);
foreach ($hValues as $hVal) {
header("$name: $hVal", false);
}
}
}
//Send body, but only if it isn't a HEAD request
if (!$this->request->isHead()) {
echo $body;
}
$this->applyHook('slim.after');
restore_error_handler();
}
/**
* Call
*
* This method finds and iterates all route objects that match the current request URI.
*/
public function call()
{
try {
if (isset($this->environment['slim.flash'])) {
$this->view()->setData('flash', $this->environment['slim.flash']);
}
$this->applyHook('slim.before');
ob_start();
$this->applyHook('slim.before.router');
$dispatched = false;
$matchedRoutes = $this->router->getMatchedRoutes($this->request->getMethod(), $this->request->getResourceUri());
foreach ($matchedRoutes as $route) {
try {
$this->applyHook('slim.before.dispatch');
$dispatched = $route->dispatch();
$this->applyHook('slim.after.dispatch');
if ($dispatched) {
break;
}
} catch (\Slim\Exception\Pass $e) {
continue;
}
}
if (!$dispatched) {
$this->notFound();
}
$this->applyHook('slim.after.router');
$this->stop();
} catch (\Slim\Exception\Stop $e) {
$this->response()->write(ob_get_clean());
} catch (\Exception $e) {
if ($this->config('debug')) {
throw $e;
} else {
try {
$this->response()->write(ob_get_clean());
$this->error($e);
} catch (\Slim\Exception\Stop $e) {
// Do nothing
}
}
}
}
/********************************************************************************
* Error Handling and Debugging
*******************************************************************************/
/**
* Convert errors into ErrorException objects
*
* This method catches PHP errors and converts them into \ErrorException objects;
* these \ErrorException objects are then thrown and caught by Slim's
* built-in or custom error handlers.
*
* @param int $errno The numeric type of the Error
* @param string $errstr The error message
* @param string $errfile The absolute path to the affected file
* @param int $errline The line number of the error in the affected file
* @return bool
* @throws \ErrorException
*/
public static function handleErrors($errno, $errstr = '', $errfile = '', $errline = '')
{
if (!($errno & error_reporting())) {
return;
}
throw new \ErrorException($errstr, $errno, 0, $errfile, $errline);
}
/**
* Generate diagnostic template markup
*
* This method accepts a title and body content to generate an HTML document layout.
*
* @param string $title The title of the HTML template
* @param string $body The body content of the HTML template
* @return string
*/
protected static function generateTemplateMarkup($title, $body)
{
return sprintf("%s%s
%s", $title, $title, $body);
}
/**
* Default Not Found handler
*/
protected function defaultNotFound()
{
echo static::generateTemplateMarkup('404 Page Not Found', 'The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.
Visit the Home Page');
}
/**
* Default Error handler
*/
protected function defaultError($e)
{
$this->getLog()->error($e);
echo self::generateTemplateMarkup('Error', 'A website error has occurred. The website administrator has been notified of the issue. Sorry for the temporary inconvenience.
');
}
}
DEEP.git/Slim/Slim/View.php 0000775 0000000 0000000 00000020277 12634026554 0015632 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
/**
* View
*
* The view is responsible for rendering a template. The view
* should subclass \Slim\View and implement this interface:
*
* public render(string $template);
*
* This method should render the specified template and return
* the resultant string.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class View
{
/**
* Data available to the view templates
* @var \Slim\Helper\Set
*/
protected $data;
/**
* Path to templates base directory (without trailing slash)
* @var string
*/
protected $templatesDirectory;
/**
* Constructor
*/
public function __construct()
{
$this->data = new \Slim\Helper\Set();
}
/********************************************************************************
* Data methods
*******************************************************************************/
/**
* Does view data have value with key?
* @param string $key
* @return boolean
*/
public function has($key)
{
return $this->data->has($key);
}
/**
* Return view data value with key
* @param string $key
* @return mixed
*/
public function get($key)
{
return $this->data->get($key);
}
/**
* Set view data value with key
* @param string $key
* @param mixed $value
*/
public function set($key, $value)
{
$this->data->set($key, $value);
}
/**
* Set view data value as Closure with key
* @param string $key
* @param mixed $value
*/
public function keep($key, \Closure $value)
{
$this->data->keep($key, $value);
}
/**
* Return view data
* @return array
*/
public function all()
{
return $this->data->all();
}
/**
* Replace view data
* @param array $data
*/
public function replace(array $data)
{
$this->data->replace($data);
}
/**
* Clear view data
*/
public function clear()
{
$this->data->clear();
}
/********************************************************************************
* Legacy data methods
*******************************************************************************/
/**
* DEPRECATION WARNING! This method will be removed in the next major point release
*
* Get data from view
*/
public function getData($key = null)
{
if (!is_null($key)) {
return isset($this->data[$key]) ? $this->data[$key] : null;
}
return $this->data->all();
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release
*
* Set data for view
*/
public function setData()
{
$args = func_get_args();
if (count($args) === 1 && is_array($args[0])) {
$this->data->replace($args[0]);
} elseif (count($args) === 2) {
// Ensure original behavior is maintained. DO NOT invoke stored Closures.
if (is_object($args[1]) && method_exists($args[1], '__invoke')) {
$this->data->set($args[0], $this->data->protect($args[1]));
} else {
$this->data->set($args[0], $args[1]);
}
} else {
throw new \InvalidArgumentException('Cannot set View data with provided arguments. Usage: `View::setData( $key, $value );` or `View::setData([ key => value, ... ]);`');
}
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release
*
* Append data to view
* @param array $data
*/
public function appendData($data)
{
if (!is_array($data)) {
throw new \InvalidArgumentException('Cannot append view data. Expected array argument.');
}
$this->data->replace($data);
}
/********************************************************************************
* Resolve template paths
*******************************************************************************/
/**
* Set the base directory that contains view templates
* @param string $directory
* @throws \InvalidArgumentException If directory is not a directory
*/
public function setTemplatesDirectory($directory)
{
$this->templatesDirectory = rtrim($directory, DIRECTORY_SEPARATOR);
}
/**
* Get templates base directory
* @return string
*/
public function getTemplatesDirectory()
{
return $this->templatesDirectory;
}
/**
* Get fully qualified path to template file using templates base directory
* @param string $file The template file pathname relative to templates base directory
* @return string
*/
public function getTemplatePathname($file)
{
return $this->templatesDirectory . DIRECTORY_SEPARATOR . ltrim($file, DIRECTORY_SEPARATOR);
}
/********************************************************************************
* Rendering
*******************************************************************************/
/**
* Display template
*
* This method echoes the rendered template to the current output buffer
*
* @param string $template Pathname of template file relative to templates directory
* @param array $data Any additonal data to be passed to the template.
*/
public function display($template, $data = null)
{
echo $this->fetch($template, $data);
}
/**
* Return the contents of a rendered template file
*
* @param string $template The template pathname, relative to the template base directory
* @param array $data Any additonal data to be passed to the template.
* @return string The rendered template
*/
public function fetch($template, $data = null)
{
return $this->render($template, $data);
}
/**
* Render a template file
*
* NOTE: This method should be overridden by custom view subclasses
*
* @param string $template The template pathname, relative to the template base directory
* @param array $data Any additonal data to be passed to the template.
* @return string The rendered template
* @throws \RuntimeException If resolved template pathname is not a valid file
*/
protected function render($template, $data = null)
{
$templatePathname = $this->getTemplatePathname($template);
if (!is_file($templatePathname)) {
throw new \RuntimeException("View cannot render `$template` because the template does not exist");
}
$data = array_merge($this->data->all(), (array) $data);
extract($data);
ob_start();
require $templatePathname;
return ob_get_clean();
}
}
DEEP.git/Slim/View.php 0000775 0000000 0000000 00000020277 12634026554 0014726 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
* @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;
/**
* View
*
* The view is responsible for rendering a template. The view
* should subclass \Slim\View and implement this interface:
*
* public render(string $template);
*
* This method should render the specified template and return
* the resultant string.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class View
{
/**
* Data available to the view templates
* @var \Slim\Helper\Set
*/
protected $data;
/**
* Path to templates base directory (without trailing slash)
* @var string
*/
protected $templatesDirectory;
/**
* Constructor
*/
public function __construct()
{
$this->data = new \Slim\Helper\Set();
}
/********************************************************************************
* Data methods
*******************************************************************************/
/**
* Does view data have value with key?
* @param string $key
* @return boolean
*/
public function has($key)
{
return $this->data->has($key);
}
/**
* Return view data value with key
* @param string $key
* @return mixed
*/
public function get($key)
{
return $this->data->get($key);
}
/**
* Set view data value with key
* @param string $key
* @param mixed $value
*/
public function set($key, $value)
{
$this->data->set($key, $value);
}
/**
* Set view data value as Closure with key
* @param string $key
* @param mixed $value
*/
public function keep($key, \Closure $value)
{
$this->data->keep($key, $value);
}
/**
* Return view data
* @return array
*/
public function all()
{
return $this->data->all();
}
/**
* Replace view data
* @param array $data
*/
public function replace(array $data)
{
$this->data->replace($data);
}
/**
* Clear view data
*/
public function clear()
{
$this->data->clear();
}
/********************************************************************************
* Legacy data methods
*******************************************************************************/
/**
* DEPRECATION WARNING! This method will be removed in the next major point release
*
* Get data from view
*/
public function getData($key = null)
{
if (!is_null($key)) {
return isset($this->data[$key]) ? $this->data[$key] : null;
}
return $this->data->all();
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release
*
* Set data for view
*/
public function setData()
{
$args = func_get_args();
if (count($args) === 1 && is_array($args[0])) {
$this->data->replace($args[0]);
} elseif (count($args) === 2) {
// Ensure original behavior is maintained. DO NOT invoke stored Closures.
if (is_object($args[1]) && method_exists($args[1], '__invoke')) {
$this->data->set($args[0], $this->data->protect($args[1]));
} else {
$this->data->set($args[0], $args[1]);
}
} else {
throw new \InvalidArgumentException('Cannot set View data with provided arguments. Usage: `View::setData( $key, $value );` or `View::setData([ key => value, ... ]);`');
}
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release
*
* Append data to view
* @param array $data
*/
public function appendData($data)
{
if (!is_array($data)) {
throw new \InvalidArgumentException('Cannot append view data. Expected array argument.');
}
$this->data->replace($data);
}
/********************************************************************************
* Resolve template paths
*******************************************************************************/
/**
* Set the base directory that contains view templates
* @param string $directory
* @throws \InvalidArgumentException If directory is not a directory
*/
public function setTemplatesDirectory($directory)
{
$this->templatesDirectory = rtrim($directory, DIRECTORY_SEPARATOR);
}
/**
* Get templates base directory
* @return string
*/
public function getTemplatesDirectory()
{
return $this->templatesDirectory;
}
/**
* Get fully qualified path to template file using templates base directory
* @param string $file The template file pathname relative to templates base directory
* @return string
*/
public function getTemplatePathname($file)
{
return $this->templatesDirectory . DIRECTORY_SEPARATOR . ltrim($file, DIRECTORY_SEPARATOR);
}
/********************************************************************************
* Rendering
*******************************************************************************/
/**
* Display template
*
* This method echoes the rendered template to the current output buffer
*
* @param string $template Pathname of template file relative to templates directory
* @param array $data Any additonal data to be passed to the template.
*/
public function display($template, $data = null)
{
echo $this->fetch($template, $data);
}
/**
* Return the contents of a rendered template file
*
* @param string $template The template pathname, relative to the template base directory
* @param array $data Any additonal data to be passed to the template.
* @return string The rendered template
*/
public function fetch($template, $data = null)
{
return $this->render($template, $data);
}
/**
* Render a template file
*
* NOTE: This method should be overridden by custom view subclasses
*
* @param string $template The template pathname, relative to the template base directory
* @param array $data Any additonal data to be passed to the template.
* @return string The rendered template
* @throws \RuntimeException If resolved template pathname is not a valid file
*/
protected function render($template, $data = null)
{
$templatePathname = $this->getTemplatePathname($template);
if (!is_file($templatePathname)) {
throw new \RuntimeException("View cannot render `$template` because the template does not exist");
}
$data = array_merge($this->data->all(), (array) $data);
extract($data);
ob_start();
require $templatePathname;
return ob_get_clean();
}
}
DEEP.git/Slim/composer.json 0000775 0000000 0000000 00000001140 12634026554 0016011 0 ustar 00root root 0000000 0000000 {
"name": "slim/slim",
"type": "library",
"description": "Slim Framework, a PHP micro framework",
"keywords": ["microframework","rest","router"],
"homepage": "http://github.com/codeguy/Slim",
"license": "MIT",
"authors": [
{
"name": "Josh Lockhart",
"email": "info@joshlockhart.com",
"homepage": "http://www.joshlockhart.com/"
}
],
"require": {
"php": ">=5.3.0"
},
"suggest": {
"ext-mcrypt": "Required for HTTP cookie encryption"
},
"autoload": {
"psr-0": { "Slim": "." }
}
}
DEEP.git/Slim/index.php 0000775 0000000 0000000 00000020505 12634026554 0015115 0 ustar 00root root 0000000 0000000 get(
'/',
function () {
$template = <<
Slim Framework for PHP 5
Welcome to Slim!
Congratulations! Your Slim application is running. If this is
your first time using Slim, start with this "Hello World" Tutorial.
Slim Framework Community
Support Forum and Knowledge Base
Visit the Slim support forum and knowledge base
to read announcements, chat with fellow Slim users, ask questions, help others, or show off your cool
Slim Framework apps.
Twitter
Follow @slimphp on Twitter to receive the very latest news
and updates about the framework.
Slim Framework Extras
Custom View classes for Smarty, Twig, Mustache, and other template
frameworks are available online in a separate repository.
Browse the Extras Repository
EOT;
echo $template;
}
);
// POST route
$app->post(
'/post',
function () {
echo 'This is a POST route';
}
);
// PUT route
$app->put(
'/put',
function () {
echo 'This is a PUT route';
}
);
// PATCH route
$app->patch('/patch', function () {
echo 'This is a PATCH route';
});
// DELETE route
$app->delete(
'/delete',
function () {
echo 'This is a DELETE route';
}
);
/**
* Step 4: Run the Slim application
*
* This method should be called last. This executes the Slim application
* and returns the HTTP response to the HTTP client.
*/
$app->run();
DEEP.git/Slim/phpunit.xml.dist 0000775 0000000 0000000 00000001232 12634026554 0016444 0 ustar 00root root 0000000 0000000
./tests/
./Slim/
DEEP.git/Slim/tests/ 0000775 0000000 0000000 00000000000 12634026554 0014432 5 ustar 00root root 0000000 0000000 DEEP.git/Slim/tests/EnvironmentTest.php 0000775 0000000 0000000 00000030414 12634026554 0020314 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
*
* 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.
*/
class EnvironmentTest extends PHPUnit_Framework_TestCase
{
/**
* Default server settings assume the Slim app is installed
* in a subdirectory `foo/` directly beneath the public document
* root directory; URL rewrite is disabled; requested app
* resource is GET `/bar/xyz` with three query params.
*
* These only provide a common baseline for the following
* tests; tests are free to override these values.
*/
public function setUp()
{
$_SERVER['DOCUMENT_ROOT'] = '/var/www';
$_SERVER['SCRIPT_FILENAME'] = '/var/www/foo/index.php';
$_SERVER['SERVER_NAME'] = 'slim';
$_SERVER['SERVER_PORT'] = '80';
$_SERVER['SCRIPT_NAME'] = '/foo/index.php';
$_SERVER['REQUEST_URI'] = '/foo/index.php/bar/xyz';
$_SERVER['PATH_INFO'] = '/bar/xyz';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['QUERY_STRING'] = 'one=1&two=2&three=3';
$_SERVER['HTTPS'] = '';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
unset($_SERVER['CONTENT_TYPE'], $_SERVER['CONTENT_LENGTH']);
}
/**
* Test mock environment
*
* This should return the custom values where specified
* and the default values otherwise.
*/
public function testMockEnvironment()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'PUT'
));
$env2 = \Slim\Environment::getInstance();
$this->assertSame($env, $env2);
$this->assertInstanceOf('\Slim\Environment', $env);
$this->assertEquals('PUT', $env['REQUEST_METHOD']);
$this->assertEquals(80, $env['SERVER_PORT']);
$this->assertNull($env['foo']);
}
/**
* Test sets HTTP method
*/
public function testSetsHttpMethod()
{
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('GET', $env['REQUEST_METHOD']);
}
/**
* Test parses script name and path info
*
* Pre-conditions:
* URL Rewrite is disabled;
* App installed in subdirectory;
*/
public function testParsesPathsWithoutUrlRewriteInSubdirectory()
{
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('/bar/xyz', $env['PATH_INFO']);
$this->assertEquals('/foo/index.php', $env['SCRIPT_NAME']);
}
/**
* Test parses script name and path info
*
* Pre-conditions:
* URL Rewrite is disabled;
* App installed in root directory;
*/
public function testParsesPathsWithoutUrlRewriteInRootDirectory()
{
$_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php';
$_SERVER['REQUEST_URI'] = '/index.php/bar/xyz';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('/bar/xyz', $env['PATH_INFO']);
$this->assertEquals('/index.php', $env['SCRIPT_NAME']);
}
/**
* Test parses script name and path info
*
* Pre-conditions:
* URL Rewrite disabled;
* App installed in root directory;
* Requested resource is "/";
*/
public function testParsesPathsWithoutUrlRewriteInRootDirectoryForAppRootUri()
{
$_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php';
$_SERVER['REQUEST_URI'] = '/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
unset($_SERVER['PATH_INFO']);
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('/', $env['PATH_INFO']);
$this->assertEquals('/index.php', $env['SCRIPT_NAME']);
}
/**
* Test parses script name and path info
*
* Pre-conditions:
* URL Rewrite enabled;
* App installed in subdirectory;
*/
public function testParsesPathsWithUrlRewriteInSubdirectory()
{
$_SERVER['SCRIPT_NAME'] = '/foo/index.php';
$_SERVER['REQUEST_URI'] = '/foo/bar/xyz';
unset($_SERVER['PATH_INFO']);
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('/bar/xyz', $env['PATH_INFO']);
$this->assertEquals('/foo', $env['SCRIPT_NAME']);
}
/**
* Test parses script name and path info
*
* Pre-conditions:
* URL Rewrite enabled;
* App installed in root directory;
*/
public function testParsesPathsWithUrlRewriteInRootDirectory()
{
$_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$_SERVER['REQUEST_URI'] = '/bar/xyz';
unset($_SERVER['PATH_INFO']);
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('/bar/xyz', $env['PATH_INFO']);
$this->assertEquals('', $env['SCRIPT_NAME']);
}
/**
* Test parses script name and path info
*
* Pre-conditions:
* URL Rewrite enabled;
* App installed in root directory;
* Requested resource is "/"
*/
public function testParsesPathsWithUrlRewriteInRootDirectoryForAppRootUri()
{
$_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php';
$_SERVER['REQUEST_URI'] = '/';
$_SERVER['SCRIPT_NAME'] = '/index.php';
unset($_SERVER['PATH_INFO']);
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('/', $env['PATH_INFO']);
$this->assertEquals('', $env['SCRIPT_NAME']);
}
/**
* Test parses query string
*
* Pre-conditions:
* $_SERVER['QUERY_STRING'] exists and is not empty;
*/
public function testParsesQueryString()
{
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('one=1&two=2&three=3', $env['QUERY_STRING']);
}
/**
* Test removes query string from PATH_INFO when using URL Rewrite
*
* Pre-conditions:
* $_SERVER['QUERY_STRING'] exists and is not empty;
* URL Rewrite enabled;
*/
public function testRemovesQueryStringFromPathInfo()
{
$_SERVER['SCRIPT_NAME'] = '/foo/index.php';
$_SERVER['REQUEST_URI'] = '/foo/bar/xyz?one=1&two=2&three=3';
unset($_SERVER['PATH_INFO']);
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('/bar/xyz', $env['PATH_INFO']);
}
/**
* Test environment's PATH_INFO retains URL encoded characters (e.g. #)
*
* In earlier version, \Slim\Environment would use PATH_INFO instead
* of REQUEST_URI to determine the root URI and resource URI.
* Unfortunately, the server would URL decode the PATH_INFO string
* before it was handed to PHP. This prevented certain URL-encoded
* characters like the octothorpe from being delivered correctly to
* the Slim application environment. This test ensures the
* REQUEST_URI is used instead and parsed as expected.
*/
public function testPathInfoRetainsUrlEncodedCharacters()
{
$_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$_SERVER['REQUEST_URI'] = '/foo/%23bar'; //<-- URL-encoded "#bar"
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('/foo/%23bar', $env['PATH_INFO']);
}
/**
* Test parses query string
*
* Pre-conditions:
* $_SERVER['QUERY_STRING'] does not exist;
*/
public function testParsesQueryStringThatDoesNotExist()
{
unset($_SERVER['QUERY_STRING']);
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('', $env['QUERY_STRING']);
}
/**
* Test SERVER_NAME is not empty
*/
public function testServerNameIsNotEmpty()
{
$env = \Slim\Environment::getInstance(true);
$this->assertFalse(empty($env['SERVER_NAME']));
}
/**
* Test SERVER_PORT is not empty
*/
public function testServerPortIsNotEmpty()
{
$env = \Slim\Environment::getInstance(true);
$this->assertFalse(empty($env['SERVER_PORT']));
}
/**
* Test unsets HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH
*
* Pre-conditions:
* HTTP_CONTENT_TYPE is sent with HTTP request;
* HTTP_CONTENT_LENGTH is sent with HTTP request;
*/
public function testUnsetsContentTypeAndContentLength()
{
$_SERVER['HTTP_CONTENT_LENGTH'] = 150;
$env = \Slim\Environment::getInstance(true);
$this->assertFalse(isset($env['HTTP_CONTENT_LENGTH']));
}
/**
* Test sets special request headers if not empty
*
* Pre-conditions:
* CONTENT_TYPE, CONTENT_LENGTH, X_REQUESTED_WITH are sent in client HTTP request;
* CONTENT_TYPE, CONTENT_LENGTH, X_REQUESTED_WITH are not empty;
*/
public function testSetsSpecialHeaders()
{
$_SERVER['CONTENT_TYPE'] = 'text/csv';
$_SERVER['CONTENT_LENGTH'] = '100';
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XmlHttpRequest';
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('text/csv', $env['CONTENT_TYPE']);
$this->assertEquals('100', $env['CONTENT_LENGTH']);
$this->assertEquals('XmlHttpRequest', $env['HTTP_X_REQUESTED_WITH']);
}
/**
* Tests X-HTTP-Method-Override is allowed through unmolested.
*
* Pre-conditions:
* X_HTTP_METHOD_OVERRIDE is sent in client HTTP request;
* X_HTTP_METHOD_OVERRIDE is not empty;
*/
public function testSetsHttpMethodOverrideHeader() {
$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'DELETE';
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('DELETE', $env['HTTP_X_HTTP_METHOD_OVERRIDE']);
}
/**
* Test detects HTTPS
*
* Pre-conditions:
* $_SERVER['HTTPS'] is set to a non-empty value;
*/
public function testHttps()
{
$_SERVER['HTTPS'] = 1;
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('https', $env['slim.url_scheme']);
}
/**
* Test detects not HTTPS
*
* Pre-conditions:
* $_SERVER['HTTPS'] is set to an empty value;
*/
public function testNotHttps()
{
$_SERVER['HTTPS'] = '';
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('http', $env['slim.url_scheme']);
}
/**
* Test detects not HTTPS on IIS
*
* Pre-conditions:
* $_SERVER['HTTPS'] is set to "off";
*/
public function testNotHttpsIIS()
{
$_SERVER['HTTPS'] = 'off';
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('http', $env['slim.url_scheme']);
}
/**
* Test input is an empty string (and not false)
*
* Pre-conditions:
* Input at php://input may only be read once; subsequent attempts
* will return `false`; in which case, use an empty string.
*/
public function testInputIsEmptyString()
{
$env = \Slim\Environment::getInstance(true);
$this->assertEquals('', $env['slim.input']);
}
/**
* Test valid resource handle to php://stdErr
*/
public function testErrorResource()
{
$env = \Slim\Environment::getInstance(true);
$this->assertTrue(is_resource($env['slim.errors']));
}
}
DEEP.git/Slim/tests/Foo.php 0000775 0000000 0000000 00000000102 12634026554 0015662 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
*
* 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.
*/
class SetTest extends PHPUnit_Framework_TestCase
{
protected $bag;
protected $property;
public function setUp()
{
$this->bag = new \Slim\Helper\Set();
$this->property = new \ReflectionProperty($this->bag, 'data');
$this->property->setAccessible(true);
}
public function testSet()
{
$this->bag->set('foo', 'bar');
$this->assertArrayHasKey('foo', $this->property->getValue($this->bag));
$bag = $this->property->getValue($this->bag);
$this->assertEquals('bar', $bag['foo']);
}
public function testGet()
{
$this->property->setValue($this->bag, array('foo' => 'bar'));
$this->assertEquals('bar', $this->bag->get('foo'));
}
public function testGetNotExists()
{
$this->property->setValue($this->bag, array('foo' => 'bar'));
$this->assertEquals('default', $this->bag->get('abc', 'default'));
}
public function testAdd()
{
$this->bag->replace(array(
'abc' => '123',
'foo' => 'bar'
));
$this->assertArrayHasKey('abc', $this->property->getValue($this->bag));
$this->assertArrayHasKey('foo', $this->property->getValue($this->bag));
$bag = $this->property->getValue($this->bag);
$this->assertEquals('123', $bag['abc']);
$this->assertEquals('bar', $bag['foo']);
}
public function testAll()
{
$data = array(
'abc' => '123',
'foo' => 'bar'
);
$this->property->setValue($this->bag, $data);
$this->assertEquals($data, $this->bag->all());
}
public function testKeys()
{
$data = array(
'abc' => '123',
'foo' => 'bar'
);
$this->property->setValue($this->bag, $data);
$this->assertEquals(array('abc', 'foo'), $this->bag->keys());
}
public function testRemove()
{
$data = array(
'abc' => '123',
'foo' => 'bar'
);
$this->property->setValue($this->bag, $data);
$this->bag->remove('foo');
$this->assertEquals(array('abc' => '123'), $this->property->getValue($this->bag));
}
public function testClear()
{
$data = array(
'abc' => '123',
'foo' => 'bar'
);
$this->property->setValue($this->bag, $data);
$this->bag->clear();
$this->assertEquals(array(), $this->property->getValue($this->bag));
}
public function testArrayAccessGet()
{
$data = array(
'abc' => '123',
'foo' => 'bar'
);
$this->property->setValue($this->bag, $data);
$this->assertEquals('bar', $this->bag['foo']);
}
public function testArrayAccessSet()
{
$data = array(
'abc' => '123',
'foo' => 'bar'
);
$this->property->setValue($this->bag, $data);
$this->bag['foo'] = 'changed';
$bag = $this->property->getValue($this->bag);
$this->assertEquals('changed', $bag['foo']);
}
public function testArrayAccessExists()
{
$data = array(
'abc' => '123',
'foo' => 'bar'
);
$this->property->setValue($this->bag, $data);
$this->assertTrue(isset($this->bag['foo']));
$this->assertFalse(isset($this->bag['bar']));
}
public function testArrayAccessUnset()
{
$data = array(
'abc' => '123',
'foo' => 'bar'
);
$this->property->setValue($this->bag, $data);
unset($this->bag['foo']);
$this->assertEquals(array('abc' => '123'), $this->property->getValue($this->bag));
}
public function testCount()
{
$data = array(
'abc' => '123',
'foo' => 'bar'
);
$this->property->setValue($this->bag, $data);
$this->assertEquals(2, count($this->bag));
}
public function testGetIterator()
{
$data = array(
'abc' => '123',
'foo' => 'bar'
);
$this->property->setValue($this->bag, $data);
$this->assertInstanceOf('\ArrayIterator', $this->bag->getIterator());
}
public function testPropertyOverloadGet()
{
$data = array(
'abc' => '123',
'foo' => 'bar'
);
$this->property->setValue($this->bag, $data);
$this->assertEquals('123', $this->bag->abc);
$this->assertEquals('bar', $this->bag->foo);
}
public function testPropertyOverloadSet()
{
$this->bag->foo = 'bar';
$this->assertArrayHasKey('foo', $this->property->getValue($this->bag));
$this->assertEquals('bar', $this->bag->foo);
}
public function testPropertyOverloadingIsset()
{
$data = array(
'abc' => '123',
'foo' => 'bar'
);
$this->property->setValue($this->bag, $data);
$this->assertTrue(isset($this->bag->abc));
$this->assertTrue(isset($this->bag->foo));
$this->assertFalse(isset($this->bag->foobar));
}
public function testPropertyOverloadingUnset()
{
$data = array(
'abc' => '123',
'foo' => 'bar'
);
$this->property->setValue($this->bag, $data);
$this->assertTrue(isset($this->bag->abc));
unset($this->bag->abc);
$this->assertFalse(isset($this->bag->abc));
$this->assertArrayNotHasKey('abc', $this->property->getValue($this->bag));
$this->assertArrayHasKey('foo', $this->property->getValue($this->bag));
}
public function testProtect()
{
$callable = function () {
return 'foo';
};
$result = $this->bag->protect($callable);
$this->assertInstanceOf('\Closure', $result);
$this->assertSame($callable, $result());
}
}
DEEP.git/Slim/tests/Http/ 0000775 0000000 0000000 00000000000 12634026554 0015351 5 ustar 00root root 0000000 0000000 DEEP.git/Slim/tests/Http/CookiesTest.php 0000775 0000000 0000000 00000006002 12634026554 0020317 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
*
* 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.
*/
class CookiesTest extends PHPUnit_Framework_TestCase
{
public function testSetWithStringValue()
{
$c = new \Slim\Http\Cookies();
$c->set('foo', 'bar');
$this->assertAttributeEquals(
array(
'foo' => array(
'value' => 'bar',
'expires' => null,
'domain' => null,
'path' => null,
'secure' => false,
'httponly' => false
)
),
'data',
$c
);
}
public function testSetWithArrayValue()
{
$now = time();
$c = new \Slim\Http\Cookies();
$c->set('foo', array(
'value' => 'bar',
'expires' => $now + 86400,
'domain' => '.example.com',
'path' => '/',
'secure' => true,
'httponly' => true
));
$this->assertAttributeEquals(
array(
'foo' => array(
'value' => 'bar',
'expires' => $now + 86400,
'domain' => '.example.com',
'path' => '/',
'secure' => true,
'httponly' => true
)
),
'data',
$c
);
}
public function testRemove()
{
$c = new \Slim\Http\Cookies();
$c->remove('foo');
$prop = new \ReflectionProperty($c, 'data');
$prop->setAccessible(true);
$cValue = $prop->getValue($c);
$this->assertEquals('', $cValue['foo']['value']);
$this->assertLessThan(time(), $cValue['foo']['expires']);
}
}
DEEP.git/Slim/tests/Http/HeadersTest.php 0000775 0000000 0000000 00000004235 12634026554 0020304 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
*
* 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.
*/
class HeadersTest extends PHPUnit_Framework_TestCase
{
public function testNormalizesKey()
{
$h = new \Slim\Http\Headers();
$h->set('Http_Content_Type', 'text/html');
$prop = new \ReflectionProperty($h, 'data');
$prop->setAccessible(true);
$this->assertArrayHasKey('Content-Type', $prop->getValue($h));
}
public function testExtractHeaders()
{
$test = array(
'HTTP_HOST' => 'foo.com',
'SERVER_NAME' => 'foo',
'CONTENT_TYPE' => 'text/html',
'X_FORWARDED_FOR' => '127.0.0.1'
);
$results = \Slim\Http\Headers::extract($test);
$this->assertEquals(array(
'HTTP_HOST' => 'foo.com',
'CONTENT_TYPE' => 'text/html',
'X_FORWARDED_FOR' => '127.0.0.1'
), $results);
}
}
DEEP.git/Slim/tests/Http/RequestTest.php 0000775 0000000 0000000 00000072332 12634026554 0020364 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
*
* 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.
*/
class RequestTest extends PHPUnit_Framework_TestCase
{
/**
* Test sets HTTP method
*/
public function testGetMethod()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'GET'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('GET', $req->getMethod());
}
/**
* Test HTTP GET method detection
*/
public function testIsGet()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'GET'
));
$req = new \Slim\Http\Request($env);
$this->assertTrue($req->isGet());
}
/**
* Test HTTP POST method detection
*/
public function testIsPost()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
));
$req = new \Slim\Http\Request($env);
$this->assertTrue($req->isPost());
}
/**
* Test HTTP PUT method detection
*/
public function testIsPut()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'PUT',
));
$req = new \Slim\Http\Request($env);
$this->assertTrue($req->isPut());
}
/**
* Test HTTP DELETE method detection
*/
public function testIsDelete()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'DELETE',
));
$req = new \Slim\Http\Request($env);
$this->assertTrue($req->isDelete());
}
/**
* Test HTTP OPTIONS method detection
*/
public function testIsOptions()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'OPTIONS',
));
$req = new \Slim\Http\Request($env);
$this->assertTrue($req->isOptions());
}
/**
* Test HTTP HEAD method detection
*/
public function testIsHead()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'HEAD',
));
$req = new \Slim\Http\Request($env);
$this->assertTrue($req->isHead());
}
/**
* Test HTTP PATCH method detection
*/
public function testIsPatch()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'PATCH',
));
$req = new \Slim\Http\Request($env);
$this->assertTrue($req->isPatch());
}
/**
* Test AJAX method detection w/ header
*/
public function testIsAjaxWithHeader()
{
$env = \Slim\Environment::mock(array(
'X_REQUESTED_WITH' => 'XMLHttpRequest'
));
$req = new \Slim\Http\Request($env);
$this->assertTrue($req->isAjax());
$this->assertTrue($req->isXhr());
}
/**
* Test AJAX method detection w/ query parameter
*/
public function testIsAjaxWithQueryParameter()
{
$env = \Slim\Environment::mock(array(
'QUERY_STRING' => 'isajax=1',
));
$req = new \Slim\Http\Request($env);
$this->assertTrue($req->isAjax());
$this->assertTrue($req->isXhr());
}
/**
* Test AJAX method detection without header or query parameter
*/
public function testIsAjaxWithoutHeaderOrQueryParameter()
{
$env = \Slim\Environment::mock();
$req = new \Slim\Http\Request($env);
$this->assertFalse($req->isAjax());
$this->assertFalse($req->isXhr());
}
/**
* Test AJAX method detection with misspelled header
*/
public function testIsAjaxWithMisspelledHeader()
{
$env = \Slim\Environment::mock(array(
'X_REQUESTED_WITH' => 'foo'
));
$req = new \Slim\Http\Request($env);
$this->assertFalse($req->isAjax());
$this->assertFalse($req->isXhr());
}
/**
* Test params from query string
*/
public function testParamsFromQueryString()
{
$env = \Slim\Environment::mock(array(
'QUERY_STRING' => 'one=1&two=2&three=3'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals(3, count($req->params()));
$this->assertEquals('1', $req->params('one'));
$this->assertNull($req->params('foo'));
$this->assertEquals(1, $req->params('foo', 1));
}
/**
* Test params from request body
*/
public function testParamsFromRequestBody()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'QUERY_STRING' => 'one=1&two=2&three=3',
'slim.input' => 'foo=bar&abc=123',
'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
'CONTENT_LENGTH' => 15
));
$req = new \Slim\Http\Request($env);
$this->assertEquals(5, count($req->params())); //Union of GET and POST
$this->assertEquals('bar', $req->params('foo'));
}
/**
* Test fetch GET params
*/
public function testGet()
{
$env = \Slim\Environment::mock(array(
'QUERY_STRING' => 'one=1&two=2&three=3'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals(3, count($req->get()));
$this->assertEquals('1', $req->get('one'));
$this->assertNull($req->get('foo'));
$this->assertFalse($req->get('foo', false));
}
/**
* Test fetch GET params without multibyte
*/
public function testGetWithoutMultibyte()
{
$env = \Slim\Environment::mock(array(
'QUERY_STRING' => 'one=1&two=2&three=3',
'slim.tests.ignore_multibyte' => true
));
$req = new \Slim\Http\Request($env);
$this->assertEquals(3, count($req->get()));
$this->assertEquals('1', $req->get('one'));
$this->assertNull($req->get('foo'));
$this->assertFalse($req->get('foo', false));
}
/**
* Test fetch POST params
*/
public function testPost()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'slim.input' => 'foo=bar&abc=123',
'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
'CONTENT_LENGTH' => 15
));
$req = new \Slim\Http\Request($env);
$this->assertEquals(2, count($req->post()));
$this->assertEquals('bar', $req->post('foo'));
$this->assertNull($req->post('xyz'));
$this->assertFalse($req->post('xyz', false));
}
/**
* Test fetch POST params without multibyte
*/
public function testPostWithoutMultibyte()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'slim.input' => 'foo=bar&abc=123',
'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
'CONTENT_LENGTH' => 15,
'slim.tests.ignore_multibyte' => true
));
$req = new \Slim\Http\Request($env);
$this->assertEquals(2, count($req->post()));
$this->assertEquals('bar', $req->post('foo'));
$this->assertNull($req->post('xyz'));
$this->assertFalse($req->post('xyz', false));
}
/**
* Test fetch POST without slim.input
*/
public function testPostWithoutInput()
{
$this->setExpectedException('RuntimeException');
$env = \Slim\Environment::mock();
unset($env['slim.input']);
$req = new \Slim\Http\Request($env);
$req->post('foo');
}
/**
* Test fetch POST params even if multipart/form-data request
*/
public function testPostWithMultipartRequest()
{
$_POST = array('foo' => 'bar'); //<-- Set by PHP
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'slim.input' => '', //<-- "php://input" is empty for multipart/form-data requests
'CONTENT_TYPE' => 'multipart/form-data',
'CONTENT_LENGTH' => 0
));
$req = new \Slim\Http\Request($env);
$this->assertEquals(1, count($req->post()));
$this->assertEquals('bar', $req->post('foo'));
$this->assertNull($req->post('xyz'));
}
/**
* Test fetch PUT params
*/
public function testPut()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'PUT',
'slim.input' => 'foo=bar&abc=123',
'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
'CONTENT_LENGTH' => 15
));
$req = new \Slim\Http\Request($env);
$this->assertEquals(2, count($req->put()));
$this->assertEquals('bar', $req->put('foo'));
$this->assertEquals('bar', $req->params('foo'));
$this->assertNull($req->put('xyz'));
$this->assertFalse($req->put('xyz', false));
}
/**
* Test fetch PATCH params
*/
public function testPatch()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'PATCH',
'slim.input' => 'foo=bar&abc=123',
'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
'CONTENT_LENGTH' => 15
));
$req = new \Slim\Http\Request($env);
$this->assertEquals(2, count($req->patch()));
$this->assertEquals('bar', $req->patch('foo'));
$this->assertEquals('bar', $req->params('foo'));
$this->assertNull($req->patch('xyz'));
$this->assertFalse($req->patch('xyz', false));
}
/**
* Test fetch DELETE params
*/
public function testDelete()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'DELETE',
'slim.input' => 'foo=bar&abc=123',
'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
'CONTENT_LENGTH' => 15
));
$req = new \Slim\Http\Request($env);
$this->assertEquals(2, count($req->delete()));
$this->assertEquals('bar', $req->delete('foo'));
$this->assertEquals('bar', $req->params('foo'));
$this->assertNull($req->delete('xyz'));
$this->assertFalse($req->delete('xyz', false));
}
/**
* Test fetch COOKIE params
*/
public function testCookies()
{
$env = \Slim\Environment::mock(array(
'HTTP_COOKIE' => 'foo=bar; abc=123'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals(2, count($req->cookies()));
$this->assertEquals('bar', $req->cookies('foo'));
$this->assertNull($req->cookies('xyz'));
}
/**
* Test is form data
*/
public function testIsFormDataContentFormUrlencoded()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'PUT',
'slim.input' => '',
'CONTENT_TYPE' => 'application/x-www-form-urlencoded'
));
$req = new \Slim\Http\Request($env);
$this->assertTrue($req->isFormData());
}
/**
* Test is form data
*/
public function testIsFormDataPostContentUnknown()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'slim.input' => '',
));
$req = new \Slim\Http\Request($env);
$this->assertTrue($req->isFormData());
}
/**
* Test is form data
*/
public function testIsFormDataPostContentUnknownWithMethodOverride()
{
$env = \Slim\Environment::mock(array(
'REQUEST_METHOD' => 'PUT',
));
$env['slim.method_override.original_method'] = 'POST';
$req = new \Slim\Http\Request($env);
$this->assertTrue($req->isPut());
$this->assertTrue($req->isFormData());
}
/**
* Test is not form data
*/
public function testIsNotFormData()
{
$env = \Slim\Environment::mock(array(
'slim.input' => '',
'CONTENT_TYPE' => 'application/json'
));
$req = new \Slim\Http\Request($env);
$this->assertFalse($req->isFormData());
}
/**
* Test headers
*/
public function testHeaders()
{
$env = \Slim\Environment::mock(array(
'HTTP_ACCEPT_ENCODING' => 'gzip'
));
$req = new \Slim\Http\Request($env);
$headers = $req->headers();
$this->assertInstanceOf('\Slim\Http\Headers', $headers);
$this->assertEquals('gzip', $req->headers('HTTP_ACCEPT_ENCODING'));
$this->assertEquals('gzip', $req->headers('HTTP-ACCEPT-ENCODING'));
$this->assertEquals('gzip', $req->headers('http_accept_encoding'));
$this->assertEquals('gzip', $req->headers('http-accept-encoding'));
$this->assertEquals('gzip', $req->headers('ACCEPT_ENCODING'));
$this->assertEquals('gzip', $req->headers('ACCEPT-ENCODING'));
$this->assertEquals('gzip', $req->headers('accept_encoding'));
$this->assertEquals('gzip', $req->headers('accept-encoding'));
$this->assertNull($req->headers('foo'));
}
/**
* Test accurately removes HTTP_ prefix from input header name
*/
public function testHeaderRemovesHttpPrefix()
{
$env = \Slim\Environment::mock(array(
'X_HTTP_METHOD_OVERRIDE' => 'PUT',
'CONTENT_TYPE' => 'application/json'
));
//fwrite(fopen('php://stdout', 'w'), print_r($env, true));
$req = new \Slim\Http\Request($env);
$this->assertEquals('PUT', $req->headers('X_HTTP_METHOD_OVERRIDE'));
$this->assertNull($req->headers('X_METHOD_OVERRIDE')); //<-- Ensures `HTTP_` is not removed if not prefix
$this->assertEquals('application/json', $req->headers('HTTP_CONTENT_TYPE')); //<-- Ensures `HTTP_` is removed if prefix
}
/**
* Test get body
*/
public function testGetBodyWhenExists()
{
$env = \Slim\Environment::mock(array(
'slim.input' => 'foo=bar&abc=123',
'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
'CONTENT_LENGTH' => 15
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('foo=bar&abc=123', $req->getBody());
}
/**
* Test get body
*/
public function testGetBodyWhenNotExists()
{
$env = \Slim\Environment::mock();
$req = new \Slim\Http\Request($env);
$this->assertEquals('', $req->getBody());
}
/**
* Test get content type
*/
public function testGetContentTypeWhenExists()
{
$env = \Slim\Environment::mock(array(
'slim.input' => '',
'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('application/json; charset=ISO-8859-4', $req->getContentType());
}
/**
* Test get content type for built-in PHP server
*/
public function testGetContentTypeForBuiltInServer()
{
$env = \Slim\Environment::mock(array(
'slim.input' => '',
'HTTP_CONTENT_TYPE' => 'application/json; charset=ISO-8859-4'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('application/json; charset=ISO-8859-4', $req->getContentType());
}
/**
* Test get content type
*/
public function testGetContentTypeWhenNotExists()
{
$env = \Slim\Environment::mock();
$req = new \Slim\Http\Request($env);
$this->assertNull($req->getContentType());
}
/**
* Test get content type with built-in server
*/
public function testGetContentTypeWithBuiltInServer()
{
$env = \Slim\Environment::mock(array(
'slim.input' => '',
'HTTP_CONTENT_TYPE' => 'application/json; charset=ISO-8859-4'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('application/json; charset=ISO-8859-4', $req->getContentType());
}
/**
* Test get media type
*/
public function testGetMediaTypeWhenExists()
{
$env = \Slim\Environment::mock(array(
'CONTENT_TYPE' => 'application/json;charset=utf-8'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('application/json', $req->getMediaType());
}
/**
* Test get media type
*/
public function testGetMediaTypeWhenNotExists()
{
$env = \Slim\Environment::mock();
$req = new \Slim\Http\Request($env);
$this->assertNull($req->getMediaType());
}
/**
* Test get media type
*/
public function testGetMediaTypeWhenNoParamsExist()
{
$env = \Slim\Environment::mock(array(
'slim.input' => '',
'CONTENT_TYPE' => 'application/json'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('application/json', $req->getMediaType());
}
/**
* Test get media type params
*/
public function testGetMediaTypeParams()
{
$env = \Slim\Environment::mock(array(
'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4'
));
$req = new \Slim\Http\Request($env);
$params = $req->getMediaTypeParams();
$this->assertEquals(1, count($params));
$this->assertArrayHasKey('charset', $params);
$this->assertEquals('ISO-8859-4', $params['charset']);
}
/**
* Test get media type params
*/
public function testGetMediaTypeParamsWhenNotExists()
{
$env = \Slim\Environment::mock();
$req = new \Slim\Http\Request($env);
$params = $req->getMediaTypeParams();
$this->assertTrue(is_array($params));
$this->assertEquals(0, count($params));
}
/**
* Test get content charset
*/
public function testGetContentCharset()
{
$env = \Slim\Environment::mock(array(
'slim.input' => '',
'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('ISO-8859-4', $req->getContentCharset());
}
/**
* Test get content charset
*/
public function testGetContentCharsetWhenNotExists()
{
$env = \Slim\Environment::mock(array(
'slim.input' => '',
'CONTENT_TYPE' => 'application/json'
));
$req = new \Slim\Http\Request($env);
$this->assertNull($req->getContentCharset());
}
/**
* Test get content length
*/
public function testGetContentLength()
{
$env = \Slim\Environment::mock(array(
'slim.input' => 'foo=bar&abc=123',
'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
'CONTENT_LENGTH' => 15
));
$req = new \Slim\Http\Request($env);
$this->assertEquals(15, $req->getContentLength());
}
/**
* Test get content length
*/
public function testGetContentLengthWhenNotExists()
{
$env = \Slim\Environment::mock(array(
'slim.input' => '',
));
$req = new \Slim\Http\Request($env);
$this->assertEquals(0, $req->getContentLength());
}
/**
* Test get host
*/
public function testGetHost()
{
$env = \Slim\Environment::mock(array(
'SERVER_NAME' => 'slim',
'HTTP_HOST' => 'slimframework.com'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('slimframework.com', $req->getHost()); //Uses HTTP_HOST if available
}
/**
* Test get host when it has a port number
*/
public function testGetHostAndStripPort()
{
$env = \Slim\Environment::mock(array(
'SERVER_NAME' => 'slim',
'HTTP_HOST' => 'slimframework.com:80'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('slimframework.com', $req->getHost()); //Uses HTTP_HOST if available
}
/**
* Test get host
*/
public function testGetHostWhenNotExists()
{
$env = \Slim\Environment::mock(array(
'SERVER_NAME' => 'slim',
'HTTP_HOST' => 'slimframework.com'
));
unset($env['HTTP_HOST']);
$req = new \Slim\Http\Request($env);
$this->assertEquals('slim', $req->getHost()); //Uses SERVER_NAME as backup
}
/**
* Test get host with port
*/
public function testGetHostWithPort()
{
$env = \Slim\Environment::mock(array(
'HTTP_HOST' => 'slimframework.com',
'SERVER_NAME' => 'slim',
'SERVER_PORT' => 80,
'slim.url_scheme' => 'http'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('slimframework.com:80', $req->getHostWithPort());
}
/**
* Test get host with port doesn't duplicate port numbers
*/
public function testGetHostDoesntDuplicatePort()
{
$env = \Slim\Environment::mock(array(
'HTTP_HOST' => 'slimframework.com:80',
'SERVER_NAME' => 'slim',
'SERVER_PORT' => 80,
'slim.url_scheme' => 'http'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('slimframework.com:80', $req->getHostWithPort());
}
/**
* Test get port
*/
public function testGetPort()
{
$env = \Slim\Environment::mock(array(
'SERVER_PORT' => 80
));
$req = new \Slim\Http\Request($env);
$this->assertTrue(is_integer($req->getPort()));
$this->assertEquals(80, $req->getPort());
}
/**
* Test get scheme
*/
public function testGetSchemeIfHttp()
{
$env = \Slim\Environment::mock(array(
'slim.url_scheme' => 'http'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('http', $req->getScheme());
}
/**
* Test get scheme
*/
public function testGetSchemeIfHttps()
{
$env = \Slim\Environment::mock(array(
'slim.url_scheme' => 'https',
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('https', $req->getScheme());
}
/**
* Test get [script name, root uri, path, path info, resource uri] in subdirectory without htaccess
*/
public function testAppPathsInSubdirectoryWithoutHtaccess()
{
$env = \Slim\Environment::mock(array(
'SCRIPT_NAME' => '/foo/index.php', //<-- Physical
'PATH_INFO' => '/bar/xyz', //<-- Virtual
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('/foo/index.php', $req->getScriptName());
$this->assertEquals('/foo/index.php', $req->getRootUri());
$this->assertEquals('/foo/index.php/bar/xyz', $req->getPath());
$this->assertEquals('/bar/xyz', $req->getPathInfo());
$this->assertEquals('/bar/xyz', $req->getResourceUri());
}
/**
* Test get [script name, root uri, path, path info, resource uri] in subdirectory with htaccess
*/
public function testAppPathsInSubdirectoryWithHtaccess()
{
$env = \Slim\Environment::mock(array(
'SCRIPT_NAME' => '/foo', //<-- Physical
'PATH_INFO' => '/bar/xyz', //<-- Virtual
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('/foo', $req->getScriptName());
$this->assertEquals('/foo', $req->getRootUri());
$this->assertEquals('/foo/bar/xyz', $req->getPath());
$this->assertEquals('/bar/xyz', $req->getPathInfo());
$this->assertEquals('/bar/xyz', $req->getResourceUri());
}
/**
* Test get [script name, root uri, path, path info, resource uri] in root directory without htaccess
*/
public function testAppPathsInRootDirectoryWithoutHtaccess()
{
$env = \Slim\Environment::mock(array(
'SCRIPT_NAME' => '/index.php', //<-- Physical
'PATH_INFO' => '/bar/xyz', //<-- Virtual
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('/index.php', $req->getScriptName());
$this->assertEquals('/index.php', $req->getRootUri());
$this->assertEquals('/index.php/bar/xyz', $req->getPath());
$this->assertEquals('/bar/xyz', $req->getPathInfo());
$this->assertEquals('/bar/xyz', $req->getResourceUri());
}
/**
* Test get [script name, root uri, path, path info, resource uri] in root directory with htaccess
*/
public function testAppPathsInRootDirectoryWithHtaccess()
{
$env = \Slim\Environment::mock(array(
'SCRIPT_NAME' => '', //<-- Physical
'PATH_INFO' => '/bar/xyz', //<-- Virtual
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('', $req->getScriptName());
$this->assertEquals('', $req->getRootUri());
$this->assertEquals('/bar/xyz', $req->getPath());
$this->assertEquals('/bar/xyz', $req->getPathInfo());
$this->assertEquals('/bar/xyz', $req->getResourceUri());
}
/**
* Test get URL
*/
public function testGetUrl()
{
$env = \Slim\Environment::mock(array(
'HTTP_HOST' => 'slimframework.com',
'SERVER_NAME' => 'slim',
'SERVER_PORT' => 80,
'slim.url_scheme' => 'http'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('http://slimframework.com', $req->getUrl());
}
/**
* Test get URL
*/
public function testGetUrlWithCustomPort()
{
$env = \Slim\Environment::mock(array(
'HTTP_HOST' => 'slimframework.com',
'SERVER_NAME' => 'slim',
'SERVER_PORT' => 8080,
'slim.url_scheme' => 'http'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('http://slimframework.com:8080', $req->getUrl());
}
/**
* Test get URL
*/
public function testGetUrlWithHttps()
{
$env = \Slim\Environment::mock(array(
'HTTP_HOST' => 'slimframework.com',
'SERVER_NAME' => 'slim',
'SERVER_PORT' => 443,
'slim.url_scheme' => 'https'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('https://slimframework.com', $req->getUrl());
}
/**
* Test get IP
* @dataProvider dataTestIp
*/
public function testGetIp(array $server, $expected)
{
$env = \Slim\Environment::mock($server);
$req = new \Slim\Http\Request($env);
$this->assertEquals($expected, $req->getIp());
}
public function dataTestIp()
{
return array(
array(array('REMOTE_ADDR' => '127.0.0.1'), '127.0.0.1'),
array(array('REMOTE_ADDR' => '127.0.0.1', 'CLIENT_IP' => '127.0.0.2'), '127.0.0.2'),
array(array('REMOTE_ADDR' => '127.0.0.1', 'CLIENT_IP' => '127.0.0.2', 'X_FORWARDED_FOR' => '127.0.0.3'), '127.0.0.3'),
array(array('REMOTE_ADDR' => '127.0.0.1', 'CLIENT_IP' => '127.0.0.2', 'HTTP_X_FORWARDED_FOR' => '127.0.0.4'), '127.0.0.4'),
array(array('REMOTE_ADDR' => '127.0.0.1', 'CLIENT_IP' => '127.0.0.2', 'X_FORWARDED_FOR' => '127.0.0.3', 'HTTP_X_FORWARDED_FOR' => '127.0.0.4'), '127.0.0.3'),
);
}
/**
* Test get referer
*/
public function testGetReferrer()
{
$env = \Slim\Environment::mock(array(
'HTTP_REFERER' => 'http://foo.com'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('http://foo.com', $req->getReferrer());
$this->assertEquals('http://foo.com', $req->getReferer());
}
/**
* Test get referer
*/
public function testGetReferrerWhenNotExists()
{
$env = \Slim\Environment::mock();
$req = new \Slim\Http\Request($env);
$this->assertNull($req->getReferrer());
$this->assertNull($req->getReferer());
}
/**
* Test get user agent string
*/
public function testGetUserAgent()
{
$env = \Slim\Environment::mock(array(
'HTTP_USER_AGENT' => 'user-agent-string'
));
$req = new \Slim\Http\Request($env);
$this->assertEquals('user-agent-string', $req->getUserAgent());
}
/**
* Test get user agent string when not set
*/
public function testGetUserAgentWhenNotExists()
{
$env = \Slim\Environment::mock();
unset($env['HTTP_USER_AGENT']);
$req = new \Slim\Http\Request($env);
$this->assertNull($req->getUserAgent());
}
}
DEEP.git/Slim/tests/Http/ResponseTest.php 0000775 0000000 0000000 00000017525 12634026554 0020535 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
*
* 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.
*/
class ResponseTest extends PHPUnit_Framework_TestCase
{
public function testConstructWithoutArgs()
{
$res = new \Slim\Http\Response();
$this->assertAttributeEquals(200, 'status', $res);
$this->assertAttributeEquals('', 'body', $res);
}
public function testConstructWithArgs()
{
$res = new \Slim\Http\Response('Foo', 201);
$this->assertAttributeEquals(201, 'status', $res);
$this->assertAttributeEquals('Foo', 'body', $res);
}
public function testGetStatus()
{
$res = new \Slim\Http\Response();
$this->assertEquals(200, $res->getStatus());
}
public function testSetStatus()
{
$res = new \Slim\Http\Response();
$res->setStatus(301);
$this->assertAttributeEquals(301, 'status', $res);
}
/**
* DEPRECATION WARNING!
*/
public function testStatusGetOld()
{
$res = new \Slim\Http\Response('', 201);
$this->assertEquals(201, $res->status());
}
/**
* DEPRECATION WARNING!
*/
public function testStatusSetOld()
{
$res = new \Slim\Http\Response();
$prop = new \ReflectionProperty($res, 'status');
$prop->setAccessible(true);
$res->status(301);
$this->assertEquals(301, $prop->getValue($res));
}
public function testGetBody()
{
$res = new \Slim\Http\Response();
$property = new \ReflectionProperty($res, 'body');
$property->setAccessible(true);
$property->setValue($res, 'foo');
$this->assertEquals('foo', $res->getBody());
}
public function testSetBody()
{
$res = new \Slim\Http\Response('bar');
$res->setBody('foo'); // <-- Should replace body
$this->assertAttributeEquals('foo', 'body', $res);
}
public function testWrite()
{
$res = new \Slim\Http\Response();
$property = new \ReflectionProperty($res, 'body');
$property->setAccessible(true);
$property->setValue($res, 'foo');
$res->write('bar'); // <-- Should append to body
$this->assertAttributeEquals('foobar', 'body', $res);
}
public function testLength()
{
$res = new \Slim\Http\Response('foo'); // <-- Sets body and length
$this->assertEquals(3, $res->getLength());
}
public function testFinalize()
{
$res = new \Slim\Http\Response();
$resFinal = $res->finalize();
$this->assertTrue(is_array($resFinal));
$this->assertEquals(3, count($resFinal));
$this->assertEquals(200, $resFinal[0]);
$this->assertInstanceOf('\Slim\Http\Headers', $resFinal[1]);
$this->assertEquals('', $resFinal[2]);
}
public function testFinalizeWithEmptyBody()
{
$res = new \Slim\Http\Response('Foo', 304);
$resFinal = $res->finalize();
$this->assertEquals('', $resFinal[2]);
}
public function testRedirect()
{
$res = new \Slim\Http\Response();
$res->redirect('/foo');
$pStatus = new \ReflectionProperty($res, 'status');
$pStatus->setAccessible(true);
$this->assertEquals(302, $pStatus->getValue($res));
$this->assertEquals('/foo', $res->headers['Location']);
}
public function testIsEmpty()
{
$r1 = new \Slim\Http\Response();
$r2 = new \Slim\Http\Response();
$r1->setStatus(404);
$r2->setStatus(201);
$this->assertFalse($r1->isEmpty());
$this->assertTrue($r2->isEmpty());
}
public function testIsClientError()
{
$r1 = new \Slim\Http\Response();
$r2 = new \Slim\Http\Response();
$r1->setStatus(404);
$r2->setStatus(500);
$this->assertTrue($r1->isClientError());
$this->assertFalse($r2->isClientError());
}
public function testIsForbidden()
{
$r1 = new \Slim\Http\Response();
$r2 = new \Slim\Http\Response();
$r1->setStatus(403);
$r2->setStatus(500);
$this->assertTrue($r1->isForbidden());
$this->assertFalse($r2->isForbidden());
}
public function testIsInformational()
{
$r1 = new \Slim\Http\Response();
$r2 = new \Slim\Http\Response();
$r1->setStatus(100);
$r2->setStatus(200);
$this->assertTrue($r1->isInformational());
$this->assertFalse($r2->isInformational());
}
public function testIsNotFound()
{
$r1 = new \Slim\Http\Response();
$r2 = new \Slim\Http\Response();
$r1->setStatus(404);
$r2->setStatus(200);
$this->assertTrue($r1->isNotFound());
$this->assertFalse($r2->isNotFound());
}
public function testIsOk()
{
$r1 = new \Slim\Http\Response();
$r2 = new \Slim\Http\Response();
$r1->setStatus(200);
$r2->setStatus(201);
$this->assertTrue($r1->isOk());
$this->assertFalse($r2->isOk());
}
public function testIsSuccessful()
{
$r1 = new \Slim\Http\Response();
$r2 = new \Slim\Http\Response();
$r3 = new \Slim\Http\Response();
$r1->setStatus(200);
$r2->setStatus(201);
$r3->setStatus(302);
$this->assertTrue($r1->isSuccessful());
$this->assertTrue($r2->isSuccessful());
$this->assertFalse($r3->isSuccessful());
}
public function testIsRedirect()
{
$r1 = new \Slim\Http\Response();
$r2 = new \Slim\Http\Response();
$r1->setStatus(307);
$r2->setStatus(304);
$this->assertTrue($r1->isRedirect());
$this->assertFalse($r2->isRedirect());
}
public function testIsRedirection()
{
$r1 = new \Slim\Http\Response();
$r2 = new \Slim\Http\Response();
$r3 = new \Slim\Http\Response();
$r1->setStatus(307);
$r2->setStatus(304);
$r3->setStatus(200);
$this->assertTrue($r1->isRedirection());
$this->assertTrue($r2->isRedirection());
$this->assertFalse($r3->isRedirection());
}
public function testIsServerError()
{
$r1 = new \Slim\Http\Response();
$r2 = new \Slim\Http\Response();
$r1->setStatus(500);
$r2->setStatus(400);
$this->assertTrue($r1->isServerError());
$this->assertFalse($r2->isServerError());
}
public function testMessageForCode()
{
$this->assertEquals('200 OK', \Slim\Http\Response::getMessageForCode(200));
}
public function testMessageForCodeWithInvalidCode()
{
$this->assertNull(\Slim\Http\Response::getMessageForCode(600));
}
}
DEEP.git/Slim/tests/Http/UtilTest.php 0000775 0000000 0000000 00000040035 12634026554 0017644 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
*
* 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.
*/
class SlimHttpUtilTest extends PHPUnit_Framework_TestCase
{
/**
* Test strip slashes when magic quotes disabled
*/
public function testStripSlashesWithoutMagicQuotes()
{
$data = "This should have \"quotes\" in it";
$stripped = \Slim\Http\Util::stripSlashesIfMagicQuotes($data, false);
$this->assertEquals($data, $stripped);
}
/**
* Test strip slashes from array when magic quotes disabled
*/
public function testStripSlashesFromArrayWithoutMagicQuotes()
{
$data = array("This should have \"quotes\" in it", "And this \"too\" has quotes");
$stripped = \Slim\Http\Util::stripSlashesIfMagicQuotes($data, false);
$this->assertEquals($data, $stripped);
}
/**
* Test strip slashes when magic quotes enabled
*/
public function testStripSlashesWithMagicQuotes()
{
$data = "This should have \"quotes\" in it";
$stripped = \Slim\Http\Util::stripSlashesIfMagicQuotes($data, true);
$this->assertEquals('This should have "quotes" in it', $stripped);
}
/**
* Test strip slashes from array when magic quotes enabled
*/
public function testStripSlashesFromArrayWithMagicQuotes()
{
$data = array("This should have \"quotes\" in it", "And this \"too\" has quotes");
$stripped = \Slim\Http\Util::stripSlashesIfMagicQuotes($data, true);
$this->assertEquals($data = array('This should have "quotes" in it', 'And this "too" has quotes'), $stripped);
}
/**
* Test encrypt and decrypt with valid data
*/
public function testEncryptAndDecryptWithValidData()
{
$data = 'foo';
$key = 'secret';
$iv = md5('initializationVector');
$encrypted = \Slim\Http\Util::encrypt($data, $key, $iv);
$decrypted = \Slim\Http\Util::decrypt($encrypted, $key, $iv);
$this->assertEquals($data, $decrypted);
$this->assertTrue($data !== $encrypted);
}
/**
* Test encrypt when data is empty string
*/
public function testEncryptWhenDataIsEmptyString()
{
$data = '';
$key = 'secret';
$iv = md5('initializationVector');
$encrypted = \Slim\Http\Util::encrypt($data, $key, $iv);
$this->assertEquals('', $encrypted);
}
/**
* Test decrypt when data is empty string
*/
public function testDecryptWhenDataIsEmptyString()
{
$data = '';
$key = 'secret';
$iv = md5('initializationVector');
$decrypted = \Slim\Http\Util::decrypt($data, $key, $iv);
$this->assertEquals('', $decrypted);
}
/**
* Test encrypt when IV and key sizes are too long
*/
public function testEncryptAndDecryptWhenKeyAndIvAreTooLong()
{
$data = 'foo';
$key = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz';
$iv = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz';
$encrypted = \Slim\Http\Util::encrypt($data, $key, $iv);
$decrypted = \Slim\Http\Util::decrypt($encrypted, $key, $iv);
$this->assertEquals($data, $decrypted);
$this->assertTrue($data !== $encrypted);
}
public function testEncodeAndDecodeSecureCookieWithValidData()
{
//Prepare cookie value
$value = 'foo';
$expires = time() + 86400;
$secret = 'password';
$algorithm = MCRYPT_RIJNDAEL_256;
$mode = MCRYPT_MODE_CBC;
$encodedValue = \Slim\Http\Util::encodeSecureCookie($value, $expires, $secret, $algorithm, $mode);
$decodedValue = \Slim\Http\Util::decodeSecureCookie($encodedValue, $secret, $algorithm, $mode);
//Test secure cookie value
$parts = explode('|', $encodedValue);
$this->assertEquals(3, count($parts));
$this->assertEquals($expires, $parts[0]);
$this->assertEquals($value, $decodedValue);
}
/**
* Test encode/decode secure cookie with old expiration
*
* In this test, the expiration date is purposefully set to a time before now.
* When decoding the encoded cookie value, FALSE is returned since the cookie
* will have expired before it is decoded.
*/
public function testEncodeAndDecodeSecureCookieWithOldExpiration()
{
$value = 'foo';
$expires = time() - 100;
$secret = 'password';
$algorithm = MCRYPT_RIJNDAEL_256;
$mode = MCRYPT_MODE_CBC;
$encodedValue = \Slim\Http\Util::encodeSecureCookie($value, $expires, $secret, $algorithm, $mode);
$decodedValue = \Slim\Http\Util::decodeSecureCookie($encodedValue, $secret, $algorithm, $mode);
$this->assertFalse($decodedValue);
}
/**
* Test encode/decode secure cookie with tampered data
*
* In this test, the encoded data is purposefully changed to simulate someone
* tampering with the client-side cookie data. When decoding the encoded cookie value,
* FALSE is returned since the verification key will not match.
*/
public function testEncodeAndDecodeSecureCookieWithTamperedData()
{
$value = 'foo';
$expires = time() + 86400;
$secret = 'password';
$algorithm = MCRYPT_RIJNDAEL_256;
$mode = MCRYPT_MODE_CBC;
$encodedValue = \Slim\Http\Util::encodeSecureCookie($value, $expires, $secret, $algorithm, $mode);
$encodedValueParts = explode('|', $encodedValue);
$encodedValueParts[1] = $encodedValueParts[1] . 'changed';
$encodedValue = implode('|', $encodedValueParts);
$decodedValue = \Slim\Http\Util::decodeSecureCookie($encodedValue, $secret, $algorithm, $mode);
$this->assertFalse($decodedValue);
}
public function testSetCookieHeaderWithNameAndValue()
{
$name = 'foo';
$value = 'bar';
$header = array();
\Slim\Http\Util::setCookieHeader($header, $name, $value);
$this->assertEquals('foo=bar', $header['Set-Cookie']);
}
public function testSetCookieHeaderWithNameAndValueWhenCookieAlreadySet()
{
$name = 'foo';
$value = 'bar';
$header = array('Set-Cookie' => 'one=two');
\Slim\Http\Util::setCookieHeader($header, $name, $value);
$this->assertEquals("one=two\nfoo=bar", $header['Set-Cookie']);
}
public function testSetCookieHeaderWithNameAndValueAndDomain()
{
$name = 'foo';
$value = 'bar';
$domain = 'foo.com';
$header = array();
\Slim\Http\Util::setCookieHeader($header, $name, array(
'value' => $value,
'domain' => $domain
));
$this->assertEquals('foo=bar; domain=foo.com', $header['Set-Cookie']);
}
public function testSetCookieHeaderWithNameAndValueAndDomainAndPath()
{
$name = 'foo';
$value = 'bar';
$domain = 'foo.com';
$path = '/foo';
$header = array();
\Slim\Http\Util::setCookieHeader($header, $name, array(
'value' => $value,
'domain' => $domain,
'path' => $path
));
$this->assertEquals('foo=bar; domain=foo.com; path=/foo', $header['Set-Cookie']);
}
public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAsString()
{
$name = 'foo';
$value = 'bar';
$domain = 'foo.com';
$path = '/foo';
$expires = '2 days';
$expiresFormat = gmdate('D, d-M-Y H:i:s e', strtotime($expires));
$header = array();
\Slim\Http\Util::setCookieHeader($header, $name, array(
'value' => $value,
'domain' => $domain,
'path' => '/foo',
'expires' => $expires
));
$this->assertEquals('foo=bar; domain=foo.com; path=/foo; expires=' . $expiresFormat, $header['Set-Cookie']);
}
public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAsInteger()
{
$name = 'foo';
$value = 'bar';
$domain = 'foo.com';
$path = '/foo';
$expires = strtotime('2 days');
$expiresFormat = gmdate('D, d-M-Y H:i:s e', $expires);
$header = array();
\Slim\Http\Util::setCookieHeader($header, $name, array(
'value' => $value,
'domain' => $domain,
'path' => '/foo',
'expires' => $expires
));
$this->assertEquals('foo=bar; domain=foo.com; path=/foo; expires=' . $expiresFormat, $header['Set-Cookie']);
}
public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAsZero()
{
$name = 'foo';
$value = 'bar';
$domain = 'foo.com';
$path = '/foo';
$expires = 0;
$header = array();
\Slim\Http\Util::setCookieHeader($header, $name, array(
'value' => $value,
'domain' => $domain,
'path' => '/foo',
'expires' => $expires
));
$this->assertEquals('foo=bar; domain=foo.com; path=/foo', $header['Set-Cookie']);
}
public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAndSecure()
{
$name = 'foo';
$value = 'bar';
$domain = 'foo.com';
$path = '/foo';
$expires = strtotime('2 days');
$expiresFormat = gmdate('D, d-M-Y H:i:s e', $expires);
$secure = true;
$header = array();
\Slim\Http\Util::setCookieHeader($header, $name, array(
'value' => $value,
'domain' => $domain,
'path' => '/foo',
'expires' => $expires,
'secure' => $secure
));
$this->assertEquals('foo=bar; domain=foo.com; path=/foo; expires=' . $expiresFormat . '; secure', $header['Set-Cookie']);
}
public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAndSecureAndHttpOnly()
{
$name = 'foo';
$value = 'bar';
$domain = 'foo.com';
$path = '/foo';
$expires = strtotime('2 days');
$expiresFormat = gmdate('D, d-M-Y H:i:s e', $expires);
$secure = true;
$httpOnly = true;
$header = array();
\Slim\Http\Util::setCookieHeader($header, $name, array(
'value' => $value,
'domain' => $domain,
'path' => '/foo',
'expires' => $expires,
'secure' => $secure,
'httponly' => $httpOnly
));
$this->assertEquals('foo=bar; domain=foo.com; path=/foo; expires=' . $expiresFormat . '; secure; HttpOnly', $header['Set-Cookie']);
}
/**
* Test serializeCookies and decrypt with string expires
*
* In this test a cookie with a string typed value for 'expires' is set,
* which should be parsed by `strtotime` to a timestamp when it's added to
* the headers; this timestamp should then be correctly parsed, and the
* value correctly decrypted, by `decodeSecureCookie`.
*/
public function testSerializeCookiesAndDecryptWithStringExpires()
{
$value = 'bar';
$headers = new \Slim\Http\Headers();
$settings = array(
'cookies.encrypt' => true,
'cookies.secret_key' => 'secret',
'cookies.cipher' => MCRYPT_RIJNDAEL_256,
'cookies.cipher_mode' => MCRYPT_MODE_CBC
);
$cookies = new \Slim\Http\Cookies();
$cookies->set('foo', array(
'value' => $value,
'expires' => '1 hour'
));
\Slim\Http\Util::serializeCookies($headers, $cookies, $settings);
$encrypted = $headers->get('Set-Cookie');
$encrypted = strstr($encrypted, ';', true);
$encrypted = urldecode(substr(strstr($encrypted, '='), 1));
$decrypted = \Slim\Http\Util::decodeSecureCookie(
$encrypted,
$settings['cookies.secret_key'],
$settings['cookies.cipher'],
$settings['cookies.cipher_mode']
);
$this->assertEquals($value, $decrypted);
$this->assertTrue($value !== $encrypted);
}
public function testDeleteCookieHeaderWithSurvivingCookie()
{
$header = array('Set-Cookie' => "foo=bar\none=two");
\Slim\Http\Util::deleteCookieHeader($header, 'foo');
$this->assertEquals(1, preg_match("@^one=two\nfoo=; expires=@", $header['Set-Cookie']));
}
public function testDeleteCookieHeaderWithoutSurvivingCookie()
{
$header = array('Set-Cookie' => "foo=bar");
\Slim\Http\Util::deleteCookieHeader($header, 'foo');
$this->assertEquals(1, preg_match("@foo=; expires=@", $header['Set-Cookie']));
}
public function testDeleteCookieHeaderWithMatchingDomain()
{
$header = array('Set-Cookie' => "foo=bar; domain=foo.com");
\Slim\Http\Util::deleteCookieHeader($header, 'foo', array(
'domain' => 'foo.com'
));
$this->assertEquals(1, preg_match("@foo=; domain=foo.com; expires=@", $header['Set-Cookie']));
}
public function testDeleteCookieHeaderWithoutMatchingDomain()
{
$header = array('Set-Cookie' => "foo=bar; domain=foo.com");
\Slim\Http\Util::deleteCookieHeader($header, 'foo', array(
'domain' => 'bar.com'
));
$this->assertEquals(1, preg_match("@foo=bar; domain=foo\.com\nfoo=; domain=bar\.com@", $header['Set-Cookie']));
}
/**
* Test parses Cookie: HTTP header
*/
public function testParsesCookieHeader()
{
$header = 'foo=bar; one=two; colors=blue';
$result = \Slim\Http\Util::parseCookieHeader($header);
$this->assertEquals(3, count($result));
$this->assertEquals('bar', $result['foo']);
$this->assertEquals('two', $result['one']);
$this->assertEquals('blue', $result['colors']);
}
/**
* Test parses Cookie: HTTP header with `=` in the cookie value
*/
public function testParsesCookieHeaderWithEqualSignInValue()
{
$header = 'foo=bar; one=two=; colors=blue';
$result = \Slim\Http\Util::parseCookieHeader($header);
$this->assertEquals(3, count($result));
$this->assertEquals('bar', $result['foo']);
$this->assertEquals('two=', $result['one']);
$this->assertEquals('blue', $result['colors']);
}
public function testParsesCookieHeaderWithCommaSeparator()
{
$header = 'foo=bar, one=two, colors=blue';
$result = \Slim\Http\Util::parseCookieHeader($header);
$this->assertEquals(3, count($result));
$this->assertEquals('bar', $result['foo']);
$this->assertEquals('two', $result['one']);
$this->assertEquals('blue', $result['colors']);
}
public function testPrefersLeftmostCookieWhenManyCookiesWithSameName()
{
$header = 'foo=bar; foo=beer';
$result = \Slim\Http\Util::parseCookieHeader($header);
$this->assertEquals('bar', $result['foo']);
}
}
DEEP.git/Slim/tests/LogTest.php 0000775 0000000 0000000 00000014074 12634026554 0016535 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
*
* 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.
*/
class MyWriter
{
public function write( $object, $level )
{
echo (string) $object;
return true;
}
}
class LogTest extends PHPUnit_Framework_TestCase
{
public function testEnabled()
{
$log = new \Slim\Log(new MyWriter());
$this->assertTrue($log->isEnabled()); //<-- Default case
$log->setEnabled(true);
$this->assertTrue($log->isEnabled());
$log->setEnabled(false);
$this->assertFalse($log->isEnabled());
}
public function testGetLevel()
{
$log = new \Slim\Log(new MyWriter());
$this->assertEquals(\Slim\Log::DEBUG, $log->getLevel());
}
public function testSetLevel()
{
$log = new \Slim\Log(new MyWriter());
$log->setLevel(\Slim\Log::WARN);
$this->assertEquals(\Slim\Log::WARN, $log->getLevel());
}
public function testSetInvalidLevel()
{
$this->setExpectedException('InvalidArgumentException');
$log = new \Slim\Log(new MyWriter());
$log->setLevel(\Slim\Log::DEBUG + 1);
}
public function testLogDebug()
{
$this->expectOutputString('Debug');
$log = new \Slim\Log(new MyWriter());
$result = $log->debug('Debug');
$this->assertTrue($result);
}
public function testLogDebugExcludedByLevel()
{
$log = new \Slim\Log(new MyWriter());
$log->setLevel(\Slim\Log::INFO);
$this->assertFalse($log->debug('Debug'));
}
public function testLogInfo()
{
$this->expectOutputString('Info');
$log = new \Slim\Log(new MyWriter());
$result = $log->info('Info');
$this->assertTrue($result);
}
public function testLogInfoExcludedByLevel()
{
$log = new \Slim\Log(new MyWriter());
$log->setLevel(\Slim\Log::NOTICE);
$this->assertFalse($log->info('Info'));
}
public function testLogNotice()
{
$this->expectOutputString('Notice');
$log = new \Slim\Log(new MyWriter());
$result = $log->notice('Notice');
$this->assertTrue($result);
}
public function testLogNoticeExcludedByLevel()
{
$log = new \Slim\Log(new MyWriter());
$log->setLevel(\Slim\Log::WARN);
$this->assertFalse($log->info('Info'));
}
public function testLogWarn()
{
$this->expectOutputString('Warn');
$log = new \Slim\Log(new MyWriter());
$result = $log->warning('Warn');
$this->assertTrue($result);
}
public function testLogWarnExcludedByLevel()
{
$log = new \Slim\Log(new MyWriter());
$log->setLevel(\Slim\Log::ERROR);
$this->assertFalse($log->warning('Warn'));
}
public function testLogError()
{
$this->expectOutputString('Error');
$log = new \Slim\Log(new MyWriter());
$result = $log->error('Error');
$this->assertTrue($result);
}
public function testLogErrorExcludedByLevel()
{
$log = new \Slim\Log(new MyWriter());
$log->setLevel(\Slim\Log::CRITICAL);
$this->assertFalse($log->error('Error'));
}
public function testLogCritical()
{
$this->expectOutputString('Critical');
$log = new \Slim\Log(new MyWriter());
$result = $log->critical('Critical');
$this->assertTrue($result);
}
public function testLogCriticalExcludedByLevel()
{
$log = new \Slim\Log(new MyWriter());
$log->setLevel(\Slim\Log::ALERT);
$this->assertFalse($log->critical('Critical'));
}
public function testLogAlert()
{
$this->expectOutputString('Alert');
$log = new \Slim\Log(new MyWriter());
$result = $log->alert('Alert');
$this->assertTrue($result);
}
public function testLogAlertExcludedByLevel()
{
$log = new \Slim\Log(new MyWriter());
$log->setLevel(\Slim\Log::EMERGENCY);
$this->assertFalse($log->alert('Alert'));
}
public function testLogEmergency()
{
$this->expectOutputString('Emergency');
$log = new \Slim\Log(new MyWriter());
$result = $log->emergency('Emergency');
$this->assertTrue($result);
}
public function testInterpolateMessage()
{
$this->expectOutputString('Hello Slim !');
$log = new \Slim\Log(new MyWriter());
$result = $log->debug(
'Hello {framework} !',
array('framework' => "Slim")
);
$this->assertTrue($result);
}
public function testGetAndSetWriter()
{
$writer1 = new MyWriter();
$writer2 = new MyWriter();
$log = new \Slim\Log($writer1);
$this->assertSame($writer1, $log->getWriter());
$log->setWriter($writer2);
$this->assertSame($writer2, $log->getWriter());
}
}
DEEP.git/Slim/tests/LogWriterTest.php 0000775 0000000 0000000 00000003574 12634026554 0017735 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
*
* 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.
*/
class LogWriterTest extends PHPUnit_Framework_TestCase
{
public function testInstantiation()
{
$this->expectOutputString('Hello!' . PHP_EOL);
$handle = fopen('php://output', 'w');
$fw = new \Slim\LogWriter($handle);
$this->assertTrue($fw->write('Hello!') > 0); //<-- Returns number of bytes written if successful
}
public function testInstantiationWithNonResource()
{
$this->setExpectedException('InvalidArgumentException');
$fw = new \Slim\LogWriter(@fopen('/foo/bar.txt', 'w'));
}
}
DEEP.git/Slim/tests/Middleware/ 0000775 0000000 0000000 00000000000 12634026554 0016507 5 ustar 00root root 0000000 0000000 DEEP.git/Slim/tests/Middleware/ContentTypesTest.php 0000775 0000000 0000000 00000012502 12634026554 0022522 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
*
* 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.
*/
class ContentTypesTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
ob_start();
}
public function tearDown()
{
ob_end_clean();
}
/**
* Test parses JSON
*/
public function testParsesJson()
{
\Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'CONTENT_TYPE' => 'application/json',
'CONENT_LENGTH' => 13,
'slim.input' => '{"foo":"bar"}'
));
$s = new \Slim\Slim();
$s->add(new \Slim\Middleware\ContentTypes());
$s->run();
$body = $s->request()->getBody();
$this->assertTrue(is_array($body));
$this->assertEquals('bar', $body['foo']);
}
/**
* Test ignores JSON with errors
*/
public function testParsesJsonWithError()
{
\Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'CONTENT_TYPE' => 'application/json',
'CONENT_LENGTH' => 12,
'slim.input' => '{"foo":"bar"' //<-- This should be incorrect!
));
$s = new \Slim\Slim();
$s->add(new \Slim\Middleware\ContentTypes());
$s->run();
$body = $s->request()->getBody();
$this->assertTrue(is_string($body));
$this->assertEquals('{"foo":"bar"', $body);
}
/**
* Test parses XML
*/
public function testParsesXml()
{
\Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'CONTENT_TYPE' => 'application/xml',
'CONENT_LENGTH' => 68,
'slim.input' => '1Clive Cussler'
));
$s = new \Slim\Slim();
$s->add(new \Slim\Middleware\ContentTypes());
$s->run();
$body = $s->request()->getBody();
$this->assertInstanceOf('SimpleXMLElement', $body);
$this->assertEquals('Clive Cussler', (string) $body->book->author);
}
/**
* Test ignores XML with errors
*/
public function testParsesXmlWithError()
{
libxml_use_internal_errors(true);
\Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'CONTENT_TYPE' => 'application/xml',
'CONTENT_LENGTH' => 68,
'slim.input' => '1Clive Cussler' //<-- This should be incorrect!
));
$s = new \Slim\Slim();
$s->add(new \Slim\Middleware\ContentTypes());
$s->run();
$body = $s->request()->getBody();
$this->assertTrue(is_string($body));
$this->assertEquals('1Clive Cussler', $body);
}
/**
* Test parses CSV
*/
public function testParsesCsv()
{
\Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'CONTENT_TYPE' => 'text/csv',
'CONTENT_LENGTH' => 44,
'slim.input' => "John,Doe,000-111-2222\nJane,Doe,111-222-3333"
));
$s = new \Slim\Slim();
$s->add(new \Slim\Middleware\ContentTypes());
$s->run();
$body = $s->request()->getBody();
$this->assertTrue(is_array($body));
$this->assertEquals(2, count($body));
$this->assertEquals('000-111-2222', $body[0][2]);
$this->assertEquals('Doe', $body[1][1]);
}
/**
* Test parses request body based on media-type only, disregarding
* any extra content-type header parameters
*/
public function testParsesRequestBodyWithMediaType()
{
\Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4',
'CONTENT_LENGTH' => 13,
'slim.input' => '{"foo":"bar"}'
));
$s = new \Slim\Slim();
$s->add(new \Slim\Middleware\ContentTypes());
$s->run();
$body = $s->request()->getBody();
$this->assertTrue(is_array($body));
$this->assertEquals('bar', $body['foo']);
}
}
DEEP.git/Slim/tests/Middleware/FlashTest.php 0000775 0000000 0000000 00000010145 12634026554 0021121 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
*
* 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.
*/
class SlimFlashTest extends PHPUnit_Framework_TestCase
{
/**
* Setup
*/
public function setUp()
{
$_SESSION = array();
}
/**
* Test set flash message for next request
*/
public function testSetFlashForNextRequest()
{
$f = new \Slim\Middleware\Flash();
$f->set('foo', 'bar');
$f->save();
$this->assertEquals('bar', $_SESSION['slim.flash']['foo']);
}
/**
* Test set flash message for current request
*/
public function testSetFlashForCurrentRequest()
{
$f = new \Slim\Middleware\Flash();
$f->now('foo', 'bar');
$this->assertEquals('bar', $f['foo']);
}
/**
* Test loads flash from previous request
*/
public function testLoadsFlashFromPreviousRequest()
{
$_SESSION['slim.flash'] = array('info' => 'foo');
$f = new \Slim\Middleware\Flash();
$f->loadMessages();
$this->assertEquals('foo', $f['info']);
}
/**
* Test keep flash message for next request
*/
public function testKeepFlashFromPreviousRequest()
{
$_SESSION['slim.flash'] = array('info' => 'foo');
$f = new \Slim\Middleware\Flash();
$f->loadMessages();
$f->keep();
$f->save();
$this->assertEquals('foo', $_SESSION['slim.flash']['info']);
}
/**
* Test flash messages from previous request do not persist to next request
*/
public function testFlashMessagesFromPreviousRequestDoNotPersist()
{
$_SESSION['slim.flash'] = array('info' => 'foo');
$f = new \Slim\Middleware\Flash();
$f->save();
$this->assertEmpty($_SESSION['slim.flash']);
}
/**
* Test set Flash using array access
*/
public function testFlashArrayAccess()
{
$_SESSION['slim.flash'] = array('info' => 'foo');
$f = new \Slim\Middleware\Flash();
$f['info'] = 'bar';
$f->save();
$this->assertTrue(isset($f['info']));
$this->assertEquals('bar', $f['info']);
unset($f['info']);
$this->assertFalse(isset($f['info']));
}
/**
* Test iteration
*/
public function testIteration()
{
$_SESSION['slim.flash'] = array('info' => 'foo', 'error' => 'bar');
$f = new \Slim\Middleware\Flash();
$f->loadMessages();
$output = '';
foreach ($f as $key => $value) {
$output .= $key . $value;
}
$this->assertEquals('infofooerrorbar', $output);
}
/**
* Test countable
*/
public function testCountable()
{
$_SESSION['slim.flash'] = array('info' => 'foo', 'error' => 'bar');
$f = new \Slim\MiddleWare\Flash();
$f->loadMessages();
$this->assertEquals(2, count($f));
}
}
DEEP.git/Slim/tests/Middleware/MethodOverrideTest.php 0000775 0000000 0000000 00000012042 12634026554 0023002 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
*
* 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.
*/
/**
* We use a mock application, instead of a Slim application.
* so that we may easily test the Method Override middleware
* in isolation.
*/
class CustomAppMethod
{
protected $environment;
public function __construct()
{
$this->environment = \Slim\Environment::getInstance();
}
public function &environment() {
return $this->environment;
}
public function call()
{
//Do nothing
}
}
class MethodOverrideTest extends PHPUnit_Framework_TestCase
{
/**
* Test overrides method as POST
*/
public function testOverrideMethodAsPost()
{
\Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
'CONTENT_LENGTH' => 11,
'slim.input' => '_METHOD=PUT'
));
$app = new CustomAppMethod();
$mw = new \Slim\Middleware\MethodOverride();
$mw->setApplication($app);
$mw->setNextMiddleware($app);
$mw->call();
$env =& $app->environment();
$this->assertEquals('PUT', $env['REQUEST_METHOD']);
$this->assertTrue(isset($env['slim.method_override.original_method']));
$this->assertEquals('POST', $env['slim.method_override.original_method']);
}
/**
* Test does not override method if not POST
*/
public function testDoesNotOverrideMethodIfNotPost()
{
\Slim\Environment::mock(array(
'REQUEST_METHOD' => 'GET',
'slim.input' => ''
));
$app = new CustomAppMethod();
$mw = new \Slim\Middleware\MethodOverride();
$mw->setApplication($app);
$mw->setNextMiddleware($app);
$mw->call();
$env =& $app->environment();
$this->assertEquals('GET', $env['REQUEST_METHOD']);
$this->assertFalse(isset($env['slim.method_override.original_method']));
}
/**
* Test does not override method if no method override parameter
*/
public function testDoesNotOverrideMethodAsPostWithoutParameter()
{
\Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'REMOTE_ADDR' => '127.0.0.1',
'SCRIPT_NAME' => '/foo/index.php', //<-- Physical
'PATH_INFO' => '/bar', //<-- Virtual
'QUERY_STRING' => 'foo=bar',
'SERVER_NAME' => 'slim',
'SERVER_PORT' => 80,
'slim.url_scheme' => 'http',
'slim.input' => '',
'slim.errors' => fopen('php://stderr', 'w')
));
$app = new CustomAppMethod();
$mw = new \Slim\Middleware\MethodOverride();
$mw->setApplication($app);
$mw->setNextMiddleware($app);
$mw->call();
$env =& $app->environment();
$this->assertEquals('POST', $env['REQUEST_METHOD']);
$this->assertFalse(isset($env['slim.method_override.original_method']));
}
/**
* Test overrides method with X-Http-Method-Override header
*/
public function testOverrideMethodAsHeader()
{
\Slim\Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'CONTENT_TYPE' => 'application/json',
'CONTENT_LENGTH' => 0,
'slim.input' => '',
'HTTP_X_HTTP_METHOD_OVERRIDE' => 'DELETE'
));
$app = new CustomAppMethod();
$mw = new \Slim\Middleware\MethodOverride();
$mw->setApplication($app);
$mw->setNextMiddleware($app);
$mw->call();
$env =& $app->environment();
$this->assertEquals('DELETE', $env['REQUEST_METHOD']);
$this->assertTrue(isset($env['slim.method_override.original_method']));
$this->assertEquals('POST', $env['slim.method_override.original_method']);
}
}
DEEP.git/Slim/tests/Middleware/PrettyExceptionsTest.php 0000775 0000000 0000000 00000012243 12634026554 0023416 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
*
* 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.
*/
class PrettyExceptionsTest extends PHPUnit_Framework_TestCase
{
/**
* Test middleware returns successful response unchanged
*/
public function testReturnsUnchangedSuccessResponse()
{
\Slim\Environment::mock(array(
'SCRIPT_NAME' => '/index.php',
'PATH_INFO' => '/foo'
));
$app = new \Slim\Slim();
$app->get('/foo', function () {
echo "Success";
});
$mw = new \Slim\Middleware\PrettyExceptions();
$mw->setApplication($app);
$mw->setNextMiddleware($app);
$mw->call();
$this->assertEquals(200, $app->response()->status());
$this->assertEquals('Success', $app->response()->body());
}
/**
* Test middleware returns diagnostic screen for error response
*/
public function testReturnsDiagnosticsForErrorResponse()
{
\Slim\Environment::mock(array(
'SCRIPT_NAME' => '/index.php',
'PATH_INFO' => '/foo'
));
$app = new \Slim\Slim(array(
'log.enabled' => false
));
$app->get('/foo', function () {
throw new \Exception('Test Message', 100);
});
$mw = new \Slim\Middleware\PrettyExceptions();
$mw->setApplication($app);
$mw->setNextMiddleware($app);
$mw->call();
$this->assertEquals(1, preg_match('@Slim Application Error@', $app->response()->body()));
$this->assertEquals(500, $app->response()->status());
}
/**
* Test middleware overrides response content type to html
*/
public function testResponseContentTypeIsOverriddenToHtml()
{
\Slim\Environment::mock(array(
'SCRIPT_NAME' => '/index.php',
'PATH_INFO' => '/foo'
));
$app = new \Slim\Slim(array(
'log.enabled' => false
));
$app->get('/foo', function () use ($app) {
$app->contentType('application/json;charset=utf-8'); //<-- set content type to something else
throw new \Exception('Test Message', 100);
});
$mw = new \Slim\Middleware\PrettyExceptions();
$mw->setApplication($app);
$mw->setNextMiddleware($app);
$mw->call();
$response = $app->response();
$this->assertEquals('text/html', $response['Content-Type']);
}
/**
* Test exception type is in response body
*/
public function testExceptionTypeIsInResponseBody()
{
\Slim\Environment::mock(array(
'SCRIPT_NAME' => '/index.php',
'PATH_INFO' => '/foo'
));
$app = new \Slim\Slim(array(
'log.enabled' => false
));
$app->get('/foo', function () use ($app) {
throw new \LogicException('Test Message', 100);
});
$mw = new \Slim\Middleware\PrettyExceptions();
$mw->setApplication($app);
$mw->setNextMiddleware($app);
$mw->call();
$this->assertContains('LogicException', $app->response()->body());
}
/**
* Test with custom log
*/
public function testWithCustomLogWriter()
{
$this->setExpectedException('\LogicException');
\Slim\Environment::mock(array(
'SCRIPT_NAME' => '/index.php',
'PATH_INFO' => '/foo'
));
$app = new \Slim\Slim(array(
'log.enabled' => false
));
$app->container->singleton('log', function () use ($app) {
return new \Slim\Log(new \Slim\LogWriter('php://temp'));
});
$app->get('/foo', function () use ($app) {
throw new \LogicException('Test Message', 100);
});
$mw = new \Slim\Middleware\PrettyExceptions();
$mw->setApplication($app);
$mw->setNextMiddleware($app);
$mw->call();
$this->assertContains('LogicException', $app->response()->body());
}
}
DEEP.git/Slim/tests/Middleware/SessionCookieTest.php 0000775 0000000 0000000 00000031127 12634026554 0022644 0 ustar 00root root 0000000 0000000
* @copyright 2011 Josh Lockhart
* @link http://www.slimframework.com
* @license http://www.slimframework.com/license
* @version 2.6.1
*
* 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.
*/
class SessionCookieTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$_SESSION = array();
}
/**
* Test session cookie is set and constructed correctly
*
* We test for two things:
*
* 1) That the HTTP cookie exists with the correct name;
* 2) That the HTTP cookie's value is the expected value;
*/
public function testSessionCookieIsCreated()
{
\Slim\Environment::mock(array(
'SCRIPT_NAME' => '/index.php',
'PATH_INFO' => '/foo'
));
$app = new \Slim\Slim();
$app->get('/foo', function () {
$_SESSION['foo'] = 'bar';
echo "Success";
});
$mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years'));
$mw->setApplication($app);
$mw->setNextMiddleware($app);
$mw->call();
list($status, $header, $body) = $app->response()->finalize();
$this->assertTrue($app->response->cookies->has('slim_session'));
$cookie = $app->response->cookies->get('slim_session');
$this->assertEquals('{"foo":"bar"}', $cookie['value']);
}
/**
* Test $_SESSION is populated from an encrypted HTTP cookie
*
* The encrypted cookie contains the serialized array ['foo' => 'bar']. The
* global secret, cipher, and cipher mode are assumed to be the default
* values.
*/
// public function testSessionIsPopulatedFromEncryptedCookie()
// {
// \Slim\Environment::mock(array(
// 'SCRIPT_NAME' => '/index.php',
// 'PATH_INFO' => '/foo',
// 'HTTP_COOKIE' => 'slim_session=1644004961%7CLKkYPwqKIMvBK7MWl6D%2BxeuhLuMaW4quN%2F512ZAaVIY%3D%7Ce0f007fa852c7101e8224bb529e26be4d0dfbd63',
// ));
// $app = new \Slim\Slim();
// // The cookie value in the test is encrypted, so cookies.encrypt must
// // be set to true
// $app->config('cookies.encrypt', true);
// $app->get('/foo', function () {
// echo "Success";
// });
// $mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years'));
// $mw->setApplication($app);
// $mw->setNextMiddleware($app);
// $mw->call();
// $this->assertEquals(array('foo' => 'bar'), $_SESSION);
// }
/**
* Test $_SESSION is populated from an unencrypted HTTP cookie
*
* The unencrypted cookie contains the serialized array ['foo' => 'bar'].
* The global cookies.encrypt setting is set to false
*/
public function testSessionIsPopulatedFromUnencryptedCookie()
{
\Slim\Environment::mock(array(
'SCRIPT_NAME' => '/index.php',
'PATH_INFO' => '/foo',
'HTTP_COOKIE' => 'slim_session={"foo":"bar"}',
));
$app = new \Slim\Slim();
// The cookie value in the test is unencrypted, so cookies.encrypt must
// be set to false
$app->config('cookies.encrypt', false);
$app->get('/foo', function () {
echo "Success";
});
$mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years'));
$mw->setApplication($app);
$mw->setNextMiddleware($app);
$mw->call();
$this->assertEquals(array('foo' => 'bar'), $_SESSION);
}
/**
* Test $_SESSION is populated from an unencrypted HTTP cookie
*
* The unencrypted cookie contains the serialized array ['foo' => 'bar'].
* The global cookies.encrypt setting is set to false
*/
public function testSessionIsPopulatedFromMalformedCookieData()
{
\Slim\Environment::mock(array(
'SCRIPT_NAME' => '/index.php',
'PATH_INFO' => '/foo',
'HTTP_COOKIE' => 'slim_session={"foo":"bar"sdkhguy5y}',
));
$app = new \Slim\Slim();
// The cookie value in the test is unencrypted, so cookies.encrypt must
// be set to false
$app->config('cookies.encrypt', false);
$app->get('/foo', function () {
echo "Success";
});
$mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years'));
$mw->setApplication($app);
$mw->setNextMiddleware($app);
$mw->call();
$this->assertEquals(array(), $_SESSION);
}
/**
* Test $_SESSION is populated as empty array if no HTTP cookie
*/
public function testSessionIsPopulatedAsEmptyIfNoCookie()
{
\Slim\Environment::mock(array(
'SCRIPT_NAME' => '/index.php',
'PATH_INFO' => '/foo'
));
$app = new \Slim\Slim();
$app->get('/foo', function () {
echo "Success";
});
$mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years'));
$mw->setApplication($app);
$mw->setNextMiddleware($app);
$mw->call();
$this->assertEquals(array(), $_SESSION);
}
public function testSerializingTooLongValueWritesLogAndDoesntCreateCookie()
{
\Slim\Environment::mock(array(
'SCRIPT_NAME' => '/index.php',
'PATH_INFO' => '/foo'
));
$logWriter = $this->getMockBuilder('Slim\LogWriter')
->disableOriginalConstructor()
->getMock();
$logWriter->expects($this->once())
->method('write')
->with('WARNING! Slim\Middleware\SessionCookie data size is larger than 4KB. Content save failed.', \Slim\Log::ERROR);
$app = new \Slim\Slim(array(
'log.writer' => $logWriter
));
$tooLongValue = $this->getTooLongValue();
$app->get('/foo', function () use ($tooLongValue) {
$_SESSION['test'] = $tooLongValue;
echo "Success";
});
$mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years'));
$mw->setApplication($app);
$mw->setNextMiddleware($app);
$mw->call();
list($status, $header, $body) = $app->response()->finalize();
$this->assertFalse($app->response->cookies->has('slim_session'));
}
/**
* Generated by http://www.random.org/strings/
*/
protected function getTooLongValue()
{
return <<