diff --git a/strillonews/batch.php b/strillonews/batch.php new file mode 100644 index 0000000..24bb5fd --- /dev/null +++ b/strillonews/batch.php @@ -0,0 +1,66 @@ + +load($dir.$resources[$i]); + + //elimino l'enstensione dal nome del file + $resource=substr($resources[$i],0, strlen($resources[$i])-4); + + //inserisco il campo id al nodo giornale + $giornale=$doc->getElementsByTagName('giornale')->item(0); + $hash_id=hash('SHA256',$resource); + + $idAttribute=$doc->createAttribute('id'); + $idAttribute->value=$hash_id; + $giornale->appendChild($idAttribute); + + //Ottengo il numero delle sezioni contenute nel file + $m=0; + $sezioni = $doc->getElementsByTagName('sezione'); + foreach ($sezioni as $sezione) { + + $m++; + } + //Riempio un array di contentente i nomi delle sezioni + $nomi = $doc->getElementsByTagName('nome'); + foreach ($nomi as $nome) { + + $nomi_sezioni[]=$nome->nodeValue; + } + + + + for ($l = 0; $l <= $m-1; $l++) { + + $sezioni = $doc->getElementsByTagName('sezione')->item($l); + $stringa_id=$resource; + $stringa_id .=$nomi_sezioni[$l]; + $hash_id=hash('SHA256', $stringa_id); + + $idAttribute=$doc->createAttribute('id'); + $idAttribute->value=$hash_id; + $sezioni->appendChild($idAttribute); + + } + + + $doc->saveXML(); + $doc->save($dir.$resources[$i]); +} + +?> \ No newline at end of file diff --git a/strillonews/composer.json b/strillonews/composer.json new file mode 100644 index 0000000..7d56e58 --- /dev/null +++ b/strillonews/composer.json @@ -0,0 +1,5 @@ +{ + "require": { + "slim/slim": "2.*" + } +} diff --git a/strillonews/composer.lock b/strillonews/composer.lock new file mode 100644 index 0000000..779841e --- /dev/null +++ b/strillonews/composer.lock @@ -0,0 +1,71 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file" + ], + "hash": "3572ef5486e01be41b96a1fdace500a6", + "packages": [ + { + "name": "slim/slim", + "version": "2.4.0", + "source": { + "type": "git", + "url": "https://github.com/codeguy/Slim.git", + "reference": "ff7d7148848fa4f45712984d7b91ac3cbced586b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/codeguy/Slim/zipball/ff7d7148848fa4f45712984d7b91ac3cbced586b", + "reference": "ff7d7148848fa4f45712984d7b91ac3cbced586b", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "suggest": { + "ext-mcrypt": "Required for HTTP cookie encryption" + }, + "type": "library", + "autoload": { + "psr-0": { + "Slim": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Josh Lockhart", + "email": "info@joshlockhart.com", + "homepage": "http://www.joshlockhart.com/" + } + ], + "description": "Slim Framework, a PHP micro framework", + "homepage": "http://github.com/codeguy/Slim", + "keywords": [ + "microframework", + "rest", + "router" + ], + "time": "2013-11-29 20:33:36" + } + ], + "packages-dev": [ + + ], + "aliases": [ + + ], + "minimum-stability": "stable", + "stability-flags": [ + + ], + "platform": [ + + ], + "platform-dev": [ + + ] +} diff --git a/strillonews/composer.phar b/strillonews/composer.phar new file mode 100644 index 0000000..a24b4ef Binary files /dev/null and b/strillonews/composer.phar differ diff --git a/strillonews/feeds/favole_racconti.xml b/strillonews/feeds/favole_racconti.xml new file mode 100644 index 0000000..af8732f --- /dev/null +++ b/strillonews/feeds/favole_racconti.xml @@ -0,0 +1,782 @@ + + + it + Favole e Racconti + 2013-05-18 + + Le favole di èsopo, volume 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Le favole di èsopo, volume 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Le favole di èsopo, volume 3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/strillonews/feeds/go_bari.xml b/strillonews/feeds/go_bari.xml new file mode 100644 index 0000000..761838b --- /dev/null +++ b/strillonews/feeds/go_bari.xml @@ -0,0 +1,6 @@ + + + it + Gofasano + 2014-11-15 + diff --git a/strillonews/feeds/go_fasano.xml b/strillonews/feeds/go_fasano.xml new file mode 100644 index 0000000..bf73ad0 --- /dev/null +++ b/strillonews/feeds/go_fasano.xml @@ -0,0 +1,111 @@ + + + it + Gofasano + 2014-11-15 + + Formazione e Lavoro + + + + + + + Gli ospiti di GoFasano + + + + + + + Politica + + + + + + diff --git a/strillonews/feeds/istruzioni_uso.xml b/strillonews/feeds/istruzioni_uso.xml new file mode 100644 index 0000000..a56a964 --- /dev/null +++ b/strillonews/feeds/istruzioni_uso.xml @@ -0,0 +1,70 @@ + + + it + Istruzioni d'uso strillone + 2014-11-15 + + Istruzioni di navigazione + + + + + + + Istruzioni per bookmarks + + + + + + + + + + + + + + + Istruzioni riconoscimento vocale + + + + + + diff --git a/strillonews/feeds/repubblicait.xml b/strillonews/feeds/repubblicait.xml new file mode 100644 index 0000000..693d6d1 --- /dev/null +++ b/strillonews/feeds/repubblicait.xml @@ -0,0 +1,2 @@ + +itRepubblica punto it2014-11-15HomepageCronacaPoliticaTecnologiaAmbienteEsteriCalcioSportAttualitaScienzeCulturaScuolaSolidaleEconomiaEconomia diff --git a/strillonews/feeds/test_inglese.xml b/strillonews/feeds/test_inglese.xml new file mode 100644 index 0000000..c04c66d --- /dev/null +++ b/strillonews/feeds/test_inglese.xml @@ -0,0 +1,121 @@ + + + en + Test News + 2012-12-28 + + Section 1: World + + + + + + + + + + + + + + + + + + + + + + + Section 2: U.S. + + + + + + + + + + + + + + + + + + + + + + + Section 3: Economy + + + + + + + + + + + + + + + + + + + + + + + Section 4: Technology + + + + + + + + + + + + + + + + + + + + + + + Section 5: Sports + + + + + + + + + + + + + + + + + + + + + + diff --git a/strillonews/feeds/test_portoghese.xml b/strillonews/feeds/test_portoghese.xml new file mode 100644 index 0000000..daa93e4 --- /dev/null +++ b/strillonews/feeds/test_portoghese.xml @@ -0,0 +1,52 @@ + + + pt + Test News + 2012-12-28 + + Section 1: Test + + + + + + + + + + + + + + + + + + diff --git a/strillonews/index.php b/strillonews/index.php new file mode 100644 index 0000000..4f1bf3e --- /dev/null +++ b/strillonews/index.php @@ -0,0 +1,67 @@ +response->headers->set('Content-Type', 'text/xml'); +# $app->config('debug', true); + +$app->get('/newspapers', 'get_newspapers'); +$app->get('/newspapers/:newspaper', 'get_newspaper'); + +$app->run(); + +function create_newspaper($doc, $lingua, $nome, $edizione, $resource, $id ,$beta = false) { + $newspaper = $doc->createElement('testata'); + + $newspaper->appendChild($doc->createElement('lingua', $lingua)); + $newspaper->appendChild($doc->createElement('nome', $nome)); + $newspaper->appendChild($doc->createElement('edizione', $edizione)); + $newspaper->appendChild($doc->createElement('resource', $resource)); + $idAttribute=$doc->createAttribute('id'); + $idAttribute->value=$id; + $newspaper->appendChild($idAttribute); + if ($beta) + $newspaper->appendChild($doc->createElement('beta', 'true')); + + return $newspaper; +} + +function get_newspapers() { + global $KEY_REPUBBLICA_IT, $KEY_GO_BARI, $KEY_GO_FASANO, $KEY_FAVOLE_E_RACCONTI, $KEY_TEST_INGLESE, $KEY_TEST_PORTOGHESE, $KEY_ISTRUZIONI_USO; + + $today = date('Y-m-d'); + $doc = new DOMDocument('1.0', 'UTF-8'); + $testate = $doc->createElement('testate'); + + $testate->appendChild(create_newspaper($doc, 'it', 'repubblica punto it', $today, $KEY_REPUBBLICA_IT ,hash('SHA256', $KEY_REPUBBLICA_IT))); + $testate->appendChild(create_newspaper($doc, 'it', 'go bari', $today, $KEY_GO_BARI,hash('SHA256', $KEY_GO_BARI))); + $testate->appendChild(create_newspaper($doc, 'it', 'go fasano', $today, $KEY_GO_FASANO,hash('SHA256', $KEY_GO_FASANO))); + $testate->appendChild(create_newspaper($doc, 'it', 'favole e racconti', $today, $KEY_FAVOLE_E_RACCONTI,hash('SHA256', $KEY_FAVOLE_E_RACCONTI))); + $testate->appendChild(create_newspaper($doc, 'en', 'test inglese', $today, $KEY_TEST_INGLESE,hash('SHA256',$KEY_TEST_INGLESE))); + $testate->appendChild(create_newspaper($doc, 'pt', 'test portoghese', $today, $KEY_TEST_PORTOGHESE,hash('SHA256',$KEY_TEST_PORTOGHESE ))); + $testate->appendChild(create_newspaper($doc, 'it', 'istruzioni d\'uso strillone', $today, $KEY_ISTRUZIONI_USO,hash('SHA256',$KEY_ISTRUZIONI_USO ))); + + + $doc->appendChild($testate); + echo $doc->saveXML(); +} + +function get_newspaper($newspaper) { + $file = 'feeds/' . $newspaper . '.xml'; + $fp = fopen($file, 'r'); + $n = fread($fp, filesize($file)); + fclose($fp); + + echo $n; +} + +?> diff --git a/strillonews/testate.php b/strillonews/testate.php new file mode 100644 index 0000000..314b958 --- /dev/null +++ b/strillonews/testate.php @@ -0,0 +1,55 @@ + + + + it + go bari + " . $today . " + http://www.walks.to/strillone/get_feed.php?giornale=go%20bari + + + + it + go fasano + " . $today . " + http://www.walks.to/strillone/get_feed.php?giornale=go%20fasano + + + + it + favole e racconti + " . $today . " + http://www.walks.to/strillone/feeds/favole_racconti.xml + + + + en + test inglese + " . $today . " + http://www.walks.to/strillone/feeds/test_inglese.xml + + + + pt + test portoghese + " . $today . " + http://www.walks.to/strillone/feeds/test_portoghese.xml + + + + it + test repubblica + " . $today . " + http://www.walks.to/strillone/feeds/test_repubblica.xml + + + +"; + +header('Content-Type: text/xml; charset=iso-8859-1'); +return $file_xml; +} diff --git a/strillonews/vendor/autoload.php b/strillonews/vendor/autoload.php new file mode 100644 index 0000000..8a68015 --- /dev/null +++ b/strillonews/vendor/autoload.php @@ -0,0 +1,7 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0 class loader + * + * See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + */ +class ClassLoader +{ + private $prefixes = array(); + private $fallbackDirs = array(); + private $useIncludePath = false; + private $classMap = array(); + + public function getPrefixes() + { + return call_user_func_array('array_merge', $this->prefixes); + } + + public function getFallbackDirs() + { + return $this->fallbackDirs; + } + + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param array $classMap Class to filename map + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of classes, merging with any others previously set. + * + * @param string $prefix The classes prefix + * @param array|string $paths The location(s) of the classes + * @param bool $prepend Prepend the location(s) + */ + public function add($prefix, $paths, $prepend = false) + { + if (!$prefix) { + if ($prepend) { + $this->fallbackDirs = array_merge( + (array) $paths, + $this->fallbackDirs + ); + } else { + $this->fallbackDirs = array_merge( + $this->fallbackDirs, + (array) $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixes[$first][$prefix])) { + $this->prefixes[$first][$prefix] = (array) $paths; + + return; + } + if ($prepend) { + $this->prefixes[$first][$prefix] = array_merge( + (array) $paths, + $this->prefixes[$first][$prefix] + ); + } else { + $this->prefixes[$first][$prefix] = array_merge( + $this->prefixes[$first][$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of classes, replacing any others previously set. + * + * @param string $prefix The classes prefix + * @param array|string $paths The location(s) of the classes + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirs = (array) $paths; + + return; + } + $this->prefixes[substr($prefix, 0, 1)][$prefix] = (array) $paths; + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + } + + /** + * Unregisters this instance as an autoloader. + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return bool|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + include $file; + + return true; + } + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731 + if ('\\' == $class[0]) { + $class = substr($class, 1); + } + + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $classPath = strtr(substr($class, 0, $pos), '\\', DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + $className = substr($class, $pos + 1); + } else { + // PEAR-like class name + $classPath = null; + $className = $class; + } + + $classPath .= strtr($className, '_', DIRECTORY_SEPARATOR) . '.php'; + + $first = $class[0]; + if (isset($this->prefixes[$first])) { + foreach ($this->prefixes[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($dir . DIRECTORY_SEPARATOR . $classPath)) { + return $dir . DIRECTORY_SEPARATOR . $classPath; + } + } + } + } + } + + foreach ($this->fallbackDirs as $dir) { + if (file_exists($dir . DIRECTORY_SEPARATOR . $classPath)) { + return $dir . DIRECTORY_SEPARATOR . $classPath; + } + } + + if ($this->useIncludePath && $file = stream_resolve_include_path($classPath)) { + return $file; + } + + return $this->classMap[$class] = false; + } +} diff --git a/strillonews/vendor/composer/autoload_classmap.php b/strillonews/vendor/composer/autoload_classmap.php new file mode 100644 index 0000000..7a91153 --- /dev/null +++ b/strillonews/vendor/composer/autoload_classmap.php @@ -0,0 +1,9 @@ + array($vendorDir . '/slim/slim'), +); diff --git a/strillonews/vendor/composer/autoload_real.php b/strillonews/vendor/composer/autoload_real.php new file mode 100644 index 0000000..9be03bc --- /dev/null +++ b/strillonews/vendor/composer/autoload_real.php @@ -0,0 +1,43 @@ + $path) { + $loader->set($namespace, $path); + } + + $classMap = require __DIR__ . '/autoload_classmap.php'; + if ($classMap) { + $loader->addClassMap($classMap); + } + + $loader->register(true); + + return $loader; + } +} diff --git a/strillonews/vendor/composer/installed.json b/strillonews/vendor/composer/installed.json new file mode 100644 index 0000000..447f19d --- /dev/null +++ b/strillonews/vendor/composer/installed.json @@ -0,0 +1,50 @@ +[ + { + "name": "slim/slim", + "version": "2.4.0", + "version_normalized": "2.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/codeguy/Slim.git", + "reference": "ff7d7148848fa4f45712984d7b91ac3cbced586b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/codeguy/Slim/zipball/ff7d7148848fa4f45712984d7b91ac3cbced586b", + "reference": "ff7d7148848fa4f45712984d7b91ac3cbced586b", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "suggest": { + "ext-mcrypt": "Required for HTTP cookie encryption" + }, + "time": "2013-11-29 20:33:36", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-0": { + "Slim": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Josh Lockhart", + "email": "info@joshlockhart.com", + "homepage": "http://www.joshlockhart.com/" + } + ], + "description": "Slim Framework, a PHP micro framework", + "homepage": "http://github.com/codeguy/Slim", + "keywords": [ + "microframework", + "rest", + "router" + ] + } +] diff --git a/strillonews/vendor/slim/slim/.htaccess b/strillonews/vendor/slim/slim/.htaccess new file mode 100644 index 0000000..b5f9c3c --- /dev/null +++ b/strillonews/vendor/slim/slim/.htaccess @@ -0,0 +1,10 @@ +RewriteEngine On + +# Some hosts may require you to use the `RewriteBase` directive. +# If you need to use the `RewriteBase` directive, it should be the +# absolute physical path to the directory that contains this htaccess file. +# +# RewriteBase / + +RewriteCond %{REQUEST_FILENAME} !-f +RewriteRule ^ index.php [QSA,L] \ No newline at end of file diff --git a/strillonews/vendor/slim/slim/.travis.yml b/strillonews/vendor/slim/slim/.travis.yml new file mode 100644 index 0000000..ac79ece --- /dev/null +++ b/strillonews/vendor/slim/slim/.travis.yml @@ -0,0 +1,8 @@ +language: php + +php: + - 5.3 + - 5.4 + - 5.5 + +script: phpunit --coverage-text diff --git a/strillonews/vendor/slim/slim/CONTRIBUTING.md b/strillonews/vendor/slim/slim/CONTRIBUTING.md new file mode 100644 index 0000000..9bbb6b1 --- /dev/null +++ b/strillonews/vendor/slim/slim/CONTRIBUTING.md @@ -0,0 +1,20 @@ +# How to Contribute + +## Pull Requests + +1. Fork the Slim Framework repository +2. Create a new branch for each feature or improvement +3. Send a pull request from each feature branch to the **develop** branch + +It is very important to separate new features or improvements into separate feature branches, and to send a +pull request for each branch. This allows me to review and pull in new features or improvements individually. + +## Style Guide + +All pull requests must adhere to the [PSR-2 standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md). + +## Unit Testing + +All pull requests must be accompanied by passing unit tests and complete code coverage. The Slim Framework uses phpunit for testing. + +[Learn about PHPUnit](https://github.com/sebastianbergmann/phpunit/) diff --git a/strillonews/vendor/slim/slim/LICENSE b/strillonews/vendor/slim/slim/LICENSE new file mode 100644 index 0000000..ec361cb --- /dev/null +++ b/strillonews/vendor/slim/slim/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012 Josh Lockhart + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/strillonews/vendor/slim/slim/README.markdown b/strillonews/vendor/slim/slim/README.markdown new file mode 100644 index 0000000..802624b --- /dev/null +++ b/strillonews/vendor/slim/slim/README.markdown @@ -0,0 +1,179 @@ +# Slim Framework + +[![Build Status](https://secure.travis-ci.org/codeguy/Slim.png?branch=master)](http://travis-ci.org/codeguy/Slim) + +Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs. +Slim is easy to use for both beginners and professionals. Slim favors cleanliness over terseness and common cases +over edge cases. Its interface is simple, intuitive, and extensively documented — both online and in the code itself. +Thank you for choosing the Slim Framework for your next project. I think you're going to love it. + +## Features + +* Powerful router + * Standard and custom HTTP methods + * Route parameters with wildcards and conditions + * Route redirect, halt, and pass + * Route middleware +* Resource Locator and DI container +* Template rendering with custom views +* Flash messages +* Secure cookies with AES-256 encryption +* HTTP caching +* Logging with custom log writers +* Error handling and debugging +* Middleware and hook architecture +* Simple configuration + +## Getting Started + +### Install + +You may install the Slim Framework with Composer (recommended) or manually. + +[Read how to install Slim](http://docs.slimframework.com/#Installation) + +### System Requirements + +You need **PHP >= 5.3.0**. If you use encrypted cookies, you'll also need the `mcrypt` extension. + +### Hello World Tutorial + +Instantiate a Slim application: + + $app = new \Slim\Slim(); + +Define a HTTP GET route: + + $app->get('/hello/:name', function ($name) { + echo "Hello, $name"; + }); + +Run the Slim application: + + $app->run(); + +### Setup your web server + +#### Apache + +Ensure the `.htaccess` and `index.php` files are in the same public-accessible directory. The `.htaccess` file +should contain this code: + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^ index.php [QSA,L] + +#### Nginx + +The nginx configuration file should contain this code (along with other settings you may need) in your `location` block: + + try_files $uri $uri/ /index.php?$args; + +This assumes that Slim's `index.php` is in the root folder of your project (www root). + +#### HipHop Virtual Machine for PHP + +Your HipHop Virtual Machine configuration file should contain this code (along with other settings you may need). +Be sure you change the `ServerRoot` setting to point to your Slim app's document root directory. + + Server { + SourceRoot = /path/to/public/directory + } + + ServerVariables { + SCRIPT_NAME = /index.php + } + + VirtualHost { + * { + Pattern = .* + RewriteRules { + * { + pattern = ^(.*)$ + to = index.php/$1 + qsa = true + } + } + } + } + +#### lighttpd #### + +Your lighttpd configuration file should contain this code (along with other settings you may need). This code requires +lighttpd >= 1.4.24. + + url.rewrite-if-not-file = ("(.*)" => "/index.php/$0") + +This assumes that Slim's `index.php` is in the root folder of your project (www root). + +#### IIS + +Ensure the `Web.config` and `index.php` files are in the same public-accessible directory. The `Web.config` file should contain this code: + + + + + + + + + + + + + + + + + + + +## Documentation + + + +## How to Contribute + +### Pull Requests + +1. Fork the Slim Framework repository +2. Create a new branch for each feature or improvement +3. Send a pull request from each feature branch to the **develop** branch + +It is very important to separate new features or improvements into separate feature branches, and to send a pull +request for each branch. This allows me to review and pull in new features or improvements individually. + +### Style Guide + +All pull requests must adhere to the [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) standard. + +### Unit Testing + +All pull requests must be accompanied by passing unit tests and complete code coverage. The Slim Framework uses +`phpunit` for testing. + +[Learn about PHPUnit](https://github.com/sebastianbergmann/phpunit/) + +## Community + +### Forum and Knowledgebase + +Visit Slim's official forum and knowledge base at where you can find announcements, +chat with fellow Slim users, ask questions, help others, or show off your cool Slim Framework apps. + +### Twitter + +Follow [@slimphp](http://www.twitter.com/slimphp) on Twitter to receive news and updates about the framework. + +## Author + +The Slim Framework is created and maintained by [Josh Lockhart](http://www.joshlockhart.com). Josh is a senior +web developer at [New Media Campaigns](http://www.newmediacampaigns.com/). Josh also created and maintains +[PHP: The Right Way](http://www.phptherightway.com/), a popular movement in the PHP community to introduce new +PHP programmers to best practices and good information. + +## License + +The Slim Framework is released under the MIT public license. + + diff --git a/strillonews/vendor/slim/slim/Slim/Environment.php b/strillonews/vendor/slim/slim/Slim/Environment.php new file mode 100644 index 0000000..8350b60 --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Environment.php @@ -0,0 +1,224 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +/** + * Environment + * + * This class creates and returns a key/value array of common + * environment variables for the current HTTP request. + * + * This is a singleton class; derived environment variables will + * be common across multiple Slim applications. + * + * This class matches the Rack (Ruby) specification as closely + * as possible. More information available below. + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +class Environment implements \ArrayAccess, \IteratorAggregate +{ + /** + * @var array + */ + protected $properties; + + /** + * @var \Slim\Environment + */ + protected static $environment; + + /** + * Get environment instance (singleton) + * + * This creates and/or returns an environment instance (singleton) + * derived from $_SERVER variables. You may override the global server + * variables by using `\Slim\Environment::mock()` instead. + * + * @param bool $refresh Refresh properties using global server variables? + * @return \Slim\Environment + */ + public static function getInstance($refresh = false) + { + if (is_null(self::$environment) || $refresh) { + self::$environment = new self(); + } + + return self::$environment; + } + + /** + * Get mock environment instance + * + * @param array $userSettings + * @return \Slim\Environment + */ + public static function mock($userSettings = array()) + { + $defaults = array( + 'REQUEST_METHOD' => 'GET', + 'SCRIPT_NAME' => '', + 'PATH_INFO' => '', + 'QUERY_STRING' => '', + 'SERVER_NAME' => 'localhost', + 'SERVER_PORT' => 80, + 'ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + 'ACCEPT_LANGUAGE' => 'en-US,en;q=0.8', + 'ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', + 'USER_AGENT' => 'Slim Framework', + 'REMOTE_ADDR' => '127.0.0.1', + 'slim.url_scheme' => 'http', + 'slim.input' => '', + 'slim.errors' => @fopen('php://stderr', 'w') + ); + self::$environment = new self(array_merge($defaults, $userSettings)); + + return self::$environment; + } + + /** + * Constructor (private access) + * + * @param array|null $settings If present, these are used instead of global server variables + */ + private function __construct($settings = null) + { + if ($settings) { + $this->properties = $settings; + } else { + $env = array(); + + //The HTTP request method + $env['REQUEST_METHOD'] = $_SERVER['REQUEST_METHOD']; + + //The IP + $env['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']; + + // Server params + $scriptName = $_SERVER['SCRIPT_NAME']; // <-- "/foo/index.php" + $requestUri = $_SERVER['REQUEST_URI']; // <-- "/foo/bar?test=abc" or "/foo/index.php/bar?test=abc" + $queryString = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''; // <-- "test=abc" or "" + + // Physical path + if (strpos($requestUri, $scriptName) !== false) { + $physicalPath = $scriptName; // <-- Without rewriting + } else { + $physicalPath = str_replace('\\', '', dirname($scriptName)); // <-- With rewriting + } + $env['SCRIPT_NAME'] = rtrim($physicalPath, '/'); // <-- Remove trailing slashes + + // Virtual path + $env['PATH_INFO'] = substr_replace($requestUri, '', 0, strlen($physicalPath)); // <-- Remove physical path + $env['PATH_INFO'] = str_replace('?' . $queryString, '', $env['PATH_INFO']); // <-- Remove query string + $env['PATH_INFO'] = '/' . ltrim($env['PATH_INFO'], '/'); // <-- Ensure leading slash + + // Query string (without leading "?") + $env['QUERY_STRING'] = $queryString; + + //Name of server host that is running the script + $env['SERVER_NAME'] = $_SERVER['SERVER_NAME']; + + //Number of server port that is running the script + $env['SERVER_PORT'] = $_SERVER['SERVER_PORT']; + + //HTTP request headers (retains HTTP_ prefix to match $_SERVER) + $headers = \Slim\Http\Headers::extract($_SERVER); + foreach ($headers as $key => $value) { + $env[$key] = $value; + } + + //Is the application running under HTTPS or HTTP protocol? + $env['slim.url_scheme'] = empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' ? 'http' : 'https'; + + //Input stream (readable one time only; not available for multipart/form-data requests) + $rawInput = @file_get_contents('php://input'); + if (!$rawInput) { + $rawInput = ''; + } + $env['slim.input'] = $rawInput; + + //Error stream + $env['slim.errors'] = @fopen('php://stderr', 'w'); + + $this->properties = $env; + } + } + + /** + * Array Access: Offset Exists + */ + public function offsetExists($offset) + { + return isset($this->properties[$offset]); + } + + /** + * Array Access: Offset Get + */ + public function offsetGet($offset) + { + if (isset($this->properties[$offset])) { + return $this->properties[$offset]; + } else { + return null; + } + } + + /** + * Array Access: Offset Set + */ + public function offsetSet($offset, $value) + { + $this->properties[$offset] = $value; + } + + /** + * Array Access: Offset Unset + */ + public function offsetUnset($offset) + { + unset($this->properties[$offset]); + } + + /** + * IteratorAggregate + * + * @return \ArrayIterator + */ + public function getIterator() + { + return new \ArrayIterator($this->properties); + } +} diff --git a/strillonews/vendor/slim/slim/Slim/Exception/Pass.php b/strillonews/vendor/slim/slim/Slim/Exception/Pass.php new file mode 100644 index 0000000..15c822e --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Exception/Pass.php @@ -0,0 +1,49 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Exception; + +/** + * Pass Exception + * + * This Exception will cause the Router::dispatch method + * to skip the current matching route and continue to the next + * matching route. If no subsequent routes are found, a + * HTTP 404 Not Found response will be sent to the client. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class Pass extends \Exception +{ +} diff --git a/strillonews/vendor/slim/slim/Slim/Exception/Stop.php b/strillonews/vendor/slim/slim/Slim/Exception/Stop.php new file mode 100644 index 0000000..ffb0560 --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Exception/Stop.php @@ -0,0 +1,47 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Exception; + +/** + * Stop Exception + * + * This Exception is thrown when the Slim application needs to abort + * processing and return control flow to the outer PHP script. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class Stop extends \Exception +{ +} diff --git a/strillonews/vendor/slim/slim/Slim/Helper/Set.php b/strillonews/vendor/slim/slim/Slim/Helper/Set.php new file mode 100644 index 0000000..e30a389 --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Helper/Set.php @@ -0,0 +1,246 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Helper; + +class Set implements \ArrayAccess, \Countable, \IteratorAggregate +{ + /** + * Key-value array of arbitrary data + * @var array + */ + protected $data = array(); + + /** + * Constructor + * @param array $items Pre-populate set with this key-value array + */ + public function __construct($items = array()) + { + $this->replace($items); + } + + /** + * Normalize data key + * + * Used to transform data key into the necessary + * key format for this set. Used in subclasses + * like \Slim\Http\Headers. + * + * @param string $key The data key + * @return mixed The transformed/normalized data key + */ + protected function normalizeKey($key) + { + return $key; + } + + /** + * Set data key to value + * @param string $key The data key + * @param mixed $value The data value + */ + public function set($key, $value) + { + $this->data[$this->normalizeKey($key)] = $value; + } + + /** + * Get data value with key + * @param string $key The data key + * @param mixed $default The value to return if data key does not exist + * @return mixed The data value, or the default value + */ + public function get($key, $default = null) + { + if ($this->has($key)) { + $isInvokable = is_object($this->data[$this->normalizeKey($key)]) && method_exists($this->data[$this->normalizeKey($key)], '__invoke'); + + return $isInvokable ? $this->data[$this->normalizeKey($key)]($this) : $this->data[$this->normalizeKey($key)]; + } + + return $default; + } + + /** + * Add data to set + * @param array $items Key-value array of data to append to this set + */ + public function replace($items) + { + foreach ($items as $key => $value) { + $this->set($key, $value); // Ensure keys are normalized + } + } + + /** + * Fetch set data + * @return array This set's key-value data array + */ + public function all() + { + return $this->data; + } + + /** + * Fetch set data keys + * @return array This set's key-value data array keys + */ + public function keys() + { + return array_keys($this->data); + } + + /** + * Does this set contain a key? + * @param string $key The data key + * @return boolean + */ + public function has($key) + { + return array_key_exists($this->normalizeKey($key), $this->data); + } + + /** + * Remove value with key from this set + * @param string $key The data key + */ + public function remove($key) + { + unset($this->data[$this->normalizeKey($key)]); + } + + /** + * Property Overloading + */ + + public function __get($key) + { + return $this->get($key); + } + + public function __set($key, $value) + { + $this->set($key, $value); + } + + public function __isset($key) + { + return $this->has($key); + } + + public function __unset($key) + { + return $this->remove($key); + } + + /** + * Clear all values + */ + public function clear() + { + $this->data = array(); + } + + /** + * Array Access + */ + + public function offsetExists($offset) + { + return $this->has($offset); + } + + public function offsetGet($offset) + { + return $this->get($offset); + } + + public function offsetSet($offset, $value) + { + $this->set($offset, $value); + } + + public function offsetUnset($offset) + { + $this->remove($offset); + } + + /** + * Countable + */ + + public function count() + { + return count($this->data); + } + + /** + * IteratorAggregate + */ + + public function getIterator() + { + return new \ArrayIterator($this->data); + } + + /** + * Ensure a value or object will remain globally unique + * @param string $key The value or object name + * @param Closure The closure that defines the object + * @return mixed + */ + public function singleton($key, $value) + { + $this->set($key, function ($c) use ($value) { + static $object; + + if (null === $object) { + $object = $value($c); + } + + return $object; + }); + } + + /** + * Protect closure from being directly invoked + * @param Closure $callable A closure to keep from being invoked and evaluated + * @return Closure + */ + public function protect(\Closure $callable) + { + return function () use ($callable) { + return $callable; + }; + } +} diff --git a/strillonews/vendor/slim/slim/Slim/Http/Cookies.php b/strillonews/vendor/slim/slim/Slim/Http/Cookies.php new file mode 100644 index 0000000..0d035b3 --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Http/Cookies.php @@ -0,0 +1,91 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Http; + +class Cookies extends \Slim\Helper\Set +{ + /** + * Default cookie settings + * @var array + */ + protected $defaults = array( + 'value' => '', + 'domain' => null, + 'path' => null, + 'expires' => null, + 'secure' => false, + 'httponly' => false + ); + + /** + * Set cookie + * + * The second argument may be a single scalar value, in which case + * it will be merged with the default settings and considered the `value` + * of the merged result. + * + * The second argument may also be an array containing any or all of + * the keys shown in the default settings above. This array will be + * merged with the defaults shown above. + * + * @param string $key Cookie name + * @param mixed $value Cookie settings + */ + public function set($key, $value) + { + if (is_array($value)) { + $cookieSettings = array_replace($this->defaults, $value); + } else { + $cookieSettings = array_replace($this->defaults, array('value' => $value)); + } + parent::set($key, $cookieSettings); + } + + /** + * Remove cookie + * + * Unlike \Slim\Helper\Set, this will actually *set* a cookie with + * an expiration date in the past. This expiration date will force + * the client-side cache to remove its cookie with the given name + * and settings. + * + * @param string $key Cookie name + * @param array $settings Optional cookie settings + */ + public function remove($key, $settings = array()) + { + $settings['value'] = ''; + $settings['expires'] = time() - 86400; + $this->set($key, array_replace($this->defaults, $settings)); + } +} diff --git a/strillonews/vendor/slim/slim/Slim/Http/Headers.php b/strillonews/vendor/slim/slim/Slim/Http/Headers.php new file mode 100644 index 0000000..ac05df3 --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Http/Headers.php @@ -0,0 +1,104 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Http; + + /** + * HTTP Headers + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +class Headers extends \Slim\Helper\Set +{ + /******************************************************************************** + * Static interface + *******************************************************************************/ + + /** + * Special-case HTTP headers that are otherwise unidentifiable as HTTP headers. + * Typically, HTTP headers in the $_SERVER array will be prefixed with + * `HTTP_` or `X_`. These are not so we list them here for later reference. + * + * @var array + */ + protected static $special = array( + 'CONTENT_TYPE', + 'CONTENT_LENGTH', + 'PHP_AUTH_USER', + 'PHP_AUTH_PW', + 'PHP_AUTH_DIGEST', + 'AUTH_TYPE' + ); + + /** + * Extract HTTP headers from an array of data (e.g. $_SERVER) + * @param array $data + * @return array + */ + public static function extract($data) + { + $results = array(); + foreach ($data as $key => $value) { + $key = strtoupper($key); + if (strpos($key, 'X_') === 0 || strpos($key, 'HTTP_') === 0 || in_array($key, static::$special)) { + if ($key === 'HTTP_CONTENT_TYPE' || $key === 'HTTP_CONTENT_LENGTH') { + continue; + } + $results[$key] = $value; + } + } + + return $results; + } + + /******************************************************************************** + * Instance interface + *******************************************************************************/ + + /** + * Transform header name into canonical form + * @param string $key + * @return string + */ + protected function normalizeKey($key) + { + $key = strtolower($key); + $key = str_replace(array('-', '_'), ' ', $key); + $key = preg_replace('#^http #', '', $key); + $key = ucwords($key); + $key = str_replace(' ', '-', $key); + + return $key; + } +} diff --git a/strillonews/vendor/slim/slim/Slim/Http/Request.php b/strillonews/vendor/slim/slim/Slim/Http/Request.php new file mode 100644 index 0000000..2a62242 --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Http/Request.php @@ -0,0 +1,614 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Http; + +/** + * Slim HTTP Request + * + * This class provides a human-friendly interface to the Slim environment variables; + * environment variables are passed by reference and will be modified directly. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class Request +{ + const METHOD_HEAD = 'HEAD'; + const METHOD_GET = 'GET'; + const METHOD_POST = 'POST'; + const METHOD_PUT = 'PUT'; + const METHOD_PATCH = 'PATCH'; + const METHOD_DELETE = 'DELETE'; + const METHOD_OPTIONS = 'OPTIONS'; + const METHOD_OVERRIDE = '_METHOD'; + + /** + * @var array + */ + protected static $formDataMediaTypes = array('application/x-www-form-urlencoded'); + + /** + * Application Environment + * @var \Slim\Environment + */ + protected $env; + + /** + * HTTP Headers + * @var \Slim\Http\Headers + */ + public $headers; + + /** + * HTTP Cookies + * @var \Slim\Helper\Set + */ + public $cookies; + + /** + * Constructor + * @param \Slim\Environment $env + */ + public function __construct(\Slim\Environment $env) + { + $this->env = $env; + $this->headers = new \Slim\Http\Headers(\Slim\Http\Headers::extract($env)); + $this->cookies = new \Slim\Helper\Set(\Slim\Http\Util::parseCookieHeader($env['HTTP_COOKIE'])); + } + + /** + * Get HTTP method + * @return string + */ + public function getMethod() + { + return $this->env['REQUEST_METHOD']; + } + + /** + * Is this a GET request? + * @return bool + */ + public function isGet() + { + return $this->getMethod() === self::METHOD_GET; + } + + /** + * Is this a POST request? + * @return bool + */ + public function isPost() + { + return $this->getMethod() === self::METHOD_POST; + } + + /** + * Is this a PUT request? + * @return bool + */ + public function isPut() + { + return $this->getMethod() === self::METHOD_PUT; + } + + /** + * Is this a PATCH request? + * @return bool + */ + public function isPatch() + { + return $this->getMethod() === self::METHOD_PATCH; + } + + /** + * Is this a DELETE request? + * @return bool + */ + public function isDelete() + { + return $this->getMethod() === self::METHOD_DELETE; + } + + /** + * Is this a HEAD request? + * @return bool + */ + public function isHead() + { + return $this->getMethod() === self::METHOD_HEAD; + } + + /** + * Is this a OPTIONS request? + * @return bool + */ + public function isOptions() + { + return $this->getMethod() === self::METHOD_OPTIONS; + } + + /** + * Is this an AJAX request? + * @return bool + */ + public function isAjax() + { + if ($this->params('isajax')) { + return true; + } elseif (isset($this->headers['X_REQUESTED_WITH']) && $this->headers['X_REQUESTED_WITH'] === 'XMLHttpRequest') { + return true; + } else { + return false; + } + } + + /** + * Is this an XHR request? (alias of Slim_Http_Request::isAjax) + * @return bool + */ + public function isXhr() + { + return $this->isAjax(); + } + + /** + * Fetch GET and POST data + * + * This method returns a union of GET and POST data as a key-value array, or the value + * of the array key if requested; if the array key does not exist, NULL is returned. + * + * @param string $key + * @return array|mixed|null + */ + public function params($key = null) + { + $union = array_merge($this->get(), $this->post()); + if ($key) { + return isset($union[$key]) ? $union[$key] : null; + } + + return $union; + } + + /** + * Fetch GET data + * + * This method returns a key-value array of data sent in the HTTP request query string, or + * the value of the array key if requested; if the array key does not exist, NULL is returned. + * + * @param string $key + * @param mixed $default Default return value when key does not exist + * @return array|mixed|null + */ + public function get($key = null, $default = null) + { + if (!isset($this->env['slim.request.query_hash'])) { + $output = array(); + if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) { + mb_parse_str($this->env['QUERY_STRING'], $output); + } else { + parse_str($this->env['QUERY_STRING'], $output); + } + $this->env['slim.request.query_hash'] = Util::stripSlashesIfMagicQuotes($output); + } + if ($key) { + if (isset($this->env['slim.request.query_hash'][$key])) { + return $this->env['slim.request.query_hash'][$key]; + } else { + return $default; + } + } else { + return $this->env['slim.request.query_hash']; + } + } + + /** + * Fetch POST data + * + * This method returns a key-value array of data sent in the HTTP request body, or + * the value of a hash key if requested; if the array key does not exist, NULL is returned. + * + * @param string $key + * @param mixed $default Default return value when key does not exist + * @return array|mixed|null + * @throws \RuntimeException If environment input is not available + */ + public function post($key = null, $default = null) + { + if (!isset($this->env['slim.input'])) { + throw new \RuntimeException('Missing slim.input in environment variables'); + } + if (!isset($this->env['slim.request.form_hash'])) { + $this->env['slim.request.form_hash'] = array(); + if ($this->isFormData() && is_string($this->env['slim.input'])) { + $output = array(); + if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) { + mb_parse_str($this->env['slim.input'], $output); + } else { + parse_str($this->env['slim.input'], $output); + } + $this->env['slim.request.form_hash'] = Util::stripSlashesIfMagicQuotes($output); + } else { + $this->env['slim.request.form_hash'] = Util::stripSlashesIfMagicQuotes($_POST); + } + } + if ($key) { + if (isset($this->env['slim.request.form_hash'][$key])) { + return $this->env['slim.request.form_hash'][$key]; + } else { + return $default; + } + } else { + return $this->env['slim.request.form_hash']; + } + } + + /** + * Fetch PUT data (alias for \Slim\Http\Request::post) + * @param string $key + * @param mixed $default Default return value when key does not exist + * @return array|mixed|null + */ + public function put($key = null, $default = null) + { + return $this->post($key, $default); + } + + /** + * Fetch PATCH data (alias for \Slim\Http\Request::post) + * @param string $key + * @param mixed $default Default return value when key does not exist + * @return array|mixed|null + */ + public function patch($key = null, $default = null) + { + return $this->post($key, $default); + } + + /** + * Fetch DELETE data (alias for \Slim\Http\Request::post) + * @param string $key + * @param mixed $default Default return value when key does not exist + * @return array|mixed|null + */ + public function delete($key = null, $default = null) + { + return $this->post($key, $default); + } + + /** + * Fetch COOKIE data + * + * This method returns a key-value array of Cookie data sent in the HTTP request, or + * the value of a array key if requested; if the array key does not exist, NULL is returned. + * + * @param string $key + * @return array|string|null + */ + public function cookies($key = null) + { + if ($key) { + return $this->cookies->get($key); + } + + return $this->cookies; + // if (!isset($this->env['slim.request.cookie_hash'])) { + // $cookieHeader = isset($this->env['COOKIE']) ? $this->env['COOKIE'] : ''; + // $this->env['slim.request.cookie_hash'] = Util::parseCookieHeader($cookieHeader); + // } + // if ($key) { + // if (isset($this->env['slim.request.cookie_hash'][$key])) { + // return $this->env['slim.request.cookie_hash'][$key]; + // } else { + // return null; + // } + // } else { + // return $this->env['slim.request.cookie_hash']; + // } + } + + /** + * Does the Request body contain parsed form data? + * @return bool + */ + public function isFormData() + { + $method = isset($this->env['slim.method_override.original_method']) ? $this->env['slim.method_override.original_method'] : $this->getMethod(); + + return ($method === self::METHOD_POST && is_null($this->getContentType())) || in_array($this->getMediaType(), self::$formDataMediaTypes); + } + + /** + * Get Headers + * + * This method returns a key-value array of headers sent in the HTTP request, or + * the value of a hash key if requested; if the array key does not exist, NULL is returned. + * + * @param string $key + * @param mixed $default The default value returned if the requested header is not available + * @return mixed + */ + public function headers($key = null, $default = null) + { + if ($key) { + return $this->headers->get($key, $default); + } + + return $this->headers; + // if ($key) { + // $key = strtoupper($key); + // $key = str_replace('-', '_', $key); + // $key = preg_replace('@^HTTP_@', '', $key); + // if (isset($this->env[$key])) { + // return $this->env[$key]; + // } else { + // return $default; + // } + // } else { + // $headers = array(); + // foreach ($this->env as $key => $value) { + // if (strpos($key, 'slim.') !== 0) { + // $headers[$key] = $value; + // } + // } + // + // return $headers; + // } + } + + /** + * Get Body + * @return string + */ + public function getBody() + { + return $this->env['slim.input']; + } + + /** + * Get Content Type + * @return string|null + */ + public function getContentType() + { + return $this->headers->get('CONTENT_TYPE'); + } + + /** + * Get Media Type (type/subtype within Content Type header) + * @return string|null + */ + public function getMediaType() + { + $contentType = $this->getContentType(); + if ($contentType) { + $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); + + return strtolower($contentTypeParts[0]); + } + + return null; + } + + /** + * Get Media Type Params + * @return array + */ + public function getMediaTypeParams() + { + $contentType = $this->getContentType(); + $contentTypeParams = array(); + if ($contentType) { + $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); + $contentTypePartsLength = count($contentTypeParts); + for ($i = 1; $i < $contentTypePartsLength; $i++) { + $paramParts = explode('=', $contentTypeParts[$i]); + $contentTypeParams[strtolower($paramParts[0])] = $paramParts[1]; + } + } + + return $contentTypeParams; + } + + /** + * Get Content Charset + * @return string|null + */ + public function getContentCharset() + { + $mediaTypeParams = $this->getMediaTypeParams(); + if (isset($mediaTypeParams['charset'])) { + return $mediaTypeParams['charset']; + } + + return null; + } + + /** + * Get Content-Length + * @return int + */ + public function getContentLength() + { + return $this->headers->get('CONTENT_LENGTH', 0); + } + + /** + * Get Host + * @return string + */ + public function getHost() + { + if (isset($this->env['HTTP_HOST'])) { + if (strpos($this->env['HTTP_HOST'], ':') !== false) { + $hostParts = explode(':', $this->env['HTTP_HOST']); + + return $hostParts[0]; + } + + return $this->env['HTTP_HOST']; + } + + return $this->env['SERVER_NAME']; + } + + /** + * Get Host with Port + * @return string + */ + public function getHostWithPort() + { + return sprintf('%s:%s', $this->getHost(), $this->getPort()); + } + + /** + * Get Port + * @return int + */ + public function getPort() + { + return (int)$this->env['SERVER_PORT']; + } + + /** + * Get Scheme (https or http) + * @return string + */ + public function getScheme() + { + return $this->env['slim.url_scheme']; + } + + /** + * Get Script Name (physical path) + * @return string + */ + public function getScriptName() + { + return $this->env['SCRIPT_NAME']; + } + + /** + * LEGACY: Get Root URI (alias for Slim_Http_Request::getScriptName) + * @return string + */ + public function getRootUri() + { + return $this->getScriptName(); + } + + /** + * Get Path (physical path + virtual path) + * @return string + */ + public function getPath() + { + return $this->getScriptName() . $this->getPathInfo(); + } + + /** + * Get Path Info (virtual path) + * @return string + */ + public function getPathInfo() + { + return $this->env['PATH_INFO']; + } + + /** + * LEGACY: Get Resource URI (alias for Slim_Http_Request::getPathInfo) + * @return string + */ + public function getResourceUri() + { + return $this->getPathInfo(); + } + + /** + * Get URL (scheme + host [ + port if non-standard ]) + * @return string + */ + public function getUrl() + { + $url = $this->getScheme() . '://' . $this->getHost(); + if (($this->getScheme() === 'https' && $this->getPort() !== 443) || ($this->getScheme() === 'http' && $this->getPort() !== 80)) { + $url .= sprintf(':%s', $this->getPort()); + } + + return $url; + } + + /** + * Get IP + * @return string + */ + public function getIp() + { + if (isset($this->env['X_FORWARDED_FOR'])) { + return $this->env['X_FORWARDED_FOR']; + } elseif (isset($this->env['CLIENT_IP'])) { + return $this->env['CLIENT_IP']; + } + + return $this->env['REMOTE_ADDR']; + } + + /** + * Get Referrer + * @return string|null + */ + public function getReferrer() + { + return $this->headers->get('HTTP_REFERER'); + } + + /** + * Get Referer (for those who can't spell) + * @return string|null + */ + public function getReferer() + { + return $this->getReferrer(); + } + + /** + * Get User Agent + * @return string|null + */ + public function getUserAgent() + { + return $this->headers->get('HTTP_USER_AGENT'); + } +} diff --git a/strillonews/vendor/slim/slim/Slim/Http/Response.php b/strillonews/vendor/slim/slim/Slim/Http/Response.php new file mode 100644 index 0000000..b740214 --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Http/Response.php @@ -0,0 +1,512 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Http; + +/** + * Response + * + * This is a simple abstraction over top an HTTP response. This + * provides methods to set the HTTP status, the HTTP headers, + * and the HTTP body. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class Response implements \ArrayAccess, \Countable, \IteratorAggregate +{ + /** + * @var int HTTP status code + */ + protected $status; + + /** + * @var \Slim\Http\Headers + */ + public $headers; + + /** + * @var \Slim\Http\Cookies + */ + public $cookies; + + /** + * @var string HTTP response body + */ + protected $body; + + /** + * @var int Length of HTTP response body + */ + protected $length; + + /** + * @var array HTTP response codes and messages + */ + protected static $messages = array( + //Informational 1xx + 100 => '100 Continue', + 101 => '101 Switching Protocols', + //Successful 2xx + 200 => '200 OK', + 201 => '201 Created', + 202 => '202 Accepted', + 203 => '203 Non-Authoritative Information', + 204 => '204 No Content', + 205 => '205 Reset Content', + 206 => '206 Partial Content', + //Redirection 3xx + 300 => '300 Multiple Choices', + 301 => '301 Moved Permanently', + 302 => '302 Found', + 303 => '303 See Other', + 304 => '304 Not Modified', + 305 => '305 Use Proxy', + 306 => '306 (Unused)', + 307 => '307 Temporary Redirect', + //Client Error 4xx + 400 => '400 Bad Request', + 401 => '401 Unauthorized', + 402 => '402 Payment Required', + 403 => '403 Forbidden', + 404 => '404 Not Found', + 405 => '405 Method Not Allowed', + 406 => '406 Not Acceptable', + 407 => '407 Proxy Authentication Required', + 408 => '408 Request Timeout', + 409 => '409 Conflict', + 410 => '410 Gone', + 411 => '411 Length Required', + 412 => '412 Precondition Failed', + 413 => '413 Request Entity Too Large', + 414 => '414 Request-URI Too Long', + 415 => '415 Unsupported Media Type', + 416 => '416 Requested Range Not Satisfiable', + 417 => '417 Expectation Failed', + 418 => '418 I\'m a teapot', + 422 => '422 Unprocessable Entity', + 423 => '423 Locked', + //Server Error 5xx + 500 => '500 Internal Server Error', + 501 => '501 Not Implemented', + 502 => '502 Bad Gateway', + 503 => '503 Service Unavailable', + 504 => '504 Gateway Timeout', + 505 => '505 HTTP Version Not Supported' + ); + + /** + * Constructor + * @param string $body The HTTP response body + * @param int $status The HTTP response status + * @param \Slim\Http\Headers|array $headers The HTTP response headers + */ + public function __construct($body = '', $status = 200, $headers = array()) + { + $this->setStatus($status); + $this->headers = new \Slim\Http\Headers(array('Content-Type' => 'text/html')); + $this->headers->replace($headers); + $this->cookies = new \Slim\Http\Cookies(); + $this->write($body); + } + + public function getStatus() + { + return $this->status; + } + + public function setStatus($status) + { + $this->status = (int)$status; + } + + /** + * DEPRECATION WARNING! Use `getStatus` or `setStatus` instead. + * + * Get and set status + * @param int|null $status + * @return int + */ + public function status($status = null) + { + if (!is_null($status)) { + $this->status = (int) $status; + } + + return $this->status; + } + + /** + * DEPRECATION WARNING! Access `headers` property directly. + * + * Get and set header + * @param string $name Header name + * @param string|null $value Header value + * @return string Header value + */ + public function header($name, $value = null) + { + if (!is_null($value)) { + $this->headers->set($name, $value); + } + + return $this->headers->get($name); + } + + /** + * DEPRECATION WARNING! Access `headers` property directly. + * + * Get headers + * @return \Slim\Http\Headers + */ + public function headers() + { + return $this->headers; + } + + public function getBody() + { + return $this->body; + } + + public function setBody($content) + { + $this->write($content, true); + } + + /** + * DEPRECATION WARNING! use `getBody` or `setBody` instead. + * + * Get and set body + * @param string|null $body Content of HTTP response body + * @return string + */ + public function body($body = null) + { + if (!is_null($body)) { + $this->write($body, true); + } + + return $this->body; + } + + /** + * Append HTTP response body + * @param string $body Content to append to the current HTTP response body + * @param bool $replace Overwrite existing response body? + * @return string The updated HTTP response body + */ + public function write($body, $replace = false) + { + if ($replace) { + $this->body = $body; + } else { + $this->body .= (string)$body; + } + $this->length = strlen($this->body); + + return $this->body; + } + + public function getLength() + { + return $this->length; + } + + /** + * DEPRECATION WARNING! Use `getLength` or `write` or `body` instead. + * + * Get and set length + * @param int|null $length + * @return int + */ + public function length($length = null) + { + if (!is_null($length)) { + $this->length = (int) $length; + } + + return $this->length; + } + + /** + * Finalize + * + * This prepares this response and returns an array + * of [status, headers, body]. This array is passed to outer middleware + * if available or directly to the Slim run method. + * + * @return array[int status, array headers, string body] + */ + public function finalize() + { + // Prepare response + if (in_array($this->status, array(204, 304))) { + $this->headers->remove('Content-Type'); + $this->headers->remove('Content-Length'); + $this->setBody(''); + } + + return array($this->status, $this->headers, $this->body); + } + + /** + * DEPRECATION WARNING! Access `cookies` property directly. + * + * Set cookie + * + * Instead of using PHP's `setcookie()` function, Slim manually constructs the HTTP `Set-Cookie` + * header on its own and delegates this responsibility to the `Slim_Http_Util` class. This + * response's header is passed by reference to the utility class and is directly modified. By not + * relying on PHP's native implementation, Slim allows middleware the opportunity to massage or + * analyze the raw header before the response is ultimately delivered to the HTTP client. + * + * @param string $name The name of the cookie + * @param string|array $value If string, the value of cookie; if array, properties for + * cookie including: value, expire, path, domain, secure, httponly + */ + public function setCookie($name, $value) + { + // Util::setCookieHeader($this->header, $name, $value); + $this->cookies->set($name, $value); + } + + /** + * DEPRECATION WARNING! Access `cookies` property directly. + * + * Delete cookie + * + * Instead of using PHP's `setcookie()` function, Slim manually constructs the HTTP `Set-Cookie` + * header on its own and delegates this responsibility to the `Slim_Http_Util` class. This + * response's header is passed by reference to the utility class and is directly modified. By not + * relying on PHP's native implementation, Slim allows middleware the opportunity to massage or + * analyze the raw header before the response is ultimately delivered to the HTTP client. + * + * This method will set a cookie with the given name that has an expiration time in the past; this will + * prompt the HTTP client to invalidate and remove the client-side cookie. Optionally, you may + * also pass a key/value array as the second argument. If the "domain" key is present in this + * array, only the Cookie with the given name AND domain will be removed. The invalidating cookie + * sent with this response will adopt all properties of the second argument. + * + * @param string $name The name of the cookie + * @param array $settings Properties for cookie including: value, expire, path, domain, secure, httponly + */ + public function deleteCookie($name, $settings = array()) + { + $this->cookies->remove($name, $settings); + // Util::deleteCookieHeader($this->header, $name, $value); + } + + /** + * Redirect + * + * This method prepares this response to return an HTTP Redirect response + * to the HTTP client. + * + * @param string $url The redirect destination + * @param int $status The redirect HTTP status code + */ + public function redirect ($url, $status = 302) + { + $this->setStatus($status); + $this->headers->set('Location', $url); + } + + /** + * Helpers: Empty? + * @return bool + */ + public function isEmpty() + { + return in_array($this->status, array(201, 204, 304)); + } + + /** + * Helpers: Informational? + * @return bool + */ + public function isInformational() + { + return $this->status >= 100 && $this->status < 200; + } + + /** + * Helpers: OK? + * @return bool + */ + public function isOk() + { + return $this->status === 200; + } + + /** + * Helpers: Successful? + * @return bool + */ + public function isSuccessful() + { + return $this->status >= 200 && $this->status < 300; + } + + /** + * Helpers: Redirect? + * @return bool + */ + public function isRedirect() + { + return in_array($this->status, array(301, 302, 303, 307)); + } + + /** + * Helpers: Redirection? + * @return bool + */ + public function isRedirection() + { + return $this->status >= 300 && $this->status < 400; + } + + /** + * Helpers: Forbidden? + * @return bool + */ + public function isForbidden() + { + return $this->status === 403; + } + + /** + * Helpers: Not Found? + * @return bool + */ + public function isNotFound() + { + return $this->status === 404; + } + + /** + * Helpers: Client error? + * @return bool + */ + public function isClientError() + { + return $this->status >= 400 && $this->status < 500; + } + + /** + * Helpers: Server Error? + * @return bool + */ + public function isServerError() + { + return $this->status >= 500 && $this->status < 600; + } + + /** + * DEPRECATION WARNING! ArrayAccess interface will be removed from \Slim\Http\Response. + * Iterate `headers` or `cookies` properties directly. + */ + + /** + * Array Access: Offset Exists + */ + public function offsetExists($offset) + { + return isset($this->headers[$offset]); + } + + /** + * Array Access: Offset Get + */ + public function offsetGet($offset) + { + return $this->headers[$offset]; + } + + /** + * Array Access: Offset Set + */ + public function offsetSet($offset, $value) + { + $this->headers[$offset] = $value; + } + + /** + * Array Access: Offset Unset + */ + public function offsetUnset($offset) + { + unset($this->headers[$offset]); + } + + /** + * DEPRECATION WARNING! Countable interface will be removed from \Slim\Http\Response. + * Call `count` on `headers` or `cookies` properties directly. + * + * Countable: Count + */ + public function count() + { + return count($this->headers); + } + + /** + * DEPRECATION WARNING! IteratorAggregate interface will be removed from \Slim\Http\Response. + * Iterate `headers` or `cookies` properties directly. + * + * Get Iterator + * + * This returns the contained `\Slim\Http\Headers` instance which + * is itself iterable. + * + * @return \Slim\Http\Headers + */ + public function getIterator() + { + return $this->headers->getIterator(); + } + + /** + * Get message for HTTP status code + * @param int $status + * @return string|null + */ + public static function getMessageForCode($status) + { + if (isset(self::$messages[$status])) { + return self::$messages[$status]; + } else { + return null; + } + } +} diff --git a/strillonews/vendor/slim/slim/Slim/Http/Util.php b/strillonews/vendor/slim/slim/Slim/Http/Util.php new file mode 100644 index 0000000..b95fe3d --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Http/Util.php @@ -0,0 +1,434 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Http; + +/** + * Slim HTTP Utilities + * + * This class provides useful methods for handling HTTP requests. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class Util +{ + /** + * Strip slashes from string or array + * + * This method strips slashes from its input. By default, this method will only + * strip slashes from its input if magic quotes are enabled. Otherwise, you may + * override the magic quotes setting with either TRUE or FALSE as the send argument + * to force this method to strip or not strip slashes from its input. + * + * @param array|string $rawData + * @param bool $overrideStripSlashes + * @return array|string + */ + public static function stripSlashesIfMagicQuotes($rawData, $overrideStripSlashes = null) + { + $strip = is_null($overrideStripSlashes) ? get_magic_quotes_gpc() : $overrideStripSlashes; + if ($strip) { + return self::stripSlashes($rawData); + } else { + return $rawData; + } + } + + /** + * Strip slashes from string or array + * @param array|string $rawData + * @return array|string + */ + protected static function stripSlashes($rawData) + { + return is_array($rawData) ? array_map(array('self', 'stripSlashes'), $rawData) : stripslashes($rawData); + } + + /** + * Encrypt data + * + * This method will encrypt data using a given key, vector, and cipher. + * By default, this will encrypt data using the RIJNDAEL/AES 256 bit cipher. You + * may override the default cipher and cipher mode by passing your own desired + * cipher and cipher mode as the final key-value array argument. + * + * @param string $data The unencrypted data + * @param string $key The encryption key + * @param string $iv The encryption initialization vector + * @param array $settings Optional key-value array with custom algorithm and mode + * @return string + */ + public static function encrypt($data, $key, $iv, $settings = array()) + { + if ($data === '' || !extension_loaded('mcrypt')) { + return $data; + } + + //Merge settings with defaults + $defaults = array( + 'algorithm' => MCRYPT_RIJNDAEL_256, + 'mode' => MCRYPT_MODE_CBC + ); + $settings = array_merge($defaults, $settings); + + //Get module + $module = mcrypt_module_open($settings['algorithm'], '', $settings['mode'], ''); + + //Validate IV + $ivSize = mcrypt_enc_get_iv_size($module); + if (strlen($iv) > $ivSize) { + $iv = substr($iv, 0, $ivSize); + } + + //Validate key + $keySize = mcrypt_enc_get_key_size($module); + if (strlen($key) > $keySize) { + $key = substr($key, 0, $keySize); + } + + //Encrypt value + mcrypt_generic_init($module, $key, $iv); + $res = @mcrypt_generic($module, $data); + mcrypt_generic_deinit($module); + + return $res; + } + + /** + * Decrypt data + * + * This method will decrypt data using a given key, vector, and cipher. + * By default, this will decrypt data using the RIJNDAEL/AES 256 bit cipher. You + * may override the default cipher and cipher mode by passing your own desired + * cipher and cipher mode as the final key-value array argument. + * + * @param string $data The encrypted data + * @param string $key The encryption key + * @param string $iv The encryption initialization vector + * @param array $settings Optional key-value array with custom algorithm and mode + * @return string + */ + public static function decrypt($data, $key, $iv, $settings = array()) + { + if ($data === '' || !extension_loaded('mcrypt')) { + return $data; + } + + //Merge settings with defaults + $defaults = array( + 'algorithm' => MCRYPT_RIJNDAEL_256, + 'mode' => MCRYPT_MODE_CBC + ); + $settings = array_merge($defaults, $settings); + + //Get module + $module = mcrypt_module_open($settings['algorithm'], '', $settings['mode'], ''); + + //Validate IV + $ivSize = mcrypt_enc_get_iv_size($module); + if (strlen($iv) > $ivSize) { + $iv = substr($iv, 0, $ivSize); + } + + //Validate key + $keySize = mcrypt_enc_get_key_size($module); + if (strlen($key) > $keySize) { + $key = substr($key, 0, $keySize); + } + + //Decrypt value + mcrypt_generic_init($module, $key, $iv); + $decryptedData = @mdecrypt_generic($module, $data); + $res = rtrim($decryptedData, "\0"); + mcrypt_generic_deinit($module); + + return $res; + } + + /** + * Serialize Response cookies into raw HTTP header + * @param \Slim\Http\Headers $headers The Response headers + * @param \Slim\Http\Cookies $cookies The Response cookies + * @param array $config The Slim app settings + */ + public static function serializeCookies(\Slim\Http\Headers &$headers, \Slim\Http\Cookies $cookies, array $config) + { + if ($config['cookies.encrypt']) { + foreach ($cookies as $name => $settings) { + if (is_string($settings['expires'])) { + $expires = strtotime($settings['expires']); + } else { + $expires = (int) $settings['expires']; + } + + $settings['value'] = static::encodeSecureCookie( + $settings['value'], + $expires, + $config['cookies.secret_key'], + $config['cookies.cipher'], + $config['cookies.cipher_mode'] + ); + static::setCookieHeader($headers, $name, $settings); + } + } else { + foreach ($cookies as $name => $settings) { + static::setCookieHeader($headers, $name, $settings); + } + } + } + + /** + * Encode secure cookie value + * + * This method will create the secure value of an HTTP cookie. The + * cookie value is encrypted and hashed so that its value is + * secure and checked for integrity when read in subsequent requests. + * + * @param string $value The insecure HTTP cookie value + * @param int $expires The UNIX timestamp at which this cookie will expire + * @param string $secret The secret key used to hash the cookie value + * @param int $algorithm The algorithm to use for encryption + * @param int $mode The algorithm mode to use for encryption + * @return string + */ + public static function encodeSecureCookie($value, $expires, $secret, $algorithm, $mode) + { + $key = hash_hmac('sha1', $expires, $secret); + $iv = self::getIv($expires, $secret); + $secureString = base64_encode( + self::encrypt( + $value, + $key, + $iv, + array( + 'algorithm' => $algorithm, + 'mode' => $mode + ) + ) + ); + $verificationString = hash_hmac('sha1', $expires . $value, $key); + + return implode('|', array($expires, $secureString, $verificationString)); + } + + /** + * Decode secure cookie value + * + * This method will decode the secure value of an HTTP cookie. The + * cookie value is encrypted and hashed so that its value is + * secure and checked for integrity when read in subsequent requests. + * + * @param string $value The secure HTTP cookie value + * @param string $secret The secret key used to hash the cookie value + * @param int $algorithm The algorithm to use for encryption + * @param int $mode The algorithm mode to use for encryption + * @return bool|string + */ + public static function decodeSecureCookie($value, $secret, $algorithm, $mode) + { + if ($value) { + $value = explode('|', $value); + if (count($value) === 3 && ((int) $value[0] === 0 || (int) $value[0] > time())) { + $key = hash_hmac('sha1', $value[0], $secret); + $iv = self::getIv($value[0], $secret); + $data = self::decrypt( + base64_decode($value[1]), + $key, + $iv, + array( + 'algorithm' => $algorithm, + 'mode' => $mode + ) + ); + $verificationString = hash_hmac('sha1', $value[0] . $data, $key); + if ($verificationString === $value[2]) { + return $data; + } + } + } + + return false; + } + + /** + * Set HTTP cookie header + * + * This method will construct and set the HTTP `Set-Cookie` header. Slim + * uses this method instead of PHP's native `setcookie` method. This allows + * more control of the HTTP header irrespective of the native implementation's + * dependency on PHP versions. + * + * This method accepts the Slim_Http_Headers object by reference as its + * first argument; this method directly modifies this object instead of + * returning a value. + * + * @param array $header + * @param string $name + * @param string $value + */ + public static function setCookieHeader(&$header, $name, $value) + { + //Build cookie header + if (is_array($value)) { + $domain = ''; + $path = ''; + $expires = ''; + $secure = ''; + $httponly = ''; + if (isset($value['domain']) && $value['domain']) { + $domain = '; domain=' . $value['domain']; + } + if (isset($value['path']) && $value['path']) { + $path = '; path=' . $value['path']; + } + if (isset($value['expires'])) { + if (is_string($value['expires'])) { + $timestamp = strtotime($value['expires']); + } else { + $timestamp = (int) $value['expires']; + } + if ($timestamp !== 0) { + $expires = '; expires=' . gmdate('D, d-M-Y H:i:s e', $timestamp); + } + } + if (isset($value['secure']) && $value['secure']) { + $secure = '; secure'; + } + if (isset($value['httponly']) && $value['httponly']) { + $httponly = '; HttpOnly'; + } + $cookie = sprintf('%s=%s%s', urlencode($name), urlencode((string) $value['value']), $domain . $path . $expires . $secure . $httponly); + } else { + $cookie = sprintf('%s=%s', urlencode($name), urlencode((string) $value)); + } + + //Set cookie header + if (!isset($header['Set-Cookie']) || $header['Set-Cookie'] === '') { + $header['Set-Cookie'] = $cookie; + } else { + $header['Set-Cookie'] = implode("\n", array($header['Set-Cookie'], $cookie)); + } + } + + /** + * Delete HTTP cookie header + * + * This method will construct and set the HTTP `Set-Cookie` header to invalidate + * a client-side HTTP cookie. If a cookie with the same name (and, optionally, domain) + * is already set in the HTTP response, it will also be removed. Slim uses this method + * instead of PHP's native `setcookie` method. This allows more control of the HTTP header + * irrespective of PHP's native implementation's dependency on PHP versions. + * + * This method accepts the Slim_Http_Headers object by reference as its + * first argument; this method directly modifies this object instead of + * returning a value. + * + * @param array $header + * @param string $name + * @param array $value + */ + public static function deleteCookieHeader(&$header, $name, $value = array()) + { + //Remove affected cookies from current response header + $cookiesOld = array(); + $cookiesNew = array(); + if (isset($header['Set-Cookie'])) { + $cookiesOld = explode("\n", $header['Set-Cookie']); + } + foreach ($cookiesOld as $c) { + if (isset($value['domain']) && $value['domain']) { + $regex = sprintf('@%s=.*domain=%s@', urlencode($name), preg_quote($value['domain'])); + } else { + $regex = sprintf('@%s=@', urlencode($name)); + } + if (preg_match($regex, $c) === 0) { + $cookiesNew[] = $c; + } + } + if ($cookiesNew) { + $header['Set-Cookie'] = implode("\n", $cookiesNew); + } else { + unset($header['Set-Cookie']); + } + + //Set invalidating cookie to clear client-side cookie + self::setCookieHeader($header, $name, array_merge(array('value' => '', 'path' => null, 'domain' => null, 'expires' => time() - 100), $value)); + } + + /** + * Parse cookie header + * + * This method will parse the HTTP request's `Cookie` header + * and extract cookies into an associative array. + * + * @param string + * @return array + */ + public static function parseCookieHeader($header) + { + $cookies = array(); + $header = rtrim($header, "\r\n"); + $headerPieces = preg_split('@\s*[;,]\s*@', $header); + foreach ($headerPieces as $c) { + $cParts = explode('=', $c); + if (count($cParts) === 2) { + $key = urldecode($cParts[0]); + $value = urldecode($cParts[1]); + if (!isset($cookies[$key])) { + $cookies[$key] = $value; + } + } + } + + return $cookies; + } + + /** + * Generate a random IV + * + * This method will generate a non-predictable IV for use with + * the cookie encryption + * + * @param int $expires The UNIX timestamp at which this cookie will expire + * @param string $secret The secret key used to hash the cookie value + * @return string Hash + */ + private static function getIv($expires, $secret) + { + $data1 = hash_hmac('sha1', 'a'.$expires.'b', $secret); + $data2 = hash_hmac('sha1', 'z'.$expires.'y', $secret); + + return pack("h*", $data1.$data2); + } +} diff --git a/strillonews/vendor/slim/slim/Slim/Log.php b/strillonews/vendor/slim/slim/Slim/Log.php new file mode 100644 index 0000000..eb9543e --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Log.php @@ -0,0 +1,349 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +/** + * Log + * + * This is the primary logger for a Slim application. You may provide + * a Log Writer in conjunction with this Log to write to various output + * destinations (e.g. a file). This class provides this interface: + * + * debug( mixed $object, array $context ) + * info( mixed $object, array $context ) + * notice( mixed $object, array $context ) + * warning( mixed $object, array $context ) + * error( mixed $object, array $context ) + * critical( mixed $object, array $context ) + * alert( mixed $object, array $context ) + * emergency( mixed $object, array $context ) + * log( mixed $level, mixed $object, array $context ) + * + * This class assumes only that your Log Writer has a public `write()` method + * that accepts any object as its one and only argument. The Log Writer + * class may write or send its argument anywhere: a file, STDERR, + * a remote web API, etc. The possibilities are endless. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class Log +{ + const EMERGENCY = 1; + const ALERT = 2; + const CRITICAL = 3; + const FATAL = 3; //DEPRECATED replace with CRITICAL + const ERROR = 4; + const WARN = 5; + const NOTICE = 6; + const INFO = 7; + const DEBUG = 8; + + /** + * @var array + */ + protected static $levels = array( + self::EMERGENCY => 'EMERGENCY', + self::ALERT => 'ALERT', + self::CRITICAL => 'CRITICAL', + self::ERROR => 'ERROR', + self::WARN => 'WARNING', + self::NOTICE => 'NOTICE', + self::INFO => 'INFO', + self::DEBUG => 'DEBUG' + ); + + /** + * @var mixed + */ + protected $writer; + + /** + * @var bool + */ + protected $enabled; + + /** + * @var int + */ + protected $level; + + /** + * Constructor + * @param mixed $writer + */ + public function __construct($writer) + { + $this->writer = $writer; + $this->enabled = true; + $this->level = self::DEBUG; + } + + /** + * Is logging enabled? + * @return bool + */ + public function getEnabled() + { + return $this->enabled; + } + + /** + * Enable or disable logging + * @param bool $enabled + */ + public function setEnabled($enabled) + { + if ($enabled) { + $this->enabled = true; + } else { + $this->enabled = false; + } + } + + /** + * Set level + * @param int $level + * @throws \InvalidArgumentException If invalid log level specified + */ + public function setLevel($level) + { + if (!isset(self::$levels[$level])) { + throw new \InvalidArgumentException('Invalid log level'); + } + $this->level = $level; + } + + /** + * Get level + * @return int + */ + public function getLevel() + { + return $this->level; + } + + /** + * Set writer + * @param mixed $writer + */ + public function setWriter($writer) + { + $this->writer = $writer; + } + + /** + * Get writer + * @return mixed + */ + public function getWriter() + { + return $this->writer; + } + + /** + * Is logging enabled? + * @return bool + */ + public function isEnabled() + { + return $this->enabled; + } + + /** + * Log debug message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function debug($object, $context = array()) + { + return $this->log(self::DEBUG, $object, $context); + } + + /** + * Log info message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function info($object, $context = array()) + { + return $this->log(self::INFO, $object, $context); + } + + /** + * Log notice message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function notice($object, $context = array()) + { + return $this->log(self::NOTICE, $object, $context); + } + + /** + * Log warning message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function warning($object, $context = array()) + { + return $this->log(self::WARN, $object, $context); + } + + /** + * DEPRECATED for function warning + * Log warning message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function warn($object, $context = array()) + { + return $this->log(self::WARN, $object, $context); + } + + /** + * Log error message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function error($object, $context = array()) + { + return $this->log(self::ERROR, $object, $context); + } + + /** + * Log critical message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function critical($object, $context = array()) + { + return $this->log(self::CRITICAL, $object, $context); + } + + /** + * DEPRECATED for function critical + * Log fatal message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function fatal($object, $context = array()) + { + return $this->log(self::CRITICAL, $object, $context); + } + + /** + * Log alert message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function alert($object, $context = array()) + { + return $this->log(self::ALERT, $object, $context); + } + + /** + * Log emergency message + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + */ + public function emergency($object, $context = array()) + { + return $this->log(self::EMERGENCY, $object, $context); + } + + /** + * Log message + * @param mixed $level + * @param mixed $object + * @param array $context + * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled + * @throws \InvalidArgumentException If invalid log level + */ + public function log($level, $object, $context = array()) + { + if (!isset(self::$levels[$level])) { + throw new \InvalidArgumentException('Invalid log level supplied to function'); + } else if ($this->enabled && $this->writer && $level <= $this->level) { + $message = (string)$object; + if (count($context) > 0) { + if (isset($context['exception']) && $context['exception'] instanceof \Exception) { + $message .= ' - ' . $context['exception']; + unset($context['exception']); + } + $message = $this->interpolate($message, $context); + } + return $this->writer->write($message, $level); + } else { + return false; + } + } + + /** + * DEPRECATED for function log + * Log message + * @param mixed $object The object to log + * @param int $level The message level + * @return int|bool + */ + protected function write($object, $level) + { + return $this->log($level, $object); + } + + /** + * Interpolate log message + * @param mixed $message The log message + * @param array $context An array of placeholder values + * @return string The processed string + */ + protected function interpolate($message, $context = array()) + { + $replace = array(); + foreach ($context as $key => $value) { + $replace['{' . $key . '}'] = $value; + } + return strtr($message, $replace); + } +} diff --git a/strillonews/vendor/slim/slim/Slim/LogWriter.php b/strillonews/vendor/slim/slim/Slim/LogWriter.php new file mode 100644 index 0000000..e230899 --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/LogWriter.php @@ -0,0 +1,75 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +/** + * Log Writer + * + * This class is used by Slim_Log to write log messages to a valid, writable + * resource handle (e.g. a file or STDERR). + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +class LogWriter +{ + /** + * @var resource + */ + protected $resource; + + /** + * Constructor + * @param resource $resource + * @throws \InvalidArgumentException If invalid resource + */ + public function __construct($resource) + { + if (!is_resource($resource)) { + throw new \InvalidArgumentException('Cannot create LogWriter. Invalid resource handle.'); + } + $this->resource = $resource; + } + + /** + * Write message + * @param mixed $message + * @param int $level + * @return int|bool + */ + public function write($message, $level = null) + { + return fwrite($this->resource, (string) $message . PHP_EOL); + } +} diff --git a/strillonews/vendor/slim/slim/Slim/Middleware.php b/strillonews/vendor/slim/slim/Slim/Middleware.php new file mode 100644 index 0000000..61d670b --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Middleware.php @@ -0,0 +1,114 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +/** + * Middleware + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +abstract class Middleware +{ + /** + * @var \Slim\Slim Reference to the primary application instance + */ + protected $app; + + /** + * @var mixed Reference to the next downstream middleware + */ + protected $next; + + /** + * Set application + * + * This method injects the primary Slim application instance into + * this middleware. + * + * @param \Slim\Slim $application + */ + final public function setApplication($application) + { + $this->app = $application; + } + + /** + * Get application + * + * This method retrieves the application previously injected + * into this middleware. + * + * @return \Slim\Slim + */ + final public function getApplication() + { + return $this->app; + } + + /** + * Set next middleware + * + * This method injects the next downstream middleware into + * this middleware so that it may optionally be called + * when appropriate. + * + * @param \Slim|\Slim\Middleware + */ + final public function setNextMiddleware($nextMiddleware) + { + $this->next = $nextMiddleware; + } + + /** + * Get next middleware + * + * This method retrieves the next downstream middleware + * previously injected into this middleware. + * + * @return \Slim\Slim|\Slim\Middleware + */ + final public function getNextMiddleware() + { + return $this->next; + } + + /** + * Call + * + * Perform actions specific to this middleware and optionally + * call the next downstream middleware. + */ + abstract public function call(); +} diff --git a/strillonews/vendor/slim/slim/Slim/Middleware/ContentTypes.php b/strillonews/vendor/slim/slim/Slim/Middleware/ContentTypes.php new file mode 100644 index 0000000..3bdde0d --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Middleware/ContentTypes.php @@ -0,0 +1,174 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Middleware; + + /** + * Content Types + * + * This is middleware for a Slim application that intercepts + * the HTTP request body and parses it into the appropriate + * PHP data structure if possible; else it returns the HTTP + * request body unchanged. This is particularly useful + * for preparing the HTTP request body for an XML or JSON API. + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +class ContentTypes extends \Slim\Middleware +{ + /** + * @var array + */ + protected $contentTypes; + + /** + * Constructor + * @param array $settings + */ + public function __construct($settings = array()) + { + $defaults = array( + 'application/json' => array($this, 'parseJson'), + 'application/xml' => array($this, 'parseXml'), + 'text/xml' => array($this, 'parseXml'), + 'text/csv' => array($this, 'parseCsv') + ); + $this->contentTypes = array_merge($defaults, $settings); + } + + /** + * Call + */ + public function call() + { + $mediaType = $this->app->request()->getMediaType(); + if ($mediaType) { + $env = $this->app->environment(); + $env['slim.input_original'] = $env['slim.input']; + $env['slim.input'] = $this->parse($env['slim.input'], $mediaType); + } + $this->next->call(); + } + + /** + * Parse input + * + * This method will attempt to parse the request body + * based on its content type if available. + * + * @param string $input + * @param string $contentType + * @return mixed + */ + protected function parse ($input, $contentType) + { + if (isset($this->contentTypes[$contentType]) && is_callable($this->contentTypes[$contentType])) { + $result = call_user_func($this->contentTypes[$contentType], $input); + if ($result) { + return $result; + } + } + + return $input; + } + + /** + * Parse JSON + * + * This method converts the raw JSON input + * into an associative array. + * + * @param string $input + * @return array|string + */ + protected function parseJson($input) + { + if (function_exists('json_decode')) { + $result = json_decode($input, true); + if ($result) { + return $result; + } + } + } + + /** + * Parse XML + * + * This method creates a SimpleXMLElement + * based upon the XML input. If the SimpleXML + * extension is not available, the raw input + * will be returned unchanged. + * + * @param string $input + * @return \SimpleXMLElement|string + */ + protected function parseXml($input) + { + if (class_exists('SimpleXMLElement')) { + try { + $backup = libxml_disable_entity_loader(true); + $result = new \SimpleXMLElement($input); + libxml_disable_entity_loader($backup); + return $result; + } catch (\Exception $e) { + // Do nothing + } + } + + return $input; + } + + /** + * Parse CSV + * + * This method parses CSV content into a numeric array + * containing an array of data for each CSV line. + * + * @param string $input + * @return array + */ + protected function parseCsv($input) + { + $temp = fopen('php://memory', 'rw'); + fwrite($temp, $input); + fseek($temp, 0); + $res = array(); + while (($data = fgetcsv($temp)) !== false) { + $res[] = $data; + } + fclose($temp); + + return $res; + } +} diff --git a/strillonews/vendor/slim/slim/Slim/Middleware/Flash.php b/strillonews/vendor/slim/slim/Slim/Middleware/Flash.php new file mode 100644 index 0000000..5cea0db --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Middleware/Flash.php @@ -0,0 +1,212 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Middleware; + + /** + * Flash + * + * This is middleware for a Slim application that enables + * Flash messaging between HTTP requests. This allows you + * set Flash messages for the current request, for the next request, + * or to retain messages from the previous request through to + * the next request. + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +class Flash extends \Slim\Middleware implements \ArrayAccess, \IteratorAggregate, \Countable +{ + /** + * @var array + */ + protected $settings; + + /** + * @var array + */ + protected $messages; + + /** + * Constructor + * @param array $settings + */ + public function __construct($settings = array()) + { + $this->settings = array_merge(array('key' => 'slim.flash'), $settings); + $this->messages = array( + 'prev' => array(), //flash messages from prev request (loaded when middleware called) + 'next' => array(), //flash messages for next request + 'now' => array() //flash messages for current request + ); + } + + /** + * Call + */ + public function call() + { + //Read flash messaging from previous request if available + $this->loadMessages(); + + //Prepare flash messaging for current request + $env = $this->app->environment(); + $env['slim.flash'] = $this; + $this->next->call(); + $this->save(); + } + + /** + * Now + * + * Specify a flash message for a given key to be shown for the current request + * + * @param string $key + * @param string $value + */ + public function now($key, $value) + { + $this->messages['now'][(string) $key] = $value; + } + + /** + * Set + * + * Specify a flash message for a given key to be shown for the next request + * + * @param string $key + * @param string $value + */ + public function set($key, $value) + { + $this->messages['next'][(string) $key] = $value; + } + + /** + * Keep + * + * Retain flash messages from the previous request for the next request + */ + public function keep() + { + foreach ($this->messages['prev'] as $key => $val) { + $this->messages['next'][$key] = $val; + } + } + + /** + * Save + */ + public function save() + { + $_SESSION[$this->settings['key']] = $this->messages['next']; + } + + /** + * Load messages from previous request if available + */ + public function loadMessages() + { + if (isset($_SESSION[$this->settings['key']])) { + $this->messages['prev'] = $_SESSION[$this->settings['key']]; + } + } + + /** + * Return array of flash messages to be shown for the current request + * + * @return array + */ + public function getMessages() + { + return array_merge($this->messages['prev'], $this->messages['now']); + } + + /** + * Array Access: Offset Exists + */ + public function offsetExists($offset) + { + $messages = $this->getMessages(); + + return isset($messages[$offset]); + } + + /** + * Array Access: Offset Get + */ + public function offsetGet($offset) + { + $messages = $this->getMessages(); + + return isset($messages[$offset]) ? $messages[$offset] : null; + } + + /** + * Array Access: Offset Set + */ + public function offsetSet($offset, $value) + { + $this->now($offset, $value); + } + + /** + * Array Access: Offset Unset + */ + public function offsetUnset($offset) + { + unset($this->messages['prev'][$offset], $this->messages['now'][$offset]); + } + + /** + * Iterator Aggregate: Get Iterator + * @return \ArrayIterator + */ + public function getIterator() + { + $messages = $this->getMessages(); + + return new \ArrayIterator($messages); + } + + /** + * Countable: Count + */ + public function count() + { + return count($this->getMessages()); + } + + + +} diff --git a/strillonews/vendor/slim/slim/Slim/Middleware/MethodOverride.php b/strillonews/vendor/slim/slim/Slim/Middleware/MethodOverride.php new file mode 100644 index 0000000..25ea749 --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Middleware/MethodOverride.php @@ -0,0 +1,94 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Middleware; + + /** + * HTTP Method Override + * + * This is middleware for a Slim application that allows traditional + * desktop browsers to submit pseudo PUT and DELETE requests by relying + * on a pre-determined request parameter. Without this middleware, + * desktop browsers are only able to submit GET and POST requests. + * + * This middleware is included automatically! + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +class MethodOverride extends \Slim\Middleware +{ + /** + * @var array + */ + protected $settings; + + /** + * Constructor + * @param array $settings + */ + public function __construct($settings = array()) + { + $this->settings = array_merge(array('key' => '_METHOD'), $settings); + } + + /** + * Call + * + * Implements Slim middleware interface. This method is invoked and passed + * an array of environment variables. This middleware inspects the environment + * variables for the HTTP method override parameter; if found, this middleware + * modifies the environment settings so downstream middleware and/or the Slim + * application will treat the request with the desired HTTP method. + * + * @return array[status, header, body] + */ + public function call() + { + $env = $this->app->environment(); + if (isset($env['HTTP_X_HTTP_METHOD_OVERRIDE'])) { + // Header commonly used by Backbone.js and others + $env['slim.method_override.original_method'] = $env['REQUEST_METHOD']; + $env['REQUEST_METHOD'] = strtoupper($env['HTTP_X_HTTP_METHOD_OVERRIDE']); + } elseif (isset($env['REQUEST_METHOD']) && $env['REQUEST_METHOD'] === 'POST') { + // HTML Form Override + $req = new \Slim\Http\Request($env); + $method = $req->post($this->settings['key']); + if ($method) { + $env['slim.method_override.original_method'] = $env['REQUEST_METHOD']; + $env['REQUEST_METHOD'] = strtoupper($method); + } + } + $this->next->call(); + } +} diff --git a/strillonews/vendor/slim/slim/Slim/Middleware/PrettyExceptions.php b/strillonews/vendor/slim/slim/Slim/Middleware/PrettyExceptions.php new file mode 100644 index 0000000..3afb966 --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Middleware/PrettyExceptions.php @@ -0,0 +1,116 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Middleware; + +/** + * Pretty Exceptions + * + * This middleware catches any Exception thrown by the surrounded + * application and displays a developer-friendly diagnostic screen. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class PrettyExceptions extends \Slim\Middleware +{ + /** + * @var array + */ + protected $settings; + + /** + * Constructor + * @param array $settings + */ + public function __construct($settings = array()) + { + $this->settings = $settings; + } + + /** + * Call + */ + public function call() + { + try { + $this->next->call(); + } catch (\Exception $e) { + $log = $this->app->getLog(); // Force Slim to append log to env if not already + $env = $this->app->environment(); + $env['slim.log'] = $log; + $env['slim.log']->error($e); + $this->app->contentType('text/html'); + $this->app->response()->status(500); + $this->app->response()->body($this->renderBody($env, $e)); + } + } + + /** + * Render response body + * @param array $env + * @param \Exception $exception + * @return string + */ + protected function renderBody(&$env, $exception) + { + $title = 'Slim Application Error'; + $code = $exception->getCode(); + $message = $exception->getMessage(); + $file = $exception->getFile(); + $line = $exception->getLine(); + $trace = $exception->getTraceAsString(); + $html = sprintf('

