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