├── .gitignore ├── README.md ├── Slim ├── Environment.php ├── Exception │ ├── Pass.php │ └── Stop.php ├── Http │ ├── Headers.php │ ├── Request.php │ ├── Response.php │ └── Util.php ├── Log.php ├── LogWriter.php ├── Middleware.php ├── Middleware │ ├── ContentTypes.php │ ├── Flash.php │ ├── MethodOverride.php │ ├── PrettyExceptions.php │ └── SessionCookie.php ├── Route.php ├── Router.php ├── Slim.php └── View.php ├── api ├── .htaccess ├── db.sqlite3 └── index.php ├── css ├── app.css └── bootstrap.min.css ├── icons └── .gitignore ├── img ├── glyphicons-halflings-white.png └── glyphicons-halflings.png ├── index.html ├── js └── app.js └── partials ├── add.html ├── edit.html └── list.html /.gitignore: -------------------------------------------------------------------------------- 1 | api/db.sqlite3 2 | icons/*.ico 3 | idea/* -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | AngularJSTutorialApp 2 | ==================== 3 | 4 | Simple AngluarJS bookmark app tutorial with a Slim php backend. -------------------------------------------------------------------------------- /Slim/Environment.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim; 34 | 35 | /** 36 | * Environment 37 | * 38 | * This class creates and returns a key/value array of common 39 | * environment variables for the current HTTP request. 40 | * 41 | * This is a singleton class; derived environment variables will 42 | * be common across multiple Slim applications. 43 | * 44 | * This class matches the Rack (Ruby) specification as closely 45 | * as possible. More information available below. 46 | * 47 | * @package Slim 48 | * @author Josh Lockhart 49 | * @since 1.6.0 50 | */ 51 | class Environment implements \ArrayAccess, \IteratorAggregate 52 | { 53 | /** 54 | * @var array 55 | */ 56 | protected $properties; 57 | 58 | /** 59 | * @var \Slim\Environment 60 | */ 61 | protected static $environment; 62 | 63 | /** 64 | * Get environment instance (singleton) 65 | * 66 | * This creates and/or returns an environment instance (singleton) 67 | * derived from $_SERVER variables. You may override the global server 68 | * variables by using `\Slim\Environment::mock()` instead. 69 | * 70 | * @param bool $refresh Refresh properties using global server variables? 71 | * @return \Slim\Environment 72 | */ 73 | public static function getInstance($refresh = false) 74 | { 75 | if (is_null(self::$environment) || $refresh) { 76 | self::$environment = new self(); 77 | } 78 | 79 | return self::$environment; 80 | } 81 | 82 | /** 83 | * Get mock environment instance 84 | * 85 | * @param array $userSettings 86 | * @return \Slim\Environment 87 | */ 88 | public static function mock($userSettings = array()) 89 | { 90 | self::$environment = new self(array_merge(array( 91 | 'REQUEST_METHOD' => 'GET', 92 | 'SCRIPT_NAME' => '', 93 | 'PATH_INFO' => '', 94 | 'QUERY_STRING' => '', 95 | 'SERVER_NAME' => 'localhost', 96 | 'SERVER_PORT' => 80, 97 | 'ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 98 | 'ACCEPT_LANGUAGE' => 'en-US,en;q=0.8', 99 | 'ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 100 | 'USER_AGENT' => 'Slim Framework', 101 | 'REMOTE_ADDR' => '127.0.0.1', 102 | 'slim.url_scheme' => 'http', 103 | 'slim.input' => '', 104 | 'slim.errors' => @fopen('php://stderr', 'w') 105 | ), $userSettings)); 106 | 107 | return self::$environment; 108 | } 109 | 110 | /** 111 | * Constructor (private access) 112 | * 113 | * @param array|null $settings If present, these are used instead of global server variables 114 | */ 115 | private function __construct($settings = null) 116 | { 117 | if ($settings) { 118 | $this->properties = $settings; 119 | } else { 120 | $env = array(); 121 | 122 | //The HTTP request method 123 | $env['REQUEST_METHOD'] = $_SERVER['REQUEST_METHOD']; 124 | 125 | //The IP 126 | $env['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']; 127 | 128 | /** 129 | * Application paths 130 | * 131 | * This derives two paths: SCRIPT_NAME and PATH_INFO. The SCRIPT_NAME 132 | * is the real, physical path to the application, be it in the root 133 | * directory or a subdirectory of the public document root. The PATH_INFO is the 134 | * virtual path to the requested resource within the application context. 135 | * 136 | * With htaccess, the SCRIPT_NAME will be an absolute path (without file name); 137 | * if not using htaccess, it will also include the file name. If it is "/", 138 | * it is set to an empty string (since it cannot have a trailing slash). 139 | * 140 | * The PATH_INFO will be an absolute path with a leading slash; this will be 141 | * used for application routing. 142 | */ 143 | if (strpos($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME']) === 0) { 144 | $env['SCRIPT_NAME'] = $_SERVER['SCRIPT_NAME']; //Without URL rewrite 145 | } else { 146 | $env['SCRIPT_NAME'] = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])); //With URL rewrite 147 | } 148 | $env['PATH_INFO'] = substr_replace($_SERVER['REQUEST_URI'], '', 0, strlen($env['SCRIPT_NAME'])); 149 | if (strpos($env['PATH_INFO'], '?') !== false) { 150 | $env['PATH_INFO'] = substr_replace($env['PATH_INFO'], '', strpos($env['PATH_INFO'], '?')); //query string is not removed automatically 151 | } 152 | $env['SCRIPT_NAME'] = rtrim($env['SCRIPT_NAME'], '/'); 153 | $env['PATH_INFO'] = '/' . ltrim($env['PATH_INFO'], '/'); 154 | 155 | //The portion of the request URI following the '?' 156 | $env['QUERY_STRING'] = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''; 157 | 158 | //Name of server host that is running the script 159 | $env['SERVER_NAME'] = $_SERVER['SERVER_NAME']; 160 | 161 | //Number of server port that is running the script 162 | $env['SERVER_PORT'] = $_SERVER['SERVER_PORT']; 163 | 164 | //HTTP request headers 165 | $specialHeaders = array('CONTENT_TYPE', 'CONTENT_LENGTH', 'PHP_AUTH_USER', 'PHP_AUTH_PW', 'PHP_AUTH_DIGEST', 'AUTH_TYPE'); 166 | foreach ($_SERVER as $key => $value) { 167 | $value = is_string($value) ? trim($value) : $value; 168 | if (strpos($key, 'HTTP_') === 0) { 169 | $env[substr($key, 5)] = $value; 170 | } elseif (strpos($key, 'X_') === 0 || in_array($key, $specialHeaders)) { 171 | $env[$key] = $value; 172 | } 173 | } 174 | 175 | //Is the application running under HTTPS or HTTP protocol? 176 | $env['slim.url_scheme'] = empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' ? 'http' : 'https'; 177 | 178 | //Input stream (readable one time only; not available for mutipart/form-data requests) 179 | $rawInput = @file_get_contents('php://input'); 180 | if (!$rawInput) { 181 | $rawInput = ''; 182 | } 183 | $env['slim.input'] = $rawInput; 184 | 185 | //Error stream 186 | $env['slim.errors'] = fopen('php://stderr', 'w'); 187 | 188 | $this->properties = $env; 189 | } 190 | } 191 | 192 | /** 193 | * Array Access: Offset Exists 194 | */ 195 | public function offsetExists($offset) 196 | { 197 | return isset($this->properties[$offset]); 198 | } 199 | 200 | /** 201 | * Array Access: Offset Get 202 | */ 203 | public function offsetGet($offset) 204 | { 205 | if (isset($this->properties[$offset])) { 206 | return $this->properties[$offset]; 207 | } else { 208 | return null; 209 | } 210 | } 211 | 212 | /** 213 | * Array Access: Offset Set 214 | */ 215 | public function offsetSet($offset, $value) 216 | { 217 | $this->properties[$offset] = $value; 218 | } 219 | 220 | /** 221 | * Array Access: Offset Unset 222 | */ 223 | public function offsetUnset($offset) 224 | { 225 | unset($this->properties[$offset]); 226 | } 227 | 228 | /** 229 | * IteratorAggregate 230 | * 231 | * @return \ArrayIterator 232 | */ 233 | public function getIterator() 234 | { 235 | return new \ArrayIterator($this->properties); 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /Slim/Exception/Pass.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim\Exception; 34 | 35 | /** 36 | * Pass Exception 37 | * 38 | * This Exception will cause the Router::dispatch method 39 | * to skip the current matching route and continue to the next 40 | * matching route. If no subsequent routes are found, a 41 | * HTTP 404 Not Found response will be sent to the client. 42 | * 43 | * @package Slim 44 | * @author Josh Lockhart 45 | * @since 1.0.0 46 | */ 47 | class Pass extends \Exception 48 | { 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Slim/Exception/Stop.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim\Exception; 34 | 35 | /** 36 | * Stop Exception 37 | * 38 | * This Exception is thrown when the Slim application needs to abort 39 | * processing and return control flow to the outer PHP script. 40 | * 41 | * @package Slim 42 | * @author Josh Lockhart 43 | * @since 1.0.0 44 | */ 45 | class Stop extends \Exception 46 | { 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Slim/Http/Headers.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim\Http; 34 | 35 | /** 36 | * HTTP Headers 37 | * 38 | * This class is an abstraction of the HTTP response headers and 39 | * provides array access to the header list while automatically 40 | * stores and retrieves headers with lowercase canonical keys regardless 41 | * of the input format. 42 | * 43 | * This class also implements the `Iterator` and `Countable` 44 | * interfaces for even more convenient usage. 45 | * 46 | * @package Slim 47 | * @author Josh Lockhart 48 | * @since 1.6.0 49 | */ 50 | class Headers implements \ArrayAccess, \Iterator, \Countable 51 | { 52 | /** 53 | * @var array HTTP headers 54 | */ 55 | protected $headers; 56 | 57 | /** 58 | * @var array Map canonical header name to original header name 59 | */ 60 | protected $map; 61 | 62 | /** 63 | * Constructor 64 | * @param array $headers 65 | */ 66 | public function __construct($headers = array()) 67 | { 68 | $this->merge($headers); 69 | } 70 | 71 | /** 72 | * Merge Headers 73 | * @param array $headers 74 | */ 75 | public function merge($headers) 76 | { 77 | foreach ($headers as $name => $value) { 78 | $this[$name] = $value; 79 | } 80 | } 81 | 82 | /** 83 | * Transform header name into canonical form 84 | * @param string $name 85 | * @return string 86 | */ 87 | protected function canonical($name) 88 | { 89 | return strtolower(trim($name)); 90 | } 91 | 92 | /** 93 | * Array Access: Offset Exists 94 | */ 95 | public function offsetExists($offset) 96 | { 97 | return isset($this->headers[$this->canonical($offset)]); 98 | } 99 | 100 | /** 101 | * Array Access: Offset Get 102 | */ 103 | public function offsetGet($offset) 104 | { 105 | $canonical = $this->canonical($offset); 106 | if (isset($this->headers[$canonical])) { 107 | return $this->headers[$canonical]; 108 | } else { 109 | return null; 110 | } 111 | } 112 | 113 | /** 114 | * Array Access: Offset Set 115 | */ 116 | public function offsetSet($offset, $value) 117 | { 118 | $canonical = $this->canonical($offset); 119 | $this->headers[$canonical] = $value; 120 | $this->map[$canonical] = $offset; 121 | } 122 | 123 | /** 124 | * Array Access: Offset Unset 125 | */ 126 | public function offsetUnset($offset) 127 | { 128 | $canonical = $this->canonical($offset); 129 | unset($this->headers[$canonical], $this->map[$canonical]); 130 | } 131 | 132 | /** 133 | * Countable: Count 134 | */ 135 | public function count() 136 | { 137 | return count($this->headers); 138 | } 139 | 140 | /** 141 | * Iterator: Rewind 142 | */ 143 | public function rewind() 144 | { 145 | reset($this->headers); 146 | } 147 | 148 | /** 149 | * Iterator: Current 150 | */ 151 | public function current() 152 | { 153 | return current($this->headers); 154 | } 155 | 156 | /** 157 | * Iterator: Key 158 | */ 159 | public function key() 160 | { 161 | $key = key($this->headers); 162 | 163 | return $this->map[$key]; 164 | } 165 | 166 | /** 167 | * Iterator: Next 168 | */ 169 | public function next() 170 | { 171 | return next($this->headers); 172 | } 173 | 174 | /** 175 | * Iterator: Valid 176 | */ 177 | public function valid() 178 | { 179 | return current($this->headers) !== false; 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /Slim/Http/Request.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim\Http; 34 | 35 | /** 36 | * Slim HTTP Request 37 | * 38 | * This class provides a human-friendly interface to the Slim environment variables; 39 | * environment variables are passed by reference and will be modified directly. 40 | * 41 | * @package Slim 42 | * @author Josh Lockhart 43 | * @since 1.0.0 44 | */ 45 | class Request 46 | { 47 | const METHOD_HEAD = 'HEAD'; 48 | const METHOD_GET = 'GET'; 49 | const METHOD_POST = 'POST'; 50 | const METHOD_PUT = 'PUT'; 51 | const METHOD_DELETE = 'DELETE'; 52 | const METHOD_OPTIONS = 'OPTIONS'; 53 | const METHOD_OVERRIDE = '_METHOD'; 54 | 55 | /** 56 | * @var array 57 | */ 58 | protected static $formDataMediaTypes = array('application/x-www-form-urlencoded'); 59 | 60 | /** 61 | * @var array 62 | */ 63 | protected $env; 64 | 65 | /** 66 | * Constructor 67 | * @param array $env 68 | * @see \Slim\Environment 69 | */ 70 | public function __construct($env) 71 | { 72 | $this->env = $env; 73 | } 74 | 75 | /** 76 | * Get HTTP method 77 | * @return string 78 | */ 79 | public function getMethod() 80 | { 81 | return $this->env['REQUEST_METHOD']; 82 | } 83 | 84 | /** 85 | * Is this a GET request? 86 | * @return bool 87 | */ 88 | public function isGet() 89 | { 90 | return $this->getMethod() === self::METHOD_GET; 91 | } 92 | 93 | /** 94 | * Is this a POST request? 95 | * @return bool 96 | */ 97 | public function isPost() 98 | { 99 | return $this->getMethod() === self::METHOD_POST; 100 | } 101 | 102 | /** 103 | * Is this a PUT request? 104 | * @return bool 105 | */ 106 | public function isPut() 107 | { 108 | return $this->getMethod() === self::METHOD_PUT; 109 | } 110 | 111 | /** 112 | * Is this a DELETE request? 113 | * @return bool 114 | */ 115 | public function isDelete() 116 | { 117 | return $this->getMethod() === self::METHOD_DELETE; 118 | } 119 | 120 | /** 121 | * Is this a HEAD request? 122 | * @return bool 123 | */ 124 | public function isHead() 125 | { 126 | return $this->getMethod() === self::METHOD_HEAD; 127 | } 128 | 129 | /** 130 | * Is this a OPTIONS request? 131 | * @return bool 132 | */ 133 | public function isOptions() 134 | { 135 | return $this->getMethod() === self::METHOD_OPTIONS; 136 | } 137 | 138 | /** 139 | * Is this an AJAX request? 140 | * @return bool 141 | */ 142 | public function isAjax() 143 | { 144 | if ($this->params('isajax')) { 145 | return true; 146 | } elseif (isset($this->env['X_REQUESTED_WITH']) && $this->env['X_REQUESTED_WITH'] === 'XMLHttpRequest') { 147 | return true; 148 | } else { 149 | return false; 150 | } 151 | } 152 | 153 | /** 154 | * Is this an XHR request? (alias of Slim_Http_Request::isAjax) 155 | * @return bool 156 | */ 157 | public function isXhr() 158 | { 159 | return $this->isAjax(); 160 | } 161 | 162 | /** 163 | * Fetch GET and POST data 164 | * 165 | * This method returns a union of GET and POST data as a key-value array, or the value 166 | * of the array key if requested; if the array key does not exist, NULL is returned. 167 | * 168 | * @param string $key 169 | * @return array|mixed|null 170 | */ 171 | public function params($key = null) 172 | { 173 | $union = array_merge($this->get(), $this->post()); 174 | if ($key) { 175 | if (isset($union[$key])) { 176 | return $union[$key]; 177 | } else { 178 | return null; 179 | } 180 | } else { 181 | return $union; 182 | } 183 | } 184 | 185 | /** 186 | * Fetch GET data 187 | * 188 | * This method returns a key-value array of data sent in the HTTP request query string, or 189 | * the value of the array key if requested; if the array key does not exist, NULL is returned. 190 | * 191 | * @param string $key 192 | * @return array|mixed|null 193 | */ 194 | public function get($key = null) 195 | { 196 | if (!isset($this->env['slim.request.query_hash'])) { 197 | $output = array(); 198 | if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) { 199 | mb_parse_str($this->env['QUERY_STRING'], $output); 200 | } else { 201 | parse_str($this->env['QUERY_STRING'], $output); 202 | } 203 | $this->env['slim.request.query_hash'] = Util::stripSlashesIfMagicQuotes($output); 204 | } 205 | if ($key) { 206 | if (isset($this->env['slim.request.query_hash'][$key])) { 207 | return $this->env['slim.request.query_hash'][$key]; 208 | } else { 209 | return null; 210 | } 211 | } else { 212 | return $this->env['slim.request.query_hash']; 213 | } 214 | } 215 | 216 | /** 217 | * Fetch POST data 218 | * 219 | * This method returns a key-value array of data sent in the HTTP request body, or 220 | * the value of a hash key if requested; if the array key does not exist, NULL is returned. 221 | * 222 | * @param string $key 223 | * @return array|mixed|null 224 | * @throws \RuntimeException If environment input is not available 225 | */ 226 | public function post($key = null) 227 | { 228 | if (!isset($this->env['slim.input'])) { 229 | throw new \RuntimeException('Missing slim.input in environment variables'); 230 | } 231 | if (!isset($this->env['slim.request.form_hash'])) { 232 | $this->env['slim.request.form_hash'] = array(); 233 | if ($this->isFormData() && is_string($this->env['slim.input'])) { 234 | $output = array(); 235 | if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) { 236 | mb_parse_str($this->env['slim.input'], $output); 237 | } else { 238 | parse_str($this->env['slim.input'], $output); 239 | } 240 | $this->env['slim.request.form_hash'] = Util::stripSlashesIfMagicQuotes($output); 241 | } else { 242 | $this->env['slim.request.form_hash'] = Util::stripSlashesIfMagicQuotes($_POST); 243 | } 244 | } 245 | if ($key) { 246 | if (isset($this->env['slim.request.form_hash'][$key])) { 247 | return $this->env['slim.request.form_hash'][$key]; 248 | } else { 249 | return null; 250 | } 251 | } else { 252 | return $this->env['slim.request.form_hash']; 253 | } 254 | } 255 | 256 | /** 257 | * Fetch PUT data (alias for \Slim\Http\Request::post) 258 | * @param string $key 259 | * @return array|mixed|null 260 | */ 261 | public function put($key = null) 262 | { 263 | return $this->post($key); 264 | } 265 | 266 | /** 267 | * Fetch DELETE data (alias for \Slim\Http\Request::post) 268 | * @param string $key 269 | * @return array|mixed|null 270 | */ 271 | public function delete($key = null) 272 | { 273 | return $this->post($key); 274 | } 275 | 276 | /** 277 | * Fetch COOKIE data 278 | * 279 | * This method returns a key-value array of Cookie data sent in the HTTP request, or 280 | * the value of a array key if requested; if the array key does not exist, NULL is returned. 281 | * 282 | * @param string $key 283 | * @return array|string|null 284 | */ 285 | public function cookies($key = null) 286 | { 287 | if (!isset($this->env['slim.request.cookie_hash'])) { 288 | $cookieHeader = isset($this->env['COOKIE']) ? $this->env['COOKIE'] : ''; 289 | $this->env['slim.request.cookie_hash'] = Util::parseCookieHeader($cookieHeader); 290 | } 291 | if ($key) { 292 | if (isset($this->env['slim.request.cookie_hash'][$key])) { 293 | return $this->env['slim.request.cookie_hash'][$key]; 294 | } else { 295 | return null; 296 | } 297 | } else { 298 | return $this->env['slim.request.cookie_hash']; 299 | } 300 | } 301 | 302 | /** 303 | * Does the Request body contain parseable form data? 304 | * @return bool 305 | */ 306 | public function isFormData() 307 | { 308 | $method = isset($this->env['slim.method_override.original_method']) ? $this->env['slim.method_override.original_method'] : $this->getMethod(); 309 | 310 | return ($method === self::METHOD_POST && is_null($this->getContentType())) || in_array($this->getMediaType(), self::$formDataMediaTypes); 311 | } 312 | 313 | /** 314 | * Get Headers 315 | * 316 | * This method returns a key-value array of headers sent in the HTTP request, or 317 | * the value of a hash key if requested; if the array key does not exist, NULL is returned. 318 | * 319 | * @param string $key 320 | * @param mixed $default The default value returned if the requested header is not available 321 | * @return mixed 322 | */ 323 | public function headers($key = null, $default = null) 324 | { 325 | if ($key) { 326 | $key = strtoupper($key); 327 | $key = str_replace('-', '_', $key); 328 | $key = preg_replace('@^HTTP_@', '', $key); 329 | if (isset($this->env[$key])) { 330 | return $this->env[$key]; 331 | } else { 332 | return $default; 333 | } 334 | } else { 335 | $headers = array(); 336 | foreach ($this->env as $key => $value) { 337 | if (strpos($key, 'slim.') !== 0) { 338 | $headers[$key] = $value; 339 | } 340 | } 341 | 342 | return $headers; 343 | } 344 | } 345 | 346 | /** 347 | * Get Body 348 | * @return string 349 | */ 350 | public function getBody() 351 | { 352 | return $this->env['slim.input']; 353 | } 354 | 355 | /** 356 | * Get Content Type 357 | * @return string 358 | */ 359 | public function getContentType() 360 | { 361 | if (isset($this->env['CONTENT_TYPE'])) { 362 | return $this->env['CONTENT_TYPE']; 363 | } else { 364 | return null; 365 | } 366 | } 367 | 368 | /** 369 | * Get Media Type (type/subtype within Content Type header) 370 | * @return string|null 371 | */ 372 | public function getMediaType() 373 | { 374 | $contentType = $this->getContentType(); 375 | if ($contentType) { 376 | $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); 377 | 378 | return strtolower($contentTypeParts[0]); 379 | } else { 380 | return null; 381 | } 382 | } 383 | 384 | /** 385 | * Get Media Type Params 386 | * @return array 387 | */ 388 | public function getMediaTypeParams() 389 | { 390 | $contentType = $this->getContentType(); 391 | $contentTypeParams = array(); 392 | if ($contentType) { 393 | $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); 394 | $contentTypePartsLength = count($contentTypeParts); 395 | for ($i = 1; $i < $contentTypePartsLength; $i++) { 396 | $paramParts = explode('=', $contentTypeParts[$i]); 397 | $contentTypeParams[strtolower($paramParts[0])] = $paramParts[1]; 398 | } 399 | } 400 | 401 | return $contentTypeParams; 402 | } 403 | 404 | /** 405 | * Get Content Charset 406 | * @return string|null 407 | */ 408 | public function getContentCharset() 409 | { 410 | $mediaTypeParams = $this->getMediaTypeParams(); 411 | if (isset($mediaTypeParams['charset'])) { 412 | return $mediaTypeParams['charset']; 413 | } else { 414 | return null; 415 | } 416 | } 417 | 418 | /** 419 | * Get Content-Length 420 | * @return int 421 | */ 422 | public function getContentLength() 423 | { 424 | if (isset($this->env['CONTENT_LENGTH'])) { 425 | return (int)$this->env['CONTENT_LENGTH']; 426 | } else { 427 | return 0; 428 | } 429 | } 430 | 431 | /** 432 | * Get Host 433 | * @return string 434 | */ 435 | public function getHost() 436 | { 437 | if (isset($this->env['HOST'])) { 438 | if (strpos($this->env['HOST'], ':') !== false) { 439 | $hostParts = explode(':', $this->env['HOST']); 440 | 441 | return $hostParts[0]; 442 | } 443 | 444 | return $this->env['HOST']; 445 | } else { 446 | return $this->env['SERVER_NAME']; 447 | } 448 | } 449 | 450 | /** 451 | * Get Host with Port 452 | * @return string 453 | */ 454 | public function getHostWithPort() 455 | { 456 | return sprintf('%s:%s', $this->getHost(), $this->getPort()); 457 | } 458 | 459 | /** 460 | * Get Port 461 | * @return int 462 | */ 463 | public function getPort() 464 | { 465 | return (int)$this->env['SERVER_PORT']; 466 | } 467 | 468 | /** 469 | * Get Scheme (https or http) 470 | * @return string 471 | */ 472 | public function getScheme() 473 | { 474 | return $this->env['slim.url_scheme']; 475 | } 476 | 477 | /** 478 | * Get Script Name (physical path) 479 | * @return string 480 | */ 481 | public function getScriptName() 482 | { 483 | return $this->env['SCRIPT_NAME']; 484 | } 485 | 486 | /** 487 | * LEGACY: Get Root URI (alias for Slim_Http_Request::getScriptName) 488 | * @return string 489 | */ 490 | public function getRootUri() 491 | { 492 | return $this->getScriptName(); 493 | } 494 | 495 | /** 496 | * Get Path (physical path + virtual path) 497 | * @return string 498 | */ 499 | public function getPath() 500 | { 501 | return $this->getScriptName() . $this->getPathInfo(); 502 | } 503 | 504 | /** 505 | * Get Path Info (virtual path) 506 | * @return string 507 | */ 508 | public function getPathInfo() 509 | { 510 | return $this->env['PATH_INFO']; 511 | } 512 | 513 | /** 514 | * LEGACY: Get Resource URI (alias for Slim_Http_Request::getPathInfo) 515 | * @return string 516 | */ 517 | public function getResourceUri() 518 | { 519 | return $this->getPathInfo(); 520 | } 521 | 522 | /** 523 | * Get URL (scheme + host [ + port if non-standard ]) 524 | * @return string 525 | */ 526 | public function getUrl() 527 | { 528 | $url = $this->getScheme() . '://' . $this->getHost(); 529 | if (($this->getScheme() === 'https' && $this->getPort() !== 443) || ($this->getScheme() === 'http' && $this->getPort() !== 80)) { 530 | $url .= sprintf(':%s', $this->getPort()); 531 | } 532 | 533 | return $url; 534 | } 535 | 536 | /** 537 | * Get IP 538 | * @return string 539 | */ 540 | public function getIp() 541 | { 542 | if (isset($this->env['X_FORWARDED_FOR'])) { 543 | return $this->env['X_FORWARDED_FOR']; 544 | } elseif (isset($this->env['CLIENT_IP'])) { 545 | return $this->env['CLIENT_IP']; 546 | } 547 | 548 | return $this->env['REMOTE_ADDR']; 549 | } 550 | 551 | /** 552 | * Get Referrer 553 | * @return string|null 554 | */ 555 | public function getReferrer() 556 | { 557 | if (isset($this->env['REFERER'])) { 558 | return $this->env['REFERER']; 559 | } else { 560 | return null; 561 | } 562 | } 563 | 564 | /** 565 | * Get Referer (for those who can't spell) 566 | * @return string|null 567 | */ 568 | public function getReferer() 569 | { 570 | return $this->getReferrer(); 571 | } 572 | 573 | /** 574 | * Get User Agent 575 | * @return string|null 576 | */ 577 | public function getUserAgent() 578 | { 579 | if (isset($this->env['USER_AGENT'])) { 580 | return $this->env['USER_AGENT']; 581 | } else { 582 | return null; 583 | } 584 | } 585 | } 586 | -------------------------------------------------------------------------------- /Slim/Http/Response.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim\Http; 34 | 35 | /** 36 | * Response 37 | * 38 | * This is a simple abstraction over top an HTTP response. This 39 | * provides methods to set the HTTP status, the HTTP headers, 40 | * and the HTTP body. 41 | * 42 | * @package Slim 43 | * @author Josh Lockhart 44 | * @since 1.0.0 45 | */ 46 | class Response implements \ArrayAccess, \Countable, \IteratorAggregate 47 | { 48 | /** 49 | * @var int HTTP status code 50 | */ 51 | protected $status; 52 | 53 | /** 54 | * @var \Slim\Http\Headers List of HTTP response headers 55 | */ 56 | protected $header; 57 | 58 | /** 59 | * @var string HTTP response body 60 | */ 61 | protected $body; 62 | 63 | /** 64 | * @var int Length of HTTP response body 65 | */ 66 | protected $length; 67 | 68 | /** 69 | * @var array HTTP response codes and messages 70 | */ 71 | protected static $messages = array( 72 | //Informational 1xx 73 | 100 => '100 Continue', 74 | 101 => '101 Switching Protocols', 75 | //Successful 2xx 76 | 200 => '200 OK', 77 | 201 => '201 Created', 78 | 202 => '202 Accepted', 79 | 203 => '203 Non-Authoritative Information', 80 | 204 => '204 No Content', 81 | 205 => '205 Reset Content', 82 | 206 => '206 Partial Content', 83 | //Redirection 3xx 84 | 300 => '300 Multiple Choices', 85 | 301 => '301 Moved Permanently', 86 | 302 => '302 Found', 87 | 303 => '303 See Other', 88 | 304 => '304 Not Modified', 89 | 305 => '305 Use Proxy', 90 | 306 => '306 (Unused)', 91 | 307 => '307 Temporary Redirect', 92 | //Client Error 4xx 93 | 400 => '400 Bad Request', 94 | 401 => '401 Unauthorized', 95 | 402 => '402 Payment Required', 96 | 403 => '403 Forbidden', 97 | 404 => '404 Not Found', 98 | 405 => '405 Method Not Allowed', 99 | 406 => '406 Not Acceptable', 100 | 407 => '407 Proxy Authentication Required', 101 | 408 => '408 Request Timeout', 102 | 409 => '409 Conflict', 103 | 410 => '410 Gone', 104 | 411 => '411 Length Required', 105 | 412 => '412 Precondition Failed', 106 | 413 => '413 Request Entity Too Large', 107 | 414 => '414 Request-URI Too Long', 108 | 415 => '415 Unsupported Media Type', 109 | 416 => '416 Requested Range Not Satisfiable', 110 | 417 => '417 Expectation Failed', 111 | 422 => '422 Unprocessable Entity', 112 | 423 => '423 Locked', 113 | //Server Error 5xx 114 | 500 => '500 Internal Server Error', 115 | 501 => '501 Not Implemented', 116 | 502 => '502 Bad Gateway', 117 | 503 => '503 Service Unavailable', 118 | 504 => '504 Gateway Timeout', 119 | 505 => '505 HTTP Version Not Supported' 120 | ); 121 | 122 | /** 123 | * Constructor 124 | * @param string $body The HTTP response body 125 | * @param int $status The HTTP response status 126 | * @param \Slim\Http\Headers|array $header The HTTP response headers 127 | */ 128 | public function __construct($body = '', $status = 200, $header = array()) 129 | { 130 | $this->status = (int)$status; 131 | $headers = array(); 132 | foreach ($header as $key => $value) { 133 | $headers[$key] = $value; 134 | } 135 | $this->header = new Headers(array_merge(array('Content-Type' => 'text/html'), $headers)); 136 | $this->body = ''; 137 | $this->write($body); 138 | } 139 | 140 | /** 141 | * Get and set status 142 | * @param int|null $status 143 | * @return int 144 | */ 145 | public function status($status = null) 146 | { 147 | if (!is_null($status)) { 148 | $this->status = (int)$status; 149 | } 150 | 151 | return $this->status; 152 | } 153 | 154 | /** 155 | * Get and set header 156 | * @param string $name Header name 157 | * @param string|null $value Header value 158 | * @return string Header value 159 | */ 160 | public function header($name, $value = null) 161 | { 162 | if (!is_null($value)) { 163 | $this[$name] = $value; 164 | } 165 | 166 | return $this[$name]; 167 | } 168 | 169 | /** 170 | * Get headers 171 | * @return \Slim\Http\Headers 172 | */ 173 | public function headers() 174 | { 175 | return $this->header; 176 | } 177 | 178 | /** 179 | * Get and set body 180 | * @param string|null $body Content of HTTP response body 181 | * @return string 182 | */ 183 | public function body($body = null) 184 | { 185 | if (!is_null($body)) { 186 | $this->write($body, true); 187 | } 188 | 189 | return $this->body; 190 | } 191 | 192 | /** 193 | * Get and set length 194 | * @param int|null $length 195 | * @return int 196 | */ 197 | public function length($length = null) 198 | { 199 | if (!is_null($length)) { 200 | $this->length = (int)$length; 201 | } 202 | 203 | return $this->length; 204 | } 205 | 206 | /** 207 | * Append HTTP response body 208 | * @param string $body Content to append to the current HTTP response body 209 | * @param bool $replace Overwrite existing response body? 210 | * @return string The updated HTTP response body 211 | */ 212 | public function write($body, $replace = false) 213 | { 214 | if ($replace) { 215 | $this->body = $body; 216 | } else { 217 | $this->body .= (string)$body; 218 | } 219 | $this->length = strlen($this->body); 220 | 221 | return $this->body; 222 | } 223 | 224 | /** 225 | * Finalize 226 | * 227 | * This prepares this response and returns an array 228 | * of [status, headers, body]. This array is passed to outer middleware 229 | * if available or directly to the Slim run method. 230 | * 231 | * @return array[int status, array headers, string body] 232 | */ 233 | public function finalize() 234 | { 235 | if (in_array($this->status, array(204, 304))) { 236 | unset($this['Content-Type'], $this['Content-Length']); 237 | 238 | return array($this->status, $this->header, ''); 239 | } else { 240 | return array($this->status, $this->header, $this->body); 241 | } 242 | } 243 | 244 | /** 245 | * Set cookie 246 | * 247 | * Instead of using PHP's `setcookie()` function, Slim manually constructs the HTTP `Set-Cookie` 248 | * header on its own and delegates this responsibility to the `Slim_Http_Util` class. This 249 | * response's header is passed by reference to the utility class and is directly modified. By not 250 | * relying on PHP's native implementation, Slim allows middleware the opportunity to massage or 251 | * analyze the raw header before the response is ultimately delivered to the HTTP client. 252 | * 253 | * @param string $name The name of the cookie 254 | * @param string|array $value If string, the value of cookie; if array, properties for 255 | * cookie including: value, expire, path, domain, secure, httponly 256 | */ 257 | public function setCookie($name, $value) 258 | { 259 | Util::setCookieHeader($this->header, $name, $value); 260 | } 261 | 262 | /** 263 | * Delete cookie 264 | * 265 | * Instead of using PHP's `setcookie()` function, Slim manually constructs the HTTP `Set-Cookie` 266 | * header on its own and delegates this responsibility to the `Slim_Http_Util` class. This 267 | * response's header is passed by reference to the utility class and is directly modified. By not 268 | * relying on PHP's native implementation, Slim allows middleware the opportunity to massage or 269 | * analyze the raw header before the response is ultimately delivered to the HTTP client. 270 | * 271 | * This method will set a cookie with the given name that has an expiration time in the past; this will 272 | * prompt the HTTP client to invalidate and remove the client-side cookie. Optionally, you may 273 | * also pass a key/value array as the second argument. If the "domain" key is present in this 274 | * array, only the Cookie with the given name AND domain will be removed. The invalidating cookie 275 | * sent with this response will adopt all properties of the second argument. 276 | * 277 | * @param string $name The name of the cookie 278 | * @param array $value Properties for cookie including: value, expire, path, domain, secure, httponly 279 | */ 280 | public function deleteCookie($name, $value = array()) 281 | { 282 | Util::deleteCookieHeader($this->header, $name, $value); 283 | } 284 | 285 | /** 286 | * Redirect 287 | * 288 | * This method prepares this response to return an HTTP Redirect response 289 | * to the HTTP client. 290 | * 291 | * @param string $url The redirect destination 292 | * @param int $status The redirect HTTP status code 293 | */ 294 | public function redirect($url, $status = 302) 295 | { 296 | $this->status = $status; 297 | $this['Location'] = $url; 298 | } 299 | 300 | /** 301 | * Helpers: Empty? 302 | * @return bool 303 | */ 304 | public function isEmpty() 305 | { 306 | return in_array($this->status, array(201, 204, 304)); 307 | } 308 | 309 | /** 310 | * Helpers: Informational? 311 | * @return bool 312 | */ 313 | public function isInformational() 314 | { 315 | return $this->status >= 100 && $this->status < 200; 316 | } 317 | 318 | /** 319 | * Helpers: OK? 320 | * @return bool 321 | */ 322 | public function isOk() 323 | { 324 | return $this->status === 200; 325 | } 326 | 327 | /** 328 | * Helpers: Successful? 329 | * @return bool 330 | */ 331 | public function isSuccessful() 332 | { 333 | return $this->status >= 200 && $this->status < 300; 334 | } 335 | 336 | /** 337 | * Helpers: Redirect? 338 | * @return bool 339 | */ 340 | public function isRedirect() 341 | { 342 | return in_array($this->status, array(301, 302, 303, 307)); 343 | } 344 | 345 | /** 346 | * Helpers: Redirection? 347 | * @return bool 348 | */ 349 | public function isRedirection() 350 | { 351 | return $this->status >= 300 && $this->status < 400; 352 | } 353 | 354 | /** 355 | * Helpers: Forbidden? 356 | * @return bool 357 | */ 358 | public function isForbidden() 359 | { 360 | return $this->status === 403; 361 | } 362 | 363 | /** 364 | * Helpers: Not Found? 365 | * @return bool 366 | */ 367 | public function isNotFound() 368 | { 369 | return $this->status === 404; 370 | } 371 | 372 | /** 373 | * Helpers: Client error? 374 | * @return bool 375 | */ 376 | public function isClientError() 377 | { 378 | return $this->status >= 400 && $this->status < 500; 379 | } 380 | 381 | /** 382 | * Helpers: Server Error? 383 | * @return bool 384 | */ 385 | public function isServerError() 386 | { 387 | return $this->status >= 500 && $this->status < 600; 388 | } 389 | 390 | /** 391 | * Array Access: Offset Exists 392 | */ 393 | public function offsetExists($offset) 394 | { 395 | return isset($this->header[$offset]); 396 | } 397 | 398 | /** 399 | * Array Access: Offset Get 400 | */ 401 | public function offsetGet($offset) 402 | { 403 | if (isset($this->header[$offset])) { 404 | return $this->header[$offset]; 405 | } else { 406 | return null; 407 | } 408 | } 409 | 410 | /** 411 | * Array Access: Offset Set 412 | */ 413 | public function offsetSet($offset, $value) 414 | { 415 | $this->header[$offset] = $value; 416 | } 417 | 418 | /** 419 | * Array Access: Offset Unset 420 | */ 421 | public function offsetUnset($offset) 422 | { 423 | unset($this->header[$offset]); 424 | } 425 | 426 | /** 427 | * Countable: Count 428 | */ 429 | public function count() 430 | { 431 | return count($this->header); 432 | } 433 | 434 | /** 435 | * Get Iterator 436 | * 437 | * This returns the contained `\Slim\Http\Headers` instance which 438 | * is itself iterable. 439 | * 440 | * @return \Slim\Http\Headers 441 | */ 442 | public function getIterator() 443 | { 444 | return $this->header; 445 | } 446 | 447 | /** 448 | * Get message for HTTP status code 449 | * @return string|null 450 | */ 451 | public static function getMessageForCode($status) 452 | { 453 | if (isset(self::$messages[$status])) { 454 | return self::$messages[$status]; 455 | } else { 456 | return null; 457 | } 458 | } 459 | } 460 | -------------------------------------------------------------------------------- /Slim/Http/Util.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim\Http; 34 | 35 | /** 36 | * Slim HTTP Utilities 37 | * 38 | * This class provides useful methods for handling HTTP requests. 39 | * 40 | * @package Slim 41 | * @author Josh Lockhart 42 | * @since 1.0.0 43 | */ 44 | class Util 45 | { 46 | /** 47 | * Strip slashes from string or array 48 | * 49 | * This method strips slashes from its input. By default, this method will only 50 | * strip slashes from its input if magic quotes are enabled. Otherwise, you may 51 | * override the magic quotes setting with either TRUE or FALSE as the send argument 52 | * to force this method to strip or not strip slashes from its input. 53 | * 54 | * @var array|string $rawData 55 | * @return array|string 56 | */ 57 | public static function stripSlashesIfMagicQuotes($rawData, $overrideStripSlashes = null) 58 | { 59 | $strip = is_null($overrideStripSlashes) ? get_magic_quotes_gpc() : $overrideStripSlashes; 60 | if ($strip) { 61 | return self::_stripSlashes($rawData); 62 | } else { 63 | return $rawData; 64 | } 65 | } 66 | 67 | /** 68 | * Strip slashes from string or array 69 | * @param array|string $rawData 70 | * @return array|string 71 | */ 72 | protected static function _stripSlashes($rawData) 73 | { 74 | return is_array($rawData) ? array_map(array('self', '_stripSlashes'), $rawData) : stripslashes($rawData); 75 | } 76 | 77 | /** 78 | * Encrypt data 79 | * 80 | * This method will encrypt data using a given key, vector, and cipher. 81 | * By default, this will encrypt data using the RIJNDAEL/AES 256 bit cipher. You 82 | * may override the default cipher and cipher mode by passing your own desired 83 | * cipher and cipher mode as the final key-value array argument. 84 | * 85 | * @param string $data The unencrypted data 86 | * @param string $key The encryption key 87 | * @param string $iv The encryption initialization vector 88 | * @param array $settings Optional key-value array with custom algorithm and mode 89 | * @return string 90 | */ 91 | public static function encrypt($data, $key, $iv, $settings = array()) 92 | { 93 | if ($data === '' || !extension_loaded('mcrypt')) { 94 | return $data; 95 | } 96 | 97 | //Merge settings with defaults 98 | $settings = array_merge(array( 99 | 'algorithm' => MCRYPT_RIJNDAEL_256, 100 | 'mode' => MCRYPT_MODE_CBC 101 | ), $settings); 102 | 103 | //Get module 104 | $module = mcrypt_module_open($settings['algorithm'], '', $settings['mode'], ''); 105 | 106 | //Validate IV 107 | $ivSize = mcrypt_enc_get_iv_size($module); 108 | if (strlen($iv) > $ivSize) { 109 | $iv = substr($iv, 0, $ivSize); 110 | } 111 | 112 | //Validate key 113 | $keySize = mcrypt_enc_get_key_size($module); 114 | if (strlen($key) > $keySize) { 115 | $key = substr($key, 0, $keySize); 116 | } 117 | 118 | //Encrypt value 119 | mcrypt_generic_init($module, $key, $iv); 120 | $res = @mcrypt_generic($module, $data); 121 | mcrypt_generic_deinit($module); 122 | 123 | return $res; 124 | } 125 | 126 | /** 127 | * Decrypt data 128 | * 129 | * This method will decrypt data using a given key, vector, and cipher. 130 | * By default, this will decrypt data using the RIJNDAEL/AES 256 bit cipher. You 131 | * may override the default cipher and cipher mode by passing your own desired 132 | * cipher and cipher mode as the final key-value array argument. 133 | * 134 | * @param string $data The encrypted data 135 | * @param string $key The encryption key 136 | * @param string $iv The encryption initialization vector 137 | * @param array $settings Optional key-value array with custom algorithm and mode 138 | * @return string 139 | */ 140 | public static function decrypt($data, $key, $iv, $settings = array()) 141 | { 142 | if ($data === '' || !extension_loaded('mcrypt')) { 143 | return $data; 144 | } 145 | 146 | //Merge settings with defaults 147 | $settings = array_merge(array( 148 | 'algorithm' => MCRYPT_RIJNDAEL_256, 149 | 'mode' => MCRYPT_MODE_CBC 150 | ), $settings); 151 | 152 | //Get module 153 | $module = mcrypt_module_open($settings['algorithm'], '', $settings['mode'], ''); 154 | 155 | //Validate IV 156 | $ivSize = mcrypt_enc_get_iv_size($module); 157 | if (strlen($iv) > $ivSize) { 158 | $iv = substr($iv, 0, $ivSize); 159 | } 160 | 161 | //Validate key 162 | $keySize = mcrypt_enc_get_key_size($module); 163 | if (strlen($key) > $keySize) { 164 | $key = substr($key, 0, $keySize); 165 | } 166 | 167 | //Decrypt value 168 | mcrypt_generic_init($module, $key, $iv); 169 | $decryptedData = @mdecrypt_generic($module, $data); 170 | $res = str_replace("\x0", '', $decryptedData); 171 | mcrypt_generic_deinit($module); 172 | 173 | return $res; 174 | } 175 | 176 | /** 177 | * Encode secure cookie value 178 | * 179 | * This method will create the secure value of an HTTP cookie. The 180 | * cookie value is encrypted and hashed so that its value is 181 | * secure and checked for integrity when read in subsequent requests. 182 | * 183 | * @param string $value The unsecure HTTP cookie value 184 | * @param int $expires The UNIX timestamp at which this cookie will expire 185 | * @param string $secret The secret key used to hash the cookie value 186 | * @param int $algorithm The algorithm to use for encryption 187 | * @param int $mode The algorithm mode to use for encryption 188 | * @param string 189 | */ 190 | public static function encodeSecureCookie($value, $expires, $secret, $algorithm, $mode) 191 | { 192 | $key = hash_hmac('sha1', $expires, $secret); 193 | $iv = self::get_iv($expires, $secret); 194 | $secureString = base64_encode(self::encrypt($value, $key, $iv, array( 195 | 'algorithm' => $algorithm, 196 | 'mode' => $mode 197 | ))); 198 | $verificationString = hash_hmac('sha1', $expires . $value, $key); 199 | 200 | return implode('|', array($expires, $secureString, $verificationString)); 201 | } 202 | 203 | /** 204 | * Decode secure cookie value 205 | * 206 | * This method will decode the secure value of an HTTP cookie. The 207 | * cookie value is encrypted and hashed so that its value is 208 | * secure and checked for integrity when read in subsequent requests. 209 | * 210 | * @param string $value The secure HTTP cookie value 211 | * @param int $expires The UNIX timestamp at which this cookie will expire 212 | * @param string $secret The secret key used to hash the cookie value 213 | * @param int $algorithm The algorithm to use for encryption 214 | * @param int $mode The algorithm mode to use for encryption 215 | * @param string 216 | */ 217 | public static function decodeSecureCookie($value, $secret, $algorithm, $mode) 218 | { 219 | if ($value) { 220 | $value = explode('|', $value); 221 | if (count($value) === 3 && ((int)$value[0] === 0 || (int)$value[0] > time())) { 222 | $key = hash_hmac('sha1', $value[0], $secret); 223 | $iv = self::get_iv($value[0], $secret); 224 | $data = self::decrypt(base64_decode($value[1]), $key, $iv, array( 225 | 'algorithm' => $algorithm, 226 | 'mode' => $mode 227 | )); 228 | $verificationString = hash_hmac('sha1', $value[0] . $data, $key); 229 | if ($verificationString === $value[2]) { 230 | return $data; 231 | } 232 | } 233 | } 234 | 235 | return false; 236 | } 237 | 238 | /** 239 | * Set HTTP cookie header 240 | * 241 | * This method will construct and set the HTTP `Set-Cookie` header. Slim 242 | * uses this method instead of PHP's native `setcookie` method. This allows 243 | * more control of the HTTP header irrespective of the native implementation's 244 | * dependency on PHP versions. 245 | * 246 | * This method accepts the Slim_Http_Headers object by reference as its 247 | * first argument; this method directly modifies this object instead of 248 | * returning a value. 249 | * 250 | * @param array $header 251 | * @param string $name 252 | * @param string $value 253 | */ 254 | public static function setCookieHeader(&$header, $name, $value) 255 | { 256 | //Build cookie header 257 | if (is_array($value)) { 258 | $domain = ''; 259 | $path = ''; 260 | $expires = ''; 261 | $secure = ''; 262 | $httponly = ''; 263 | if (isset($value['domain']) && $value['domain']) { 264 | $domain = '; domain=' . $value['domain']; 265 | } 266 | if (isset($value['path']) && $value['path']) { 267 | $path = '; path=' . $value['path']; 268 | } 269 | if (isset($value['expires'])) { 270 | if (is_string($value['expires'])) { 271 | $timestamp = strtotime($value['expires']); 272 | } else { 273 | $timestamp = (int)$value['expires']; 274 | } 275 | if ($timestamp !== 0) { 276 | $expires = '; expires=' . gmdate('D, d-M-Y H:i:s e', $timestamp); 277 | } 278 | } 279 | if (isset($value['secure']) && $value['secure']) { 280 | $secure = '; secure'; 281 | } 282 | if (isset($value['httponly']) && $value['httponly']) { 283 | $httponly = '; HttpOnly'; 284 | } 285 | $cookie = sprintf('%s=%s%s', urlencode($name), urlencode((string)$value['value']), $domain . $path . $expires . $secure . $httponly); 286 | } else { 287 | $cookie = sprintf('%s=%s', urlencode($name), urlencode((string)$value)); 288 | } 289 | 290 | //Set cookie header 291 | if (!isset($header['Set-Cookie']) || $header['Set-Cookie'] === '') { 292 | $header['Set-Cookie'] = $cookie; 293 | } else { 294 | $header['Set-Cookie'] = implode("\n", array($header['Set-Cookie'], $cookie)); 295 | } 296 | } 297 | 298 | /** 299 | * Delete HTTP cookie header 300 | * 301 | * This method will construct and set the HTTP `Set-Cookie` header to invalidate 302 | * a client-side HTTP cookie. If a cookie with the same name (and, optionally, domain) 303 | * is already set in the HTTP response, it will also be removed. Slim uses this method 304 | * instead of PHP's native `setcookie` method. This allows more control of the HTTP header 305 | * irrespective of PHP's native implementation's dependency on PHP versions. 306 | * 307 | * This method accepts the Slim_Http_Headers object by reference as its 308 | * first argument; this method directly modifies this object instead of 309 | * returning a value. 310 | * 311 | * @param array $header 312 | * @param string $name 313 | * @param string $value 314 | */ 315 | public static function deleteCookieHeader(&$header, $name, $value = array()) 316 | { 317 | //Remove affected cookies from current response header 318 | $cookiesOld = array(); 319 | $cookiesNew = array(); 320 | if (isset($header['Set-Cookie'])) { 321 | $cookiesOld = explode("\n", $header['Set-Cookie']); 322 | } 323 | foreach ($cookiesOld as $c) { 324 | if (isset($value['domain']) && $value['domain']) { 325 | $regex = sprintf('@%s=.*domain=%s@', urlencode($name), preg_quote($value['domain'])); 326 | } else { 327 | $regex = sprintf('@%s=@', urlencode($name)); 328 | } 329 | if (preg_match($regex, $c) === 0) { 330 | $cookiesNew[] = $c; 331 | } 332 | } 333 | if ($cookiesNew) { 334 | $header['Set-Cookie'] = implode("\n", $cookiesNew); 335 | } else { 336 | unset($header['Set-Cookie']); 337 | } 338 | 339 | //Set invalidating cookie to clear client-side cookie 340 | self::setCookieHeader($header, $name, array_merge(array('value' => '', 'path' => null, 'domain' => null, 'expires' => time() - 100), $value)); 341 | } 342 | 343 | /** 344 | * Parse cookie header 345 | * 346 | * This method will parse the HTTP requst's `Cookie` header 347 | * and extract cookies into an associative array. 348 | * 349 | * @param string 350 | * @return array 351 | */ 352 | public static function parseCookieHeader($header) 353 | { 354 | $cookies = array(); 355 | $header = rtrim($header, "\r\n"); 356 | $headerPieces = preg_split('@\s*[;,]\s*@', $header); 357 | foreach ($headerPieces as $c) { 358 | $cParts = explode('=', $c); 359 | if (count($cParts) === 2) { 360 | $key = urldecode($cParts[0]); 361 | $value = urldecode($cParts[1]); 362 | if (!isset($cookies[$key])) { 363 | $cookies[$key] = $value; 364 | } 365 | } 366 | } 367 | 368 | return $cookies; 369 | } 370 | 371 | /** 372 | * Generate a random IV 373 | * 374 | * This method will generate a non-predictable IV for use with 375 | * the cookie encryption 376 | * 377 | * @param int $expires The UNIX timestamp at which this cookie will expire 378 | * @param string $secret The secret key used to hash the cookie value 379 | * @return binary string with length 40 380 | */ 381 | private static function get_iv($expires, $secret) 382 | { 383 | $data1 = hash_hmac('sha1', 'a' . $expires . 'b', $secret); 384 | $data2 = hash_hmac('sha1', 'z' . $expires . 'y', $secret); 385 | 386 | return pack("h*", $data1 . $data2); 387 | } 388 | 389 | } 390 | -------------------------------------------------------------------------------- /Slim/Log.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim; 34 | 35 | /** 36 | * Log 37 | * 38 | * This is the primary logger for a Slim application. You may provide 39 | * a Log Writer in conjunction with this Log to write to various output 40 | * destinations (e.g. a file). This class provides this interface: 41 | * 42 | * debug( mixed $object ) 43 | * info( mixed $object ) 44 | * warn( mixed $object ) 45 | * error( mixed $object ) 46 | * fatal( mixed $object ) 47 | * 48 | * This class assumes only that your Log Writer has a public `write()` method 49 | * that accepts any object as its one and only argument. The Log Writer 50 | * class may write or send its argument anywhere: a file, STDERR, 51 | * a remote web API, etc. The possibilities are endless. 52 | * 53 | * @package Slim 54 | * @author Josh Lockhart 55 | * @since 1.0.0 56 | */ 57 | class Log 58 | { 59 | const FATAL = 0; 60 | const ERROR = 1; 61 | const WARN = 2; 62 | const INFO = 3; 63 | const DEBUG = 4; 64 | 65 | /** 66 | * @var array 67 | */ 68 | protected static $levels = array( 69 | self::FATAL => 'FATAL', 70 | self::ERROR => 'ERROR', 71 | self::WARN => 'WARN', 72 | self::INFO => 'INFO', 73 | self::DEBUG => 'DEBUG' 74 | ); 75 | 76 | /** 77 | * @var mixed 78 | */ 79 | protected $writer; 80 | 81 | /** 82 | * @var bool 83 | */ 84 | protected $enabled; 85 | 86 | /** 87 | * @var int 88 | */ 89 | protected $level; 90 | 91 | /** 92 | * Constructor 93 | * @param mixed $writer 94 | */ 95 | public function __construct($writer) 96 | { 97 | $this->writer = $writer; 98 | $this->enabled = true; 99 | $this->level = self::DEBUG; 100 | } 101 | 102 | /** 103 | * Is logging enabled? 104 | * @return bool 105 | */ 106 | public function getEnabled() 107 | { 108 | return $this->enabled; 109 | } 110 | 111 | /** 112 | * Enable or disable logging 113 | * @param bool $enabled 114 | */ 115 | public function setEnabled($enabled) 116 | { 117 | if ($enabled) { 118 | $this->enabled = true; 119 | } else { 120 | $this->enabled = false; 121 | } 122 | } 123 | 124 | /** 125 | * Set level 126 | * @param int $level 127 | * @throws \InvalidArgumentException If invalid log level specified 128 | */ 129 | public function setLevel($level) 130 | { 131 | if (!isset(self::$levels[$level])) { 132 | throw new \InvalidArgumentException('Invalid log level'); 133 | } 134 | $this->level = $level; 135 | } 136 | 137 | /** 138 | * Get level 139 | * @return int 140 | */ 141 | public function getLevel() 142 | { 143 | return $this->level; 144 | } 145 | 146 | /** 147 | * Set writer 148 | * @param mixed $writer 149 | */ 150 | public function setWriter($writer) 151 | { 152 | $this->writer = $writer; 153 | } 154 | 155 | /** 156 | * Get writer 157 | * @return mixed 158 | */ 159 | public function getWriter() 160 | { 161 | return $this->writer; 162 | } 163 | 164 | /** 165 | * Is logging enabled? 166 | * @return bool 167 | */ 168 | public function isEnabled() 169 | { 170 | return $this->enabled; 171 | } 172 | 173 | /** 174 | * Log debug message 175 | * @param mixed $object 176 | * @return mixed|false What the Logger returns, or false if Logger not set or not enabled 177 | */ 178 | public function debug($object) 179 | { 180 | return $this->write($object, self::DEBUG); 181 | } 182 | 183 | /** 184 | * Log info message 185 | * @param mixed $object 186 | * @return mixed|false What the Logger returns, or false if Logger not set or not enabled 187 | */ 188 | public function info($object) 189 | { 190 | return $this->write($object, self::INFO); 191 | } 192 | 193 | /** 194 | * Log warn message 195 | * @param mixed $object 196 | * @return mixed|false What the Logger returns, or false if Logger not set or not enabled 197 | */ 198 | public function warn($object) 199 | { 200 | return $this->write($object, self::WARN); 201 | } 202 | 203 | /** 204 | * Log error message 205 | * @param mixed $object 206 | * @return mixed|false What the Logger returns, or false if Logger not set or not enabled 207 | */ 208 | public function error($object) 209 | { 210 | return $this->write($object, self::ERROR); 211 | } 212 | 213 | /** 214 | * Log fatal message 215 | * @param mixed $object 216 | * @return mixed|false What the Logger returns, or false if Logger not set or not enabled 217 | */ 218 | public function fatal($object) 219 | { 220 | return $this->write($object, self::FATAL); 221 | } 222 | 223 | /** 224 | * Log message 225 | * @param mixed The object to log 226 | * @param int The message level 227 | * @return int|false 228 | */ 229 | protected function write($object, $level) 230 | { 231 | if ($this->enabled && $this->writer && $level <= $this->level) { 232 | return $this->writer->write($object, $level); 233 | } else { 234 | return false; 235 | } 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /Slim/LogWriter.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim; 34 | 35 | /** 36 | * Log Writer 37 | * 38 | * This class is used by Slim_Log to write log messages to a valid, writable 39 | * resource handle (e.g. a file or STDERR). 40 | * 41 | * @package Slim 42 | * @author Josh Lockhart 43 | * @since 1.6.0 44 | */ 45 | class LogWriter 46 | { 47 | /** 48 | * @var resource 49 | */ 50 | protected $resource; 51 | 52 | /** 53 | * Constructor 54 | * @param resource $resource 55 | * @throws \InvalidArgumentException If invalid resource 56 | */ 57 | public function __construct($resource) 58 | { 59 | if (!is_resource($resource)) { 60 | throw new \InvalidArgumentException('Cannot create LogWriter. Invalid resource handle.'); 61 | } 62 | $this->resource = $resource; 63 | } 64 | 65 | /** 66 | * Write message 67 | * @param mixed $message 68 | * @param int $level 69 | * @return int|false 70 | */ 71 | public function write($message, $level = null) 72 | { 73 | return fwrite($this->resource, (string)$message . PHP_EOL); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Slim/Middleware.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim; 34 | 35 | /** 36 | * Middleware 37 | * 38 | * @package Slim 39 | * @author Josh Lockhart 40 | * @since 1.6.0 41 | */ 42 | abstract class Middleware 43 | { 44 | /** 45 | * @var \Slim Reference to the primary application instance 46 | */ 47 | protected $app; 48 | 49 | /** 50 | * @var mixed Reference to the next downstream middleware 51 | */ 52 | protected $next; 53 | 54 | /** 55 | * Set application 56 | * 57 | * This method injects the primary Slim application instance into 58 | * this middleware. 59 | * 60 | * @param \Slim $application 61 | */ 62 | final public function setApplication($application) 63 | { 64 | $this->app = $application; 65 | } 66 | 67 | /** 68 | * Get application 69 | * 70 | * This method retrieves the application previously injected 71 | * into this middleware. 72 | * 73 | * @return \Slim 74 | */ 75 | final public function getApplication() 76 | { 77 | return $this->app; 78 | } 79 | 80 | /** 81 | * Set next middleware 82 | * 83 | * This method injects the next downstream middleware into 84 | * this middleware so that it may optionally be called 85 | * when appropriate. 86 | * 87 | * @param \Slim|\Slim\Middleware 88 | */ 89 | final public function setNextMiddleware($nextMiddleware) 90 | { 91 | $this->next = $nextMiddleware; 92 | } 93 | 94 | /** 95 | * Get next middleware 96 | * 97 | * This method retrieves the next downstream middleware 98 | * previously injected into this middleware. 99 | * 100 | * @return \Slim|\Slim\Middleware 101 | */ 102 | final public function getNextMiddleware() 103 | { 104 | return $this->next; 105 | } 106 | 107 | /** 108 | * Call 109 | * 110 | * Perform actions specific to this middleware and optionally 111 | * call the next downstream middleware. 112 | */ 113 | abstract public function call(); 114 | } 115 | -------------------------------------------------------------------------------- /Slim/Middleware/ContentTypes.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim\Middleware; 34 | 35 | /** 36 | * Content Types 37 | * 38 | * This is middleware for a Slim application that intercepts 39 | * the HTTP request body and parses it into the appropriate 40 | * PHP data structure if possible; else it returns the HTTP 41 | * request body unchanged. This is particularly useful 42 | * for preparing the HTTP request body for an XML or JSON API. 43 | * 44 | * @package Slim 45 | * @author Josh Lockhart 46 | * @since 1.6.0 47 | */ 48 | class ContentTypes extends \Slim\Middleware 49 | { 50 | /** 51 | * @var array 52 | */ 53 | protected $contentTypes; 54 | 55 | /** 56 | * Constructor 57 | * @param array $settings 58 | */ 59 | public function __construct($settings = array()) 60 | { 61 | $this->contentTypes = array_merge(array( 62 | 'application/json' => array($this, 'parseJson'), 63 | 'application/xml' => array($this, 'parseXml'), 64 | 'text/xml' => array($this, 'parseXml'), 65 | 'text/csv' => array($this, 'parseCsv') 66 | ), $settings); 67 | } 68 | 69 | /** 70 | * Call 71 | */ 72 | public function call() 73 | { 74 | $mediaType = $this->app->request()->getMediaType(); 75 | if ($mediaType) { 76 | $env = $this->app->environment(); 77 | $env['slim.input_original'] = $env['slim.input']; 78 | $env['slim.input'] = $this->parse($env['slim.input'], $mediaType); 79 | } 80 | $this->next->call(); 81 | } 82 | 83 | /** 84 | * Parse input 85 | * 86 | * This method will attempt to parse the request body 87 | * based on its content type if available. 88 | * 89 | * @param string $input 90 | * @param string $contentType 91 | * @return mixed 92 | */ 93 | protected function parse($input, $contentType) 94 | { 95 | if (isset($this->contentTypes[$contentType]) && is_callable($this->contentTypes[$contentType])) { 96 | $result = call_user_func($this->contentTypes[$contentType], $input); 97 | if ($result) { 98 | return $result; 99 | } 100 | } 101 | 102 | return $input; 103 | } 104 | 105 | /** 106 | * Parse JSON 107 | * 108 | * This method converts the raw JSON input 109 | * into an associative array. 110 | * 111 | * @param string $input 112 | * @return array|string 113 | */ 114 | protected function parseJson($input) 115 | { 116 | if (function_exists('json_decode')) { 117 | $result = json_decode($input, true); 118 | if ($result) { 119 | return $result; 120 | } 121 | } 122 | } 123 | 124 | /** 125 | * Parse XML 126 | * 127 | * This method creates a SimpleXMLElement 128 | * based upon the XML input. If the SimpleXML 129 | * extension is not available, the raw input 130 | * will be returned unchanged. 131 | * 132 | * @param string $input 133 | * @return \SimpleXMLElement|string 134 | */ 135 | protected function parseXml($input) 136 | { 137 | if (class_exists('SimpleXMLElement')) { 138 | try { 139 | return new \SimpleXMLElement($input); 140 | } catch (\Exception $e) { 141 | // Do nothing 142 | } 143 | } 144 | 145 | return $input; 146 | } 147 | 148 | /** 149 | * Parse CSV 150 | * 151 | * This method parses CSV content into a numeric array 152 | * containing an array of data for each CSV line. 153 | * 154 | * @param string $input 155 | * @return array 156 | */ 157 | protected function parseCsv($input) 158 | { 159 | $temp = fopen('php://memory', 'rw'); 160 | fwrite($temp, $input); 161 | fseek($temp, 0); 162 | $res = array(); 163 | while (($data = fgetcsv($temp)) !== false) { 164 | $res[] = $data; 165 | } 166 | fclose($temp); 167 | 168 | return $res; 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /Slim/Middleware/Flash.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim\Middleware; 34 | 35 | /** 36 | * Flash 37 | * 38 | * This is middleware for a Slim application that enables 39 | * Flash messaging between HTTP requests. This allows you 40 | * set Flash messages for the current request, for the next request, 41 | * or to retain messages from the previous request through to 42 | * the next request. 43 | * 44 | * @package Slim 45 | * @author Josh Lockhart 46 | * @since 1.6.0 47 | */ 48 | class Flash extends \Slim\Middleware implements \ArrayAccess, \IteratorAggregate 49 | { 50 | /** 51 | * @var array 52 | */ 53 | protected $settings; 54 | 55 | /** 56 | * @var array 57 | */ 58 | protected $messages; 59 | 60 | /** 61 | * Constructor 62 | * @param \Slim $app 63 | * @param array $settings 64 | */ 65 | public function __construct($settings = array()) 66 | { 67 | $this->settings = array_merge(array('key' => 'slim.flash'), $settings); 68 | $this->messages = array( 69 | 'prev' => array(), //flash messages from prev request (loaded when middleware called) 70 | 'next' => array(), //flash messages for next request 71 | 'now' => array() //flash messages for current request 72 | ); 73 | } 74 | 75 | /** 76 | * Call 77 | */ 78 | public function call() 79 | { 80 | //Read flash messaging from previous request if available 81 | $this->loadMessages(); 82 | 83 | //Prepare flash messaging for current request 84 | $env = $this->app->environment(); 85 | $env['slim.flash'] = $this; 86 | $this->next->call(); 87 | $this->save(); 88 | } 89 | 90 | /** 91 | * Now 92 | * 93 | * Specify a flash message for a given key to be shown for the current request 94 | * 95 | * @param string $key 96 | * @param string $value 97 | */ 98 | public function now($key, $value) 99 | { 100 | $this->messages['now'][(string)$key] = $value; 101 | } 102 | 103 | /** 104 | * Set 105 | * 106 | * Specify a flash message for a given key to be shown for the next request 107 | * 108 | * @param string $key 109 | * @param string $value 110 | */ 111 | public function set($key, $value) 112 | { 113 | $this->messages['next'][(string)$key] = $value; 114 | } 115 | 116 | /** 117 | * Keep 118 | * 119 | * Retain flash messages from the previous request for the next request 120 | */ 121 | public function keep() 122 | { 123 | foreach ($this->messages['prev'] as $key => $val) { 124 | $this->messages['next'][$key] = $val; 125 | } 126 | } 127 | 128 | /** 129 | * Save 130 | */ 131 | public function save() 132 | { 133 | $_SESSION[$this->settings['key']] = $this->messages['next']; 134 | } 135 | 136 | /** 137 | * Load messages from previous request if available 138 | */ 139 | public function loadMessages() 140 | { 141 | if (isset($_SESSION[$this->settings['key']])) { 142 | $this->messages['prev'] = $_SESSION[$this->settings['key']]; 143 | } 144 | } 145 | 146 | /** 147 | * Return array of flash messages to be shown for the current request 148 | * 149 | * @return array 150 | */ 151 | public function getMessages() 152 | { 153 | return array_merge($this->messages['prev'], $this->messages['now']); 154 | } 155 | 156 | /** 157 | * Array Access: Offset Exists 158 | */ 159 | public function offsetExists($offset) 160 | { 161 | $messages = $this->getMessages(); 162 | 163 | return isset($messages[$offset]); 164 | } 165 | 166 | /** 167 | * Array Access: Offset Get 168 | */ 169 | public function offsetGet($offset) 170 | { 171 | $messages = $this->getMessages(); 172 | 173 | return isset($messages[$offset]) ? $messages[$offset] : null; 174 | } 175 | 176 | /** 177 | * Array Access: Offset Set 178 | */ 179 | public function offsetSet($offset, $value) 180 | { 181 | $this->now($offset, $value); 182 | } 183 | 184 | /** 185 | * Array Access: Offset Unset 186 | */ 187 | public function offsetUnset($offset) 188 | { 189 | unset($this->messages['prev'][$offset], $this->messages['now'][$offset]); 190 | } 191 | 192 | /** 193 | * Iterator Aggregate: Get Iterator 194 | * @return \ArrayIterator 195 | */ 196 | public function getIterator() 197 | { 198 | $messages = $this->getMessages(); 199 | 200 | return new \ArrayIterator($messages); 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /Slim/Middleware/MethodOverride.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim\Middleware; 34 | 35 | /** 36 | * HTTP Method Override 37 | * 38 | * This is middleware for a Slim application that allows traditional 39 | * desktop browsers to submit psuedo PUT and DELETE requests by relying 40 | * on a pre-determined request parameter. Without this middleware, 41 | * desktop browsers are only able to submit GET and POST requests. 42 | * 43 | * This middleware is included automatically! 44 | * 45 | * @package Slim 46 | * @author Josh Lockhart 47 | * @since 1.6.0 48 | */ 49 | class MethodOverride extends \Slim\Middleware 50 | { 51 | /** 52 | * @var array 53 | */ 54 | protected $settings; 55 | 56 | /** 57 | * Constructor 58 | * @param \Slim $app 59 | * @param array $settings 60 | */ 61 | public function __construct($settings = array()) 62 | { 63 | $this->settings = array_merge(array('key' => '_METHOD'), $settings); 64 | } 65 | 66 | /** 67 | * Call 68 | * 69 | * Implements Slim middleware interface. This method is invoked and passed 70 | * an array of environment variables. This middleware inspects the environment 71 | * variables for the HTTP method override parameter; if found, this middleware 72 | * modifies the environment settings so downstream middleware and/or the Slim 73 | * application will treat the request with the desired HTTP method. 74 | * 75 | * @param array $env 76 | * @return array[status, header, body] 77 | */ 78 | public function call() 79 | { 80 | $env = $this->app->environment(); 81 | if (isset($env['X_HTTP_METHOD_OVERRIDE'])) { 82 | // Header commonly used by Backbone.js and others 83 | $env['slim.method_override.original_method'] = $env['REQUEST_METHOD']; 84 | $env['REQUEST_METHOD'] = strtoupper($env['X_HTTP_METHOD_OVERRIDE']); 85 | } elseif (isset($env['REQUEST_METHOD']) && $env['REQUEST_METHOD'] === 'POST') { 86 | // HTML Form Override 87 | $req = new \Slim\Http\Request($env); 88 | $method = $req->post($this->settings['key']); 89 | if ($method) { 90 | $env['slim.method_override.original_method'] = $env['REQUEST_METHOD']; 91 | $env['REQUEST_METHOD'] = strtoupper($method); 92 | } 93 | } 94 | $this->next->call(); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /Slim/Middleware/PrettyExceptions.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim\Middleware; 34 | 35 | /** 36 | * Pretty Exceptions 37 | * 38 | * This middleware catches any Exception thrown by the surrounded 39 | * application and displays a developer-friendly diagnostic screen. 40 | * 41 | * @package Slim 42 | * @author Josh Lockhart 43 | * @since 1.0.0 44 | */ 45 | class PrettyExceptions extends \Slim\Middleware 46 | { 47 | /** 48 | * @var array 49 | */ 50 | protected $settings; 51 | 52 | /** 53 | * Constructor 54 | * @param array $settings 55 | */ 56 | public function __construct($settings = array()) 57 | { 58 | $this->settings = $settings; 59 | } 60 | 61 | /** 62 | * Call 63 | */ 64 | public function call() 65 | { 66 | try { 67 | $this->next->call(); 68 | } catch (\Exception $e) { 69 | $env = $this->app->environment(); 70 | $env['slim.log']->error($e); 71 | $this->app->contentType('text/html'); 72 | $this->app->response()->status(500); 73 | $this->app->response()->body($this->renderBody($env, $e)); 74 | } 75 | } 76 | 77 | /** 78 | * Render response body 79 | * @param array $env 80 | * @param \Exception $exception 81 | * @return string 82 | */ 83 | protected function renderBody(&$env, $exception) 84 | { 85 | $title = 'Slim Application Error'; 86 | $code = $exception->getCode(); 87 | $message = $exception->getMessage(); 88 | $file = $exception->getFile(); 89 | $line = $exception->getLine(); 90 | $trace = $exception->getTraceAsString(); 91 | $html = sprintf('
The application could not run because of the following error:
'; 93 | $html .= '%s', $trace); 110 | } 111 | 112 | 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'); 1300 | } 1301 | 1302 | /** 1303 | * Default Error handler 1304 | */ 1305 | protected function defaultError($e) 1306 | { 1307 | $this->getLog()->error($e); 1308 | echo self::generateTemplateMarkup('Error', 'A website error has occured. The website administrator has been notified of the issue. Sorry for the temporary inconvenience.
'); 1309 | } 1310 | } 1311 | -------------------------------------------------------------------------------- /Slim/View.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2011 Josh Lockhart 7 | * @link http://www.slimframework.com 8 | * @license http://www.slimframework.com/license 9 | * @version 2.2.0 10 | * @package Slim 11 | * 12 | * MIT LICENSE 13 | * 14 | * Permission is hereby granted, free of charge, to any person obtaining 15 | * a copy of this software and associated documentation files (the 16 | * "Software"), to deal in the Software without restriction, including 17 | * without limitation the rights to use, copy, modify, merge, publish, 18 | * distribute, sublicense, and/or sell copies of the Software, and to 19 | * permit persons to whom the Software is furnished to do so, subject to 20 | * the following conditions: 21 | * 22 | * The above copyright notice and this permission notice shall be 23 | * included in all copies or substantial portions of the Software. 24 | * 25 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 26 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 27 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 28 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 29 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 30 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 31 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 32 | */ 33 | namespace Slim; 34 | 35 | /** 36 | * View 37 | * 38 | * The view is responsible for rendering a template. The view 39 | * should subclass \Slim\View and implement this interface: 40 | * 41 | * public render(string $template); 42 | * 43 | * This method should render the specified template and return 44 | * the resultant string. 45 | * 46 | * @package Slim 47 | * @author Josh Lockhart 48 | * @since 1.0.0 49 | */ 50 | class View 51 | { 52 | /** 53 | * @var string Absolute or relative filesystem path to a specific template 54 | * 55 | * DEPRECATION WARNING! 56 | * This variable will be removed in the near future 57 | */ 58 | protected $templatePath = ''; 59 | 60 | /** 61 | * @var array Associative array of template variables 62 | */ 63 | protected $data = array(); 64 | 65 | /** 66 | * @var string Absolute or relative path to the application's templates directory 67 | */ 68 | protected $templatesDirectory; 69 | 70 | /** 71 | * Constructor 72 | * 73 | * This is empty but may be implemented in a subclass 74 | */ 75 | public function __construct() 76 | { 77 | 78 | } 79 | 80 | /** 81 | * Get data 82 | * @param string|null $key 83 | * @return mixed If key is null, array of template data; 84 | * If key exists, value of datum with key; 85 | * If key does not exist, null; 86 | */ 87 | public function getData($key = null) 88 | { 89 | if (!is_null($key)) { 90 | return isset($this->data[$key]) ? $this->data[$key] : null; 91 | } else { 92 | return $this->data; 93 | } 94 | } 95 | 96 | /** 97 | * Set data 98 | * 99 | * If two arguments: 100 | * A single datum with key is assigned value; 101 | * 102 | * $view->setData('color', 'red'); 103 | * 104 | * If one argument: 105 | * Replace all data with provided array keys and values; 106 | * 107 | * $view->setData(array('color' => 'red', 'number' => 1)); 108 | * 109 | * @param mixed 110 | * @param mixed 111 | * @throws InvalidArgumentException If incorrect method signature 112 | */ 113 | public function setData() 114 | { 115 | $args = func_get_args(); 116 | if (count($args) === 1 && is_array($args[0])) { 117 | $this->data = $args[0]; 118 | } elseif (count($args) === 2) { 119 | $this->data[(string)$args[0]] = $args[1]; 120 | } else { 121 | throw new \InvalidArgumentException('Cannot set View data with provided arguments. Usage: `View::setData( $key, $value );` or `View::setData([ key => value, ... ]);`'); 122 | } 123 | } 124 | 125 | /** 126 | * Append new data to existing template data 127 | * @param array 128 | * @throws InvalidArgumentException If not given an array argument 129 | */ 130 | public function appendData($data) 131 | { 132 | if (!is_array($data)) { 133 | throw new \InvalidArgumentException('Cannot append view data. Expected array argument.'); 134 | } 135 | $this->data = array_merge($this->data, $data); 136 | } 137 | 138 | /** 139 | * Get templates directory 140 | * @return string|null Path to templates directory without trailing slash; 141 | * Returns null if templates directory not set; 142 | */ 143 | public function getTemplatesDirectory() 144 | { 145 | return $this->templatesDirectory; 146 | } 147 | 148 | /** 149 | * Set templates directory 150 | * @param string $dir 151 | */ 152 | public function setTemplatesDirectory($dir) 153 | { 154 | $this->templatesDirectory = rtrim($dir, '/'); 155 | } 156 | 157 | /** 158 | * Set template 159 | * @param string $template 160 | * @throws RuntimeException If template file does not exist 161 | * 162 | * DEPRECATION WARNING! 163 | * This method will be removed in the near future. 164 | */ 165 | public function setTemplate($template) 166 | { 167 | $this->templatePath = $this->getTemplatesDirectory() . '/' . ltrim($template, '/'); 168 | if (!file_exists($this->templatePath)) { 169 | throw new \RuntimeException('View cannot render template `' . $this->templatePath . '`. Template does not exist.'); 170 | } 171 | } 172 | 173 | /** 174 | * Display template 175 | * 176 | * This method echoes the rendered template to the current output buffer 177 | * 178 | * @param string $template Pathname of template file relative to templates directoy 179 | */ 180 | public function display($template) 181 | { 182 | echo $this->fetch($template); 183 | } 184 | 185 | /** 186 | * Fetch rendered template 187 | * 188 | * This method returns the rendered template 189 | * 190 | * @param string $template Pathname of template file relative to templates directory 191 | * @return string 192 | */ 193 | public function fetch($template) 194 | { 195 | return $this->render($template); 196 | } 197 | 198 | /** 199 | * Render template 200 | * 201 | * @param string $template Pathname of template file relative to templates directory 202 | * @return string 203 | * 204 | * DEPRECATION WARNING! 205 | * Use `\Slim\View::fetch` to return a rendered template instead of `\Slim\View::render`. 206 | */ 207 | public function render($template) 208 | { 209 | $this->setTemplate($template); 210 | extract($this->data); 211 | ob_start(); 212 | require $this->templatePath; 213 | 214 | return ob_get_clean(); 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /api/.htaccess: -------------------------------------------------------------------------------- 1 | RewriteEngine On 2 | RewriteBase /bookmark/api/ 3 | RewriteCond %{REQUEST_FILENAME} !-f 4 | RewriteRule ^ index.php [QSA,L] -------------------------------------------------------------------------------- /api/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cacodaimon/AngularJSTutorialApp/98107d2c9d708fe33c547553a2b29b8f55cd88d6/api/db.sqlite3 -------------------------------------------------------------------------------- /api/index.php: -------------------------------------------------------------------------------- 1 | contentType('application/json'); 7 | $app->expires('-1000000'); 8 | $db = new PDO('sqlite:db.sqlite3'); 9 | 10 | function getTitleFromUrl($url) 11 | { 12 | preg_match('/5 | 9 | | 10 ||
---|---|
15 | |
21 |
22 |
23 |
24 |
25 |
27 |
28 | |
29 |