%s

', $title); + $html .= '

The application could not run because of the following error:

'; + $html .= '

Details

'; + $html .= sprintf('
Type: %s
', get_class($exception)); + if ($code) { + $html .= sprintf('
Code: %s
', $code); + } + if ($message) { + $html .= sprintf('
Message: %s
', $message); + } + if ($file) { + $html .= sprintf('
File: %s
', $file); + } + if ($line) { + $html .= sprintf('
Line: %s
', $line); + } + if ($trace) { + $html .= '

Trace

'; + $html .= sprintf('
%s
', $trace); + } + + return sprintf("%s%s", $title, $html); + } +} diff --git a/strillonews/vendor/slim/slim/Slim/Middleware/SessionCookie.php b/strillonews/vendor/slim/slim/Slim/Middleware/SessionCookie.php new file mode 100644 index 0000000..cf6a02c --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Middleware/SessionCookie.php @@ -0,0 +1,210 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim\Middleware; + +/** + * Session Cookie + * + * This class provides an HTTP cookie storage mechanism + * for session data. This class avoids using a PHP session + * and instead serializes/unserializes the $_SESSION global + * variable to/from an HTTP cookie. + * + * You should NEVER store sensitive data in a client-side cookie + * in any format, encrypted (with cookies.encrypt) or not. If you + * need to store sensitive user information in a session, you should + * rely on PHP's native session implementation, or use other middleware + * to store session data in a database or alternative server-side cache. + * + * Because this class stores serialized session data in an HTTP cookie, + * you are inherently limited to 4 Kb. If you attempt to store + * more than this amount, serialization will fail. + * + * @package Slim + * @author Josh Lockhart + * @since 1.6.0 + */ +class SessionCookie extends \Slim\Middleware +{ + /** + * @var array + */ + protected $settings; + + /** + * Constructor + * + * @param array $settings + */ + public function __construct($settings = array()) + { + $defaults = array( + 'expires' => '20 minutes', + 'path' => '/', + 'domain' => null, + 'secure' => false, + 'httponly' => false, + 'name' => 'slim_session', + ); + $this->settings = array_merge($defaults, $settings); + if (is_string($this->settings['expires'])) { + $this->settings['expires'] = strtotime($this->settings['expires']); + } + + /** + * Session + * + * We must start a native PHP session to initialize the $_SESSION superglobal. + * However, we won't be using the native session store for persistence, so we + * disable the session cookie and cache limiter. We also set the session + * handler to this class instance to avoid PHP's native session file locking. + */ + ini_set('session.use_cookies', 0); + session_cache_limiter(false); + session_set_save_handler( + array($this, 'open'), + array($this, 'close'), + array($this, 'read'), + array($this, 'write'), + array($this, 'destroy'), + array($this, 'gc') + ); + } + + /** + * Call + */ + public function call() + { + $this->loadSession(); + $this->next->call(); + $this->saveSession(); + } + + /** + * Load session + */ + protected function loadSession() + { + if (session_id() === '') { + session_start(); + } + + $value = $this->app->getCookie($this->settings['name']); + + if ($value) { + try { + $_SESSION = unserialize($value); + } catch (\Exception $e) { + $this->app->getLog()->error('Error unserializing session cookie value! ' . $e->getMessage()); + } + } else { + $_SESSION = array(); + } + } + + /** + * Save session + */ + protected function saveSession() + { + $value = serialize($_SESSION); + + if (strlen($value) > 4096) { + $this->app->getLog()->error('WARNING! Slim\Middleware\SessionCookie data size is larger than 4KB. Content save failed.'); + } else { + $this->app->setCookie( + $this->settings['name'], + $value, + $this->settings['expires'], + $this->settings['path'], + $this->settings['domain'], + $this->settings['secure'], + $this->settings['httponly'] + ); + } + // session_destroy(); + } + + /******************************************************************************** + * Session Handler + *******************************************************************************/ + + /** + * @codeCoverageIgnore + */ + public function open($savePath, $sessionName) + { + return true; + } + + /** + * @codeCoverageIgnore + */ + public function close() + { + return true; + } + + /** + * @codeCoverageIgnore + */ + public function read($id) + { + return ''; + } + + /** + * @codeCoverageIgnore + */ + public function write($id, $data) + { + return true; + } + + /** + * @codeCoverageIgnore + */ + public function destroy($id) + { + return true; + } + + /** + * @codeCoverageIgnore + */ + public function gc($maxlifetime) + { + return true; + } +} diff --git a/strillonews/vendor/slim/slim/Slim/Route.php b/strillonews/vendor/slim/slim/Slim/Route.php new file mode 100644 index 0000000..2d963c7 --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Route.php @@ -0,0 +1,444 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +/** + * Route + * @package Slim + * @author Josh Lockhart, Thomas Bley + * @since 1.0.0 + */ +class Route +{ + /** + * @var string The route pattern (e.g. "/books/:id") + */ + protected $pattern; + + /** + * @var mixed The route callable + */ + protected $callable; + + /** + * @var array Conditions for this route's URL parameters + */ + protected $conditions = array(); + + /** + * @var array Default conditions applied to all route instances + */ + protected static $defaultConditions = array(); + + /** + * @var string The name of this route (optional) + */ + protected $name; + + /** + * @var array Key-value array of URL parameters + */ + protected $params = array(); + + /** + * @var array value array of URL parameter names + */ + protected $paramNames = array(); + + /** + * @var array key array of URL parameter names with + at the end + */ + protected $paramNamesPath = array(); + + /** + * @var array HTTP methods supported by this Route + */ + protected $methods = array(); + + /** + * @var array[Callable] Middleware to be run before only this route instance + */ + protected $middleware = array(); + + /** + * Constructor + * @param string $pattern The URL pattern (e.g. "/books/:id") + * @param mixed $callable Anything that returns TRUE for is_callable() + */ + public function __construct($pattern, $callable) + { + $this->setPattern($pattern); + $this->setCallable($callable); + $this->setConditions(self::getDefaultConditions()); + } + + /** + * Set default route conditions for all instances + * @param array $defaultConditions + */ + public static function setDefaultConditions(array $defaultConditions) + { + self::$defaultConditions = $defaultConditions; + } + + /** + * Get default route conditions for all instances + * @return array + */ + public static function getDefaultConditions() + { + return self::$defaultConditions; + } + + /** + * Get route pattern + * @return string + */ + public function getPattern() + { + return $this->pattern; + } + + /** + * Set route pattern + * @param string $pattern + */ + public function setPattern($pattern) + { + $this->pattern = $pattern; + } + + /** + * Get route callable + * @return mixed + */ + public function getCallable() + { + return $this->callable; + } + + /** + * Set route callable + * @param mixed $callable + * @throws \InvalidArgumentException If argument is not callable + */ + public function setCallable($callable) + { + $matches = array(); + if (is_string($callable) && preg_match('!^([^\:]+)\:([[:alnum:]]+)$!', $callable, $matches)) { + $callable = array(new $matches[1], $matches[2]); + } + + if (!is_callable($callable)) { + throw new \InvalidArgumentException('Route callable must be callable'); + } + + $this->callable = $callable; + } + + /** + * Get route conditions + * @return array + */ + public function getConditions() + { + return $this->conditions; + } + + /** + * Set route conditions + * @param array $conditions + */ + public function setConditions(array $conditions) + { + $this->conditions = $conditions; + } + + /** + * Get route name + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Set route name + * @param string $name + */ + public function setName($name) + { + $this->name = (string)$name; + } + + /** + * Get route parameters + * @return array + */ + public function getParams() + { + return $this->params; + } + + /** + * Set route parameters + * @param array $params + */ + public function setParams($params) + { + $this->params = $params; + } + + /** + * Get route parameter value + * @param string $index Name of URL parameter + * @return string + * @throws \InvalidArgumentException If route parameter does not exist at index + */ + public function getParam($index) + { + if (!isset($this->params[$index])) { + throw new \InvalidArgumentException('Route parameter does not exist at specified index'); + } + + return $this->params[$index]; + } + + /** + * Set route parameter value + * @param string $index Name of URL parameter + * @param mixed $value The new parameter value + * @throws \InvalidArgumentException If route parameter does not exist at index + */ + public function setParam($index, $value) + { + if (!isset($this->params[$index])) { + throw new \InvalidArgumentException('Route parameter does not exist at specified index'); + } + $this->params[$index] = $value; + } + + /** + * Add supported HTTP method(s) + */ + public function setHttpMethods() + { + $args = func_get_args(); + $this->methods = $args; + } + + /** + * Get supported HTTP methods + * @return array + */ + public function getHttpMethods() + { + return $this->methods; + } + + /** + * Append supported HTTP methods + */ + public function appendHttpMethods() + { + $args = func_get_args(); + $this->methods = array_merge($this->methods, $args); + } + + /** + * Append supported HTTP methods (alias for Route::appendHttpMethods) + * @return \Slim\Route + */ + public function via() + { + $args = func_get_args(); + $this->methods = array_merge($this->methods, $args); + + return $this; + } + + /** + * Detect support for an HTTP method + * @param string $method + * @return bool + */ + public function supportsHttpMethod($method) + { + return in_array($method, $this->methods); + } + + /** + * Get middleware + * @return array[Callable] + */ + public function getMiddleware() + { + return $this->middleware; + } + + /** + * Set middleware + * + * This method allows middleware to be assigned to a specific Route. + * If the method argument `is_callable` (including callable arrays!), + * we directly append the argument to `$this->middleware`. Else, we + * assume the argument is an array of callables and merge the array + * with `$this->middleware`. Each middleware is checked for is_callable() + * and an InvalidArgumentException is thrown immediately if it isn't. + * + * @param Callable|array[Callable] + * @return \Slim\Route + * @throws \InvalidArgumentException If argument is not callable or not an array of callables. + */ + public function setMiddleware($middleware) + { + if (is_callable($middleware)) { + $this->middleware[] = $middleware; + } elseif (is_array($middleware)) { + foreach ($middleware as $callable) { + if (!is_callable($callable)) { + throw new \InvalidArgumentException('All Route middleware must be callable'); + } + } + $this->middleware = array_merge($this->middleware, $middleware); + } else { + throw new \InvalidArgumentException('Route middleware must be callable or an array of callables'); + } + + return $this; + } + + /** + * Matches URI? + * + * Parse this route's pattern, and then compare it to an HTTP resource URI + * This method was modeled after the techniques demonstrated by Dan Sosedoff at: + * + * http://blog.sosedoff.com/2009/09/20/rails-like-php-url-router/ + * + * @param string $resourceUri A Request URI + * @return bool + */ + public function matches($resourceUri) + { + //Convert URL params into regex patterns, construct a regex for this route, init params + $patternAsRegex = preg_replace_callback( + '#:([\w]+)\+?#', + array($this, 'matchesCallback'), + str_replace(')', ')?', (string)$this->pattern) + ); + if (substr($this->pattern, -1) === '/') { + $patternAsRegex .= '?'; + } + + //Cache URL params' names and values if this route matches the current HTTP request + if (!preg_match('#^' . $patternAsRegex . '$#', $resourceUri, $paramValues)) { + return false; + } + foreach ($this->paramNames as $name) { + if (isset($paramValues[$name])) { + if (isset($this->paramNamesPath[$name])) { + $this->params[$name] = explode('/', urldecode($paramValues[$name])); + } else { + $this->params[$name] = urldecode($paramValues[$name]); + } + } + } + + return true; + } + + /** + * Convert a URL parameter (e.g. ":id", ":id+") into a regular expression + * @param array $m URL parameters + * @return string Regular expression for URL parameter + */ + protected function matchesCallback($m) + { + $this->paramNames[] = $m[1]; + if (isset($this->conditions[$m[1]])) { + return '(?P<' . $m[1] . '>' . $this->conditions[$m[1]] . ')'; + } + if (substr($m[0], -1) === '+') { + $this->paramNamesPath[$m[1]] = 1; + + return '(?P<' . $m[1] . '>.+)'; + } + + return '(?P<' . $m[1] . '>[^/]+)'; + } + + /** + * Set route name + * @param string $name The name of the route + * @return \Slim\Route + */ + public function name($name) + { + $this->setName($name); + + return $this; + } + + /** + * Merge route conditions + * @param array $conditions Key-value array of URL parameter conditions + * @return \Slim\Route + */ + public function conditions(array $conditions) + { + $this->conditions = array_merge($this->conditions, $conditions); + + return $this; + } + + /** + * Dispatch route + * + * This method invokes the route object's callable. If middleware is + * registered for the route, each callable middleware is invoked in + * the order specified. + * + * @return bool + */ + public function dispatch() + { + foreach ($this->middleware as $mw) { + call_user_func_array($mw, array($this)); + } + + $return = call_user_func_array($this->getCallable(), array_values($this->getParams())); + return ($return === false) ? false : true; + } +} diff --git a/strillonews/vendor/slim/slim/Slim/Router.php b/strillonews/vendor/slim/slim/Slim/Router.php new file mode 100644 index 0000000..0ff47b9 --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Router.php @@ -0,0 +1,257 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +/** + * Router + * + * This class organizes, iterates, and dispatches \Slim\Route objects. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class Router +{ + /** + * @var Route The current route (most recently dispatched) + */ + protected $currentRoute; + + /** + * @var array Lookup hash of all route objects + */ + protected $routes; + + /** + * @var array Lookup hash of named route objects, keyed by route name (lazy-loaded) + */ + protected $namedRoutes; + + /** + * @var array Array of route objects that match the request URI (lazy-loaded) + */ + protected $matchedRoutes; + + /** + * @var array Array containing all route groups + */ + protected $routeGroups; + + /** + * Constructor + */ + public function __construct() + { + $this->routes = array(); + $this->routeGroups = array(); + } + + /** + * Get Current Route object or the first matched one if matching has been performed + * @return \Slim\Route|null + */ + public function getCurrentRoute() + { + if ($this->currentRoute !== null) { + return $this->currentRoute; + } + + if (is_array($this->matchedRoutes) && count($this->matchedRoutes) > 0) { + return $this->matchedRoutes[0]; + } + + return null; + } + + /** + * Return route objects that match the given HTTP method and URI + * @param string $httpMethod The HTTP method to match against + * @param string $resourceUri The resource URI to match against + * @param bool $reload Should matching routes be re-parsed? + * @return array[\Slim\Route] + */ + public function getMatchedRoutes($httpMethod, $resourceUri, $reload = false) + { + if ($reload || is_null($this->matchedRoutes)) { + $this->matchedRoutes = array(); + foreach ($this->routes as $route) { + if (!$route->supportsHttpMethod($httpMethod) && !$route->supportsHttpMethod("ANY")) { + continue; + } + + if ($route->matches($resourceUri)) { + $this->matchedRoutes[] = $route; + } + } + } + + return $this->matchedRoutes; + } + + /** + * Add a route object to the router + * @param \Slim\Route $route The Slim Route + */ + public function map(\Slim\Route $route) + { + list($groupPattern, $groupMiddleware) = $this->processGroups(); + + $route->setPattern($groupPattern . $route->getPattern()); + $this->routes[] = $route; + + + foreach ($groupMiddleware as $middleware) { + $route->setMiddleware($middleware); + } + } + + /** + * A helper function for processing the group's pattern and middleware + * @return array Returns an array with the elements: pattern, middlewareArr + */ + protected function processGroups() + { + $pattern = ""; + $middleware = array(); + foreach ($this->routeGroups as $group) { + $k = key($group); + $pattern .= $k; + if (is_array($group[$k])) { + $middleware = array_merge($middleware, $group[$k]); + } + } + return array($pattern, $middleware); + } + + /** + * Add a route group to the array + * @param string $group The group pattern (ie. "/books/:id") + * @param array|null $middleware Optional parameter array of middleware + * @return int The index of the new group + */ + public function pushGroup($group, $middleware = array()) + { + return array_push($this->routeGroups, array($group => $middleware)); + } + + /** + * Removes the last route group from the array + * @return bool True if successful, else False + */ + public function popGroup() + { + return (array_pop($this->routeGroups) !== null); + } + + /** + * Get URL for named route + * @param string $name The name of the route + * @param array $params Associative array of URL parameter names and replacement values + * @throws \RuntimeException If named route not found + * @return string The URL for the given route populated with provided replacement values + */ + public function urlFor($name, $params = array()) + { + if (!$this->hasNamedRoute($name)) { + throw new \RuntimeException('Named route not found for name: ' . $name); + } + $search = array(); + foreach ($params as $key => $value) { + $search[] = '#:' . preg_quote($key, '#') . '\+?(?!\w)#'; + } + $pattern = preg_replace($search, $params, $this->getNamedRoute($name)->getPattern()); + + //Remove remnants of unpopulated, trailing optional pattern segments, escaped special characters + return preg_replace('#\(/?:.+\)|\(|\)|\\\\#', '', $pattern); + } + + /** + * Add named route + * @param string $name The route name + * @param \Slim\Route $route The route object + * @throws \RuntimeException If a named route already exists with the same name + */ + public function addNamedRoute($name, \Slim\Route $route) + { + if ($this->hasNamedRoute($name)) { + throw new \RuntimeException('Named route already exists with name: ' . $name); + } + $this->namedRoutes[(string) $name] = $route; + } + + /** + * Has named route + * @param string $name The route name + * @return bool + */ + public function hasNamedRoute($name) + { + $this->getNamedRoutes(); + + return isset($this->namedRoutes[(string) $name]); + } + + /** + * Get named route + * @param string $name + * @return \Slim\Route|null + */ + public function getNamedRoute($name) + { + $this->getNamedRoutes(); + if ($this->hasNamedRoute($name)) { + return $this->namedRoutes[(string) $name]; + } else { + return null; + } + } + + /** + * Get named routes + * @return \ArrayIterator + */ + public function getNamedRoutes() + { + if (is_null($this->namedRoutes)) { + $this->namedRoutes = array(); + foreach ($this->routes as $route) { + if ($route->getName() !== null) { + $this->addNamedRoute($route->getName(), $route); + } + } + } + + return new \ArrayIterator($this->namedRoutes); + } +} diff --git a/strillonews/vendor/slim/slim/Slim/Slim.php b/strillonews/vendor/slim/slim/Slim/Slim.php new file mode 100644 index 0000000..d0ca651 --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/Slim.php @@ -0,0 +1,1401 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +// Ensure mcrypt constants are defined even if mcrypt extension is not loaded +if (!extension_loaded('mcrypt')) { + define('MCRYPT_MODE_CBC', 0); + define('MCRYPT_RIJNDAEL_256', 0); +} + +/** + * Slim + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + * + * @property \Slim\Environment $environment + * @property \Slim\Http\Response $response + * @property \Slim\Http\Request $request + * @property \Slim\Router $router + */ +class Slim +{ + /** + * @const string + */ + const VERSION = '2.4.0'; + + /** + * @var \Slim\Helper\Set + */ + public $container; + + /** + * @var array[\Slim] + */ + protected static $apps = array(); + + /** + * @var string + */ + protected $name; + + /** + * @var array + */ + protected $middleware; + + /** + * @var mixed Callable to be invoked if application error + */ + protected $error; + + /** + * @var mixed Callable to be invoked if no matching routes are found + */ + protected $notFound; + + /** + * @var array + */ + protected $hooks = array( + 'slim.before' => array(array()), + 'slim.before.router' => array(array()), + 'slim.before.dispatch' => array(array()), + 'slim.after.dispatch' => array(array()), + 'slim.after.router' => array(array()), + 'slim.after' => array(array()) + ); + + /******************************************************************************** + * PSR-0 Autoloader + * + * Do not use if you are using Composer to autoload dependencies. + *******************************************************************************/ + + /** + * Slim PSR-0 autoloader + */ + public static function autoload($className) + { + $thisClass = str_replace(__NAMESPACE__.'\\', '', __CLASS__); + + $baseDir = __DIR__; + + if (substr($baseDir, -strlen($thisClass)) === $thisClass) { + $baseDir = substr($baseDir, 0, -strlen($thisClass)); + } + + $className = ltrim($className, '\\'); + $fileName = $baseDir; + $namespace = ''; + if ($lastNsPos = strripos($className, '\\')) { + $namespace = substr($className, 0, $lastNsPos); + $className = substr($className, $lastNsPos + 1); + $fileName .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; + } + $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; + + if (file_exists($fileName)) { + require $fileName; + } + } + + /** + * Register Slim's PSR-0 autoloader + */ + public static function registerAutoloader() + { + spl_autoload_register(__NAMESPACE__ . "\\Slim::autoload"); + } + + /******************************************************************************** + * Instantiation and Configuration + *******************************************************************************/ + + /** + * Constructor + * @param array $userSettings Associative array of application settings + */ + public function __construct(array $userSettings = array()) + { + // Setup IoC container + $this->container = new \Slim\Helper\Set(); + $this->container['settings'] = array_merge(static::getDefaultSettings(), $userSettings); + + // Default environment + $this->container->singleton('environment', function ($c) { + return \Slim\Environment::getInstance(); + }); + + // Default request + $this->container->singleton('request', function ($c) { + return new \Slim\Http\Request($c['environment']); + }); + + // Default response + $this->container->singleton('response', function ($c) { + return new \Slim\Http\Response(); + }); + + // Default router + $this->container->singleton('router', function ($c) { + return new \Slim\Router(); + }); + + // Default view + $this->container->singleton('view', function ($c) { + $viewClass = $c['settings']['view']; + $templatesPath = $c['settings']['templates.path']; + + $view = ($viewClass instanceOf \Slim\View) ? $viewClass : new $viewClass; + $view->setTemplatesDirectory($templatesPath); + return $view; + }); + + // Default log writer + $this->container->singleton('logWriter', function ($c) { + $logWriter = $c['settings']['log.writer']; + + return is_object($logWriter) ? $logWriter : new \Slim\LogWriter($c['environment']['slim.errors']); + }); + + // Default log + $this->container->singleton('log', function ($c) { + $log = new \Slim\Log($c['logWriter']); + $log->setEnabled($c['settings']['log.enabled']); + $log->setLevel($c['settings']['log.level']); + $env = $c['environment']; + $env['slim.log'] = $log; + + return $log; + }); + + // Default mode + $this->container['mode'] = function ($c) { + $mode = $c['settings']['mode']; + + if (isset($_ENV['SLIM_MODE'])) { + $mode = $_ENV['SLIM_MODE']; + } else { + $envMode = getenv('SLIM_MODE'); + if ($envMode !== false) { + $mode = $envMode; + } + } + + return $mode; + }; + + // Define default middleware stack + $this->middleware = array($this); + $this->add(new \Slim\Middleware\Flash()); + $this->add(new \Slim\Middleware\MethodOverride()); + + // Make default if first instance + if (is_null(static::getInstance())) { + $this->setName('default'); + } + } + + public function __get($name) + { + return $this->container[$name]; + } + + public function __set($name, $value) + { + $this->container[$name] = $value; + } + + public function __isset($name) + { + return isset($this->container[$name]); + } + + public function __unset($name) + { + unset($this->container[$name]); + } + + /** + * Get application instance by name + * @param string $name The name of the Slim application + * @return \Slim\Slim|null + */ + public static function getInstance($name = 'default') + { + return isset(static::$apps[$name]) ? static::$apps[$name] : null; + } + + /** + * Set Slim application name + * @param string $name The name of this Slim application + */ + public function setName($name) + { + $this->name = $name; + static::$apps[$name] = $this; + } + + /** + * Get Slim application name + * @return string|null + */ + public function getName() + { + return $this->name; + } + + /** + * Get default application settings + * @return array + */ + public static function getDefaultSettings() + { + return array( + // Application + 'mode' => 'development', + // Debugging + 'debug' => true, + // Logging + 'log.writer' => null, + 'log.level' => \Slim\Log::DEBUG, + 'log.enabled' => true, + // View + 'templates.path' => './templates', + 'view' => '\Slim\View', + // Cookies + 'cookies.encrypt' => false, + 'cookies.lifetime' => '20 minutes', + 'cookies.path' => '/', + 'cookies.domain' => null, + 'cookies.secure' => false, + 'cookies.httponly' => false, + // Encryption + 'cookies.secret_key' => 'CHANGE_ME', + 'cookies.cipher' => MCRYPT_RIJNDAEL_256, + 'cookies.cipher_mode' => MCRYPT_MODE_CBC, + // HTTP + 'http.version' => '1.1' + ); + } + + /** + * Configure Slim Settings + * + * This method defines application settings and acts as a setter and a getter. + * + * If only one argument is specified and that argument is a string, the value + * of the setting identified by the first argument will be returned, or NULL if + * that setting does not exist. + * + * If only one argument is specified and that argument is an associative array, + * the array will be merged into the existing application settings. + * + * If two arguments are provided, the first argument is the name of the setting + * to be created or updated, and the second argument is the setting value. + * + * @param string|array $name If a string, the name of the setting to set or retrieve. Else an associated array of setting names and values + * @param mixed $value If name is a string, the value of the setting identified by $name + * @return mixed The value of a setting if only one argument is a string + */ + public function config($name, $value = null) + { + if (func_num_args() === 1) { + if (is_array($name)) { + $this->settings = array_merge($this->settings, $name); + } else { + return isset($this->settings[$name]) ? $this->settings[$name] : null; + } + } else { + $settings = $this->settings; + $settings[$name] = $value; + $this->settings = $settings; + } + } + + /******************************************************************************** + * Application Modes + *******************************************************************************/ + + /** + * Get application mode + * + * This method determines the application mode. It first inspects the $_ENV + * superglobal for key `SLIM_MODE`. If that is not found, it queries + * the `getenv` function. Else, it uses the application `mode` setting. + * + * @return string + */ + public function getMode() + { + return $this->mode; + } + + /** + * Configure Slim for a given mode + * + * This method will immediately invoke the callable if + * the specified mode matches the current application mode. + * Otherwise, the callable is ignored. This should be called + * only _after_ you initialize your Slim app. + * + * @param string $mode + * @param mixed $callable + * @return void + */ + public function configureMode($mode, $callable) + { + if ($mode === $this->getMode() && is_callable($callable)) { + call_user_func($callable); + } + } + + /******************************************************************************** + * Logging + *******************************************************************************/ + + /** + * Get application log + * @return \Slim\Log + */ + public function getLog() + { + return $this->log; + } + + /******************************************************************************** + * Routing + *******************************************************************************/ + + /** + * Add GET|POST|PUT|PATCH|DELETE route + * + * Adds a new route to the router with associated callable. This + * route will only be invoked when the HTTP request's method matches + * this route's method. + * + * ARGUMENTS: + * + * First: string The URL pattern (REQUIRED) + * In-Between: mixed Anything that returns TRUE for `is_callable` (OPTIONAL) + * Last: mixed Anything that returns TRUE for `is_callable` (REQUIRED) + * + * The first argument is required and must always be the + * route pattern (ie. '/books/:id'). + * + * The last argument is required and must always be the callable object + * to be invoked when the route matches an HTTP request. + * + * You may also provide an unlimited number of in-between arguments; + * each interior argument must be callable and will be invoked in the + * order specified before the route's callable is invoked. + * + * USAGE: + * + * Slim::get('/foo'[, middleware, middleware, ...], callable); + * + * @param array (See notes above) + * @return \Slim\Route + */ + protected function mapRoute($args) + { + $pattern = array_shift($args); + $callable = array_pop($args); + $route = new \Slim\Route($pattern, $callable); + $this->router->map($route); + if (count($args) > 0) { + $route->setMiddleware($args); + } + + return $route; + } + + /** + * Add generic route without associated HTTP method + * @see mapRoute() + * @return \Slim\Route + */ + public function map() + { + $args = func_get_args(); + + return $this->mapRoute($args); + } + + /** + * Add GET route + * @see mapRoute() + * @return \Slim\Route + */ + public function get() + { + $args = func_get_args(); + + return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_GET, \Slim\Http\Request::METHOD_HEAD); + } + + /** + * Add POST route + * @see mapRoute() + * @return \Slim\Route + */ + public function post() + { + $args = func_get_args(); + + return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_POST); + } + + /** + * Add PUT route + * @see mapRoute() + * @return \Slim\Route + */ + public function put() + { + $args = func_get_args(); + + return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_PUT); + } + + /** + * Add PATCH route + * @see mapRoute() + * @return \Slim\Route + */ + public function patch() + { + $args = func_get_args(); + + return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_PATCH); + } + + /** + * Add DELETE route + * @see mapRoute() + * @return \Slim\Route + */ + public function delete() + { + $args = func_get_args(); + + return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_DELETE); + } + + /** + * Add OPTIONS route + * @see mapRoute() + * @return \Slim\Route + */ + public function options() + { + $args = func_get_args(); + + return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_OPTIONS); + } + + /** + * Route Groups + * + * This method accepts a route pattern and a callback all Route + * declarations in the callback will be prepended by the group(s) + * that it is in + * + * Accepts the same parameters as a standard route so: + * (pattern, middleware1, middleware2, ..., $callback) + */ + public function group() + { + $args = func_get_args(); + $pattern = array_shift($args); + $callable = array_pop($args); + $this->router->pushGroup($pattern, $args); + if (is_callable($callable)) { + call_user_func($callable); + } + $this->router->popGroup(); + } + + /* + * Add route for any HTTP method + * @see mapRoute() + * @return \Slim\Route + */ + public function any() + { + $args = func_get_args(); + + return $this->mapRoute($args)->via("ANY"); + } + + /** + * Not Found Handler + * + * This method defines or invokes the application-wide Not Found handler. + * There are two contexts in which this method may be invoked: + * + * 1. When declaring the handler: + * + * If the $callable parameter is not null and is callable, this + * method will register the callable to be invoked when no + * routes match the current HTTP request. It WILL NOT invoke the callable. + * + * 2. When invoking the handler: + * + * If the $callable parameter is null, Slim assumes you want + * to invoke an already-registered handler. If the handler has been + * registered and is callable, it is invoked and sends a 404 HTTP Response + * whose body is the output of the Not Found handler. + * + * @param mixed $callable Anything that returns true for is_callable() + */ + public function notFound ($callable = null) + { + if (is_callable($callable)) { + $this->notFound = $callable; + } else { + ob_start(); + if (is_callable($this->notFound)) { + call_user_func($this->notFound); + } else { + call_user_func(array($this, 'defaultNotFound')); + } + $this->halt(404, ob_get_clean()); + } + } + + /** + * Error Handler + * + * This method defines or invokes the application-wide Error handler. + * There are two contexts in which this method may be invoked: + * + * 1. When declaring the handler: + * + * If the $argument parameter is callable, this + * method will register the callable to be invoked when an uncaught + * Exception is detected, or when otherwise explicitly invoked. + * The handler WILL NOT be invoked in this context. + * + * 2. When invoking the handler: + * + * If the $argument parameter is not callable, Slim assumes you want + * to invoke an already-registered handler. If the handler has been + * registered and is callable, it is invoked and passed the caught Exception + * as its one and only argument. The error handler's output is captured + * into an output buffer and sent as the body of a 500 HTTP Response. + * + * @param mixed $argument Callable|\Exception + */ + public function error($argument = null) + { + if (is_callable($argument)) { + //Register error handler + $this->error = $argument; + } else { + //Invoke error handler + $this->response->status(500); + $this->response->body(''); + $this->response->write($this->callErrorHandler($argument)); + $this->stop(); + } + } + + /** + * Call error handler + * + * This will invoke the custom or default error handler + * and RETURN its output. + * + * @param \Exception|null $argument + * @return string + */ + protected function callErrorHandler($argument = null) + { + ob_start(); + if (is_callable($this->error)) { + call_user_func_array($this->error, array($argument)); + } else { + call_user_func_array(array($this, 'defaultError'), array($argument)); + } + + return ob_get_clean(); + } + + /******************************************************************************** + * Application Accessors + *******************************************************************************/ + + /** + * Get a reference to the Environment object + * @return \Slim\Environment + */ + public function environment() + { + return $this->environment; + } + + /** + * Get the Request object + * @return \Slim\Http\Request + */ + public function request() + { + return $this->request; + } + + /** + * Get the Response object + * @return \Slim\Http\Response + */ + public function response() + { + return $this->response; + } + + /** + * Get the Router object + * @return \Slim\Router + */ + public function router() + { + return $this->router; + } + + /** + * Get and/or set the View + * + * This method declares the View to be used by the Slim application. + * If the argument is a string, Slim will instantiate a new object + * of the same class. If the argument is an instance of View or a subclass + * of View, Slim will use the argument as the View. + * + * If a View already exists and this method is called to create a + * new View, data already set in the existing View will be + * transferred to the new View. + * + * @param string|\Slim\View $viewClass The name or instance of a \Slim\View subclass + * @return \Slim\View + */ + public function view($viewClass = null) + { + if (!is_null($viewClass)) { + $existingData = is_null($this->view) ? array() : $this->view->getData(); + if ($viewClass instanceOf \Slim\View) { + $this->view = $viewClass; + } else { + $this->view = new $viewClass(); + } + $this->view->appendData($existingData); + $this->view->setTemplatesDirectory($this->config('templates.path')); + } + + return $this->view; + } + + /******************************************************************************** + * Rendering + *******************************************************************************/ + + /** + * Render a template + * + * Call this method within a GET, POST, PUT, PATCH, DELETE, NOT FOUND, or ERROR + * callable to render a template whose output is appended to the + * current HTTP response body. How the template is rendered is + * delegated to the current View. + * + * @param string $template The name of the template passed into the view's render() method + * @param array $data Associative array of data made available to the view + * @param int $status The HTTP response status code to use (optional) + */ + public function render($template, $data = array(), $status = null) + { + if (!is_null($status)) { + $this->response->status($status); + } + $this->view->appendData($data); + $this->view->display($template); + } + + /******************************************************************************** + * HTTP Caching + *******************************************************************************/ + + /** + * Set Last-Modified HTTP Response Header + * + * Set the HTTP 'Last-Modified' header and stop if a conditional + * GET request's `If-Modified-Since` header matches the last modified time + * of the resource. The `time` argument is a UNIX timestamp integer value. + * When the current request includes an 'If-Modified-Since' header that + * matches the specified last modified time, the application will stop + * and send a '304 Not Modified' response to the client. + * + * @param int $time The last modified UNIX timestamp + * @throws \InvalidArgumentException If provided timestamp is not an integer + */ + public function lastModified($time) + { + if (is_integer($time)) { + $this->response->headers->set('Last-Modified', gmdate('D, d M Y H:i:s T', $time)); + if ($time === strtotime($this->request->headers->get('IF_MODIFIED_SINCE'))) { + $this->halt(304); + } + } else { + throw new \InvalidArgumentException('Slim::lastModified only accepts an integer UNIX timestamp value.'); + } + } + + /** + * Set ETag HTTP Response Header + * + * Set the etag header and stop if the conditional GET request matches. + * The `value` argument is a unique identifier for the current resource. + * The `type` argument indicates whether the etag should be used as a strong or + * weak cache validator. + * + * When the current request includes an 'If-None-Match' header with + * a matching etag, execution is immediately stopped. If the request + * method is GET or HEAD, a '304 Not Modified' response is sent. + * + * @param string $value The etag value + * @param string $type The type of etag to create; either "strong" or "weak" + * @throws \InvalidArgumentException If provided type is invalid + */ + public function etag($value, $type = 'strong') + { + //Ensure type is correct + if (!in_array($type, array('strong', 'weak'))) { + throw new \InvalidArgumentException('Invalid Slim::etag type. Expected "strong" or "weak".'); + } + + //Set etag value + $value = '"' . $value . '"'; + if ($type === 'weak') { + $value = 'W/'.$value; + } + $this->response['ETag'] = $value; + + //Check conditional GET + if ($etagsHeader = $this->request->headers->get('IF_NONE_MATCH')) { + $etags = preg_split('@\s*,\s*@', $etagsHeader); + if (in_array($value, $etags) || in_array('*', $etags)) { + $this->halt(304); + } + } + } + + /** + * Set Expires HTTP response header + * + * The `Expires` header tells the HTTP client the time at which + * the current resource should be considered stale. At that time the HTTP + * client will send a conditional GET request to the server; the server + * may return a 200 OK if the resource has changed, else a 304 Not Modified + * if the resource has not changed. The `Expires` header should be used in + * conjunction with the `etag()` or `lastModified()` methods above. + * + * @param string|int $time If string, a time to be parsed by `strtotime()`; + * If int, a UNIX timestamp; + */ + public function expires($time) + { + if (is_string($time)) { + $time = strtotime($time); + } + $this->response->headers->set('Expires', gmdate('D, d M Y H:i:s T', $time)); + } + + /******************************************************************************** + * HTTP Cookies + *******************************************************************************/ + + /** + * Set HTTP cookie to be sent with the HTTP response + * + * @param string $name The cookie name + * @param string $value The cookie value + * @param int|string $time The duration of the cookie; + * If integer, should be UNIX timestamp; + * If string, converted to UNIX timestamp with `strtotime`; + * @param string $path The path on the server in which the cookie will be available on + * @param string $domain The domain that the cookie is available to + * @param bool $secure Indicates that the cookie should only be transmitted over a secure + * HTTPS connection to/from the client + * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol + */ + public function setCookie($name, $value, $time = null, $path = null, $domain = null, $secure = null, $httponly = null) + { + $settings = array( + 'value' => $value, + 'expires' => is_null($time) ? $this->config('cookies.lifetime') : $time, + 'path' => is_null($path) ? $this->config('cookies.path') : $path, + 'domain' => is_null($domain) ? $this->config('cookies.domain') : $domain, + 'secure' => is_null($secure) ? $this->config('cookies.secure') : $secure, + 'httponly' => is_null($httponly) ? $this->config('cookies.httponly') : $httponly + ); + $this->response->cookies->set($name, $settings); + } + + /** + * Get value of HTTP cookie from the current HTTP request + * + * Return the value of a cookie from the current HTTP request, + * or return NULL if cookie does not exist. Cookies created during + * the current request will not be available until the next request. + * + * @param string $name + * @param bool $deleteIfInvalid + * @return string|null + */ + public function getCookie($name, $deleteIfInvalid = true) + { + // Get cookie value + $value = $this->request->cookies->get($name); + + // Decode if encrypted + if ($this->config('cookies.encrypt')) { + $value = \Slim\Http\Util::decodeSecureCookie( + $value, + $this->config('cookies.secret_key'), + $this->config('cookies.cipher'), + $this->config('cookies.cipher_mode') + ); + if ($value === false && $deleteIfInvalid) { + $this->deleteCookie($name); + } + } + + return $value; + } + + /** + * DEPRECATION WARNING! Use `setCookie` with the `cookies.encrypt` app setting set to `true`. + * + * Set encrypted HTTP cookie + * + * @param string $name The cookie name + * @param mixed $value The cookie value + * @param mixed $expires The duration of the cookie; + * If integer, should be UNIX timestamp; + * If string, converted to UNIX timestamp with `strtotime`; + * @param string $path The path on the server in which the cookie will be available on + * @param string $domain The domain that the cookie is available to + * @param bool $secure Indicates that the cookie should only be transmitted over a secure + * HTTPS connection from the client + * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol + */ + public function setEncryptedCookie($name, $value, $expires = null, $path = null, $domain = null, $secure = false, $httponly = false) + { + $this->setCookie($name, $value, $expires, $path, $domain, $secure, $httponly); + } + + /** + * DEPRECATION WARNING! Use `getCookie` with the `cookies.encrypt` app setting set to `true`. + * + * Get value of encrypted HTTP cookie + * + * Return the value of an encrypted cookie from the current HTTP request, + * or return NULL if cookie does not exist. Encrypted cookies created during + * the current request will not be available until the next request. + * + * @param string $name + * @param bool $deleteIfInvalid + * @return string|bool + */ + public function getEncryptedCookie($name, $deleteIfInvalid = true) + { + return $this->getCookie($name, $deleteIfInvalid); + } + + /** + * Delete HTTP cookie (encrypted or unencrypted) + * + * Remove a Cookie from the client. This method will overwrite an existing Cookie + * with a new, empty, auto-expiring Cookie. This method's arguments must match + * the original Cookie's respective arguments for the original Cookie to be + * removed. If any of this method's arguments are omitted or set to NULL, the + * default Cookie setting values (set during Slim::init) will be used instead. + * + * @param string $name The cookie name + * @param string $path The path on the server in which the cookie will be available on + * @param string $domain The domain that the cookie is available to + * @param bool $secure Indicates that the cookie should only be transmitted over a secure + * HTTPS connection from the client + * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol + */ + public function deleteCookie($name, $path = null, $domain = null, $secure = null, $httponly = null) + { + $settings = array( + 'domain' => is_null($domain) ? $this->config('cookies.domain') : $domain, + 'path' => is_null($path) ? $this->config('cookies.path') : $path, + 'secure' => is_null($secure) ? $this->config('cookies.secure') : $secure, + 'httponly' => is_null($httponly) ? $this->config('cookies.httponly') : $httponly + ); + $this->response->cookies->remove($name, $settings); + } + + /******************************************************************************** + * Helper Methods + *******************************************************************************/ + + /** + * Get the absolute path to this Slim application's root directory + * + * This method returns the absolute path to the Slim application's + * directory. If the Slim application is installed in a public-accessible + * sub-directory, the sub-directory path will be included. This method + * will always return an absolute path WITH a trailing slash. + * + * @return string + */ + public function root() + { + return rtrim($_SERVER['DOCUMENT_ROOT'], '/') . rtrim($this->request->getRootUri(), '/') . '/'; + } + + /** + * Clean current output buffer + */ + protected function cleanBuffer() + { + if (ob_get_level() !== 0) { + ob_clean(); + } + } + + /** + * Stop + * + * The thrown exception will be caught in application's `call()` method + * and the response will be sent as is to the HTTP client. + * + * @throws \Slim\Exception\Stop + */ + public function stop() + { + throw new \Slim\Exception\Stop(); + } + + /** + * Halt + * + * Stop the application and immediately send the response with a + * specific status and body to the HTTP client. This may send any + * type of response: info, success, redirect, client error, or server error. + * If you need to render a template AND customize the response status, + * use the application's `render()` method instead. + * + * @param int $status The HTTP response status + * @param string $message The HTTP response body + */ + public function halt($status, $message = '') + { + $this->cleanBuffer(); + $this->response->status($status); + $this->response->body($message); + $this->stop(); + } + + /** + * Pass + * + * The thrown exception is caught in the application's `call()` method causing + * the router's current iteration to stop and continue to the subsequent route if available. + * If no subsequent matching routes are found, a 404 response will be sent to the client. + * + * @throws \Slim\Exception\Pass + */ + public function pass() + { + $this->cleanBuffer(); + throw new \Slim\Exception\Pass(); + } + + /** + * Set the HTTP response Content-Type + * @param string $type The Content-Type for the Response (ie. text/html) + */ + public function contentType($type) + { + $this->response->headers->set('Content-Type', $type); + } + + /** + * Set the HTTP response status code + * @param int $code The HTTP response status code + */ + public function status($code) + { + $this->response->setStatus($code); + } + + /** + * Get the URL for a named route + * @param string $name The route name + * @param array $params Associative array of URL parameters and replacement values + * @throws \RuntimeException If named route does not exist + * @return string + */ + public function urlFor($name, $params = array()) + { + return $this->request->getRootUri() . $this->router->urlFor($name, $params); + } + + /** + * Redirect + * + * This method immediately redirects to a new URL. By default, + * this issues a 302 Found response; this is considered the default + * generic redirect response. You may also specify another valid + * 3xx status code if you want. This method will automatically set the + * HTTP Location header for you using the URL parameter. + * + * @param string $url The destination URL + * @param int $status The HTTP redirect status code (optional) + */ + public function redirect($url, $status = 302) + { + $this->response->redirect($url, $status); + $this->halt($status); + } + + /******************************************************************************** + * Flash Messages + *******************************************************************************/ + + /** + * Set flash message for subsequent request + * @param string $key + * @param mixed $value + */ + public function flash($key, $value) + { + if (isset($this->environment['slim.flash'])) { + $this->environment['slim.flash']->set($key, $value); + } + } + + /** + * Set flash message for current request + * @param string $key + * @param mixed $value + */ + public function flashNow($key, $value) + { + if (isset($this->environment['slim.flash'])) { + $this->environment['slim.flash']->now($key, $value); + } + } + + /** + * Keep flash messages from previous request for subsequent request + */ + public function flashKeep() + { + if (isset($this->environment['slim.flash'])) { + $this->environment['slim.flash']->keep(); + } + } + + /******************************************************************************** + * Hooks + *******************************************************************************/ + + /** + * Assign hook + * @param string $name The hook name + * @param mixed $callable A callable object + * @param int $priority The hook priority; 0 = high, 10 = low + */ + public function hook($name, $callable, $priority = 10) + { + if (!isset($this->hooks[$name])) { + $this->hooks[$name] = array(array()); + } + if (is_callable($callable)) { + $this->hooks[$name][(int) $priority][] = $callable; + } + } + + /** + * Invoke hook + * @param string $name The hook name + * @param mixed $hookArg (Optional) Argument for hooked functions + */ + public function applyHook($name, $hookArg = null) + { + if (!isset($this->hooks[$name])) { + $this->hooks[$name] = array(array()); + } + if (!empty($this->hooks[$name])) { + // Sort by priority, low to high, if there's more than one priority + if (count($this->hooks[$name]) > 1) { + ksort($this->hooks[$name]); + } + foreach ($this->hooks[$name] as $priority) { + if (!empty($priority)) { + foreach ($priority as $callable) { + call_user_func($callable, $hookArg); + } + } + } + } + } + + /** + * Get hook listeners + * + * Return an array of registered hooks. If `$name` is a valid + * hook name, only the listeners attached to that hook are returned. + * Else, all listeners are returned as an associative array whose + * keys are hook names and whose values are arrays of listeners. + * + * @param string $name A hook name (Optional) + * @return array|null + */ + public function getHooks($name = null) + { + if (!is_null($name)) { + return isset($this->hooks[(string) $name]) ? $this->hooks[(string) $name] : null; + } else { + return $this->hooks; + } + } + + /** + * Clear hook listeners + * + * Clear all listeners for all hooks. If `$name` is + * a valid hook name, only the listeners attached + * to that hook will be cleared. + * + * @param string $name A hook name (Optional) + */ + public function clearHooks($name = null) + { + if (!is_null($name) && isset($this->hooks[(string) $name])) { + $this->hooks[(string) $name] = array(array()); + } else { + foreach ($this->hooks as $key => $value) { + $this->hooks[$key] = array(array()); + } + } + } + + /******************************************************************************** + * Middleware + *******************************************************************************/ + + /** + * Add middleware + * + * This method prepends new middleware to the application middleware stack. + * The argument must be an instance that subclasses Slim_Middleware. + * + * @param \Slim\Middleware + */ + public function add(\Slim\Middleware $newMiddleware) + { + $newMiddleware->setApplication($this); + $newMiddleware->setNextMiddleware($this->middleware[0]); + array_unshift($this->middleware, $newMiddleware); + } + + /******************************************************************************** + * Runner + *******************************************************************************/ + + /** + * Run + * + * This method invokes the middleware stack, including the core Slim application; + * the result is an array of HTTP status, header, and body. These three items + * are returned to the HTTP client. + */ + public function run() + { + set_error_handler(array('\Slim\Slim', 'handleErrors')); + + //Apply final outer middleware layers + if ($this->config('debug')) { + //Apply pretty exceptions only in debug to avoid accidental information leakage in production + $this->add(new \Slim\Middleware\PrettyExceptions()); + } + + //Invoke middleware and application stack + $this->middleware[0]->call(); + + //Fetch status, header, and body + list($status, $headers, $body) = $this->response->finalize(); + + // Serialize cookies (with optional encryption) + \Slim\Http\Util::serializeCookies($headers, $this->response->cookies, $this->settings); + + //Send headers + if (headers_sent() === false) { + //Send status + if (strpos(PHP_SAPI, 'cgi') === 0) { + header(sprintf('Status: %s', \Slim\Http\Response::getMessageForCode($status))); + } else { + header(sprintf('HTTP/%s %s', $this->config('http.version'), \Slim\Http\Response::getMessageForCode($status))); + } + + //Send headers + foreach ($headers as $name => $value) { + $hValues = explode("\n", $value); + foreach ($hValues as $hVal) { + header("$name: $hVal", false); + } + } + } + + //Send body, but only if it isn't a HEAD request + if (!$this->request->isHead()) { + echo $body; + } + + restore_error_handler(); + } + + /** + * Call + * + * This method finds and iterates all route objects that match the current request URI. + */ + public function call() + { + try { + if (isset($this->environment['slim.flash'])) { + $this->view()->setData('flash', $this->environment['slim.flash']); + } + $this->applyHook('slim.before'); + ob_start(); + $this->applyHook('slim.before.router'); + $dispatched = false; + $matchedRoutes = $this->router->getMatchedRoutes($this->request->getMethod(), $this->request->getResourceUri()); + foreach ($matchedRoutes as $route) { + try { + $this->applyHook('slim.before.dispatch'); + $dispatched = $route->dispatch(); + $this->applyHook('slim.after.dispatch'); + if ($dispatched) { + break; + } + } catch (\Slim\Exception\Pass $e) { + continue; + } + } + if (!$dispatched) { + $this->notFound(); + } + $this->applyHook('slim.after.router'); + $this->stop(); + } catch (\Slim\Exception\Stop $e) { + $this->response()->write(ob_get_clean()); + $this->applyHook('slim.after'); + } catch (\Exception $e) { + if ($this->config('debug')) { + throw $e; + } else { + try { + $this->error($e); + } catch (\Slim\Exception\Stop $e) { + // Do nothing + } + } + } + } + + /******************************************************************************** + * Error Handling and Debugging + *******************************************************************************/ + + /** + * Convert errors into ErrorException objects + * + * This method catches PHP errors and converts them into \ErrorException objects; + * these \ErrorException objects are then thrown and caught by Slim's + * built-in or custom error handlers. + * + * @param int $errno The numeric type of the Error + * @param string $errstr The error message + * @param string $errfile The absolute path to the affected file + * @param int $errline The line number of the error in the affected file + * @return bool + * @throws \ErrorException + */ + public static function handleErrors($errno, $errstr = '', $errfile = '', $errline = '') + { + if (!($errno & error_reporting())) { + return; + } + + throw new \ErrorException($errstr, $errno, 0, $errfile, $errline); + } + + /** + * Generate diagnostic template markup + * + * This method accepts a title and body content to generate an HTML document layout. + * + * @param string $title The title of the HTML template + * @param string $body The body content of the HTML template + * @return string + */ + protected static function generateTemplateMarkup($title, $body) + { + return sprintf("%s

%s

%s", $title, $title, $body); + } + + /** + * Default Not Found handler + */ + protected function defaultNotFound() + { + echo static::generateTemplateMarkup('404 Page Not Found', '

The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.

Visit the Home Page'); + } + + /** + * Default Error handler + */ + protected function defaultError($e) + { + $this->getLog()->error($e); + echo self::generateTemplateMarkup('Error', '

A website error has occurred. The website administrator has been notified of the issue. Sorry for the temporary inconvenience.

'); + } +} diff --git a/strillonews/vendor/slim/slim/Slim/View.php b/strillonews/vendor/slim/slim/Slim/View.php new file mode 100644 index 0000000..eff83aa --- /dev/null +++ b/strillonews/vendor/slim/slim/Slim/View.php @@ -0,0 +1,282 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace Slim; + +/** + * View + * + * The view is responsible for rendering a template. The view + * should subclass \Slim\View and implement this interface: + * + * public render(string $template); + * + * This method should render the specified template and return + * the resultant string. + * + * @package Slim + * @author Josh Lockhart + * @since 1.0.0 + */ +class View +{ + /** + * Data available to the view templates + * @var \Slim\Helper\Set + */ + protected $data; + + /** + * Path to templates base directory (without trailing slash) + * @var string + */ + protected $templatesDirectory; + + /** + * Constructor + */ + public function __construct() + { + $this->data = new \Slim\Helper\Set(); + } + + /******************************************************************************** + * Data methods + *******************************************************************************/ + + /** + * Does view data have value with key? + * @param string $key + * @return boolean + */ + public function has($key) + { + return $this->data->has($key); + } + + /** + * Return view data value with key + * @param string $key + * @return mixed + */ + public function get($key) + { + return $this->data->get($key); + } + + /** + * Set view data value with key + * @param string $key + * @param mixed $value + */ + public function set($key, $value) + { + $this->data->set($key, $value); + } + + /** + * Set view data value as Closure with key + * @param string $key + * @param mixed $value + */ + public function keep($key, Closure $value) + { + $this->data->keep($key, $value); + } + + /** + * Return view data + * @return array + */ + public function all() + { + return $this->data->all(); + } + + /** + * Replace view data + * @param array $data + */ + public function replace(array $data) + { + $this->data->replace($data); + } + + /** + * Clear view data + */ + public function clear() + { + $this->data->clear(); + } + + /******************************************************************************** + * Legacy data methods + *******************************************************************************/ + + /** + * DEPRECATION WARNING! This method will be removed in the next major point release + * + * Get data from view + */ + public function getData($key = null) + { + if (!is_null($key)) { + return isset($this->data[$key]) ? $this->data[$key] : null; + } else { + return $this->data->all(); + } + } + + /** + * DEPRECATION WARNING! This method will be removed in the next major point release + * + * Set data for view + */ + public function setData() + { + $args = func_get_args(); + if (count($args) === 1 && is_array($args[0])) { + $this->data->replace($args[0]); + } elseif (count($args) === 2) { + // Ensure original behavior is maintained. DO NOT invoke stored Closures. + if (is_object($args[1]) && method_exists($args[1], '__invoke')) { + $this->data->set($args[0], $this->data->protect($args[1])); + } else { + $this->data->set($args[0], $args[1]); + } + } else { + throw new \InvalidArgumentException('Cannot set View data with provided arguments. Usage: `View::setData( $key, $value );` or `View::setData([ key => value, ... ]);`'); + } + } + + /** + * DEPRECATION WARNING! This method will be removed in the next major point release + * + * Append data to view + * @param array $data + */ + public function appendData($data) + { + if (!is_array($data)) { + throw new \InvalidArgumentException('Cannot append view data. Expected array argument.'); + } + $this->data->replace($data); + } + + /******************************************************************************** + * Resolve template paths + *******************************************************************************/ + + /** + * Set the base directory that contains view templates + * @param string $directory + * @throws \InvalidArgumentException If directory is not a directory + */ + public function setTemplatesDirectory($directory) + { + $this->templatesDirectory = rtrim($directory, DIRECTORY_SEPARATOR); + } + + /** + * Get templates base directory + * @return string + */ + public function getTemplatesDirectory() + { + return $this->templatesDirectory; + } + + /** + * Get fully qualified path to template file using templates base directory + * @param string $file The template file pathname relative to templates base directory + * @return string + */ + public function getTemplatePathname($file) + { + return $this->templatesDirectory . DIRECTORY_SEPARATOR . ltrim($file, DIRECTORY_SEPARATOR); + } + + /******************************************************************************** + * Rendering + *******************************************************************************/ + + /** + * Display template + * + * This method echoes the rendered template to the current output buffer + * + * @param string $template Pathname of template file relative to templates directory + * @param array $data Any additonal data to be passed to the template. + */ + public function display($template, $data = null) + { + echo $this->fetch($template, $data); + } + + /** + * Return the contents of a rendered template file + * + * @param string $template The template pathname, relative to the template base directory + * @param array $data Any additonal data to be passed to the template. + * @return string The rendered template + */ + public function fetch($template, $data = null) + { + return $this->render($template, $data); + } + + /** + * Render a template file + * + * NOTE: This method should be overridden by custom view subclasses + * + * @param string $template The template pathname, relative to the template base directory + * @param array $data Any additonal data to be passed to the template. + * @return string The rendered template + * @throws \RuntimeException If resolved template pathname is not a valid file + */ + protected function render($template, $data = null) + { + $templatePathname = $this->getTemplatePathname($template); + if (!is_file($templatePathname)) { + throw new \RuntimeException("View cannot render `$template` because the template does not exist"); + } + + $data = array_merge($this->data->all(), (array) $data); + extract($data); + ob_start(); + require $templatePathname; + + return ob_get_clean(); + } +} diff --git a/strillonews/vendor/slim/slim/composer.json b/strillonews/vendor/slim/slim/composer.json new file mode 100644 index 0000000..0becfe6 --- /dev/null +++ b/strillonews/vendor/slim/slim/composer.json @@ -0,0 +1,24 @@ +{ + "name": "slim/slim", + "type": "library", + "description": "Slim Framework, a PHP micro framework", + "keywords": ["microframework","rest","router"], + "homepage": "http://github.com/codeguy/Slim", + "license": "MIT", + "authors": [ + { + "name": "Josh Lockhart", + "email": "info@joshlockhart.com", + "homepage": "http://www.joshlockhart.com/" + } + ], + "require": { + "php": ">=5.3.0" + }, + "suggest": { + "ext-mcrypt": "Required for HTTP cookie encryption" + }, + "autoload": { + "psr-0": { "Slim": "." } + } +} diff --git a/strillonews/vendor/slim/slim/index.php b/strillonews/vendor/slim/slim/index.php new file mode 100644 index 0000000..9bfd62d --- /dev/null +++ b/strillonews/vendor/slim/slim/index.php @@ -0,0 +1,169 @@ +get( + '/', + function () { + $template = << + + + + Slim Framework for PHP 5 + + + +
+ Slim +
+

Welcome to Slim!

+

+ Congratulations! Your Slim application is running. If this is + your first time using Slim, start with this "Hello World" Tutorial. +

+
+

Get Started

+
    +
  1. The application code is in index.php
  2. +
  3. Read the online documentation
  4. +
  5. Follow @slimphp on Twitter
  6. +
+
+
+

Slim Framework Community

+ +

Support Forum and Knowledge Base

+

+ Visit the Slim support forum and knowledge base + to read announcements, chat with fellow Slim users, ask questions, help others, or show off your cool + Slim Framework apps. +

+ +

Twitter

+

+ Follow @slimphp on Twitter to receive the very latest news + and updates about the framework. +

+
+
+

Slim Framework Extras

+

+ Custom View classes for Smarty, Twig, Mustache, and other template + frameworks are available online in a separate repository. +

+

Browse the Extras Repository

+
+ + +EOT; + echo $template; + } +); + +// POST route +$app->post( + '/post', + function () { + echo 'This is a POST route'; + } +); + +// PUT route +$app->put( + '/put', + function () { + echo 'This is a PUT route'; + } +); + +// PATCH route +$app->patch('/patch', function () { + echo 'This is a PATCH route'; +}); + +// DELETE route +$app->delete( + '/delete', + function () { + echo 'This is a DELETE route'; + } +); + +/** + * Step 4: Run the Slim application + * + * This method should be called last. This executes the Slim application + * and returns the HTTP response to the HTTP client. + */ +$app->run(); diff --git a/strillonews/vendor/slim/slim/phpunit.xml.dist b/strillonews/vendor/slim/slim/phpunit.xml.dist new file mode 100644 index 0000000..c4da172 --- /dev/null +++ b/strillonews/vendor/slim/slim/phpunit.xml.dist @@ -0,0 +1,25 @@ + + + + + + ./tests/ + + + + + + ./Slim/ + + + diff --git a/strillonews/vendor/slim/slim/tests/EnvironmentTest.php b/strillonews/vendor/slim/slim/tests/EnvironmentTest.php new file mode 100644 index 0000000..cb2b500 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/EnvironmentTest.php @@ -0,0 +1,378 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class EnvironmentTest extends PHPUnit_Framework_TestCase +{ + /** + * Default server settings assume the Slim app is installed + * in a subdirectory `foo/` directly beneath the public document + * root directory; URL rewrite is disabled; requested app + * resource is GET `/bar/xyz` with three query params. + * + * These only provide a common baseline for the following + * tests; tests are free to override these values. + */ + public function setUp() + { + $_SERVER['DOCUMENT_ROOT'] = '/var/www'; + $_SERVER['SCRIPT_FILENAME'] = '/var/www/foo/index.php'; + $_SERVER['SERVER_NAME'] = 'slim'; + $_SERVER['SERVER_PORT'] = '80'; + $_SERVER['SCRIPT_NAME'] = '/foo/index.php'; + $_SERVER['REQUEST_URI'] = '/foo/index.php/bar/xyz'; + $_SERVER['PATH_INFO'] = '/bar/xyz'; + $_SERVER['REQUEST_METHOD'] = 'GET'; + $_SERVER['QUERY_STRING'] = 'one=1&two=2&three=3'; + $_SERVER['HTTPS'] = ''; + $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; + unset($_SERVER['CONTENT_TYPE'], $_SERVER['CONTENT_LENGTH']); + } + + /** + * Test mock environment + * + * This should return the custom values where specified + * and the default values otherwise. + */ + public function testMockEnvironment() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'PUT' + )); + $env2 = \Slim\Environment::getInstance(); + $this->assertSame($env, $env2); + $this->assertInstanceOf('\Slim\Environment', $env); + $this->assertEquals('PUT', $env['REQUEST_METHOD']); + $this->assertEquals(80, $env['SERVER_PORT']); + $this->assertNull($env['foo']); + } + + /** + * Test sets HTTP method + */ + public function testSetsHttpMethod() + { + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('GET', $env['REQUEST_METHOD']); + } + + /** + * Test parses script name and path info + * + * Pre-conditions: + * URL Rewrite is disabled; + * App installed in subdirectory; + */ + public function testParsesPathsWithoutUrlRewriteInSubdirectory() + { + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('/bar/xyz', $env['PATH_INFO']); + $this->assertEquals('/foo/index.php', $env['SCRIPT_NAME']); + } + + /** + * Test parses script name and path info + * + * Pre-conditions: + * URL Rewrite is disabled; + * App installed in root directory; + */ + public function testParsesPathsWithoutUrlRewriteInRootDirectory() + { + $_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php'; + $_SERVER['REQUEST_URI'] = '/index.php/bar/xyz'; + $_SERVER['SCRIPT_NAME'] = '/index.php'; + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('/bar/xyz', $env['PATH_INFO']); + $this->assertEquals('/index.php', $env['SCRIPT_NAME']); + } + + /** + * Test parses script name and path info + * + * Pre-conditions: + * URL Rewrite disabled; + * App installed in root directory; + * Requested resource is "/"; + */ + public function testParsesPathsWithoutUrlRewriteInRootDirectoryForAppRootUri() + { + $_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php'; + $_SERVER['REQUEST_URI'] = '/index.php'; + $_SERVER['SCRIPT_NAME'] = '/index.php'; + unset($_SERVER['PATH_INFO']); + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('/', $env['PATH_INFO']); + $this->assertEquals('/index.php', $env['SCRIPT_NAME']); + } + + /** + * Test parses script name and path info + * + * Pre-conditions: + * URL Rewrite enabled; + * App installed in subdirectory; + */ + public function testParsesPathsWithUrlRewriteInSubdirectory() + { + $_SERVER['SCRIPT_NAME'] = '/foo/index.php'; + $_SERVER['REQUEST_URI'] = '/foo/bar/xyz'; + unset($_SERVER['PATH_INFO']); + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('/bar/xyz', $env['PATH_INFO']); + $this->assertEquals('/foo', $env['SCRIPT_NAME']); + } + + /** + * Test parses script name and path info + * + * Pre-conditions: + * URL Rewrite enabled; + * App installed in root directory; + */ + public function testParsesPathsWithUrlRewriteInRootDirectory() + { + $_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php'; + $_SERVER['SCRIPT_NAME'] = '/index.php'; + $_SERVER['REQUEST_URI'] = '/bar/xyz'; + unset($_SERVER['PATH_INFO']); + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('/bar/xyz', $env['PATH_INFO']); + $this->assertEquals('', $env['SCRIPT_NAME']); + } + + /** + * Test parses script name and path info + * + * Pre-conditions: + * URL Rewrite enabled; + * App installed in root directory; + * Requested resource is "/" + */ + public function testParsesPathsWithUrlRewriteInRootDirectoryForAppRootUri() + { + $_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php'; + $_SERVER['REQUEST_URI'] = '/'; + $_SERVER['SCRIPT_NAME'] = '/index.php'; + unset($_SERVER['PATH_INFO']); + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('/', $env['PATH_INFO']); + $this->assertEquals('', $env['SCRIPT_NAME']); + } + + /** + * Test parses query string + * + * Pre-conditions: + * $_SERVER['QUERY_STRING'] exists and is not empty; + */ + public function testParsesQueryString() + { + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('one=1&two=2&three=3', $env['QUERY_STRING']); + } + + /** + * Test removes query string from PATH_INFO when using URL Rewrite + * + * Pre-conditions: + * $_SERVER['QUERY_STRING'] exists and is not empty; + * URL Rewrite enabled; + */ + public function testRemovesQueryStringFromPathInfo() + { + $_SERVER['SCRIPT_NAME'] = '/foo/index.php'; + $_SERVER['REQUEST_URI'] = '/foo/bar/xyz?one=1&two=2&three=3'; + unset($_SERVER['PATH_INFO']); + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('/bar/xyz', $env['PATH_INFO']); + } + + /** + * Test environment's PATH_INFO retains URL encoded characters (e.g. #) + * + * In earlier version, \Slim\Environment would use PATH_INFO instead + * of REQUEST_URI to determine the root URI and resource URI. + * Unfortunately, the server would URL decode the PATH_INFO string + * before it was handed to PHP. This prevented certain URL-encoded + * characters like the octothorpe from being delivered correctly to + * the Slim application environment. This test ensures the + * REQUEST_URI is used instead and parsed as expected. + */ + public function testPathInfoRetainsUrlEncodedCharacters() + { + $_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php'; + $_SERVER['SCRIPT_NAME'] = '/index.php'; + $_SERVER['REQUEST_URI'] = '/foo/%23bar'; //<-- URL-encoded "#bar" + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('/foo/%23bar', $env['PATH_INFO']); + } + + /** + * Test parses query string + * + * Pre-conditions: + * $_SERVER['QUERY_STRING'] does not exist; + */ + public function testParsesQueryStringThatDoesNotExist() + { + unset($_SERVER['QUERY_STRING']); + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('', $env['QUERY_STRING']); + } + + /** + * Test SERVER_NAME is not empty + */ + public function testServerNameIsNotEmpty() + { + $env = \Slim\Environment::getInstance(true); + $this->assertFalse(empty($env['SERVER_NAME'])); + } + + /** + * Test SERVER_PORT is not empty + */ + public function testServerPortIsNotEmpty() + { + $env = \Slim\Environment::getInstance(true); + $this->assertFalse(empty($env['SERVER_PORT'])); + } + + /** + * Test unsets HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH + * + * Pre-conditions: + * HTTP_CONTENT_TYPE is sent with HTTP request; + * HTTP_CONTENT_LENGTH is sent with HTTP request; + */ + public function testUnsetsContentTypeAndContentLength() + { + $_SERVER['HTTP_CONTENT_TYPE'] = 'text/csv'; + $_SERVER['HTTP_CONTENT_LENGTH'] = 150; + $env = \Slim\Environment::getInstance(true); + $this->assertFalse(isset($env['HTTP_CONTENT_TYPE'])); + $this->assertFalse(isset($env['HTTP_CONTENT_LENGTH'])); + } + + /** + * Test sets special request headers if not empty + * + * Pre-conditions: + * CONTENT_TYPE, CONTENT_LENGTH, X_REQUESTED_WITH are sent in client HTTP request; + * CONTENT_TYPE, CONTENT_LENGTH, X_REQUESTED_WITH are not empty; + */ + public function testSetsSpecialHeaders() + { + $_SERVER['CONTENT_TYPE'] = 'text/csv'; + $_SERVER['CONTENT_LENGTH'] = '100'; + $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XmlHttpRequest'; + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('text/csv', $env['CONTENT_TYPE']); + $this->assertEquals('100', $env['CONTENT_LENGTH']); + $this->assertEquals('XmlHttpRequest', $env['HTTP_X_REQUESTED_WITH']); + } + + /** + * Tests X-HTTP-Method-Override is allowed through unmolested. + * + * Pre-conditions: + * X_HTTP_METHOD_OVERRIDE is sent in client HTTP request; + * X_HTTP_METHOD_OVERRIDE is not empty; + */ + public function testSetsHttpMethodOverrideHeader() { + $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'DELETE'; + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('DELETE', $env['HTTP_X_HTTP_METHOD_OVERRIDE']); + } + + /** + * Test detects HTTPS + * + * Pre-conditions: + * $_SERVER['HTTPS'] is set to a non-empty value; + */ + public function testHttps() + { + $_SERVER['HTTPS'] = 1; + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('https', $env['slim.url_scheme']); + } + + /** + * Test detects not HTTPS + * + * Pre-conditions: + * $_SERVER['HTTPS'] is set to an empty value; + */ + public function testNotHttps() + { + $_SERVER['HTTPS'] = ''; + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('http', $env['slim.url_scheme']); + } + + /** + * Test detects not HTTPS on IIS + * + * Pre-conditions: + * $_SERVER['HTTPS'] is set to "off"; + */ + public function testNotHttpsIIS() + { + $_SERVER['HTTPS'] = 'off'; + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('http', $env['slim.url_scheme']); + } + + /** + * Test input is an empty string (and not false) + * + * Pre-conditions: + * Input at php://input may only be read once; subsequent attempts + * will return `false`; in which case, use an empty string. + */ + public function testInputIsEmptyString() + { + $env = \Slim\Environment::getInstance(true); + $this->assertEquals('', $env['slim.input']); + } + + /** + * Test valid resource handle to php://stdErr + */ + public function testErrorResource() + { + $env = \Slim\Environment::getInstance(true); + $this->assertTrue(is_resource($env['slim.errors'])); + } +} diff --git a/strillonews/vendor/slim/slim/tests/Foo.php b/strillonews/vendor/slim/slim/tests/Foo.php new file mode 100644 index 0000000..d772d02 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/Foo.php @@ -0,0 +1,7 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class SetTest extends PHPUnit_Framework_TestCase +{ + protected $bag; + protected $property; + + public function setUp() + { + $this->bag = new \Slim\Helper\Set(); + $this->property = new \ReflectionProperty($this->bag, 'data'); + $this->property->setAccessible(true); + } + + public function testSet() + { + $this->bag->set('foo', 'bar'); + $this->assertArrayHasKey('foo', $this->property->getValue($this->bag)); + $bag = $this->property->getValue($this->bag); + $this->assertEquals('bar', $bag['foo']); + } + + public function testGet() + { + $this->property->setValue($this->bag, array('foo' => 'bar')); + $this->assertEquals('bar', $this->bag->get('foo')); + } + + public function testGetNotExists() + { + $this->property->setValue($this->bag, array('foo' => 'bar')); + $this->assertEquals('default', $this->bag->get('abc', 'default')); + } + + public function testAdd() + { + $this->bag->replace(array( + 'abc' => '123', + 'foo' => 'bar' + )); + $this->assertArrayHasKey('abc', $this->property->getValue($this->bag)); + $this->assertArrayHasKey('foo', $this->property->getValue($this->bag)); + $bag = $this->property->getValue($this->bag); + $this->assertEquals('123', $bag['abc']); + $this->assertEquals('bar', $bag['foo']); + } + + public function testAll() + { + $data = array( + 'abc' => '123', + 'foo' => 'bar' + ); + $this->property->setValue($this->bag, $data); + $this->assertEquals($data, $this->bag->all()); + } + + public function testKeys() + { + $data = array( + 'abc' => '123', + 'foo' => 'bar' + ); + $this->property->setValue($this->bag, $data); + $this->assertEquals(array('abc', 'foo'), $this->bag->keys()); + } + + public function testRemove() + { + $data = array( + 'abc' => '123', + 'foo' => 'bar' + ); + $this->property->setValue($this->bag, $data); + $this->bag->remove('foo'); + $this->assertEquals(array('abc' => '123'), $this->property->getValue($this->bag)); + } + + public function testClear() + { + $data = array( + 'abc' => '123', + 'foo' => 'bar' + ); + $this->property->setValue($this->bag, $data); + $this->bag->clear(); + $this->assertEquals(array(), $this->property->getValue($this->bag)); + } + + public function testArrayAccessGet() + { + $data = array( + 'abc' => '123', + 'foo' => 'bar' + ); + $this->property->setValue($this->bag, $data); + $this->assertEquals('bar', $this->bag['foo']); + } + + public function testArrayAccessSet() + { + $data = array( + 'abc' => '123', + 'foo' => 'bar' + ); + $this->property->setValue($this->bag, $data); + $this->bag['foo'] = 'changed'; + $bag = $this->property->getValue($this->bag); + $this->assertEquals('changed', $bag['foo']); + } + + public function testArrayAccessExists() + { + $data = array( + 'abc' => '123', + 'foo' => 'bar' + ); + $this->property->setValue($this->bag, $data); + $this->assertTrue(isset($this->bag['foo'])); + $this->assertFalse(isset($this->bag['bar'])); + } + + public function testArrayAccessUnset() + { + $data = array( + 'abc' => '123', + 'foo' => 'bar' + ); + $this->property->setValue($this->bag, $data); + unset($this->bag['foo']); + $this->assertEquals(array('abc' => '123'), $this->property->getValue($this->bag)); + } + + public function testCount() + { + $data = array( + 'abc' => '123', + 'foo' => 'bar' + ); + $this->property->setValue($this->bag, $data); + $this->assertEquals(2, count($this->bag)); + } + + public function testGetIterator() + { + $data = array( + 'abc' => '123', + 'foo' => 'bar' + ); + $this->property->setValue($this->bag, $data); + $this->assertInstanceOf('\ArrayIterator', $this->bag->getIterator()); + } + + public function testPropertyOverloadGet() + { + $data = array( + 'abc' => '123', + 'foo' => 'bar' + ); + $this->property->setValue($this->bag, $data); + + $this->assertEquals('123', $this->bag->abc); + $this->assertEquals('bar', $this->bag->foo); + } + + public function testPropertyOverloadSet() + { + $this->bag->foo = 'bar'; + $this->assertArrayHasKey('foo', $this->property->getValue($this->bag)); + $this->assertEquals('bar', $this->bag->foo); + } + + public function testPropertyOverloadingIsset() + { + $data = array( + 'abc' => '123', + 'foo' => 'bar' + ); + $this->property->setValue($this->bag, $data); + + $this->assertTrue(isset($this->bag->abc)); + $this->assertTrue(isset($this->bag->foo)); + $this->assertFalse(isset($this->bag->foobar)); + } + + public function testPropertyOverloadingUnset() + { + $data = array( + 'abc' => '123', + 'foo' => 'bar' + ); + $this->property->setValue($this->bag, $data); + + $this->assertTrue(isset($this->bag->abc)); + unset($this->bag->abc); + $this->assertFalse(isset($this->bag->abc)); + $this->assertArrayNotHasKey('abc', $this->property->getValue($this->bag)); + $this->assertArrayHasKey('foo', $this->property->getValue($this->bag)); + } + + public function testProtect() + { + $callable = function () { + return 'foo'; + }; + $result = $this->bag->protect($callable); + + $this->assertInstanceOf('\Closure', $result); + $this->assertSame($callable, $result()); + } +} diff --git a/strillonews/vendor/slim/slim/tests/Http/CookiesTest.php b/strillonews/vendor/slim/slim/tests/Http/CookiesTest.php new file mode 100644 index 0000000..e73d44f --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/Http/CookiesTest.php @@ -0,0 +1,92 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +class CookiesTest extends PHPUnit_Framework_TestCase +{ + public function testSetWithStringValue() + { + $c = new \Slim\Http\Cookies(); + $c->set('foo', 'bar'); + $this->assertAttributeEquals( + array( + 'foo' => array( + 'value' => 'bar', + 'expires' => null, + 'domain' => null, + 'path' => null, + 'secure' => false, + 'httponly' => false + ) + ), + 'data', + $c + ); + } + + public function testSetWithArrayValue() + { + $now = time(); + $c = new \Slim\Http\Cookies(); + $c->set('foo', array( + 'value' => 'bar', + 'expires' => $now + 86400, + 'domain' => '.example.com', + 'path' => '/', + 'secure' => true, + 'httponly' => true + )); + $this->assertAttributeEquals( + array( + 'foo' => array( + 'value' => 'bar', + 'expires' => $now + 86400, + 'domain' => '.example.com', + 'path' => '/', + 'secure' => true, + 'httponly' => true + ) + ), + 'data', + $c + ); + } + + public function testRemove() + { + $c = new \Slim\Http\Cookies(); + $c->remove('foo'); + $prop = new \ReflectionProperty($c, 'data'); + $prop->setAccessible(true); + $cValue = $prop->getValue($c); + $this->assertEquals('', $cValue['foo']['value']); + $this->assertLessThan(time(), $cValue['foo']['expires']); + } +} diff --git a/strillonews/vendor/slim/slim/tests/Http/HeadersTest.php b/strillonews/vendor/slim/slim/tests/Http/HeadersTest.php new file mode 100644 index 0000000..4245806 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/Http/HeadersTest.php @@ -0,0 +1,59 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class HeadersTest extends PHPUnit_Framework_TestCase +{ + public function testNormalizesKey() + { + $h = new \Slim\Http\Headers(); + $h->set('Http_Content_Type', 'text/html'); + $prop = new \ReflectionProperty($h, 'data'); + $prop->setAccessible(true); + $this->assertArrayHasKey('Content-Type', $prop->getValue($h)); + } + + public function testExtractHeaders() + { + $test = array( + 'HTTP_HOST' => 'foo.com', + 'SERVER_NAME' => 'foo', + 'CONTENT_TYPE' => 'text/html', + 'X_FORWARDED_FOR' => '127.0.0.1' + ); + $results = \Slim\Http\Headers::extract($test); + $this->assertEquals(array( + 'HTTP_HOST' => 'foo.com', + 'CONTENT_TYPE' => 'text/html', + 'X_FORWARDED_FOR' => '127.0.0.1' + ), $results); + } +} diff --git a/strillonews/vendor/slim/slim/tests/Http/RequestTest.php b/strillonews/vendor/slim/slim/tests/Http/RequestTest.php new file mode 100644 index 0000000..9ffea71 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/Http/RequestTest.php @@ -0,0 +1,939 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class RequestTest extends PHPUnit_Framework_TestCase +{ + /** + * Test sets HTTP method + */ + public function testGetMethod() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'GET' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('GET', $req->getMethod()); + } + + /** + * Test HTTP GET method detection + */ + public function testIsGet() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'GET' + )); + $req = new \Slim\Http\Request($env); + $this->assertTrue($req->isGet()); + } + + /** + * Test HTTP POST method detection + */ + public function testIsPost() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + )); + $req = new \Slim\Http\Request($env); + $this->assertTrue($req->isPost()); + } + + /** + * Test HTTP PUT method detection + */ + public function testIsPut() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'PUT', + )); + $req = new \Slim\Http\Request($env); + $this->assertTrue($req->isPut()); + } + + /** + * Test HTTP DELETE method detection + */ + public function testIsDelete() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'DELETE', + )); + $req = new \Slim\Http\Request($env); + $this->assertTrue($req->isDelete()); + } + + /** + * Test HTTP OPTIONS method detection + */ + public function testIsOptions() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'OPTIONS', + )); + $req = new \Slim\Http\Request($env); + $this->assertTrue($req->isOptions()); + } + + /** + * Test HTTP HEAD method detection + */ + public function testIsHead() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'HEAD', + )); + $req = new \Slim\Http\Request($env); + $this->assertTrue($req->isHead()); + } + + /** + * Test HTTP PATCH method detection + */ + public function testIsPatch() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'PATCH', + )); + $req = new \Slim\Http\Request($env); + $this->assertTrue($req->isPatch()); + } + + /** + * Test AJAX method detection w/ header + */ + public function testIsAjaxWithHeader() + { + $env = \Slim\Environment::mock(array( + 'X_REQUESTED_WITH' => 'XMLHttpRequest' + )); + $req = new \Slim\Http\Request($env); + $this->assertTrue($req->isAjax()); + $this->assertTrue($req->isXhr()); + } + + /** + * Test AJAX method detection w/ query parameter + */ + public function testIsAjaxWithQueryParameter() + { + $env = \Slim\Environment::mock(array( + 'QUERY_STRING' => 'isajax=1', + )); + $req = new \Slim\Http\Request($env); + $this->assertTrue($req->isAjax()); + $this->assertTrue($req->isXhr()); + } + + /** + * Test AJAX method detection without header or query parameter + */ + public function testIsAjaxWithoutHeaderOrQueryParameter() + { + $env = \Slim\Environment::mock(); + $req = new \Slim\Http\Request($env); + $this->assertFalse($req->isAjax()); + $this->assertFalse($req->isXhr()); + } + + /** + * Test AJAX method detection with misspelled header + */ + public function testIsAjaxWithMisspelledHeader() + { + $env = \Slim\Environment::mock(array( + 'X_REQUESTED_WITH' => 'foo' + )); + $req = new \Slim\Http\Request($env); + $this->assertFalse($req->isAjax()); + $this->assertFalse($req->isXhr()); + } + + /** + * Test params from query string + */ + public function testParamsFromQueryString() + { + $env = \Slim\Environment::mock(array( + 'QUERY_STRING' => 'one=1&two=2&three=3' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals(3, count($req->params())); + $this->assertEquals('1', $req->params('one')); + $this->assertNull($req->params('foo')); + } + + /** + * Test params from request body + */ + public function testParamsFromRequestBody() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'QUERY_STRING' => 'one=1&two=2&three=3', + 'slim.input' => 'foo=bar&abc=123', + 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', + 'CONTENT_LENGTH' => 15 + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals(5, count($req->params())); //Union of GET and POST + $this->assertEquals('bar', $req->params('foo')); + } + + /** + * Test fetch GET params + */ + public function testGet() + { + $env = \Slim\Environment::mock(array( + 'QUERY_STRING' => 'one=1&two=2&three=3' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals(3, count($req->get())); + $this->assertEquals('1', $req->get('one')); + $this->assertNull($req->get('foo')); + $this->assertFalse($req->get('foo', false)); + } + + /** + * Test fetch GET params without multibyte + */ + public function testGetWithoutMultibyte() + { + $env = \Slim\Environment::mock(array( + 'QUERY_STRING' => 'one=1&two=2&three=3', + 'slim.tests.ignore_multibyte' => true + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals(3, count($req->get())); + $this->assertEquals('1', $req->get('one')); + $this->assertNull($req->get('foo')); + $this->assertFalse($req->get('foo', false)); + } + + /** + * Test fetch POST params + */ + public function testPost() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'slim.input' => 'foo=bar&abc=123', + 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', + 'CONTENT_LENGTH' => 15 + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals(2, count($req->post())); + $this->assertEquals('bar', $req->post('foo')); + $this->assertNull($req->post('xyz')); + $this->assertFalse($req->post('xyz', false)); + } + + /** + * Test fetch POST params without multibyte + */ + public function testPostWithoutMultibyte() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'slim.input' => 'foo=bar&abc=123', + 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', + 'CONTENT_LENGTH' => 15, + 'slim.tests.ignore_multibyte' => true + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals(2, count($req->post())); + $this->assertEquals('bar', $req->post('foo')); + $this->assertNull($req->post('xyz')); + $this->assertFalse($req->post('xyz', false)); + } + + /** + * Test fetch POST without slim.input + */ + public function testPostWithoutInput() + { + $this->setExpectedException('RuntimeException'); + $env = \Slim\Environment::mock(); + unset($env['slim.input']); + $req = new \Slim\Http\Request($env); + $req->post('foo'); + } + + /** + * Test fetch POST params even if multipart/form-data request + */ + public function testPostWithMultipartRequest() + { + $_POST = array('foo' => 'bar'); //<-- Set by PHP + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'slim.input' => '', //<-- "php://input" is empty for multipart/form-data requests + 'CONTENT_TYPE' => 'multipart/form-data', + 'CONTENT_LENGTH' => 0 + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals(1, count($req->post())); + $this->assertEquals('bar', $req->post('foo')); + $this->assertNull($req->post('xyz')); + } + + /** + * Test fetch PUT params + */ + public function testPut() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'PUT', + 'slim.input' => 'foo=bar&abc=123', + 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', + 'CONTENT_LENGTH' => 15 + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals(2, count($req->put())); + $this->assertEquals('bar', $req->put('foo')); + $this->assertEquals('bar', $req->params('foo')); + $this->assertNull($req->put('xyz')); + $this->assertFalse($req->put('xyz', false)); + } + + /** + * Test fetch PATCH params + */ + public function testPatch() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'PATCH', + 'slim.input' => 'foo=bar&abc=123', + 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', + 'CONTENT_LENGTH' => 15 + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals(2, count($req->patch())); + $this->assertEquals('bar', $req->patch('foo')); + $this->assertEquals('bar', $req->params('foo')); + $this->assertNull($req->patch('xyz')); + $this->assertFalse($req->patch('xyz', false)); + } + + /** + * Test fetch DELETE params + */ + public function testDelete() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'DELETE', + 'slim.input' => 'foo=bar&abc=123', + 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', + 'CONTENT_LENGTH' => 15 + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals(2, count($req->delete())); + $this->assertEquals('bar', $req->delete('foo')); + $this->assertEquals('bar', $req->params('foo')); + $this->assertNull($req->delete('xyz')); + $this->assertFalse($req->delete('xyz', false)); + } + + /** + * Test fetch COOKIE params + */ + public function testCookies() + { + $env = \Slim\Environment::mock(array( + 'HTTP_COOKIE' => 'foo=bar; abc=123' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals(2, count($req->cookies())); + $this->assertEquals('bar', $req->cookies('foo')); + $this->assertNull($req->cookies('xyz')); + } + + /** + * Test is form data + */ + public function testIsFormDataContentFormUrlencoded() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'PUT', + 'slim.input' => '', + 'CONTENT_TYPE' => 'application/x-www-form-urlencoded' + )); + $req = new \Slim\Http\Request($env); + $this->assertTrue($req->isFormData()); + } + + /** + * Test is form data + */ + public function testIsFormDataPostContentUnknown() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'slim.input' => '', + )); + $req = new \Slim\Http\Request($env); + $this->assertTrue($req->isFormData()); + } + + /** + * Test is form data + */ + public function testIsFormDataPostContentUnknownWithMethodOverride() + { + $env = \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'PUT', + )); + $env['slim.method_override.original_method'] = 'POST'; + $req = new \Slim\Http\Request($env); + $this->assertTrue($req->isPut()); + $this->assertTrue($req->isFormData()); + } + + /** + * Test is not form data + */ + public function testIsNotFormData() + { + $env = \Slim\Environment::mock(array( + 'slim.input' => '', + 'CONTENT_TYPE' => 'application/json' + )); + $req = new \Slim\Http\Request($env); + $this->assertFalse($req->isFormData()); + } + + /** + * Test headers + */ + public function testHeaders() + { + $env = \Slim\Environment::mock(array( + 'HTTP_ACCEPT_ENCODING' => 'gzip' + )); + $req = new \Slim\Http\Request($env); + $headers = $req->headers(); + $this->assertInstanceOf('\Slim\Http\Headers', $headers); + $this->assertEquals('gzip', $req->headers('HTTP_ACCEPT_ENCODING')); + $this->assertEquals('gzip', $req->headers('HTTP-ACCEPT-ENCODING')); + $this->assertEquals('gzip', $req->headers('http_accept_encoding')); + $this->assertEquals('gzip', $req->headers('http-accept-encoding')); + $this->assertEquals('gzip', $req->headers('ACCEPT_ENCODING')); + $this->assertEquals('gzip', $req->headers('ACCEPT-ENCODING')); + $this->assertEquals('gzip', $req->headers('accept_encoding')); + $this->assertEquals('gzip', $req->headers('accept-encoding')); + $this->assertNull($req->headers('foo')); + } + + /** + * Test accurately removes HTTP_ prefix from input header name + */ + public function testHeaderRemovesHttpPrefix() + { + $env = \Slim\Environment::mock(array( + 'X_HTTP_METHOD_OVERRIDE' => 'PUT', + 'CONTENT_TYPE' => 'application/json' + )); + //fwrite(fopen('php://stdout', 'w'), print_r($env, true)); + $req = new \Slim\Http\Request($env); + $this->assertEquals('PUT', $req->headers('X_HTTP_METHOD_OVERRIDE')); + $this->assertNull($req->headers('X_METHOD_OVERRIDE')); //<-- Ensures `HTTP_` is not removed if not prefix + $this->assertEquals('application/json', $req->headers('HTTP_CONTENT_TYPE')); //<-- Ensures `HTTP_` is removed if prefix + } + + /** + * Test get body + */ + public function testGetBodyWhenExists() + { + $env = \Slim\Environment::mock(array( + 'slim.input' => 'foo=bar&abc=123', + 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', + 'CONTENT_LENGTH' => 15 + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('foo=bar&abc=123', $req->getBody()); + } + + /** + * Test get body + */ + public function testGetBodyWhenNotExists() + { + $env = \Slim\Environment::mock(); + $req = new \Slim\Http\Request($env); + $this->assertEquals('', $req->getBody()); + } + + /** + * Test get content type + */ + public function testGetContentTypeWhenExists() + { + $env = \Slim\Environment::mock(array( + 'slim.input' => '', + 'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('application/json; charset=ISO-8859-4', $req->getContentType()); + } + + /** + * Test get content type + */ + public function testGetContentTypeWhenNotExists() + { + $env = \Slim\Environment::mock(); + $req = new \Slim\Http\Request($env); + $this->assertNull($req->getContentType()); + } + + /** + * Test get media type + */ + public function testGetMediaTypeWhenExists() + { + $env = \Slim\Environment::mock(array( + 'CONTENT_TYPE' => 'application/json;charset=utf-8' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('application/json', $req->getMediaType()); + } + + /** + * Test get media type + */ + public function testGetMediaTypeWhenNotExists() + { + $env = \Slim\Environment::mock(); + $req = new \Slim\Http\Request($env); + $this->assertNull($req->getMediaType()); + } + + /** + * Test get media type + */ + public function testGetMediaTypeWhenNoParamsExist() + { + $env = \Slim\Environment::mock(array( + 'slim.input' => '', + 'CONTENT_TYPE' => 'application/json' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('application/json', $req->getMediaType()); + } + + /** + * Test get media type params + */ + public function testGetMediaTypeParams() + { + $env = \Slim\Environment::mock(array( + 'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4' + )); + $req = new \Slim\Http\Request($env); + $params = $req->getMediaTypeParams(); + $this->assertEquals(1, count($params)); + $this->assertArrayHasKey('charset', $params); + $this->assertEquals('ISO-8859-4', $params['charset']); + } + + /** + * Test get media type params + */ + public function testGetMediaTypeParamsWhenNotExists() + { + $env = \Slim\Environment::mock(); + $req = new \Slim\Http\Request($env); + $params = $req->getMediaTypeParams(); + $this->assertTrue(is_array($params)); + $this->assertEquals(0, count($params)); + } + + /** + * Test get content charset + */ + public function testGetContentCharset() + { + $env = \Slim\Environment::mock(array( + 'slim.input' => '', + 'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('ISO-8859-4', $req->getContentCharset()); + } + + /** + * Test get content charset + */ + public function testGetContentCharsetWhenNotExists() + { + $env = \Slim\Environment::mock(array( + 'slim.input' => '', + 'CONTENT_TYPE' => 'application/json' + )); + $req = new \Slim\Http\Request($env); + $this->assertNull($req->getContentCharset()); + } + + /** + * Test get content length + */ + public function testGetContentLength() + { + $env = \Slim\Environment::mock(array( + 'slim.input' => 'foo=bar&abc=123', + 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', + 'CONTENT_LENGTH' => 15 + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals(15, $req->getContentLength()); + } + + /** + * Test get content length + */ + public function testGetContentLengthWhenNotExists() + { + $env = \Slim\Environment::mock(array( + 'slim.input' => '', + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals(0, $req->getContentLength()); + } + + /** + * Test get host + */ + public function testGetHost() + { + $env = \Slim\Environment::mock(array( + 'SERVER_NAME' => 'slim', + 'HTTP_HOST' => 'slimframework.com' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('slimframework.com', $req->getHost()); //Uses HTTP_HOST if available + } + + /** + * Test get host when it has a port number + */ + public function testGetHostAndStripPort() + { + $env = \Slim\Environment::mock(array( + 'SERVER_NAME' => 'slim', + 'HTTP_HOST' => 'slimframework.com:80' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('slimframework.com', $req->getHost()); //Uses HTTP_HOST if available + } + + /** + * Test get host + */ + public function testGetHostWhenNotExists() + { + $env = \Slim\Environment::mock(array( + 'SERVER_NAME' => 'slim', + 'HTTP_HOST' => 'slimframework.com' + )); + unset($env['HTTP_HOST']); + $req = new \Slim\Http\Request($env); + $this->assertEquals('slim', $req->getHost()); //Uses SERVER_NAME as backup + } + + /** + * Test get host with port + */ + public function testGetHostWithPort() + { + $env = \Slim\Environment::mock(array( + 'HTTP_HOST' => 'slimframework.com', + 'SERVER_NAME' => 'slim', + 'SERVER_PORT' => 80, + 'slim.url_scheme' => 'http' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('slimframework.com:80', $req->getHostWithPort()); + } + + /** + * Test get host with port doesn't duplicate port numbers + */ + public function testGetHostDoesntDuplicatePort() + { + $env = \Slim\Environment::mock(array( + 'HTTP_HOST' => 'slimframework.com:80', + 'SERVER_NAME' => 'slim', + 'SERVER_PORT' => 80, + 'slim.url_scheme' => 'http' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('slimframework.com:80', $req->getHostWithPort()); + } + + /** + * Test get port + */ + public function testGetPort() + { + $env = \Slim\Environment::mock(array( + 'SERVER_PORT' => 80 + )); + $req = new \Slim\Http\Request($env); + $this->assertTrue(is_integer($req->getPort())); + $this->assertEquals(80, $req->getPort()); + } + + /** + * Test get scheme + */ + public function testGetSchemeIfHttp() + { + $env = \Slim\Environment::mock(array( + 'slim.url_scheme' => 'http' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('http', $req->getScheme()); + } + + /** + * Test get scheme + */ + public function testGetSchemeIfHttps() + { + $env = \Slim\Environment::mock(array( + 'slim.url_scheme' => 'https', + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('https', $req->getScheme()); + } + + /** + * Test get [script name, root uri, path, path info, resource uri] in subdirectory without htaccess + */ + public function testAppPathsInSubdirectoryWithoutHtaccess() + { + $env = \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo/index.php', //<-- Physical + 'PATH_INFO' => '/bar/xyz', //<-- Virtual + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('/foo/index.php', $req->getScriptName()); + $this->assertEquals('/foo/index.php', $req->getRootUri()); + $this->assertEquals('/foo/index.php/bar/xyz', $req->getPath()); + $this->assertEquals('/bar/xyz', $req->getPathInfo()); + $this->assertEquals('/bar/xyz', $req->getResourceUri()); + } + + /** + * Test get [script name, root uri, path, path info, resource uri] in subdirectory with htaccess + */ + public function testAppPathsInSubdirectoryWithHtaccess() + { + $env = \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar/xyz', //<-- Virtual + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('/foo', $req->getScriptName()); + $this->assertEquals('/foo', $req->getRootUri()); + $this->assertEquals('/foo/bar/xyz', $req->getPath()); + $this->assertEquals('/bar/xyz', $req->getPathInfo()); + $this->assertEquals('/bar/xyz', $req->getResourceUri()); + } + + /** + * Test get [script name, root uri, path, path info, resource uri] in root directory without htaccess + */ + public function testAppPathsInRootDirectoryWithoutHtaccess() + { + $env = \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/index.php', //<-- Physical + 'PATH_INFO' => '/bar/xyz', //<-- Virtual + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('/index.php', $req->getScriptName()); + $this->assertEquals('/index.php', $req->getRootUri()); + $this->assertEquals('/index.php/bar/xyz', $req->getPath()); + $this->assertEquals('/bar/xyz', $req->getPathInfo()); + $this->assertEquals('/bar/xyz', $req->getResourceUri()); + } + + /** + * Test get [script name, root uri, path, path info, resource uri] in root directory with htaccess + */ + public function testAppPathsInRootDirectoryWithHtaccess() + { + $env = \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '', //<-- Physical + 'PATH_INFO' => '/bar/xyz', //<-- Virtual + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('', $req->getScriptName()); + $this->assertEquals('', $req->getRootUri()); + $this->assertEquals('/bar/xyz', $req->getPath()); + $this->assertEquals('/bar/xyz', $req->getPathInfo()); + $this->assertEquals('/bar/xyz', $req->getResourceUri()); + } + + /** + * Test get URL + */ + public function testGetUrl() + { + $env = \Slim\Environment::mock(array( + 'HTTP_HOST' => 'slimframework.com', + 'SERVER_NAME' => 'slim', + 'SERVER_PORT' => 80, + 'slim.url_scheme' => 'http' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('http://slimframework.com', $req->getUrl()); + } + + /** + * Test get URL + */ + public function testGetUrlWithCustomPort() + { + $env = \Slim\Environment::mock(array( + 'HTTP_HOST' => 'slimframework.com', + 'SERVER_NAME' => 'slim', + 'SERVER_PORT' => 8080, + 'slim.url_scheme' => 'http' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('http://slimframework.com:8080', $req->getUrl()); + } + + /** + * Test get URL + */ + public function testGetUrlWithHttps() + { + $env = \Slim\Environment::mock(array( + 'HTTP_HOST' => 'slimframework.com', + 'SERVER_NAME' => 'slim', + 'SERVER_PORT' => 443, + 'slim.url_scheme' => 'https' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('https://slimframework.com', $req->getUrl()); + } + + /** + * Test get IP + */ + public function testGetIp() + { + $env = \Slim\Environment::mock(array( + 'REMOTE_ADDR' => '127.0.0.1' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('127.0.0.1', $req->getIp()); + } + + /** + * Test get IP with proxy server and Client-Ip header + */ + public function testGetIpWithClientIp() + { + $env = \Slim\Environment::mock(array( + 'REMOTE_ADDR' => '127.0.0.1', + 'CLIENT_IP' => '127.0.0.2' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('127.0.0.2', $req->getIp()); + } + + /** + * Test get IP with proxy server and X-Forwarded-For header + */ + public function testGetIpWithForwardedFor() + { + $env = \Slim\Environment::mock(array( + 'REMOTE_ADDR' => '127.0.0.1', + 'CLIENT_IP' => '127.0.0.2', + 'X_FORWARDED_FOR' => '127.0.0.3' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('127.0.0.3', $req->getIp()); + } + + /** + * Test get referer + */ + public function testGetReferrer() + { + $env = \Slim\Environment::mock(array( + 'HTTP_REFERER' => 'http://foo.com' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('http://foo.com', $req->getReferrer()); + $this->assertEquals('http://foo.com', $req->getReferer()); + } + + /** + * Test get referer + */ + public function testGetReferrerWhenNotExists() + { + $env = \Slim\Environment::mock(); + $req = new \Slim\Http\Request($env); + $this->assertNull($req->getReferrer()); + $this->assertNull($req->getReferer()); + } + + /** + * Test get user agent string + */ + public function testGetUserAgent() + { + $env = \Slim\Environment::mock(array( + 'HTTP_USER_AGENT' => 'user-agent-string' + )); + $req = new \Slim\Http\Request($env); + $this->assertEquals('user-agent-string', $req->getUserAgent()); + } + + /** + * Test get user agent string when not set + */ + public function testGetUserAgentWhenNotExists() + { + $env = \Slim\Environment::mock(); + unset($env['HTTP_USER_AGENT']); + $req = new \Slim\Http\Request($env); + $this->assertNull($req->getUserAgent()); + } +} diff --git a/strillonews/vendor/slim/slim/tests/Http/ResponseTest.php b/strillonews/vendor/slim/slim/tests/Http/ResponseTest.php new file mode 100644 index 0000000..0b80445 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/Http/ResponseTest.php @@ -0,0 +1,271 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class ResponseTest extends PHPUnit_Framework_TestCase +{ + public function testConstructWithoutArgs() + { + $res = new \Slim\Http\Response(); + + $this->assertAttributeEquals(200, 'status', $res); + $this->assertAttributeEquals('', 'body', $res); + } + + public function testConstructWithArgs() + { + $res = new \Slim\Http\Response('Foo', 201); + + $this->assertAttributeEquals(201, 'status', $res); + $this->assertAttributeEquals('Foo', 'body', $res); + } + + public function testGetStatus() + { + $res = new \Slim\Http\Response(); + + $this->assertEquals(200, $res->getStatus()); + } + + public function testSetStatus() + { + $res = new \Slim\Http\Response(); + $res->setStatus(301); + + $this->assertAttributeEquals(301, 'status', $res); + } + + /** + * DEPRECATION WARNING! + */ + public function testStatusGetOld() + { + $res = new \Slim\Http\Response('', 201); + $this->assertEquals(201, $res->status()); + } + + /** + * DEPRECATION WARNING! + */ + public function testStatusSetOld() + { + $res = new \Slim\Http\Response(); + $prop = new \ReflectionProperty($res, 'status'); + $prop->setAccessible(true); + $res->status(301); + + $this->assertEquals(301, $prop->getValue($res)); + } + + public function testGetBody() + { + $res = new \Slim\Http\Response(); + $property = new \ReflectionProperty($res, 'body'); + $property->setAccessible(true); + $property->setValue($res, 'foo'); + + $this->assertEquals('foo', $res->getBody()); + } + + public function testSetBody() + { + $res = new \Slim\Http\Response('bar'); + $res->setBody('foo'); // <-- Should replace body + + $this->assertAttributeEquals('foo', 'body', $res); + } + + public function testWrite() + { + $res = new \Slim\Http\Response(); + $property = new \ReflectionProperty($res, 'body'); + $property->setAccessible(true); + $property->setValue($res, 'foo'); + $res->write('bar'); // <-- Should append to body + + $this->assertAttributeEquals('foobar', 'body', $res); + } + + public function testLength() + { + $res = new \Slim\Http\Response('foo'); // <-- Sets body and length + + $this->assertEquals(3, $res->getLength()); + } + + public function testFinalize() + { + $res = new \Slim\Http\Response(); + $resFinal = $res->finalize(); + + $this->assertTrue(is_array($resFinal)); + $this->assertEquals(3, count($resFinal)); + $this->assertEquals(200, $resFinal[0]); + $this->assertInstanceOf('\Slim\Http\Headers', $resFinal[1]); + $this->assertEquals('', $resFinal[2]); + } + + public function testFinalizeWithEmptyBody() + { + $res = new \Slim\Http\Response('Foo', 304); + $resFinal = $res->finalize(); + + $this->assertEquals('', $resFinal[2]); + } + + public function testRedirect() + { + $res = new \Slim\Http\Response(); + $res->redirect('/foo'); + + $pStatus = new \ReflectionProperty($res, 'status'); + $pStatus->setAccessible(true); + + $this->assertEquals(302, $pStatus->getValue($res)); + $this->assertEquals('/foo', $res->headers['Location']); + } + + public function testIsEmpty() + { + $r1 = new \Slim\Http\Response(); + $r2 = new \Slim\Http\Response(); + $r1->setStatus(404); + $r2->setStatus(201); + $this->assertFalse($r1->isEmpty()); + $this->assertTrue($r2->isEmpty()); + } + + public function testIsClientError() + { + $r1 = new \Slim\Http\Response(); + $r2 = new \Slim\Http\Response(); + $r1->setStatus(404); + $r2->setStatus(500); + $this->assertTrue($r1->isClientError()); + $this->assertFalse($r2->isClientError()); + } + + public function testIsForbidden() + { + $r1 = new \Slim\Http\Response(); + $r2 = new \Slim\Http\Response(); + $r1->setStatus(403); + $r2->setStatus(500); + $this->assertTrue($r1->isForbidden()); + $this->assertFalse($r2->isForbidden()); + } + + public function testIsInformational() + { + $r1 = new \Slim\Http\Response(); + $r2 = new \Slim\Http\Response(); + $r1->setStatus(100); + $r2->setStatus(200); + $this->assertTrue($r1->isInformational()); + $this->assertFalse($r2->isInformational()); + } + + public function testIsNotFound() + { + $r1 = new \Slim\Http\Response(); + $r2 = new \Slim\Http\Response(); + $r1->setStatus(404); + $r2->setStatus(200); + $this->assertTrue($r1->isNotFound()); + $this->assertFalse($r2->isNotFound()); + } + + public function testIsOk() + { + $r1 = new \Slim\Http\Response(); + $r2 = new \Slim\Http\Response(); + $r1->setStatus(200); + $r2->setStatus(201); + $this->assertTrue($r1->isOk()); + $this->assertFalse($r2->isOk()); + } + + public function testIsSuccessful() + { + $r1 = new \Slim\Http\Response(); + $r2 = new \Slim\Http\Response(); + $r3 = new \Slim\Http\Response(); + $r1->setStatus(200); + $r2->setStatus(201); + $r3->setStatus(302); + $this->assertTrue($r1->isSuccessful()); + $this->assertTrue($r2->isSuccessful()); + $this->assertFalse($r3->isSuccessful()); + } + + public function testIsRedirect() + { + $r1 = new \Slim\Http\Response(); + $r2 = new \Slim\Http\Response(); + $r1->setStatus(307); + $r2->setStatus(304); + $this->assertTrue($r1->isRedirect()); + $this->assertFalse($r2->isRedirect()); + } + + public function testIsRedirection() + { + $r1 = new \Slim\Http\Response(); + $r2 = new \Slim\Http\Response(); + $r3 = new \Slim\Http\Response(); + $r1->setStatus(307); + $r2->setStatus(304); + $r3->setStatus(200); + $this->assertTrue($r1->isRedirection()); + $this->assertTrue($r2->isRedirection()); + $this->assertFalse($r3->isRedirection()); + } + + public function testIsServerError() + { + $r1 = new \Slim\Http\Response(); + $r2 = new \Slim\Http\Response(); + $r1->setStatus(500); + $r2->setStatus(400); + $this->assertTrue($r1->isServerError()); + $this->assertFalse($r2->isServerError()); + } + + public function testMessageForCode() + { + $this->assertEquals('200 OK', \Slim\Http\Response::getMessageForCode(200)); + } + + public function testMessageForCodeWithInvalidCode() + { + $this->assertNull(\Slim\Http\Response::getMessageForCode(600)); + } +} diff --git a/strillonews/vendor/slim/slim/tests/Http/UtilTest.php b/strillonews/vendor/slim/slim/tests/Http/UtilTest.php new file mode 100644 index 0000000..544a664 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/Http/UtilTest.php @@ -0,0 +1,432 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class SlimHttpUtilTest extends PHPUnit_Framework_TestCase +{ + /** + * Test strip slashes when magic quotes disabled + */ + public function testStripSlashesWithoutMagicQuotes() + { + $data = "This should have \"quotes\" in it"; + $stripped = \Slim\Http\Util::stripSlashesIfMagicQuotes($data, false); + $this->assertEquals($data, $stripped); + } + + /** + * Test strip slashes from array when magic quotes disabled + */ + public function testStripSlashesFromArrayWithoutMagicQuotes() + { + $data = array("This should have \"quotes\" in it", "And this \"too\" has quotes"); + $stripped = \Slim\Http\Util::stripSlashesIfMagicQuotes($data, false); + $this->assertEquals($data, $stripped); + } + + /** + * Test strip slashes when magic quotes enabled + */ + public function testStripSlashesWithMagicQuotes() + { + $data = "This should have \"quotes\" in it"; + $stripped = \Slim\Http\Util::stripSlashesIfMagicQuotes($data, true); + $this->assertEquals('This should have "quotes" in it', $stripped); + } + + /** + * Test strip slashes from array when magic quotes enabled + */ + public function testStripSlashesFromArrayWithMagicQuotes() + { + $data = array("This should have \"quotes\" in it", "And this \"too\" has quotes"); + $stripped = \Slim\Http\Util::stripSlashesIfMagicQuotes($data, true); + $this->assertEquals($data = array('This should have "quotes" in it', 'And this "too" has quotes'), $stripped); + } + + /** + * Test encrypt and decrypt with valid data + */ + public function testEncryptAndDecryptWithValidData() + { + $data = 'foo'; + $key = 'secret'; + $iv = md5('initializationVector'); + $encrypted = \Slim\Http\Util::encrypt($data, $key, $iv); + $decrypted = \Slim\Http\Util::decrypt($encrypted, $key, $iv); + $this->assertEquals($data, $decrypted); + $this->assertTrue($data !== $encrypted); + } + + /** + * Test encrypt when data is empty string + */ + public function testEncryptWhenDataIsEmptyString() + { + $data = ''; + $key = 'secret'; + $iv = md5('initializationVector'); + $encrypted = \Slim\Http\Util::encrypt($data, $key, $iv); + $this->assertEquals('', $encrypted); + } + + /** + * Test decrypt when data is empty string + */ + public function testDecryptWhenDataIsEmptyString() + { + $data = ''; + $key = 'secret'; + $iv = md5('initializationVector'); + $decrypted = \Slim\Http\Util::decrypt($data, $key, $iv); + $this->assertEquals('', $decrypted); + } + + /** + * Test encrypt when IV and key sizes are too long + */ + public function testEncryptAndDecryptWhenKeyAndIvAreTooLong() + { + $data = 'foo'; + $key = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'; + $iv = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'; + $encrypted = \Slim\Http\Util::encrypt($data, $key, $iv); + $decrypted = \Slim\Http\Util::decrypt($encrypted, $key, $iv); + $this->assertEquals($data, $decrypted); + $this->assertTrue($data !== $encrypted); + } + + public function testEncodeAndDecodeSecureCookieWithValidData() + { + //Prepare cookie value + $value = 'foo'; + $expires = time() + 86400; + $secret = 'password'; + $algorithm = MCRYPT_RIJNDAEL_256; + $mode = MCRYPT_MODE_CBC; + $encodedValue = \Slim\Http\Util::encodeSecureCookie($value, $expires, $secret, $algorithm, $mode); + $decodedValue = \Slim\Http\Util::decodeSecureCookie($encodedValue, $secret, $algorithm, $mode); + + //Test secure cookie value + $parts = explode('|', $encodedValue); + $this->assertEquals(3, count($parts)); + $this->assertEquals($expires, $parts[0]); + $this->assertEquals($value, $decodedValue); + } + + /** + * Test encode/decode secure cookie with old expiration + * + * In this test, the expiration date is purposefully set to a time before now. + * When decoding the encoded cookie value, FALSE is returned since the cookie + * will have expired before it is decoded. + */ + public function testEncodeAndDecodeSecureCookieWithOldExpiration() + { + $value = 'foo'; + $expires = time() - 100; + $secret = 'password'; + $algorithm = MCRYPT_RIJNDAEL_256; + $mode = MCRYPT_MODE_CBC; + $encodedValue = \Slim\Http\Util::encodeSecureCookie($value, $expires, $secret, $algorithm, $mode); + $decodedValue = \Slim\Http\Util::decodeSecureCookie($encodedValue, $secret, $algorithm, $mode); + $this->assertFalse($decodedValue); + } + + /** + * Test encode/decode secure cookie with tampered data + * + * In this test, the encoded data is purposefully changed to simulate someone + * tampering with the client-side cookie data. When decoding the encoded cookie value, + * FALSE is returned since the verification key will not match. + */ + public function testEncodeAndDecodeSecureCookieWithTamperedData() + { + $value = 'foo'; + $expires = time() + 86400; + $secret = 'password'; + $algorithm = MCRYPT_RIJNDAEL_256; + $mode = MCRYPT_MODE_CBC; + $encodedValue = \Slim\Http\Util::encodeSecureCookie($value, $expires, $secret, $algorithm, $mode); + $encodedValueParts = explode('|', $encodedValue); + $encodedValueParts[1] = $encodedValueParts[1] . 'changed'; + $encodedValue = implode('|', $encodedValueParts); + $decodedValue = \Slim\Http\Util::decodeSecureCookie($encodedValue, $secret, $algorithm, $mode); + $this->assertFalse($decodedValue); + } + + public function testSetCookieHeaderWithNameAndValue() + { + $name = 'foo'; + $value = 'bar'; + $header = array(); + \Slim\Http\Util::setCookieHeader($header, $name, $value); + $this->assertEquals('foo=bar', $header['Set-Cookie']); + } + + public function testSetCookieHeaderWithNameAndValueWhenCookieAlreadySet() + { + $name = 'foo'; + $value = 'bar'; + $header = array('Set-Cookie' => 'one=two'); + \Slim\Http\Util::setCookieHeader($header, $name, $value); + $this->assertEquals("one=two\nfoo=bar", $header['Set-Cookie']); + } + + public function testSetCookieHeaderWithNameAndValueAndDomain() + { + $name = 'foo'; + $value = 'bar'; + $domain = 'foo.com'; + $header = array(); + \Slim\Http\Util::setCookieHeader($header, $name, array( + 'value' => $value, + 'domain' => $domain + )); + $this->assertEquals('foo=bar; domain=foo.com', $header['Set-Cookie']); + } + + public function testSetCookieHeaderWithNameAndValueAndDomainAndPath() + { + $name = 'foo'; + $value = 'bar'; + $domain = 'foo.com'; + $path = '/foo'; + $header = array(); + \Slim\Http\Util::setCookieHeader($header, $name, array( + 'value' => $value, + 'domain' => $domain, + 'path' => $path + )); + $this->assertEquals('foo=bar; domain=foo.com; path=/foo', $header['Set-Cookie']); + } + + public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAsString() + { + $name = 'foo'; + $value = 'bar'; + $domain = 'foo.com'; + $path = '/foo'; + $expires = '2 days'; + $expiresFormat = gmdate('D, d-M-Y H:i:s e', strtotime($expires)); + $header = array(); + \Slim\Http\Util::setCookieHeader($header, $name, array( + 'value' => $value, + 'domain' => $domain, + 'path' => '/foo', + 'expires' => $expires + )); + $this->assertEquals('foo=bar; domain=foo.com; path=/foo; expires=' . $expiresFormat, $header['Set-Cookie']); + } + + public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAsInteger() + { + $name = 'foo'; + $value = 'bar'; + $domain = 'foo.com'; + $path = '/foo'; + $expires = strtotime('2 days'); + $expiresFormat = gmdate('D, d-M-Y H:i:s e', $expires); + $header = array(); + \Slim\Http\Util::setCookieHeader($header, $name, array( + 'value' => $value, + 'domain' => $domain, + 'path' => '/foo', + 'expires' => $expires + )); + $this->assertEquals('foo=bar; domain=foo.com; path=/foo; expires=' . $expiresFormat, $header['Set-Cookie']); + } + + public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAsZero() + { + $name = 'foo'; + $value = 'bar'; + $domain = 'foo.com'; + $path = '/foo'; + $expires = 0; + $header = array(); + \Slim\Http\Util::setCookieHeader($header, $name, array( + 'value' => $value, + 'domain' => $domain, + 'path' => '/foo', + 'expires' => $expires + )); + $this->assertEquals('foo=bar; domain=foo.com; path=/foo', $header['Set-Cookie']); + } + + public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAndSecure() + { + $name = 'foo'; + $value = 'bar'; + $domain = 'foo.com'; + $path = '/foo'; + $expires = strtotime('2 days'); + $expiresFormat = gmdate('D, d-M-Y H:i:s e', $expires); + $secure = true; + $header = array(); + \Slim\Http\Util::setCookieHeader($header, $name, array( + 'value' => $value, + 'domain' => $domain, + 'path' => '/foo', + 'expires' => $expires, + 'secure' => $secure + )); + $this->assertEquals('foo=bar; domain=foo.com; path=/foo; expires=' . $expiresFormat . '; secure', $header['Set-Cookie']); + } + + public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAndSecureAndHttpOnly() + { + $name = 'foo'; + $value = 'bar'; + $domain = 'foo.com'; + $path = '/foo'; + $expires = strtotime('2 days'); + $expiresFormat = gmdate('D, d-M-Y H:i:s e', $expires); + $secure = true; + $httpOnly = true; + $header = array(); + \Slim\Http\Util::setCookieHeader($header, $name, array( + 'value' => $value, + 'domain' => $domain, + 'path' => '/foo', + 'expires' => $expires, + 'secure' => $secure, + 'httponly' => $httpOnly + )); + $this->assertEquals('foo=bar; domain=foo.com; path=/foo; expires=' . $expiresFormat . '; secure; HttpOnly', $header['Set-Cookie']); + } + + /** + * Test serializeCookies and decrypt with string expires + * + * In this test a cookie with a string typed value for 'expires' is set, + * which should be parsed by `strtotime` to a timestamp when it's added to + * the headers; this timestamp should then be correctly parsed, and the + * value correctly decrypted, by `decodeSecureCookie`. + */ + public function testSerializeCookiesAndDecryptWithStringExpires() + { + $value = 'bar'; + + $headers = new \Slim\Http\Headers(); + + $settings = array( + 'cookies.encrypt' => true, + 'cookies.secret_key' => 'secret', + 'cookies.cipher' => MCRYPT_RIJNDAEL_256, + 'cookies.cipher_mode' => MCRYPT_MODE_CBC + ); + + $cookies = new \Slim\Http\Cookies(); + $cookies->set('foo', array( + 'value' => $value, + 'expires' => '1 hour' + )); + + \Slim\Http\Util::serializeCookies($headers, $cookies, $settings); + + $encrypted = $headers->get('Set-Cookie'); + $encrypted = strstr($encrypted, ';', true); + $encrypted = urldecode(substr(strstr($encrypted, '='), 1)); + + $decrypted = \Slim\Http\Util::decodeSecureCookie( + $encrypted, + $settings['cookies.secret_key'], + $settings['cookies.cipher'], + $settings['cookies.cipher_mode'] + ); + + $this->assertEquals($value, $decrypted); + $this->assertTrue($value !== $encrypted); + } + + public function testDeleteCookieHeaderWithSurvivingCookie() + { + $header = array('Set-Cookie' => "foo=bar\none=two"); + \Slim\Http\Util::deleteCookieHeader($header, 'foo'); + $this->assertEquals(1, preg_match("@^one=two\nfoo=; expires=@", $header['Set-Cookie'])); + } + + public function testDeleteCookieHeaderWithoutSurvivingCookie() + { + $header = array('Set-Cookie' => "foo=bar"); + \Slim\Http\Util::deleteCookieHeader($header, 'foo'); + $this->assertEquals(1, preg_match("@foo=; expires=@", $header['Set-Cookie'])); + } + + public function testDeleteCookieHeaderWithMatchingDomain() + { + $header = array('Set-Cookie' => "foo=bar; domain=foo.com"); + \Slim\Http\Util::deleteCookieHeader($header, 'foo', array( + 'domain' => 'foo.com' + )); + $this->assertEquals(1, preg_match("@foo=; domain=foo.com; expires=@", $header['Set-Cookie'])); + } + + public function testDeleteCookieHeaderWithoutMatchingDomain() + { + $header = array('Set-Cookie' => "foo=bar; domain=foo.com"); + \Slim\Http\Util::deleteCookieHeader($header, 'foo', array( + 'domain' => 'bar.com' + )); + $this->assertEquals(1, preg_match("@foo=bar; domain=foo\.com\nfoo=; domain=bar\.com@", $header['Set-Cookie'])); + } + + /** + * Test parses Cookie: HTTP header + */ + public function testParsesCookieHeader() + { + $header = 'foo=bar; one=two; colors=blue'; + $result = \Slim\Http\Util::parseCookieHeader($header); + $this->assertEquals(3, count($result)); + $this->assertEquals('bar', $result['foo']); + $this->assertEquals('two', $result['one']); + $this->assertEquals('blue', $result['colors']); + } + + public function testParsesCookieHeaderWithCommaSeparator() + { + $header = 'foo=bar, one=two, colors=blue'; + $result = \Slim\Http\Util::parseCookieHeader($header); + $this->assertEquals(3, count($result)); + $this->assertEquals('bar', $result['foo']); + $this->assertEquals('two', $result['one']); + $this->assertEquals('blue', $result['colors']); + } + + public function testPrefersLeftmostCookieWhenManyCookiesWithSameName() + { + $header = 'foo=bar; foo=beer'; + $result = \Slim\Http\Util::parseCookieHeader($header); + $this->assertEquals('bar', $result['foo']); + } +} diff --git a/strillonews/vendor/slim/slim/tests/LogTest.php b/strillonews/vendor/slim/slim/tests/LogTest.php new file mode 100644 index 0000000..04954c5 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/LogTest.php @@ -0,0 +1,208 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class MyWriter +{ + public function write( $object, $level ) + { + echo (string) $object; + + return true; + } +} + +class LogTest extends PHPUnit_Framework_TestCase +{ + public function testEnabled() + { + $log = new \Slim\Log(new MyWriter()); + $this->assertTrue($log->isEnabled()); //<-- Default case + $log->setEnabled(true); + $this->assertTrue($log->isEnabled()); + $log->setEnabled(false); + $this->assertFalse($log->isEnabled()); + } + + public function testGetLevel() + { + $log = new \Slim\Log(new MyWriter()); + $this->assertEquals(\Slim\Log::DEBUG, $log->getLevel()); + } + + public function testSetLevel() + { + $log = new \Slim\Log(new MyWriter()); + $log->setLevel(\Slim\Log::WARN); + $this->assertEquals(\Slim\Log::WARN, $log->getLevel()); + } + + public function testSetInvalidLevel() + { + $this->setExpectedException('InvalidArgumentException'); + $log = new \Slim\Log(new MyWriter()); + $log->setLevel(\Slim\Log::DEBUG + 1); + } + + public function testLogDebug() + { + $this->expectOutputString('Debug'); + $log = new \Slim\Log(new MyWriter()); + $result = $log->debug('Debug'); + $this->assertTrue($result); + } + + public function testLogDebugExcludedByLevel() + { + $log = new \Slim\Log(new MyWriter()); + $log->setLevel(\Slim\Log::INFO); + $this->assertFalse($log->debug('Debug')); + } + + public function testLogInfo() + { + $this->expectOutputString('Info'); + $log = new \Slim\Log(new MyWriter()); + $result = $log->info('Info'); + $this->assertTrue($result); + } + + public function testLogInfoExcludedByLevel() + { + $log = new \Slim\Log(new MyWriter()); + $log->setLevel(\Slim\Log::NOTICE); + $this->assertFalse($log->info('Info')); + } + + public function testLogNotice() + { + $this->expectOutputString('Notice'); + $log = new \Slim\Log(new MyWriter()); + $result = $log->notice('Notice'); + $this->assertTrue($result); + } + + public function testLogNoticeExcludedByLevel() + { + $log = new \Slim\Log(new MyWriter()); + $log->setLevel(\Slim\Log::WARN); + $this->assertFalse($log->info('Info')); + } + + public function testLogWarn() + { + $this->expectOutputString('Warn'); + $log = new \Slim\Log(new MyWriter()); + $result = $log->warning('Warn'); + $this->assertTrue($result); + } + + public function testLogWarnExcludedByLevel() + { + $log = new \Slim\Log(new MyWriter()); + $log->setLevel(\Slim\Log::ERROR); + $this->assertFalse($log->warning('Warn')); + } + + public function testLogError() + { + $this->expectOutputString('Error'); + $log = new \Slim\Log(new MyWriter()); + $result = $log->error('Error'); + $this->assertTrue($result); + } + + public function testLogErrorExcludedByLevel() + { + $log = new \Slim\Log(new MyWriter()); + $log->setLevel(\Slim\Log::CRITICAL); + $this->assertFalse($log->error('Error')); + } + + public function testLogCritical() + { + $this->expectOutputString('Critical'); + $log = new \Slim\Log(new MyWriter()); + $result = $log->critical('Critical'); + $this->assertTrue($result); + } + + public function testLogCriticalExcludedByLevel() + { + $log = new \Slim\Log(new MyWriter()); + $log->setLevel(\Slim\Log::ALERT); + $this->assertFalse($log->critical('Critical')); + } + + public function testLogAlert() + { + $this->expectOutputString('Alert'); + $log = new \Slim\Log(new MyWriter()); + $result = $log->alert('Alert'); + $this->assertTrue($result); + } + + public function testLogAlertExcludedByLevel() + { + $log = new \Slim\Log(new MyWriter()); + $log->setLevel(\Slim\Log::EMERGENCY); + $this->assertFalse($log->alert('Alert')); + } + + public function testLogEmergency() + { + $this->expectOutputString('Emergency'); + $log = new \Slim\Log(new MyWriter()); + $result = $log->emergency('Emergency'); + $this->assertTrue($result); + } + + public function testInterpolateMessage() + { + $this->expectOutputString('Hello Slim !'); + $log = new \Slim\Log(new MyWriter()); + $result = $log->debug( + 'Hello {framework} !', + array('framework' => "Slim") + ); + $this->assertTrue($result); + } + + public function testGetAndSetWriter() + { + $writer1 = new MyWriter(); + $writer2 = new MyWriter(); + $log = new \Slim\Log($writer1); + $this->assertSame($writer1, $log->getWriter()); + $log->setWriter($writer2); + $this->assertSame($writer2, $log->getWriter()); + } +} diff --git a/strillonews/vendor/slim/slim/tests/LogWriterTest.php b/strillonews/vendor/slim/slim/tests/LogWriterTest.php new file mode 100644 index 0000000..e116f37 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/LogWriterTest.php @@ -0,0 +1,48 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class LogWriterTest extends PHPUnit_Framework_TestCase +{ + public function testInstantiation() + { + $this->expectOutputString('Hello!' . PHP_EOL); + $handle = fopen('php://output', 'w'); + $fw = new \Slim\LogWriter($handle); + $this->assertTrue($fw->write('Hello!') > 0); //<-- Returns number of bytes written if successful + } + + public function testInstantiationWithNonResource() + { + $this->setExpectedException('InvalidArgumentException'); + $fw = new \Slim\LogWriter(@fopen('/foo/bar.txt', 'w')); + } +} diff --git a/strillonews/vendor/slim/slim/tests/Middleware/ContentTypesTest.php b/strillonews/vendor/slim/slim/tests/Middleware/ContentTypesTest.php new file mode 100644 index 0000000..3fdfad1 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/Middleware/ContentTypesTest.php @@ -0,0 +1,162 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class ContentTypesTest extends PHPUnit_Framework_TestCase +{ + public function setUp() + { + ob_start(); + } + + public function tearDown() + { + ob_end_clean(); + } + + /** + * Test parses JSON + */ + public function testParsesJson() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'CONTENT_TYPE' => 'application/json', + 'CONENT_LENGTH' => 13, + 'slim.input' => '{"foo":"bar"}' + )); + $s = new \Slim\Slim(); + $s->add(new \Slim\Middleware\ContentTypes()); + $s->run(); + $body = $s->request()->getBody(); + $this->assertTrue(is_array($body)); + $this->assertEquals('bar', $body['foo']); + } + + /** + * Test ignores JSON with errors + */ + public function testParsesJsonWithError() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'CONTENT_TYPE' => 'application/json', + 'CONENT_LENGTH' => 12, + 'slim.input' => '{"foo":"bar"' //<-- This should be incorrect! + )); + $s = new \Slim\Slim(); + $s->add(new \Slim\Middleware\ContentTypes()); + $s->run(); + $body = $s->request()->getBody(); + $this->assertTrue(is_string($body)); + $this->assertEquals('{"foo":"bar"', $body); + } + + /** + * Test parses XML + */ + public function testParsesXml() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'CONTENT_TYPE' => 'application/xml', + 'CONENT_LENGTH' => 68, + 'slim.input' => '1Clive Cussler' + )); + $s = new \Slim\Slim(); + $s->add(new \Slim\Middleware\ContentTypes()); + $s->run(); + $body = $s->request()->getBody(); + $this->assertInstanceOf('SimpleXMLElement', $body); + $this->assertEquals('Clive Cussler', (string) $body->book->author); + } + + /** + * Test ignores XML with errors + */ + public function testParsesXmlWithError() + { + libxml_use_internal_errors(true); + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'CONTENT_TYPE' => 'application/xml', + 'CONTENT_LENGTH' => 68, + 'slim.input' => '1Clive Cussler' //<-- This should be incorrect! + )); + $s = new \Slim\Slim(); + $s->add(new \Slim\Middleware\ContentTypes()); + $s->run(); + $body = $s->request()->getBody(); + $this->assertTrue(is_string($body)); + $this->assertEquals('1Clive Cussler', $body); + } + + /** + * Test parses CSV + */ + public function testParsesCsv() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'CONTENT_TYPE' => 'text/csv', + 'CONTENT_LENGTH' => 44, + 'slim.input' => "John,Doe,000-111-2222\nJane,Doe,111-222-3333" + )); + $s = new \Slim\Slim(); + $s->add(new \Slim\Middleware\ContentTypes()); + $s->run(); + $body = $s->request()->getBody(); + $this->assertTrue(is_array($body)); + $this->assertEquals(2, count($body)); + $this->assertEquals('000-111-2222', $body[0][2]); + $this->assertEquals('Doe', $body[1][1]); + } + + /** + * Test parses request body based on media-type only, disregarding + * any extra content-type header parameters + */ + public function testParsesRequestBodyWithMediaType() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4', + 'CONTENT_LENGTH' => 13, + 'slim.input' => '{"foo":"bar"}' + )); + $s = new \Slim\Slim(); + $s->add(new \Slim\Middleware\ContentTypes()); + $s->run(); + $body = $s->request()->getBody(); + $this->assertTrue(is_array($body)); + $this->assertEquals('bar', $body['foo']); + } +} diff --git a/strillonews/vendor/slim/slim/tests/Middleware/FlashTest.php b/strillonews/vendor/slim/slim/tests/Middleware/FlashTest.php new file mode 100644 index 0000000..24238e1 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/Middleware/FlashTest.php @@ -0,0 +1,141 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class SlimFlashTest extends PHPUnit_Framework_TestCase +{ + /** + * Setup + */ + public function setUp() + { + $_SESSION = array(); + } + + /** + * Test set flash message for next request + */ + public function testSetFlashForNextRequest() + { + $f = new \Slim\Middleware\Flash(); + $f->set('foo', 'bar'); + $f->save(); + $this->assertEquals('bar', $_SESSION['slim.flash']['foo']); + } + + /** + * Test set flash message for current request + */ + public function testSetFlashForCurrentRequest() + { + $f = new \Slim\Middleware\Flash(); + $f->now('foo', 'bar'); + $this->assertEquals('bar', $f['foo']); + } + + /** + * Test loads flash from previous request + */ + public function testLoadsFlashFromPreviousRequest() + { + $_SESSION['slim.flash'] = array('info' => 'foo'); + $f = new \Slim\Middleware\Flash(); + $f->loadMessages(); + $this->assertEquals('foo', $f['info']); + } + + /** + * Test keep flash message for next request + */ + public function testKeepFlashFromPreviousRequest() + { + $_SESSION['slim.flash'] = array('info' => 'foo'); + $f = new \Slim\Middleware\Flash(); + $f->loadMessages(); + $f->keep(); + $f->save(); + $this->assertEquals('foo', $_SESSION['slim.flash']['info']); + } + + /** + * Test flash messages from previous request do not persist to next request + */ + public function testFlashMessagesFromPreviousRequestDoNotPersist() + { + $_SESSION['slim.flash'] = array('info' => 'foo'); + $f = new \Slim\Middleware\Flash(); + $f->save(); + $this->assertEmpty($_SESSION['slim.flash']); + } + + /** + * Test set Flash using array access + */ + public function testFlashArrayAccess() + { + $_SESSION['slim.flash'] = array('info' => 'foo'); + $f = new \Slim\Middleware\Flash(); + $f['info'] = 'bar'; + $f->save(); + $this->assertTrue(isset($f['info'])); + $this->assertEquals('bar', $f['info']); + unset($f['info']); + $this->assertFalse(isset($f['info'])); + } + + /** + * Test iteration + */ + public function testIteration() + { + $_SESSION['slim.flash'] = array('info' => 'foo', 'error' => 'bar'); + $f = new \Slim\Middleware\Flash(); + $f->loadMessages(); + $output = ''; + foreach ($f as $key => $value) { + $output .= $key . $value; + } + $this->assertEquals('infofooerrorbar', $output); + } + + /** + * Test countable + */ + public function testCountable() + { + $_SESSION['slim.flash'] = array('info' => 'foo', 'error' => 'bar'); + $f = new \Slim\MiddleWare\Flash(); + $f->loadMessages(); + $this->assertEquals(2, count($f)); + } + + +} diff --git a/strillonews/vendor/slim/slim/tests/Middleware/MethodOverrideTest.php b/strillonews/vendor/slim/slim/tests/Middleware/MethodOverrideTest.php new file mode 100644 index 0000000..1427d13 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/Middleware/MethodOverrideTest.php @@ -0,0 +1,149 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * We use a mock application, instead of a Slim application. + * so that we may easily test the Method Override middleware + * in isolation. + */ +class CustomAppMethod +{ + protected $environment; + + public function __construct() + { + $this->environment = \Slim\Environment::getInstance(); + } + + public function &environment() { + return $this->environment; + } + + public function call() + { + //Do nothing + } +} + +class MethodOverrideTest extends PHPUnit_Framework_TestCase +{ + /** + * Test overrides method as POST + */ + public function testOverrideMethodAsPost() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', + 'CONTENT_LENGTH' => 11, + 'slim.input' => '_METHOD=PUT' + )); + $app = new CustomAppMethod(); + $mw = new \Slim\Middleware\MethodOverride(); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + $env =& $app->environment(); + $this->assertEquals('PUT', $env['REQUEST_METHOD']); + $this->assertTrue(isset($env['slim.method_override.original_method'])); + $this->assertEquals('POST', $env['slim.method_override.original_method']); + } + + /** + * Test does not override method if not POST + */ + public function testDoesNotOverrideMethodIfNotPost() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'GET', + 'slim.input' => '' + )); + $app = new CustomAppMethod(); + $mw = new \Slim\Middleware\MethodOverride(); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + $env =& $app->environment(); + $this->assertEquals('GET', $env['REQUEST_METHOD']); + $this->assertFalse(isset($env['slim.method_override.original_method'])); + } + + /** + * Test does not override method if no method override parameter + */ + public function testDoesNotOverrideMethodAsPostWithoutParameter() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'REMOTE_ADDR' => '127.0.0.1', + 'SCRIPT_NAME' => '/foo/index.php', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + 'QUERY_STRING' => 'foo=bar', + 'SERVER_NAME' => 'slim', + 'SERVER_PORT' => 80, + 'slim.url_scheme' => 'http', + 'slim.input' => '', + 'slim.errors' => fopen('php://stderr', 'w') + )); + $app = new CustomAppMethod(); + $mw = new \Slim\Middleware\MethodOverride(); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + $env =& $app->environment(); + $this->assertEquals('POST', $env['REQUEST_METHOD']); + $this->assertFalse(isset($env['slim.method_override.original_method'])); + } + + /** + * Test overrides method with X-Http-Method-Override header + */ + public function testOverrideMethodAsHeader() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'CONTENT_TYPE' => 'application/json', + 'CONTENT_LENGTH' => 0, + 'slim.input' => '', + 'HTTP_X_HTTP_METHOD_OVERRIDE' => 'DELETE' + )); + $app = new CustomAppMethod(); + $mw = new \Slim\Middleware\MethodOverride(); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + $env =& $app->environment(); + $this->assertEquals('DELETE', $env['REQUEST_METHOD']); + $this->assertTrue(isset($env['slim.method_override.original_method'])); + $this->assertEquals('POST', $env['slim.method_override.original_method']); + } +} diff --git a/strillonews/vendor/slim/slim/tests/Middleware/PrettyExceptionsTest.php b/strillonews/vendor/slim/slim/tests/Middleware/PrettyExceptionsTest.php new file mode 100644 index 0000000..97c6956 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/Middleware/PrettyExceptionsTest.php @@ -0,0 +1,153 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class PrettyExceptionsTest extends PHPUnit_Framework_TestCase +{ + /** + * Test middleware returns successful response unchanged + */ + public function testReturnsUnchangedSuccessResponse() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/index.php', + 'PATH_INFO' => '/foo' + )); + $app = new \Slim\Slim(); + $app->get('/foo', function () { + echo "Success"; + }); + $mw = new \Slim\Middleware\PrettyExceptions(); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + $this->assertEquals(200, $app->response()->status()); + $this->assertEquals('Success', $app->response()->body()); + } + + /** + * Test middleware returns diagnostic screen for error response + */ + public function testReturnsDiagnosticsForErrorResponse() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/index.php', + 'PATH_INFO' => '/foo' + )); + $app = new \Slim\Slim(array( + 'log.enabled' => false + )); + $app->get('/foo', function () { + throw new \Exception('Test Message', 100); + }); + $mw = new \Slim\Middleware\PrettyExceptions(); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + $this->assertEquals(1, preg_match('@Slim Application Error@', $app->response()->body())); + $this->assertEquals(500, $app->response()->status()); + } + + /** + * Test middleware overrides response content type to html + */ + public function testResponseContentTypeIsOverriddenToHtml() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/index.php', + 'PATH_INFO' => '/foo' + )); + $app = new \Slim\Slim(array( + 'log.enabled' => false + )); + $app->get('/foo', function () use ($app) { + $app->contentType('application/json;charset=utf-8'); //<-- set content type to something else + throw new \Exception('Test Message', 100); + }); + $mw = new \Slim\Middleware\PrettyExceptions(); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + $response = $app->response(); + $this->assertEquals('text/html', $response['Content-Type']); + } + + /** + * Test exception type is in response body + */ + public function testExceptionTypeIsInResponseBody() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/index.php', + 'PATH_INFO' => '/foo' + )); + $app = new \Slim\Slim(array( + 'log.enabled' => false + )); + $app->get('/foo', function () use ($app) { + throw new \LogicException('Test Message', 100); + }); + $mw = new \Slim\Middleware\PrettyExceptions(); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + + $this->assertContains('LogicException', $app->response()->body()); + } + + /** + * Test with custom log + */ + public function testWithCustomLogWriter() + { + $this->setExpectedException('\LogicException'); + + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/index.php', + 'PATH_INFO' => '/foo' + )); + $app = new \Slim\Slim(array( + 'log.enabled' => false + )); + $app->container->singleton('log', function () use ($app) { + return new \Slim\Log(new \Slim\LogWriter('php://temp')); + }); + $app->get('/foo', function () use ($app) { + throw new \LogicException('Test Message', 100); + }); + $mw = new \Slim\Middleware\PrettyExceptions(); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + + $this->assertContains('LogicException', $app->response()->body()); + } +} diff --git a/strillonews/vendor/slim/slim/tests/Middleware/SessionCookieTest.php b/strillonews/vendor/slim/slim/tests/Middleware/SessionCookieTest.php new file mode 100644 index 0000000..e281f4f --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/Middleware/SessionCookieTest.php @@ -0,0 +1,469 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class SessionCookieTest extends PHPUnit_Framework_TestCase +{ + public function setUp() + { + $_SESSION = array(); + } + + /** + * Test session cookie is set and constructed correctly + * + * We test for two things: + * + * 1) That the HTTP cookie exists with the correct name; + * 2) That the HTTP cookie's value is the expected value; + */ + public function testSessionCookieIsCreated() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/index.php', + 'PATH_INFO' => '/foo' + )); + $app = new \Slim\Slim(); + $app->get('/foo', function () { + $_SESSION['foo'] = 'bar'; + echo "Success"; + }); + $mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years')); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + list($status, $header, $body) = $app->response()->finalize(); + $this->assertTrue($app->response->cookies->has('slim_session')); + $cookie = $app->response->cookies->get('slim_session'); + $this->assertEquals(serialize(array('foo' => 'bar')), $cookie['value']); + } + + /** + * Test $_SESSION is populated from an encrypted HTTP cookie + * + * The encrypted cookie contains the serialized array ['foo' => 'bar']. The + * global secret, cipher, and cipher mode are assumed to be the default + * values. + */ + public function testSessionIsPopulatedFromEncryptedCookie() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/index.php', + 'PATH_INFO' => '/foo', + 'HTTP_COOKIE' => 'slim_session=1644004961%7CLKkYPwqKIMvBK7MWl6D%2BxeuhLuMaW4quN%2F512ZAaVIY%3D%7Ce0f007fa852c7101e8224bb529e26be4d0dfbd63', + )); + $app = new \Slim\Slim(); + // The cookie value in the test is encrypted, so cookies.encrypt must + // be set to true + $app->config('cookies.encrypt', true); + $app->get('/foo', function () { + echo "Success"; + }); + $mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years')); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + $this->assertEquals(array('foo' => 'bar'), $_SESSION); + } + + /** + * Test $_SESSION is populated from an unencrypted HTTP cookie + * + * The unencrypted cookie contains the serialized array ['foo' => 'bar']. + * The global cookies.encrypt setting is set to false + */ + public function testSessionIsPopulatedFromUnencryptedCookie() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/index.php', + 'PATH_INFO' => '/foo', + 'HTTP_COOKIE' => 'slim_session=a%3A1%3A%7Bs%3A3%3A%22foo%22%3Bs%3A3%3A%22bar%22%3B%7D', + )); + $app = new \Slim\Slim(); + // The cookie value in the test is unencrypted, so cookies.encrypt must + // be set to false + $app->config('cookies.encrypt', false); + $app->get('/foo', function () { + echo "Success"; + }); + $mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years')); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + $this->assertEquals(array('foo' => 'bar'), $_SESSION); + } + + public function testUnserializeErrorsAreCaughtAndLogged() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/index.php', + 'PATH_INFO' => '/foo', + 'HTTP_COOKIE' => 'slim_session=1644004961%7CLKkYPwqKIMvBK7MWl6D%2BxeuhLuMaW4quN%2F512ZAaVIY%3D%7Ce0f007fa852c7101e8224bb529e26be4d0dfbd63', + )); + + $logWriter = $this->getMockBuilder('Slim\LogWriter') + ->disableOriginalConstructor() + ->getMock(); + + $logWriter->expects($this->once()) + ->method('write'); + $oldLevel = error_reporting(E_ALL); + + $app = new \Slim\Slim(array( + 'log.writer' => $logWriter + )); + // Unserializing an encrypted value fails if cookie not decrpyted + $app->config('cookies.encrypt', false); + $app->get('/foo', function () { + echo "Success"; + }); + $mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years')); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + $this->assertEquals(array(), $_SESSION); + + error_reporting($oldLevel); + } + + /** + * Test $_SESSION is populated as empty array if no HTTP cookie + */ + public function testSessionIsPopulatedAsEmptyIfNoCookie() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/index.php', + 'PATH_INFO' => '/foo' + )); + $app = new \Slim\Slim(); + $app->get('/foo', function () { + echo "Success"; + }); + $mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years')); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + $this->assertEquals(array(), $_SESSION); + } + + public function testSerializingTooLongValueWritesLogAndDoesntCreateCookie() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/index.php', + 'PATH_INFO' => '/foo' + )); + + $logWriter = $this->getMockBuilder('Slim\LogWriter') + ->disableOriginalConstructor() + ->getMock(); + + $logWriter->expects($this->once()) + ->method('write') + ->with('WARNING! Slim\Middleware\SessionCookie data size is larger than 4KB. Content save failed.', \Slim\Log::ERROR); + + $app = new \Slim\Slim(array( + 'log.writer' => $logWriter + )); + + $tooLongValue = $this->getTooLongValue(); + + $app->get('/foo', function () use ($tooLongValue) { + $_SESSION['test'] = $tooLongValue; + echo "Success"; + }); + + $mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years')); + $mw->setApplication($app); + $mw->setNextMiddleware($app); + $mw->call(); + list($status, $header, $body) = $app->response()->finalize(); + $this->assertFalse($app->response->cookies->has('slim_session')); + } + + /** + * Generated by http://www.random.org/strings/ + */ + protected function getTooLongValue() + { + return << + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class MyMiddleware extends \Slim\Middleware +{ + public function call() {} +} + +class MiddlewareTest extends PHPUnit_Framework_TestCase +{ + public function testSetApplication() + { + $app = new stdClass(); + $mw = new MyMiddleware(); + $mw->setApplication($app); + + $this->assertAttributeSame($app, 'app', $mw); + } + + public function testGetApplication() + { + $app = new stdClass(); + $mw = new MyMiddleware(); + $property = new \ReflectionProperty($mw, 'app'); + $property->setAccessible(true); + $property->setValue($mw, $app); + + $this->assertSame($app, $mw->getApplication()); + } + + public function testSetNextMiddleware() + { + $mw1 = new MyMiddleware(); + $mw2 = new MyMiddleware(); + $mw1->setNextMiddleware($mw2); + + $this->assertAttributeSame($mw2, 'next', $mw1); + } + + public function testGetNextMiddleware() + { + $mw1 = new MyMiddleware(); + $mw2 = new MyMiddleware(); + $property = new \ReflectionProperty($mw1, 'next'); + $property->setAccessible(true); + $property->setValue($mw1, $mw2); + + $this->assertSame($mw2, $mw1->getNextMiddleware()); + } +} diff --git a/strillonews/vendor/slim/slim/tests/README b/strillonews/vendor/slim/slim/tests/README new file mode 100644 index 0000000..7bc611c --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/README @@ -0,0 +1,18 @@ +Slim Framework Unit Tests + +Follow the directions below to run the Slim Framework unit tests. You'll need the latest version of PHPUnit. To save development time, these unit tests require PHP >= 5.3. However, the Slim Framework itself requires only PHP >= 5.2. + +1. Install the latest version of PHPUnit +Visit http://www.phpunit.de/ for installation instructions. + +2. Run PHPUnit +From the filesystem directory that contains the `tests` directory, you may run all unit tests or specific unit tests. Here are several examples. The '$>' in the examples below is your command prompt. + +To run all tests: +$> phpunit tests + +To run all HTTP-related tests: +$> phpunit tests/Http + +To run only the HTTP Request tests: +$> phpunit tests/Http/RequestTest \ No newline at end of file diff --git a/strillonews/vendor/slim/slim/tests/RouteTest.php b/strillonews/vendor/slim/slim/tests/RouteTest.php new file mode 100644 index 0000000..5d0ee7a --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/RouteTest.php @@ -0,0 +1,535 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +class RouteTest extends PHPUnit_Framework_TestCase +{ + public function testGetPattern() + { + $route = new \Slim\Route('/foo', function () {}); + + $this->assertEquals('/foo', $route->getPattern()); + } + + public function testGetName() + { + $route = new \Slim\Route('/foo', function () {}); + + $property = new \ReflectionProperty($route, 'name'); + $property->setAccessible(true); + $property->setValue($route, 'foo'); + + $this->assertEquals('foo', $route->getName()); + } + + public function testSetName() + { + $route = new \Slim\Route('/foo', function () {}); + $route->name('foo'); // <-- Alias for `setName()` + + $this->assertAttributeEquals('foo', 'name', $route); + } + + public function testGetCallable() + { + $callable = function () { + echo 'Foo'; + }; + $route = new \Slim\Route('/foo', $callable); + + $this->assertSame($callable, $route->getCallable()); + } + + public function testGetCallableAsClass() + { + $route = new \Slim\Route('/foo', '\Slim\Router:getCurrentRoute'); + + $callable = $route->getCallable(); + $this->assertInstanceOf('\Slim\Router', $callable[0]); + $this->assertEquals('getCurrentRoute', $callable[1]); + } + + public function testGetCallableAsStaticMethod() + { + $route = new \Slim\Route('/bar', '\Slim\Slim::getInstance'); + + $callable = $route->getCallable(); + $this->assertEquals('\Slim\Slim::getInstance', $callable); + } + + public function testSetCallable() + { + $callable = function () { + echo 'Foo'; + }; + $route = new \Slim\Route('/foo', $callable); // <-- Called inside __construct() + + $this->assertAttributeSame($callable, 'callable', $route); + } + + public function testSetCallableWithInvalidArgument() + { + $this->setExpectedException('\InvalidArgumentException'); + $route = new \Slim\Route('/foo', 'doesNotExist'); // <-- Called inside __construct() + } + + public function testGetParams() + { + $route = new \Slim\Route('/hello/:first/:last', function () {}); + $route->matches('/hello/mr/anderson'); // <-- Parses params from argument + + $this->assertEquals(array( + 'first' => 'mr', + 'last' => 'anderson' + ), $route->getParams()); + } + + public function testSetParams() + { + $route = new \Slim\Route('/hello/:first/:last', function () {}); + $route->matches('/hello/mr/anderson'); // <-- Parses params from argument + $route->setParams(array( + 'first' => 'agent', + 'last' => 'smith' + )); + + $this->assertAttributeEquals(array( + 'first' => 'agent', + 'last' => 'smith' + ), 'params', $route); + } + + public function testGetParam() + { + $route = new \Slim\Route('/hello/:first/:last', function () {}); + + $property = new \ReflectionProperty($route, 'params'); + $property->setAccessible(true); + $property->setValue($route, array( + 'first' => 'foo', + 'last' => 'bar' + )); + + $this->assertEquals('foo', $route->getParam('first')); + } + + public function testGetParamThatDoesNotExist() + { + $this->setExpectedException('InvalidArgumentException'); + + $route = new \Slim\Route('/hello/:first/:last', function () {}); + + $property = new \ReflectionProperty($route, 'params'); + $property->setAccessible(true); + $property->setValue($route, array( + 'first' => 'foo', + 'last' => 'bar' + )); + + $route->getParam('middle'); + } + + public function testSetParam() + { + $route = new \Slim\Route('/hello/:first/:last', function () {}); + $route->matches('/hello/mr/anderson'); // <-- Parses params from argument + $route->setParam('last', 'smith'); + + $this->assertAttributeEquals(array( + 'first' => 'mr', + 'last' => 'smith' + ), 'params', $route); + } + + public function testSetParamThatDoesNotExist() + { + $this->setExpectedException('InvalidArgumentException'); + + $route = new \Slim\Route('/hello/:first/:last', function () {}); + $route->matches('/hello/mr/anderson'); // <-- Parses params from argument + $route->setParam('middle', 'smith'); // <-- Should trigger InvalidArgumentException + } + + public function testMatches() + { + $route = new \Slim\Route('/hello/:name', function () {}); + + $this->assertTrue($route->matches('/hello/josh')); + } + + public function testMatchesIsFalse() + { + $route = new \Slim\Route('/foo', function () {}); + + $this->assertFalse($route->matches('/bar')); + } + + public function testMatchesPatternWithTrailingSlash() + { + $route = new \Slim\Route('/foo/', function () {}); + + $this->assertTrue($route->matches('/foo/')); + $this->assertTrue($route->matches('/foo')); + } + + public function testMatchesPatternWithoutTrailingSlash() + { + $route = new \Slim\Route('/foo', function () {}); + + $this->assertFalse($route->matches('/foo/')); + $this->assertTrue($route->matches('/foo')); + } + + public function testMatchesWithConditions() + { + $route = new \Slim\Route('/hello/:first/and/:second', function () {}); + $route->conditions(array( + 'first' => '[a-zA-Z]{3,}' + )); + + $this->assertTrue($route->matches('/hello/Josh/and/John')); + } + + public function testMatchesWithConditionsIsFalse() + { + $route = new \Slim\Route('/hello/:first/and/:second', function () {}); + $route->conditions(array( + 'first' => '[a-z]{3,}' + )); + + $this->assertFalse($route->matches('/hello/Josh/and/John')); + } + + /* + * Route should match URI with valid path component according to rfc2396 + * + * "Uniform Resource Identifiers (URI): Generic Syntax" http://www.ietf.org/rfc/rfc2396.txt + * + * Excludes "+" which is valid but decodes into a space character + */ + public function testMatchesWithValidRfc2396PathComponent() + { + $symbols = ':@&=$,'; + $route = new \Slim\Route('/rfc2386/:symbols', function () {}); + + $this->assertTrue($route->matches('/rfc2386/' . $symbols)); + } + + /* + * Route should match URI including unreserved punctuation marks from rfc2396 + * + * "Uniform Resource Identifiers (URI): Generic Syntax" http://www.ietf.org/rfc/rfc2396.txt + */ + public function testMatchesWithUnreservedMarks() + { + $marks = "-_.!~*'()"; + $route = new \Slim\Route('/marks/:marks', function () {}); + + $this->assertTrue($route->matches('/marks/' . $marks)); + } + + public function testMatchesOptionalParameters() + { + $pattern = '/archive/:year(/:month(/:day))'; + + $route1 = new \Slim\Route($pattern, function () {}); + $this->assertTrue($route1->matches('/archive/2010')); + $this->assertEquals(array('year' => '2010'), $route1->getParams()); + + $route2 = new \Slim\Route($pattern, function () {}); + $this->assertTrue($route2->matches('/archive/2010/05')); + $this->assertEquals(array('year' => '2010', 'month' => '05'), $route2->getParams()); + + $route3 = new \Slim\Route($pattern, function () {}); + $this->assertTrue($route3->matches('/archive/2010/05/13')); + $this->assertEquals(array('year' => '2010', 'month' => '05', 'day' => '13'), $route3->getParams()); + } + + public function testGetConditions() + { + $route = new \Slim\Route('/foo', function () {}); + + $property = new \ReflectionProperty($route, 'conditions'); + $property->setAccessible(true); + $property->setValue($route, array('foo' => '\d{3}')); + + $this->assertEquals(array('foo' => '\d{3}'), $route->getConditions()); + } + + public function testSetDefaultConditions() + { + \Slim\Route::setDefaultConditions(array( + 'id' => '\d+' + )); + + $property = new \ReflectionProperty('\Slim\Route', 'defaultConditions'); + $property->setAccessible(true); + + $this->assertEquals(array( + 'id' => '\d+' + ), $property->getValue()); + } + + public function testGetDefaultConditions() + { + $property = new \ReflectionProperty('\Slim\Route', 'defaultConditions'); + $property->setAccessible(true); + $property->setValue(array( + 'id' => '\d+' + )); + + $this->assertEquals(array( + 'id' => '\d+' + ), \Slim\Route::getDefaultConditions()); + } + + public function testDefaultConditionsAssignedToInstance() + { + $staticProperty = new \ReflectionProperty('\Slim\Route', 'defaultConditions'); + $staticProperty->setAccessible(true); + $staticProperty->setValue(array( + 'id' => '\d+' + )); + $route = new \Slim\Route('/foo', function () {}); + + $this->assertAttributeEquals(array( + 'id' => '\d+' + ), 'conditions', $route); + } + + public function testMatchesWildcard() + { + $route = new \Slim\Route('/hello/:path+/world', function () {}); + + $this->assertTrue($route->matches('/hello/foo/bar/world')); + $this->assertAttributeEquals(array( + 'path' => array('foo', 'bar') + ), 'params', $route); + } + + public function testMatchesMultipleWildcards() + { + $route = new \Slim\Route('/hello/:path+/world/:date+', function () {}); + + $this->assertTrue($route->matches('/hello/foo/bar/world/2012/03/10')); + $this->assertAttributeEquals(array( + 'path' => array('foo', 'bar'), + 'date' => array('2012', '03', '10') + ), 'params', $route); + } + + public function testMatchesParamsAndWildcards() + { + $route = new \Slim\Route('/hello/:path+/world/:year/:month/:day/:path2+', function () {}); + + $this->assertTrue($route->matches('/hello/foo/bar/world/2012/03/10/first/second')); + $this->assertAttributeEquals(array( + 'path' => array('foo', 'bar'), + 'year' => '2012', + 'month' => '03', + 'day' => '10', + 'path2' => array('first', 'second') + ), 'params', $route); + } + + public function testMatchesParamsWithOptionalWildcard() + { + $route = new \Slim\Route('/hello(/:foo(/:bar+))', function () {}); + + $this->assertTrue($route->matches('/hello')); + $this->assertTrue($route->matches('/hello/world')); + $this->assertTrue($route->matches('/hello/world/foo')); + $this->assertTrue($route->matches('/hello/world/foo/bar')); + } + + public function testSetMiddleware() + { + $route = new \Slim\Route('/foo', function () {}); + $mw = function () { + echo 'Foo'; + }; + $route->setMiddleware($mw); + + $this->assertAttributeContains($mw, 'middleware', $route); + } + + public function testSetMiddlewareMultipleTimes() + { + $route = new \Slim\Route('/foo', function () {}); + $mw1 = function () { + echo 'Foo'; + }; + $mw2 = function () { + echo 'Bar'; + }; + $route->setMiddleware($mw1); + $route->setMiddleware($mw2); + + $this->assertAttributeContains($mw1, 'middleware', $route); + $this->assertAttributeContains($mw2, 'middleware', $route); + } + + public function testSetMiddlewareWithArray() + { + $route = new \Slim\Route('/foo', function () {}); + $mw1 = function () { + echo 'Foo'; + }; + $mw2 = function () { + echo 'Bar'; + }; + $route->setMiddleware(array($mw1, $mw2)); + + $this->assertAttributeContains($mw1, 'middleware', $route); + $this->assertAttributeContains($mw2, 'middleware', $route); + } + + public function testSetMiddlewareWithInvalidArgument() + { + $this->setExpectedException('InvalidArgumentException'); + + $route = new \Slim\Route('/foo', function () {}); + $route->setMiddleware('doesNotExist'); // <-- Should throw InvalidArgumentException + } + + public function testSetMiddlewareWithArrayWithInvalidArgument() + { + $this->setExpectedException('InvalidArgumentException'); + + $route = new \Slim\Route('/foo', function () {}); + $route->setMiddleware(array('doesNotExist')); + } + + public function testGetMiddleware() + { + $route = new \Slim\Route('/foo', function () {}); + + $property = new \ReflectionProperty($route, 'middleware'); + $property->setAccessible(true); + $property->setValue($route, array('foo' => 'bar')); + + $this->assertEquals(array('foo' => 'bar'), $route->getMiddleware()); + } + + public function testSetHttpMethods() + { + $route = new \Slim\Route('/foo', function () {}); + $route->setHttpMethods('GET', 'POST'); + + $this->assertAttributeEquals(array('GET', 'POST'), 'methods', $route); + } + + public function testGetHttpMethods() + { + $route = new \Slim\Route('/foo', function () {}); + + $property = new \ReflectionProperty($route, 'methods'); + $property->setAccessible(true); + $property->setValue($route, array('GET', 'POST')); + + $this->assertEquals(array('GET', 'POST'), $route->getHttpMethods()); + } + + public function testAppendHttpMethods() + { + $route = new \Slim\Route('/foo', function () {}); + + $property = new \ReflectionProperty($route, 'methods'); + $property->setAccessible(true); + $property->setValue($route, array('GET', 'POST')); + + $route->appendHttpMethods('PUT'); + + $this->assertAttributeEquals(array('GET', 'POST', 'PUT'), 'methods', $route); + } + + public function testAppendHttpMethodsWithVia() + { + $route = new \Slim\Route('/foo', function () {}); + $route->via('PUT'); + + $this->assertAttributeContains('PUT', 'methods', $route); + } + + public function testSupportsHttpMethod() + { + $route = new \Slim\Route('/foo', function () {}); + + $property = new \ReflectionProperty($route, 'methods'); + $property->setAccessible(true); + $property->setValue($route, array('POST')); + + $this->assertTrue($route->supportsHttpMethod('POST')); + $this->assertFalse($route->supportsHttpMethod('PUT')); + } + + /** + * Test dispatch with params + */ + public function testDispatch() + { + $this->expectOutputString('Hello josh'); + $route = new \Slim\Route('/hello/:name', function ($name) { echo "Hello $name"; }); + $route->matches('/hello/josh'); //<-- Extracts params from resource URI + $route->dispatch(); + } + + /** + * Test dispatch with middleware + */ + public function testDispatchWithMiddleware() + { + $this->expectOutputString('First! Second! Hello josh'); + $route = new \Slim\Route('/hello/:name', function ($name) { echo "Hello $name"; }); + $route->setMiddleware(function () { + echo "First! "; + }); + $route->setMiddleware(function () { + echo "Second! "; + }); + $route->matches('/hello/josh'); //<-- Extracts params from resource URI + $route->dispatch(); + } + + /** + * Test middleware with arguments + */ + public function testRouteMiddlwareArguments() + { + $this->expectOutputString('foobar'); + $route = new \Slim\Route('/foo', function () { echo "bar"; }); + $route->setName('foo'); + $route->setMiddleware(function ($route) { + echo $route->getName(); + }); + $route->matches('/foo'); //<-- Extracts params from resource URI + $route->dispatch(); + } +} diff --git a/strillonews/vendor/slim/slim/tests/RouterTest.php b/strillonews/vendor/slim/slim/tests/RouterTest.php new file mode 100644 index 0000000..a128b23 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/RouterTest.php @@ -0,0 +1,250 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class RouterTest extends PHPUnit_Framework_TestCase +{ + /** + * Constructor should initialize routes as empty array + */ + public function testConstruct() + { + $router = new \Slim\Router(); + + $this->assertAttributeEquals(array(), 'routes', $router); + } + + /** + * Map should set and return instance of \Slim\Route + */ + public function testMap() + { + $router = new \Slim\Router(); + $route = new \Slim\Route('/foo', function() {}); + $router->map($route); + + $this->assertAttributeContains($route, 'routes', $router); + } + + /** + * Named route should be added and indexed by name + */ + public function testAddNamedRoute() + { + $router = new \Slim\Router(); + $route = new \Slim\Route('/foo', function () {}); + $router->addNamedRoute('foo', $route); + + $property = new \ReflectionProperty($router, 'namedRoutes'); + $property->setAccessible(true); + + $rV = $property->getValue($router); + $this->assertSame($route, $rV['foo']); + } + + /** + * Named route should have unique name + */ + public function testAddNamedRouteWithDuplicateKey() + { + $this->setExpectedException('RuntimeException'); + + $router = new \Slim\Router(); + $route = new \Slim\Route('/foo', function () {}); + $router->addNamedRoute('foo', $route); + $router->addNamedRoute('foo', $route); + } + + /** + * Router should return named route by name, or null if not found + */ + public function testGetNamedRoute() + { + $router = new \Slim\Router(); + $route = new \Slim\Route('/foo', function () {}); + + $property = new \ReflectionProperty($router, 'namedRoutes'); + $property->setAccessible(true); + $property->setValue($router, array('foo' => $route)); + + $this->assertSame($route, $router->getNamedRoute('foo')); + $this->assertNull($router->getNamedRoute('bar')); + } + + /** + * Router should determine named routes and cache results + */ + public function testGetNamedRoutes() + { + $router = new \Slim\Router(); + $route1 = new \Slim\Route('/foo', function () {}); + $route2 = new \Slim\Route('/bar', function () {}); + + // Init router routes to array + $propertyRouterRoutes = new \ReflectionProperty($router, 'routes'); + $propertyRouterRoutes->setAccessible(true); + $propertyRouterRoutes->setValue($router, array($route1, $route2)); + + // Init router named routes to null + $propertyRouterNamedRoutes = new \ReflectionProperty($router, 'namedRoutes'); + $propertyRouterNamedRoutes->setAccessible(true); + $propertyRouterNamedRoutes->setValue($router, null); + + // Init route name + $propertyRouteName = new \ReflectionProperty($route2, 'name'); + $propertyRouteName->setAccessible(true); + $propertyRouteName->setValue($route2, 'bar'); + + $namedRoutes = $router->getNamedRoutes(); + $this->assertCount(1, $namedRoutes); + $this->assertSame($route2, $namedRoutes['bar']); + } + + /** + * Router should detect presence of a named route by name + */ + public function testHasNamedRoute() + { + $router = new \Slim\Router(); + $route = new \Slim\Route('/foo', function () {}); + + $property = new \ReflectionProperty($router, 'namedRoutes'); + $property->setAccessible(true); + $property->setValue($router, array('foo' => $route)); + + $this->assertTrue($router->hasNamedRoute('foo')); + $this->assertFalse($router->hasNamedRoute('bar')); + } + + /** + * Router should return current route if set during iteration + */ + public function testGetCurrentRoute() + { + $router = new \Slim\Router(); + $route = new \Slim\Route('/foo', function () {}); + + $property = new \ReflectionProperty($router, 'currentRoute'); + $property->setAccessible(true); + $property->setValue($router, $route); + + $this->assertSame($route, $router->getCurrentRoute()); + } + + /** + * Router should return first matching route if current route not set yet by iteration + */ + public function testGetCurrentRouteIfMatchedRoutes() + { + $router = new \Slim\Router(); + $route = new \Slim\Route('/foo', function () {}); + + $propertyMatchedRoutes = new \ReflectionProperty($router, 'matchedRoutes'); + $propertyMatchedRoutes->setAccessible(true); + $propertyMatchedRoutes->setValue($router, array($route)); + + $propertyCurrentRoute = new \ReflectionProperty($router, 'currentRoute'); + $propertyCurrentRoute->setAccessible(true); + $propertyCurrentRoute->setValue($router, null); + + $this->assertSame($route, $router->getCurrentRoute()); + } + + /** + * Router should return `null` if current route not set yet and there are no matching routes + */ + public function testGetCurrentRouteIfNoMatchedRoutes() + { + $router = new \Slim\Router(); + + $propertyMatchedRoutes = new \ReflectionProperty($router, 'matchedRoutes'); + $propertyMatchedRoutes->setAccessible(true); + $propertyMatchedRoutes->setValue($router, array()); + + $propertyCurrentRoute = new \ReflectionProperty($router, 'currentRoute'); + $propertyCurrentRoute->setAccessible(true); + $propertyCurrentRoute->setValue($router, null); + + $this->assertNull($router->getCurrentRoute()); + } + + public function testGetMatchedRoutes() + { + $router = new \Slim\Router(); + + $route1 = new \Slim\Route('/foo', function () {}); + $route1 = $route1->via('GET'); + + $route2 = new \Slim\Route('/foo', function () {}); + $route2 = $route2->via('POST'); + + $route3 = new \Slim\Route('/bar', function () {}); + $route3 = $route3->via('PUT'); + + $routes = new \ReflectionProperty($router, 'routes'); + $routes->setAccessible(true); + $routes->setValue($router, array($route1, $route2, $route3)); + + $matchedRoutes = $router->getMatchedRoutes('GET', '/foo'); + $this->assertSame($route1, $matchedRoutes[0]); + } + + // Test url for named route + + public function testUrlFor() + { + $router = new \Slim\Router(); + + $route1 = new \Slim\Route('/hello/:first/:last', function () {}); + $route1 = $route1->via('GET')->name('hello'); + + $route2 = new \Slim\Route('/path/(:foo\.:bar)', function () {}); + $route2 = $route2->via('GET')->name('regexRoute'); + + $routes = new \ReflectionProperty($router, 'namedRoutes'); + $routes->setAccessible(true); + $routes->setValue($router, array( + 'hello' => $route1, + 'regexRoute' => $route2 + )); + + $this->assertEquals('/hello/Josh/Lockhart', $router->urlFor('hello', array('first' => 'Josh', 'last' => 'Lockhart'))); + $this->assertEquals('/path/Hello.Josh', $router->urlFor('regexRoute', array('foo' => 'Hello', 'bar' => 'Josh'))); + } + + public function testUrlForIfNoSuchRoute() + { + $this->setExpectedException('RuntimeException'); + + $router = new \Slim\Router(); + $router->urlFor('foo', array('abc' => '123')); + } +} diff --git a/strillonews/vendor/slim/slim/tests/SlimTest.php b/strillonews/vendor/slim/slim/tests/SlimTest.php new file mode 100644 index 0000000..3a0deb1 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/SlimTest.php @@ -0,0 +1,1538 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +//Mock custom view +class CustomView extends \Slim\View +{ + public function render($template, $data = null) { echo "Custom view"; } +} + +//Echo Logger +class EchoErrorLogger +{ + public function error($object) { echo get_class($object) .':'.$object->getMessage(); } +} + +//Mock extending class +class Derived extends \Slim\Slim +{ + public static function getDefaultSettings() + { + return array_merge( + array("late-static-binding" => true) + , parent::getDefaultSettings()); + } +} + +//Mock middleware +class CustomMiddleware extends \Slim\Middleware +{ + public function call() + { + $env = $this->app->environment(); + $res = $this->app->response(); + $env['slim.test'] = 'Hello'; + $this->next->call(); + $res->header('X-Slim-Test', 'Hello'); + $res->write('Hello'); + } +} + +class SlimTest extends PHPUnit_Framework_TestCase +{ + public function setUp() + { + //Remove environment mode if set + unset($_ENV['SLIM_MODE']); + + //Reset session + $_SESSION = array(); + + //Prepare default environment variables + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + 'QUERY_STRING' => 'one=foo&two=bar', + 'SERVER_NAME' => 'slimframework.com', + )); + } + + /************************************************ + * INSTANTIATION + ************************************************/ + + /** + * Test version constant is string + */ + public function testHasVersionConstant() + { + $this->assertTrue(is_string(\Slim\Slim::VERSION)); + } + + /** + * Test default instance properties + */ + public function testDefaultInstanceProperties() + { + $s = new \Slim\Slim(); + $this->assertInstanceOf('\Slim\Http\Request', $s->request()); + $this->assertInstanceOf('\Slim\Http\Response', $s->response()); + $this->assertInstanceOf('\Slim\Router', $s->router()); + $this->assertInstanceOf('\Slim\View', $s->view()); + $this->assertInstanceOf('\Slim\Log', $s->getLog()); + $this->assertEquals(\Slim\Log::DEBUG, $s->getLog()->getLevel()); + $this->assertTrue($s->getLog()->getEnabled()); + $this->assertInstanceOf('\Slim\Environment', $s->environment()); + } + + /** + * Test get default instance + */ + public function testGetDefaultInstance() + { + $s = new \Slim\Slim(); + $s->setName('default'); //We must do this manually since a default app is already set in prev tests + $this->assertEquals('default', $s->getName()); + $this->assertInstanceOf('\Slim\Slim', \Slim\Slim::getInstance()); + $this->assertSame($s, \Slim\Slim::getInstance()); + } + + /** + * Test get named instance + */ + public function testGetNamedInstance() + { + $s = new \Slim\Slim(); + $s->setName('foo'); + $this->assertSame($s, \Slim\Slim::getInstance('foo')); + } + + /** + * Test Slim autoloader ignores non-Slim classes + * + * Pre-conditions: + * Instantiate a non-Slim class; + * + * Post-conditions: + * Slim autoloader returns without requiring a class file; + */ + public function testSlimAutoloaderIgnoresNonSlimClass() + { + $foo = new Foo(); + } + + /************************************************ + * SETTINGS + ************************************************/ + + /** + * Test get setting that exists + */ + public function testGetSettingThatExists() + { + $s = new \Slim\Slim(); + $this->assertEquals('./templates', $s->config('templates.path')); + } + + /** + * Test get setting that does not exist + */ + public function testGetSettingThatDoesNotExist() + { + $s = new \Slim\Slim(); + $this->assertNull($s->config('foo')); + } + + /** + * Test set setting + */ + public function testSetSetting() + { + $s = new \Slim\Slim(); + $this->assertEquals('./templates', $s->config('templates.path')); + $s->config('templates.path', './tmpl'); + $this->assertEquals('./tmpl', $s->config('templates.path')); + } + + /** + * Test batch set settings + */ + public function testBatchSetSettings() + { + $s = new \Slim\Slim(); + $this->assertEquals('./templates', $s->config('templates.path')); + $this->assertTrue($s->config('debug')); + $s->config(array( + 'templates.path' => './tmpl', + 'debug' => false + )); + $this->assertEquals('./tmpl', $s->config('templates.path')); + $this->assertFalse($s->config('debug')); + } + + /************************************************ + * MODES + ************************************************/ + + /** + * Test default mode + */ + public function testGetDefaultMode() + { + $s = new \Slim\Slim(); + $this->assertEquals('development', $s->getMode()); + } + + /** + * Test custom mode from environment + */ + public function testGetModeFromEnvironment() + { + $_ENV['SLIM_MODE'] = 'production'; + $s = new \Slim\Slim(); + $this->assertEquals('production', $s->getMode()); + } + + /** + * Test custom mode from app settings + */ + public function testGetModeFromSettings() + { + $s = new \Slim\Slim(array( + 'mode' => 'test' + )); + $this->assertEquals('test', $s->getMode()); + } + + /** + * Test mode configuration + */ + public function testModeConfiguration() + { + $flag = 0; + $configureTest = function () use (&$flag) { + $flag = 'test'; + }; + $configureProduction = function () use (&$flag) { + $flag = 'production'; + }; + $s = new \Slim\Slim(array('mode' => 'test')); + $s->configureMode('test', $configureTest); + $s->configureMode('production', $configureProduction); + $this->assertEquals('test', $flag); + } + + /** + * Test mode configuration when mode does not match + */ + public function testModeConfigurationWhenModeDoesNotMatch() + { + $flag = 0; + $configureTest = function () use (&$flag) { + $flag = 'test'; + }; + $s = new \Slim\Slim(array('mode' => 'production')); + $s->configureMode('test', $configureTest); + $this->assertEquals(0, $flag); + } + + /** + * Test mode configuration when not callable + */ + public function testModeConfigurationWhenNotCallable() + { + $flag = 0; + $s = new \Slim\Slim(array('mode' => 'production')); + $s->configureMode('production', 'foo'); + $this->assertEquals(0, $flag); + } + + /** + * Test custom mode from getenv() + */ + public function testGetModeFromGetEnv() + { + putenv('SLIM_MODE=production'); + $s = new \Slim\Slim(); + $this->assertEquals('production', $s->getMode()); + } + + /************************************************ + * ROUTING + ************************************************/ + + /** + * Test GENERIC route + */ + public function testGenericRoute() + { + $s = new \Slim\Slim(); + $callable = function () { echo "foo"; }; + $route = $s->map('/bar', $callable); + $this->assertInstanceOf('\Slim\Route', $route); + $this->assertEmpty($route->getHttpMethods()); + } + + /** + * Test GET routes also get mapped as a HEAD route + */ + public function testGetRouteIsAlsoMappedAsHead() + { + $s = new \Slim\Slim(); + $route = $s->get('/foo', function () {}); + $this->assertTrue($route->supportsHttpMethod(\Slim\Http\Request::METHOD_GET)); + $this->assertTrue($route->supportsHttpMethod(\Slim\Http\Request::METHOD_HEAD)); + } + + /** + * Test GET route + */ + public function testGetRoute() + { + $s = new \Slim\Slim(); + $mw1 = function () { echo "foo"; }; + $mw2 = function () { echo "bar"; }; + $callable = function () { echo "xyz"; }; + $route = $s->get('/bar', $mw1, $mw2, $callable); + $s->call(); + $this->assertEquals('foobarxyz', $s->response()->body()); + $this->assertEquals('/bar', $route->getPattern()); + $this->assertSame($callable, $route->getCallable()); + } + + /** + * Test POST route + */ + public function testPostRoute() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'POST', + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + )); + $s = new \Slim\Slim(); + $mw1 = function () { echo "foo"; }; + $mw2 = function () { echo "bar"; }; + $callable = function () { echo "xyz"; }; + $route = $s->post('/bar', $mw1, $mw2, $callable); + $s->call(); + $this->assertEquals('foobarxyz', $s->response()->body()); + $this->assertEquals('/bar', $route->getPattern()); + $this->assertSame($callable, $route->getCallable()); + } + + /** + * Test PUT route + */ + public function testPutRoute() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'PUT', + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + )); + $s = new \Slim\Slim(); + $mw1 = function () { echo "foo"; }; + $mw2 = function () { echo "bar"; }; + $callable = function () { echo "xyz"; }; + $route = $s->put('/bar', $mw1, $mw2, $callable); + $s->call(); + $this->assertEquals('foobarxyz', $s->response()->body()); + $this->assertEquals('/bar', $route->getPattern()); + $this->assertSame($callable, $route->getCallable()); + } + + /** + * Test PATCH route + */ + public function testPatchRoute() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'PATCH', + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + )); + $s = new \Slim\Slim(); + $mw1 = function () { echo "foo"; }; + $mw2 = function () { echo "bar"; }; + $callable = function () { echo "xyz"; }; + $route = $s->patch('/bar', $mw1, $mw2, $callable); + $s->call(); + $this->assertEquals('foobarxyz', $s->response()->body()); + $this->assertEquals('/bar', $route->getPattern()); + $this->assertSame($callable, $route->getCallable()); + } + + /** + * Test DELETE route + */ + public function testDeleteRoute() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'DELETE', + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + )); + $s = new \Slim\Slim(); + $mw1 = function () { echo "foo"; }; + $mw2 = function () { echo "bar"; }; + $callable = function () { echo "xyz"; }; + $route = $s->delete('/bar', $mw1, $mw2, $callable); + $s->call(); + $this->assertEquals('foobarxyz', $s->response()->body()); + $this->assertEquals('/bar', $route->getPattern()); + $this->assertSame($callable, $route->getCallable()); + } + + /** + * Test OPTIONS route + */ + public function testOptionsRoute() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'OPTIONS', + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + )); + $s = new \Slim\Slim(); + $mw1 = function () { echo "foo"; }; + $mw2 = function () { echo "bar"; }; + $callable = function () { echo "xyz"; }; + $route = $s->options('/bar', $mw1, $mw2, $callable); + $s->call(); + $this->assertEquals('foobarxyz', $s->response()->body()); + $this->assertEquals('/bar', $route->getPattern()); + $this->assertSame($callable, $route->getCallable()); + } + + /** + * Test route groups + */ + public function testRouteGroups() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'GET', + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar/baz', //<-- Virtual' + )); + $s = new \Slim\Slim(); + $mw1 = function () { echo "foo"; }; + $mw2 = function () { echo "bar"; }; + $callable = function () { echo "xyz"; }; + $s->group('/bar', $mw1, function () use ($s, $mw2, $callable) { + $s->get('/baz', $mw2, $callable); + }); + $s->call(); + $this->assertEquals('foobarxyz', $s->response()->body()); + } + + /* + * Test ANY route + */ + public function testAnyRoute() + { + $mw1 = function () { echo "foo"; }; + $mw2 = function () { echo "bar"; }; + $callable = function () { echo "xyz"; }; + $methods = array('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'); + foreach ($methods as $i => $method) { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => $method, + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + )); + $s = new \Slim\Slim(); + $route = $s->any('/bar', $mw1, $mw2, $callable); + $s->call(); + $this->assertEquals('foobarxyz', $s->response()->body()); + $this->assertEquals('/bar', $route->getPattern()); + $this->assertSame($callable, $route->getCallable()); + } + } + + /** + * Test if route does NOT expect trailing slash and URL has one + */ + public function testRouteWithoutSlashAndUrlWithOne() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar/', //<-- Virtual + )); + $s = new \Slim\Slim(); + $s->get('/bar', function () { echo "xyz"; }); + $s->call(); + $this->assertEquals(404, $s->response()->status()); + } + + /** + * Test if route contains URL encoded characters + */ + public function testRouteWithUrlEncodedCharacters() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar/jo%20hn/smi%20th', //<-- Virtual + )); + $s = new \Slim\Slim(); + $s->get('/bar/:one/:two', function ($one, $two) { echo $one . $two; }); + $s->call(); + $this->assertEquals('jo hnsmi th', $s->response()->body()); + } + + /************************************************ + * VIEW + ************************************************/ + + /** + * Test set view with string class name + */ + public function testSetSlimViewFromString() + { + $s = new \Slim\Slim(); + $this->assertInstanceOf('\Slim\View', $s->view()); + $s->view('CustomView'); + $this->assertInstanceOf('CustomView', $s->view()); + } + + /** + * Test set view with object instance + */ + public function testSetSlimViewFromInstance() + { + $s = new \Slim\Slim(); + $this->assertInstanceOf('\Slim\View', $s->view()); + $s->view(new CustomView()); + $this->assertInstanceOf('CustomView', $s->view()); + } + + /** + * Test view data is transferred to newer view + */ + public function testViewDataTransfer() + { + $data = array('foo' => 'bar'); + $s = new \Slim\Slim(); + $s->view()->setData($data); + $s->view('CustomView'); + $this->assertSame($data, $s->view()->getData()); + } + + /************************************************ + * RENDERING + ************************************************/ + + /** + * Test template path is passed to view + */ + public function testViewGetsTemplatesPath() + { + $path = dirname(__FILE__) . '/templates'; + $s = new \Slim\Slim(array('templates.path' => $path)); + $this->assertEquals($s->view->getTemplatesDirectory(), $path); + } + + /** + * Test render with template and data + */ + public function testRenderTemplateWithData() + { + $s = new \Slim\Slim(array('templates.path' => dirname(__FILE__) . '/templates')); + $s->get('/bar', function () use ($s) { + $s->render('test.php', array('foo' => 'bar')); + }); + $s->call(); + list($status, $header, $body) = $s->response()->finalize(); + $this->assertEquals(200, $status); + $this->assertEquals('test output bar', $body); + } + + /** + * Test render with template and data and status + */ + public function testRenderTemplateWithDataAndStatus() + { + $s = new \Slim\Slim(array('templates.path' => dirname(__FILE__) . '/templates')); + $s->get('/bar', function () use ($s) { + $s->render('test.php', array('foo' => 'bar'), 500); + }); + $s->call(); + list($status, $header, $body) = $s->response()->finalize(); + $this->assertEquals(500, $status); + $this->assertEquals('test output bar', $body); + } + + /************************************************ + * LOG + ************************************************/ + + /** + * Test get log + * + * This asserts that a Slim app has a default Log + * upon instantiation. The Log itself is tested + * separately in another file. + */ + public function testGetLog() + { + $s = new \Slim\Slim(); + $this->assertInstanceOf('\Slim\Log', $s->getLog()); + } + + /************************************************ + * HTTP CACHING + ************************************************/ + + /** + * Test Last-Modified match + */ + public function testLastModifiedMatch() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'GET', + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + 'HTTP_IF_MODIFIED_SINCE' => 'Sun, 03 Oct 2010 21:00:52 GMT', + )); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->lastModified(1286139652); + }); + $s->call(); + $this->assertEquals(304, $s->response()->status()); + } + + /** + * Test Last-Modified match + */ + public function testLastModifiedDoesNotMatch() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + 'IF_MODIFIED_SINCE' => 'Sun, 03 Oct 2010 21:00:52 GMT', + )); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->lastModified(1286139250); + }); + $s->call(); + $this->assertEquals(200, $s->response()->status()); + } + + public function testLastModifiedOnlyAcceptsIntegers() + { + $this->setExpectedException('\InvalidArgumentException'); + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + )); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->lastModified('Test'); + }); + $s->call(); + } + + /** + * Test Last Modified header format + */ + public function testLastModifiedHeaderFormat() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + )); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->lastModified(1286139652); + }); + $s->call(); + list($status, $header, $body) = $s->response()->finalize(); + $this->assertTrue(isset($header['Last-Modified'])); + $this->assertEquals('Sun, 03 Oct 2010 21:00:52 GMT', $header['Last-Modified']); + } + + /** + * Test ETag matches + */ + public function testEtagMatches() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + 'HTTP_IF_NONE_MATCH' => '"abc123"', + )); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->etag('abc123'); + }); + $s->call(); + $this->assertEquals(304, $s->response()->status()); + } + + /** + * Test ETag does not match + */ + public function testEtagDoesNotMatch() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + 'IF_NONE_MATCH' => '"abc1234"', + )); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->etag('abc123'); + }); + $s->call(); + $this->assertEquals(200, $s->response()->status()); + } + + /** + * Test ETag with invalid type + */ + public function testETagWithInvalidType() + { + $this->setExpectedException('\InvalidArgumentException'); + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + 'IF_NONE_MATCH' => '"abc1234"', + )); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->etag('123','foo'); + }); + $s->call(); + } + + /** + * Test Expires + */ + public function testExpiresAsString() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + )); + $expectedDate = gmdate('D, d M Y H:i:s T', strtotime('5 days')); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->expires('5 days'); + }); + $s->call(); + list($status, $header, $body) = $s->response()->finalize(); + $this->assertTrue(isset($header['Expires'])); + $this->assertEquals($header['Expires'], $expectedDate); + } + + /** + * Test Expires + */ + public function testExpiresAsInteger() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + )); + $fiveDaysFromNow = time() + (60 * 60 * 24 * 5); + $expectedDate = gmdate('D, d M Y H:i:s T', $fiveDaysFromNow); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s, $fiveDaysFromNow) { + $s->expires($fiveDaysFromNow); + }); + $s->call(); + list($status, $header, $body) = $s->response()->finalize(); + $this->assertTrue(isset($header['Expires'])); + $this->assertEquals($header['Expires'], $expectedDate); + } + + /************************************************ + * COOKIES + ************************************************/ + + /** + * Set cookie + * + * This tests that the Slim application instance sets + * a cookie in the HTTP response header. This does NOT + * test the implementation of setting the cookie; that is + * tested in a separate file. + */ + public function testSetCookie() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + )); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->setCookie('foo', 'bar', '2 days'); + $s->setCookie('foo1', 'bar1', '2 days'); + }); + $s->call(); + $cookie1 = $s->response->cookies->get('foo'); + $cookie2 = $s->response->cookies->get('foo1'); + $this->assertEquals(2, count($s->response->cookies)); + $this->assertEquals('bar', $cookie1['value']); + $this->assertEquals('bar1', $cookie2['value']); + } + + /** + * Test get cookie + * + * This method ensures that the `Cookie:` HTTP request + * header is parsed if present, and made accessible via the + * Request object. + */ + public function testGetCookie() + { + \Slim\Environment::mock(array( + 'REQUEST_METHOD' => 'GET', + 'REMOTE_ADDR' => '127.0.0.1', + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + 'QUERY_STRING' => 'one=foo&two=bar', + 'SERVER_NAME' => 'slimframework.com', + 'SERVER_PORT' => 80, + 'HTTP_COOKIE' => 'foo=bar; foo2=bar2', + 'slim.url_scheme' => 'http', + 'slim.input' => '', + 'slim.errors' => @fopen('php://stderr', 'w') + )); + $s = new \Slim\Slim(); + $this->assertEquals('bar', $s->getCookie('foo')); + $this->assertEquals('bar2', $s->getCookie('foo2')); + } + + /** + * Test get cookie when cookie does not exist + */ + public function testGetCookieThatDoesNotExist() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + )); + $s = new \Slim\Slim(); + $this->assertNull($s->getCookie('foo')); + } + + /** + * Test delete cookie + * + * This method ensures that the `Set-Cookie:` HTTP response + * header is set. The implementation of setting the response + * cookie is tested separately in another file. + */ + public function testDeleteCookie() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/bar', //<-- Virtual + 'COOKIE' => 'foo=bar; foo2=bar2', + )); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->setCookie('foo', 'bar'); + $s->deleteCookie('foo'); + }); + $s->call(); + $cookie = $s->response->cookies->get('foo'); + $this->assertEquals(1, count($s->response->cookies)); + $this->assertEquals('', $cookie['value']); + $this->assertLessThan(time(), $cookie['expires']); + } + + /************************************************ + * HELPERS + ************************************************/ + + /** + * Test get filesystem path to Slim app root directory + */ + public function testGetRoot() + { + $_SERVER['DOCUMENT_ROOT'] = dirname(__FILE__); //<-- No trailing slash + $s = new \Slim\Slim(); + $this->assertEquals($_SERVER['DOCUMENT_ROOT'] . '/foo/', $s->root()); //<-- Appends physical app path with trailing slash + } + + /** + * Test stop + */ + public function testStop() + { + $this->setExpectedException('\Slim\Exception\Stop'); + $s = new \Slim\Slim(); + $s->stop(); + } + + /** + * Test stop with subsequent output + */ + public function testStopWithSubsequentOutput() + { + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + echo "Foo"; //<-- Should be in response body! + $s->stop(); + echo "Bar"; //<-- Should not be in response body! + }); + $s->call(); + $this->assertEquals('Foo', $s->response()->body()); + } + + /** + * Test stop with output buffer on and pre content + */ + public function testStopOutputWithOutputBufferingOnAndPreContent() + { + $this->expectOutputString('1.2.Foo.3'); //<-- PHP unit uses OB here + echo "1."; + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + echo "Foo"; + $s->stop(); + }); + echo "2."; + $s->run(); //<-- Needs to be run to actually echo body + echo ".3"; + } + + /** + * Test stop does not leave output buffers open + */ + public function testStopDoesNotLeaveOutputBuffersOpen() + { + $level_start = ob_get_level(); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->stop(); + }); + $s->run(); + $this->assertEquals($level_start, ob_get_level()); + } + + /** + * Test halt + */ + public function testHalt() + { + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + echo "Foo!"; //<-- Should not be in response body! + $s->halt(500, 'Something broke'); + }); + $s->call(); + list($status, $header, $body) = $s->response()->finalize(); + $this->assertEquals(500, $status); + $this->assertEquals('Something broke', $body); + } + + /** + * Test halt with output buffering and pre content + */ + public function testHaltOutputWithOutputBufferingOnAndPreContent() + { + $this->expectOutputString('1.2.Something broke.3'); //<-- PHP unit uses OB here + echo "1."; + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + echo "Foo!"; //<-- Should not be in response body! + $s->halt(500, 'Something broke'); + }); + echo "2."; + $s->run(); + echo ".3"; + } + + /** + * Test halt does not leave output buffers open + */ + public function testHaltDoesNotLeaveOutputBuffersOpen() + { + $level_start = ob_get_level(); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->halt(500, ''); + }); + $s->run(); + $this->assertEquals($level_start, ob_get_level()); + } + + /** + * Test pass cleans buffer and throws exception + */ + public function testPass() + { + ob_start(); + $s = new \Slim\Slim(); + echo "Foo"; + try { + $s->pass(); + $this->fail('Did not catch Slim_Exception_Pass'); + } catch ( \Slim\Exception\Pass $e ) {} + $output = ob_get_clean(); + $this->assertEquals('', $output); + } + + /** + * Test pass when there is a subsequent fallback route + */ + public function testPassWithSubsequentRoute() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/name/Frank', //<-- Virtual + )); + $s = new \Slim\Slim(); + $s->get('/name/Frank', function () use ($s) { + echo "Fail"; //<-- Should not be in response body! + $s->pass(); + }); + $s->get('/name/:name', function ($name) { + echo $name; //<-- Should be in response body! + }); + $s->call(); + $this->assertEquals('Frank', $s->response()->body()); + } + + /** + * Test pass when there is not a subsequent fallback route + */ + public function testPassWithoutSubsequentRoute() + { + \Slim\Environment::mock(array( + 'SCRIPT_NAME' => '/foo', //<-- Physical + 'PATH_INFO' => '/name/Frank', //<-- Virtual + )); + $s = new \Slim\Slim(); + $s->get('/name/Frank', function () use ($s) { + echo "Fail"; //<-- Should not be in response body! + $s->pass(); + }); + $s->call(); + $this->assertEquals(404, $s->response()->status()); + } + + /** + * Test content type + */ + public function testContentType() + { + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->contentType('application/json'); + }); + $s->call(); + list($status, $header, $body) = $s->response()->finalize(); + $this->assertEquals('application/json', $header['Content-Type']); + } + + /** + * Test status + */ + public function testStatus() + { + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->status(403); + }); + $s->call(); + $this->assertEquals(403, $s->response()->status()); + } + + /** + * Test URL for + */ + public function testSlimUrlFor() + { + $s = new \Slim\Slim(); + $s->get('/hello/:name', function () {})->name('hello'); + $this->assertEquals('/foo/hello/Josh', $s->urlFor('hello', array('name' => 'Josh'))); //<-- Prepends physical path! + } + + /** + * Test redirect sets status and header + */ + public function testRedirect() + { + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + echo "Foo"; //<-- Should not be in response body! + $s->redirect('/somewhere/else', 303); + }); + $s->call(); + list($status, $header, $body) = $s->response()->finalize(); + $this->assertEquals(303, $status); + $this->assertEquals('/somewhere/else', $header['Location']); + $this->assertEquals('', $body); + } + + /************************************************ + * RUNNER + ************************************************/ + + /** + * Test that runner sends headers and body + */ + public function testRun() + { + $this->expectOutputString('Foo'); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + echo "Foo"; + }); + $s->run(); + } + + /** + * Test runner output with output buffering on and pre content + */ + public function testRunOutputWithOutputBufferingOnAndPreContent() + { + $this->expectOutputString('1.2.Foo.3'); //<-- PHP unit uses OB here + $s = new \Slim\Slim(); + echo "1."; + $s->get('/bar', function () use ($s) { + echo "Foo"; + }); + echo "2."; + $s->run(); + echo ".3"; + } + + /** + * Test that runner does not leave output buffers open + */ + public function testRunDoesNotLeaveAnyOutputBuffersOpen() + { + $level_start = ob_get_level(); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) {}); + $s->run(); + $this->assertEquals($level_start, ob_get_level()); + } + + /************************************************ + * MIDDLEWARE + ************************************************/ + + /** + * Test add middleware + * + * This asserts that middleware are queued and called + * in sequence. This also asserts that the environment + * variables are passed by reference. + */ + public function testAddMiddleware() + { + $this->expectOutputString('FooHello'); + $s = new \Slim\Slim(); + $s->add(new CustomMiddleware()); //<-- See top of this file for class definition + $s->get('/bar', function () { + echo 'Foo'; + }); + $s->run(); + $this->assertEquals('Hello', $s->response()->header('X-Slim-Test')); + } + + /************************************************ + * FLASH MESSAGING + ************************************************/ + + public function testSetFlashForNextRequest() + { + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->flash('info', 'bar'); + }); + $this->assertFalse(isset($_SESSION['slim.flash'])); + $s->run(); + $this->assertEquals('bar', $_SESSION['slim.flash']['info']); + } + + public function testSetFlashForCurrentRequest() + { + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->flashNow('info', 'bar'); + }); + $s->run(); + $env = $s->environment(); + $this->assertEquals('bar', $env['slim.flash']['info']); + } + + public function testKeepFlashForNextRequest() + { + $_SESSION['slim.flash'] = array('info' => 'Foo'); + $s = new \Slim\Slim(); + $s->get('/bar', function () use ($s) { + $s->flashKeep(); + }); + $s->run(); + $this->assertEquals('Foo', $_SESSION['slim.flash']['info']); + } + + /************************************************ + * NOT FOUND HANDLING + ************************************************/ + + /** + * Test custom Not Found handler + */ + public function testNotFound() + { + $s = new \Slim\Slim(); + $s->notFound(function () { + echo "Not Found"; + }); + $s->get('/foo', function () {}); + $s->call(); + list($status, $header, $body) = $s->response()->finalize(); + $this->assertEquals(404, $status); + $this->assertEquals('Not Found', $body); + } + + /************************************************ + * ERROR HANDLING + ************************************************/ + + /** + * Test default and custom error handlers + * + * Pre-conditions: + * Invoked app route calls default error handler; + * + * Post-conditions: + * Response status code is 500; + */ + public function testSlimError() + { + $s = new \Slim\Slim(array( + "log.enabled" => false + )); + $s->get('/bar', function () use ($s) { + $s->error(); + }); + $s->call(); + $this->assertEquals(500, $s->response()->status()); + } + + /** + * Test default error handler logs the error when debug is false. + * + * Pre-conditions: + * Invoked app route calls default error handler; + * + * Post-conditions: + * Error log is called + */ + public function testDefaultHandlerLogsTheErrorWhenDebugIsFalse() + { + $s = new \Slim\Slim(array('debug' => false)); + $s->container->singleton('log', function ($c) { + return new EchoErrorLogger(); + }); + $s->get('/bar', function () use ($s) { + throw new \InvalidArgumentException('my specific error message'); + }); + + ob_start(); + $s->run(); + $output = ob_get_clean(); + $this->assertTrue(strpos($output, 'InvalidArgumentException:my specific error message') !== false); + } + + /** + * Test triggered errors are converted to ErrorExceptions + * + * Pre-conditions: + * Custom error handler defined; + * Invoked app route triggers error; + * + * Post-conditions: + * Response status is 500; + * Response body is equal to triggered error message; + * Error handler's argument is ErrorException instance; + */ + public function DISABLEDtestTriggeredErrorsAreConvertedToErrorExceptions() + { + $s = new \Slim\Slim(array( + 'debug' => false + )); + $s->error(function ( $e ) { + if ($e instanceof \ErrorException) { + echo $e->getMessage(); + } + }); + $s->get('/bar', function () { + trigger_error('Foo I say!'); + }); + $s->call(); + list($status, $header, $body) = $s->response()->finalize(); + $this->assertEquals(500, $status); + $this->assertEquals('Foo I say!', $body); + } + + /** + * Test error triggered with multiple applications + * + * Pre-conditions: + * Multiple Slim apps are instantiated; + * Both apps are run; + * One app returns 200 OK; + * One app triggers an error; + * + * Post-conditions: + * One app returns 200 OK with no Exceptions; + * One app returns 500 Error; + * Error triggered does not affect other app; + */ + public function testErrorWithMultipleApps() + { + $s1 = new \Slim\Slim(array( + 'debug' => false, + 'log.enabled' => false + )); + $s2 = new \Slim\Slim(); + $s1->get('/bar', function () use ($s1) { + $s1->error(); + }); + $s2->get('/bar', function () { + echo 'success'; + }); + $s1->call(); + $s2->call(); + $this->assertEquals(500, $s1->response()->status()); + $this->assertEquals(200, $s2->response()->status()); + } + + /** + * Test custom error handler uses existing Response object + */ + public function testErrorHandlerUsesCurrentResponseObject() + { + $s = new \Slim\Slim(array( + 'debug' => false + )); + $s->error(function ( \Exception $e ) use ($s) { + $r = $s->response(); + $r->status(503); + $r->write('Foo'); + $r['X-Powered-By'] = 'Slim'; + echo 'Bar'; + }); + $s->get('/bar', function () { + throw new \Exception('Foo'); + }); + $s->call(); + list($status, $header, $body) = $s->response()->finalize(); + $this->assertEquals(503, $status); + $this->assertEquals('FooBar', $body); + $this->assertEquals('Slim', $header['X-Powered-By']); + } + + /** + * Test custom global error handler + */ + public function testHandleErrors() + { + $defaultErrorReporting = error_reporting(); + + // Test 1 + error_reporting(E_ALL ^ E_NOTICE); // <-- Report all errors EXCEPT notices + try { + \Slim\Slim::handleErrors(E_NOTICE, 'test error', 'Slim.php', 119); + } catch (\ErrorException $e) { + $this->fail('Slim::handleErrors reported a disabled error level.'); + } + + // Test 2 + error_reporting(E_ALL | E_STRICT); // <-- Report all errors, including E_STRICT + try { + \Slim\Slim::handleErrors(E_STRICT, 'test error', 'Slim.php', 119); + $this->fail('Slim::handleErrors didn\'t report a enabled error level'); + } catch (\ErrorException $e) {} + + error_reporting($defaultErrorReporting); + } + + /** + * Slim should keep reference to a callable error callback + */ + public function testErrorHandler() { + $s = new \Slim\Slim(); + $errCallback = function () { echo "404"; }; + $s->error($errCallback); + $this->assertSame($errCallback, PHPUnit_Framework_Assert::readAttribute($s, 'error')); + } + + /** + * Slim should throw a Slim_Exception_Stop if error callback is not callable + */ + public function testErrorHandlerIfNotCallable() { + $this->setExpectedException('\Slim\Exception\Stop'); + $s = new \Slim\Slim(array("log.enabled" => false)); + $errCallback = 'foo'; + $s->error($errCallback); + } + + /** + * Slim should keep reference to a callable NotFound callback + */ + public function testNotFoundHandler() { + $s = new \Slim\Slim(); + $notFoundCallback = function () { echo "404"; }; + $s->notFound($notFoundCallback); + $this->assertSame($notFoundCallback, PHPUnit_Framework_Assert::readAttribute($s, 'notFound')); + } + + /** + * Slim should throw a Slim_Exception_Stop if NotFound callback is not callable + */ + public function testNotFoundHandlerIfNotCallable() { + $this->setExpectedException('\Slim\Exception\Stop'); + $s = new \Slim\Slim(); + $notFoundCallback = 'foo'; + $s->notFound($notFoundCallback); + } + + /************************************************ + * HOOKS + ************************************************/ + + /** + * Test hook listener + * + * Pre-conditions: + * Slim app instantiated; + * Hook name does not exist; + * Listeners are callable objects; + * + * Post-conditions: + * Callables are invoked in expected order; + */ + public function testRegistersAndCallsHooksByPriority() + { + $this->expectOutputString('barfoo'); + $app = new \Slim\Slim(); + $callable1 = function () { echo "foo"; }; + $callable2 = function () { echo "bar"; }; + $app->hook('test.hook.one', $callable1); //default is 10 + $app->hook('test.hook.one', $callable2, 8); + $hooks = $app->getHooks(); + $this->assertEquals(7, count($hooks)); //6 default, 1 custom + $app->applyHook('test.hook.one'); + } + + /** + * Test hook listener if listener is not callable + * + * Pre-conditions: + * Slim app instantiated; + * Hook name does not exist; + * Listener is NOT a callable object; + * + * Post-conditions: + * Hook is created; + * Callable is NOT assigned to hook; + */ + public function testHookInvalidCallable() + { + $app = new \Slim\Slim(); + $callable = 'test'; //NOT callable + $app->hook('test.hook.one', $callable); + $this->assertEquals(array(array()), $app->getHooks('test.hook.one')); + } + + /** + * Test hook invocation if hook does not exist + * + * Pre-conditions: + * Slim app instantiated; + * Hook name does not exist; + * + * Post-conditions: + * Hook is created; + * Hook initialized with empty array; + */ + public function testHookInvocationIfNotExists() + { + $app = new \Slim\Slim(); + $app->applyHook('test.hook.one'); + $this->assertEquals(array(array()), $app->getHooks('test.hook.one')); + } + + /** + * Test clear hooks + * + * Pre-conditions: + * Slim app instantiated; + * Two hooks exist, each with one listener; + * + * Post-conditions: + * Case A: Listeners for 'test.hook.one' are cleared; + * Case B: Listeners for all hooks are cleared; + */ + public function testHookClear() + { + $app = new \Slim\Slim(); + $app->hook('test.hook.one', function () {}); + $app->hook('test.hook.two', function () {}); + $app->clearHooks('test.hook.two'); + $this->assertEquals(array(array()), $app->getHooks('test.hook.two')); + $hookOne = $app->getHooks('test.hook.one'); + $this->assertTrue(count($hookOne[10]) === 1); + $app->clearHooks(); + $this->assertEquals(array(array()), $app->getHooks('test.hook.one')); + } + + /** + * Test late static binding + * + * Pre-conditions: + * Slim app is extended by Derived class and instantiated; + * Derived class overrides the 'getDefaultSettings' function and adds an extra default config value + * Test that the new config value exists + * + * Post-conditions: + * Config value exists and is equal to expected value + */ + public function testDerivedClassCanOverrideStaticFunction() + { + $app = new Derived(); + $this->assertEquals($app->config("late-static-binding"), true); + } +} diff --git a/strillonews/vendor/slim/slim/tests/ViewTest.php b/strillonews/vendor/slim/slim/tests/ViewTest.php new file mode 100644 index 0000000..e0f681d --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/ViewTest.php @@ -0,0 +1,198 @@ + + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.0 + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +class ViewTest extends PHPUnit_Framework_TestCase +{ + public function testGetDataAll() + { + $view = new \Slim\View(); + $prop = new \ReflectionProperty($view, 'data'); + $prop->setAccessible(true); + $prop->setValue($view, new \Slim\Helper\Set(array('foo' => 'bar'))); + + $this->assertSame(array('foo' => 'bar'), $view->getData()); + } + + public function testGetDataKeyExists() + { + $view = new \Slim\View(); + $prop = new \ReflectionProperty($view, 'data'); + $prop->setAccessible(true); + $prop->setValue($view, new \Slim\Helper\Set(array('foo' => 'bar'))); + + $this->assertEquals('bar', $view->getData('foo')); + } + + public function testGetDataKeyNotExists() + { + $view = new \Slim\View(); + $prop = new \ReflectionProperty($view, 'data'); + $prop->setAccessible(true); + $prop->setValue($view, new \Slim\Helper\Set(array('foo' => 'bar'))); + + $this->assertNull($view->getData('abc')); + } + + public function testSetDataKeyValue() + { + $view = new \Slim\View(); + $prop = new \ReflectionProperty($view, 'data'); + $prop->setAccessible(true); + $view->setData('foo', 'bar'); + + $this->assertEquals(array('foo' => 'bar'), $prop->getValue($view)->all()); + } + + public function testSetDataKeyValueAsClosure() + { + $view = new \Slim\View(); + $prop = new \ReflectionProperty($view, 'data'); + $prop->setAccessible(true); + + $view->setData('fooClosure', function () { + return 'foo'; + }); + + $value = $prop->getValue($view)->get('fooClosure'); + $this->assertInstanceOf('Closure', $value); + $this->assertEquals('foo', $value()); + } + + public function testSetDataArray() + { + $view = new \Slim\View(); + $prop = new \ReflectionProperty($view, 'data'); + $prop->setAccessible(true); + $view->setData(array('foo' => 'bar')); + + $this->assertEquals(array('foo' => 'bar'), $prop->getValue($view)->all()); + } + + public function testSetDataInvalidArgument() + { + $this->setExpectedException('InvalidArgumentException'); + + $view = new \Slim\View(); + $view->setData('foo'); + } + + public function testAppendData() + { + $view = new \Slim\View(); + $prop = new \ReflectionProperty($view, 'data'); + $prop->setAccessible(true); + $view->appendData(array('foo' => 'bar')); + + $this->assertEquals(array('foo' => 'bar'), $prop->getValue($view)->all()); + } + + public function testLocalData() + { + $view = new \Slim\View(); + $prop1 = new \ReflectionProperty($view, 'data'); + $prop1->setAccessible(true); + $prop1->setValue($view, new \Slim\Helper\Set(array('foo' => 'bar'))); + + $prop2 = new \ReflectionProperty($view, 'templatesDirectory'); + $prop2->setAccessible(true); + $prop2->setValue($view, dirname(__FILE__) . '/templates'); + + $output = $view->fetch('test.php', array('foo' => 'baz')); + $this->assertEquals('test output baz', $output); + } + + public function testAppendDataOverwrite() + { + $view = new \Slim\View(); + $prop = new \ReflectionProperty($view, 'data'); + $prop->setAccessible(true); + $prop->setValue($view, new \Slim\Helper\Set(array('foo' => 'bar'))); + $view->appendData(array('foo' => '123')); + + $this->assertEquals(array('foo' => '123'), $prop->getValue($view)->all()); + } + + public function testAppendDataInvalidArgument() + { + $this->setExpectedException('InvalidArgumentException'); + + $view = new \Slim\View(); + $view->appendData('foo'); + } + + public function testGetTemplatesDirectory() + { + $view = new \Slim\View(); + $property = new \ReflectionProperty($view, 'templatesDirectory'); + $property->setAccessible(true); + $property->setValue($view, 'templates'); + + $this->assertEquals('templates', $view->getTemplatesDirectory()); + } + + public function testSetTemplatesDirectory() + { + $view = new \Slim\View(); + $view->setTemplatesDirectory('templates/'); // <-- Should strip trailing slash + + $this->assertAttributeEquals('templates', 'templatesDirectory', $view); + } + + public function testDisplay() + { + $this->expectOutputString('test output bar'); + + $view = new \Slim\View(); + $prop1 = new \ReflectionProperty($view, 'data'); + $prop1->setAccessible(true); + $prop1->setValue($view, new \Slim\Helper\Set(array('foo' => 'bar'))); + + $prop2 = new \ReflectionProperty($view, 'templatesDirectory'); + $prop2->setAccessible(true); + $prop2->setValue($view, dirname(__FILE__) . '/templates'); + + $view->display('test.php'); + } + + public function testDisplayTemplateThatDoesNotExist() + { + $this->setExpectedException('\RuntimeException'); + + $view = new \Slim\View(); + + $prop2 = new \ReflectionProperty($view, 'templatesDirectory'); + $prop2->setAccessible(true); + $prop2->setValue($view, dirname(__FILE__) . '/templates'); + + $view->display('foo.php'); + } +} diff --git a/strillonews/vendor/slim/slim/tests/bootstrap.php b/strillonews/vendor/slim/slim/tests/bootstrap.php new file mode 100644 index 0000000..0705e54 --- /dev/null +++ b/strillonews/vendor/slim/slim/tests/bootstrap.php @@ -0,0 +1,19 @@ +