From 2916f58ead8ddc0f22558448ad217477a8e4cd94 Mon Sep 17 00:00:00 2001 From: Alexis Lahouze Date: Thu, 24 Jan 2013 00:01:42 +0100 Subject: [PATCH] Rewrote the application in Python/Flask/SQLAlchemy --- src/.gitignore | 2 + src/api/__init__.py | 0 src/api/controller/__init__.py | 0 src/api/controller/accounts.py | 75 + src/api/controller/entries.py | 88 ++ src/api/model/__init__.py | 0 src/api/model/accounts.py | 12 + src/api/model/entries.py | 33 + src/app.py | 12 + src/html/api/.htaccess | 11 - src/html/api/Slim/Environment.php | 237 --- src/html/api/Slim/Exception/Pass.php | 50 - src/html/api/Slim/Exception/Stop.php | 48 - src/html/api/Slim/Http/Headers.php | 181 --- src/html/api/Slim/Http/Request.php | 585 -------- src/html/api/Slim/Http/Response.php | 459 ------ src/html/api/Slim/Http/Util.php | 389 ----- src/html/api/Slim/Log.php | 237 --- src/html/api/Slim/LogWriter.php | 75 - src/html/api/Slim/Middleware.php | 114 -- src/html/api/Slim/Middleware/ContentTypes.php | 170 --- src/html/api/Slim/Middleware/Flash.php | 202 --- .../api/Slim/Middleware/MethodOverride.php | 96 -- .../api/Slim/Middleware/PrettyExceptions.php | 114 -- .../api/Slim/Middleware/SessionCookie.php | 203 --- src/html/api/Slim/Route.php | 416 ------ src/html/api/Slim/Router.php | 235 --- src/html/api/Slim/Slim.php | 1309 ----------------- src/html/api/Slim/View.php | 216 --- src/html/api/index.php | 216 --- src/html/js/entries.js | 36 +- src/main.py | 10 + src/static.py | 13 + 33 files changed, 266 insertions(+), 5578 deletions(-) create mode 100644 src/.gitignore create mode 100644 src/api/__init__.py create mode 100644 src/api/controller/__init__.py create mode 100644 src/api/controller/accounts.py create mode 100644 src/api/controller/entries.py create mode 100644 src/api/model/__init__.py create mode 100644 src/api/model/accounts.py create mode 100644 src/api/model/entries.py create mode 100644 src/app.py delete mode 100644 src/html/api/.htaccess delete mode 100644 src/html/api/Slim/Environment.php delete mode 100644 src/html/api/Slim/Exception/Pass.php delete mode 100644 src/html/api/Slim/Exception/Stop.php delete mode 100644 src/html/api/Slim/Http/Headers.php delete mode 100644 src/html/api/Slim/Http/Request.php delete mode 100644 src/html/api/Slim/Http/Response.php delete mode 100644 src/html/api/Slim/Http/Util.php delete mode 100644 src/html/api/Slim/Log.php delete mode 100644 src/html/api/Slim/LogWriter.php delete mode 100644 src/html/api/Slim/Middleware.php delete mode 100644 src/html/api/Slim/Middleware/ContentTypes.php delete mode 100644 src/html/api/Slim/Middleware/Flash.php delete mode 100644 src/html/api/Slim/Middleware/MethodOverride.php delete mode 100644 src/html/api/Slim/Middleware/PrettyExceptions.php delete mode 100644 src/html/api/Slim/Middleware/SessionCookie.php delete mode 100644 src/html/api/Slim/Route.php delete mode 100644 src/html/api/Slim/Router.php delete mode 100644 src/html/api/Slim/Slim.php delete mode 100644 src/html/api/Slim/View.php delete mode 100644 src/html/api/index.php create mode 100644 src/main.py create mode 100644 src/static.py diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 0000000..a295864 --- /dev/null +++ b/src/.gitignore @@ -0,0 +1,2 @@ +*.pyc +__pycache__ diff --git a/src/api/__init__.py b/src/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/api/controller/__init__.py b/src/api/controller/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/api/controller/accounts.py b/src/api/controller/accounts.py new file mode 100644 index 0000000..8c98d22 --- /dev/null +++ b/src/api/controller/accounts.py @@ -0,0 +1,75 @@ + +from app import app +from app import db +from app import session + +from api.model.accounts import Account +from api.model.entries import Entry + +from flask import json, request + +from sqlalchemy import func, case, cast, extract, distinct + +@app.route("/api/accounts", methods=["GET"]) +def get_accounts(): + """ + Returns accounts with their solds. + """ + + query=session.query( + Account.id.label("id"), + Account.name.label("name"), + func.sum(Entry.value).label("future"), + func.sum(case([(Entry.operation_date != None, Entry.value,)], else_=cast(0, db.Numeric(15, 2)))).label("pointed"), + func.sum(case([(Entry.value_date < func.now(), Entry.value,)], else_=cast(0, db.Numeric(15, 2)))).label("current") + ).outerjoin(Entry).group_by(Account.id).order_by(Account.id) + + return json.dumps([{ + "id": i.id, + "name": i.name, + "current": str(i.current), + "pointed": str(i.pointed), + "future": str(i.future) + } for i in query.all()]) + +@app.route("/api/accounts//months") +def get_months(account_id): + query=session.query( + distinct(extract("year", Entry.value_date)).label("year"), + extract("month", Entry.value_date).label("month") + ).filter(Entry.account_id == account_id).order_by("year", "month") + + return json.dumps([{ + "year": i.year, + "month": i.month + } for i in query.all()]) + +@app.route("/api/accounts", methods=["PUT"]) +def add_account(): + account = Account(request.json['name']) + + session.add(account) + session.commit() + + return json.dumps("Account added.") + +@app.route("/api/accounts/", methods=["PUT"]) +def update_account(account_id): + account = session.query(Account).filter(Account.id == account_id).first() + + account.name = request.json['name'] + + session.merge(account) + session.commit() + + return json.dumps("Account #%s updated." % account_id) + +@app.route("/api/accounts/", methods=["DELETE"]) +def delete_account(account_id): + account = session.query(Account).filter(Account.id == account_id).first() + + session.delete(account) + session.commit() + + return json.dumps("Account #%s deleted." % account_id) + diff --git a/src/api/controller/entries.py b/src/api/controller/entries.py new file mode 100644 index 0000000..262fe1d --- /dev/null +++ b/src/api/controller/entries.py @@ -0,0 +1,88 @@ +from app import app +from app import db +from app import session + +from api.model.entries import Entry + +from sqlalchemy import func, desc +from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method +from sqlalchemy.orm import sessionmaker, column_property +from sqlalchemy.sql import func, select + +#from sqlalchemy import * + +from flask import json, request + +@app.route("/api/entries///") +def get_entries(account_id, year, month): + """ + Return entries for an account, year, and month. + """ + query=session.query( + Entry + ).select_from( + session.query(Entry) + .filter(Entry.account_id == account_id) + .order_by( + desc(Entry.value_date), + desc(Entry.operation_date), + Entry.label, + Entry.value + ).subquery() + ).filter(func.date_trunc('month', Entry.value_date) == "%s-%s-01" % (year, month)) + + return json.dumps([{ + "id": i.id, + "value_date": i.value_date.strftime("%Y-%m-%d"), + "operation_date": i.operation_date.strftime("%Y-%m-%d") if i.operation_date else None, + "label": i.label, + "value": str(i.value), + "category": i.category, + "sold": str(i.sold), + "pointedsold": str(i.pointedsold), + "account_id": i.account_id + } for i in query.all()]) + +@app.route("/api/entries", methods=["PUT"]) +def add_entry(): + entry = Entry( + value_date = request.json['value_date'], + operation_date = request.json['operation_date'], + label = request.json['label'], + value = request.json['value'], + category = request.json['category'], + account_id = request.json['account_id'] + ) + + session.add(entry) + session.commit() + + return json.dumps("Entry added.") + +@app.route("/api/entries/", methods=["PUT"]) +def update_entry(entry_id): + entry = session.query(Entry).filter(Entry.id == entry_id).first() + + entry.id = entry_id + entry.value_date = request.json['value_date'] + entry.operation_date = request.json['operation_date'] + entry.label = request.json['label'] + entry.value = request.json['value'] + entry.category = request.json['category'] + entry.account_id = request.json['account_id'] + + session.merge(entry) + session.commit() + + return json.dumps("Entry #%s updated." % entry_id) + +@app.route("/api/entries/", methods=["DELETE"]) +def delete_entry(entry_id): + entry = session.query(Entry).filter(Entry.id == entry_id).first() + + session.delete(entry) + session.commit() + + return json.dumps("Entry #%s deleted." % entry_id) + + diff --git a/src/api/model/__init__.py b/src/api/model/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/api/model/accounts.py b/src/api/model/accounts.py new file mode 100644 index 0000000..4e061dd --- /dev/null +++ b/src/api/model/accounts.py @@ -0,0 +1,12 @@ +from app import app +from app import db + +from collections import OrderedDict + +class Account(db.Model): + id = db.Column(db.Integer, primary_key = True) + name = db.Column(db.String(200), nullable = False) + + def __init__(self, name): + self.name = name + diff --git a/src/api/model/entries.py b/src/api/model/entries.py new file mode 100644 index 0000000..edaa1e3 --- /dev/null +++ b/src/api/model/entries.py @@ -0,0 +1,33 @@ +from app import app +from app import db + +from api.model.accounts import Account + +from sqlalchemy import func, desc +from sqlalchemy.orm import column_property +from sqlalchemy.sql import func, select + +from collections import OrderedDict + +class Entry(db.Model): + id = db.Column(db.Integer, primary_key=True) + value_date = db.Column(db.Date, nullable = False) + operation_date = db.Column(db.Date, nullable = True) + label = db.Column(db.String(500), nullable = False) + value = db.Column(db.Numeric(15, 2), nullable = False) + account_id = db.Column(db.Integer, db.ForeignKey('account.id')) + + account = db.relationship(Account, backref = db.backref('entry', lazy="Dynamic")) + + category = db.Column(db.String(100), nullable = True) + sold = column_property(func.sum(value).over(order_by="value_date, operation_date, label desc, value desc")) + pointedsold = column_property(func.sum(value).over(partition_by="operation_date is not null", order_by="value_date, operation_date, label desc, value desc")) + + def __init__(self, value_date, label, value, account_id, operation_date = None, category = None): + self.value_date = value_date + self.operation_date = operation_date + self.label = label + self.value = value + self.account_id = account_id + self.category = category + diff --git a/src/app.py b/src/app.py new file mode 100644 index 0000000..573cce8 --- /dev/null +++ b/src/app.py @@ -0,0 +1,12 @@ +from flask import Flask +from flask.ext.sqlalchemy import SQLAlchemy +from sqlalchemy.orm import sessionmaker + +app = Flask(__name__) + +app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://accountant:accountant@localhost/accountant' +app.config['SQLALCHEMY_RECORD_QUERIES'] = True + +db = SQLAlchemy(app) +session = db.create_scoped_session() + diff --git a/src/html/api/.htaccess b/src/html/api/.htaccess deleted file mode 100644 index c1245d1..0000000 --- a/src/html/api/.htaccess +++ /dev/null @@ -1,11 +0,0 @@ -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] - diff --git a/src/html/api/Slim/Environment.php b/src/html/api/Slim/Environment.php deleted file mode 100644 index 147d00f..0000000 --- a/src/html/api/Slim/Environment.php +++ /dev/null @@ -1,237 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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()) - { - self::$environment = new self(array_merge(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') - ), $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']; - - /** - * Application paths - * - * This derives two paths: SCRIPT_NAME and PATH_INFO. The SCRIPT_NAME - * is the real, physical path to the application, be it in the root - * directory or a subdirectory of the public document root. The PATH_INFO is the - * virtual path to the requested resource within the application context. - * - * With htaccess, the SCRIPT_NAME will be an absolute path (without file name); - * if not using htaccess, it will also include the file name. If it is "/", - * it is set to an empty string (since it cannot have a trailing slash). - * - * The PATH_INFO will be an absolute path with a leading slash; this will be - * used for application routing. - */ - if (strpos($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME']) === 0) { - $env['SCRIPT_NAME'] = $_SERVER['SCRIPT_NAME']; //Without URL rewrite - } else { - $env['SCRIPT_NAME'] = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']) ); //With URL rewrite - } - $env['PATH_INFO'] = substr_replace($_SERVER['REQUEST_URI'], '', 0, strlen($env['SCRIPT_NAME'])); - if (strpos($env['PATH_INFO'], '?') !== false) { - $env['PATH_INFO'] = substr_replace($env['PATH_INFO'], '', strpos($env['PATH_INFO'], '?')); //query string is not removed automatically - } - $env['SCRIPT_NAME'] = rtrim($env['SCRIPT_NAME'], '/'); - $env['PATH_INFO'] = '/' . ltrim($env['PATH_INFO'], '/'); - - //The portion of the request URI following the '?' - $env['QUERY_STRING'] = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''; - - //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 - $specialHeaders = array('CONTENT_TYPE', 'CONTENT_LENGTH', 'PHP_AUTH_USER', 'PHP_AUTH_PW', 'PHP_AUTH_DIGEST', 'AUTH_TYPE'); - foreach ($_SERVER as $key => $value) { - $value = is_string($value) ? trim($value) : $value; - if (strpos($key, 'HTTP_') === 0) { - $env[substr($key, 5)] = $value; - } elseif (strpos($key, 'X_') === 0 || in_array($key, $specialHeaders)) { - $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 mutipart/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/src/html/api/Slim/Exception/Pass.php b/src/html/api/Slim/Exception/Pass.php deleted file mode 100644 index f4f25fa..0000000 --- a/src/html/api/Slim/Exception/Pass.php +++ /dev/null @@ -1,50 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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/src/html/api/Slim/Exception/Stop.php b/src/html/api/Slim/Exception/Stop.php deleted file mode 100644 index f008959..0000000 --- a/src/html/api/Slim/Exception/Stop.php +++ /dev/null @@ -1,48 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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/src/html/api/Slim/Http/Headers.php b/src/html/api/Slim/Http/Headers.php deleted file mode 100644 index 0185f08..0000000 --- a/src/html/api/Slim/Http/Headers.php +++ /dev/null @@ -1,181 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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 - * - * This class is an abstraction of the HTTP response headers and - * provides array access to the header list while automatically - * stores and retrieves headers with lowercase canonical keys regardless - * of the input format. - * - * This class also implements the `Iterator` and `Countable` - * interfaces for even more convenient usage. - * - * @package Slim - * @author Josh Lockhart - * @since 1.6.0 - */ -class Headers implements \ArrayAccess, \Iterator, \Countable -{ - /** - * @var array HTTP headers - */ - protected $headers; - - /** - * @var array Map canonical header name to original header name - */ - protected $map; - - /** - * Constructor - * @param array $headers - */ - public function __construct($headers = array()) - { - $this->merge($headers); - } - - /** - * Merge Headers - * @param array $headers - */ - public function merge($headers) - { - foreach ($headers as $name => $value) { - $this[$name] = $value; - } - } - - /** - * Transform header name into canonical form - * @param string $name - * @return string - */ - protected function canonical($name) - { - return strtolower(trim($name)); - } - - /** - * Array Access: Offset Exists - */ - public function offsetExists($offset) - { - return isset($this->headers[$this->canonical($offset)]); - } - - /** - * Array Access: Offset Get - */ - public function offsetGet($offset) - { - $canonical = $this->canonical($offset); - if (isset($this->headers[$canonical])) { - return $this->headers[$canonical]; - } else { - return null; - } - } - - /** - * Array Access: Offset Set - */ - public function offsetSet($offset, $value) - { - $canonical = $this->canonical($offset); - $this->headers[$canonical] = $value; - $this->map[$canonical] = $offset; - } - - /** - * Array Access: Offset Unset - */ - public function offsetUnset($offset) - { - $canonical = $this->canonical($offset); - unset($this->headers[$canonical], $this->map[$canonical]); - } - - /** - * Countable: Count - */ - public function count() - { - return count($this->headers); - } - - /** - * Iterator: Rewind - */ - public function rewind() - { - reset($this->headers); - } - - /** - * Iterator: Current - */ - public function current() - { - return current($this->headers); - } - - /** - * Iterator: Key - */ - public function key() - { - $key = key($this->headers); - - return $this->map[$key]; - } - - /** - * Iterator: Next - */ - public function next() - { - return next($this->headers); - } - - /** - * Iterator: Valid - */ - public function valid() - { - return current($this->headers) !== false; - } -} diff --git a/src/html/api/Slim/Http/Request.php b/src/html/api/Slim/Http/Request.php deleted file mode 100644 index e508394..0000000 --- a/src/html/api/Slim/Http/Request.php +++ /dev/null @@ -1,585 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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_DELETE = 'DELETE'; - const METHOD_OPTIONS = 'OPTIONS'; - const METHOD_OVERRIDE = '_METHOD'; - - /** - * @var array - */ - protected static $formDataMediaTypes = array('application/x-www-form-urlencoded'); - - /** - * @var array - */ - protected $env; - - /** - * Constructor - * @param array $env - * @see \Slim\Environment - */ - public function __construct($env) - { - $this->env = $env; - } - - /** - * 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 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->env['X_REQUESTED_WITH']) && $this->env['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) { - if (isset($union[$key])) { - return $union[$key]; - } else { - return null; - } - } else { - 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 - * @return array|mixed|null - */ - public function get($key = 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 null; - } - } 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 - * @return array|mixed|null - * @throws \RuntimeException If environment input is not available - */ - public function post($key = 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 null; - } - } else { - return $this->env['slim.request.form_hash']; - } - } - - /** - * Fetch PUT data (alias for \Slim\Http\Request::post) - * @param string $key - * @return array|mixed|null - */ - public function put($key = null) - { - return $this->post($key); - } - - /** - * Fetch DELETE data (alias for \Slim\Http\Request::post) - * @param string $key - * @return array|mixed|null - */ - public function delete($key = null) - { - return $this->post($key); - } - - /** - * 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 (!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 parseable 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) { - $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 - */ - public function getContentType() - { - if (isset($this->env['CONTENT_TYPE'])) { - return $this->env['CONTENT_TYPE']; - } else { - return null; - } - } - - /** - * 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]); - } else { - 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']; - } else { - return null; - } - } - - /** - * Get Content-Length - * @return int - */ - public function getContentLength() - { - if (isset($this->env['CONTENT_LENGTH'])) { - return (int) $this->env['CONTENT_LENGTH']; - } else { - return 0; - } - } - - /** - * Get Host - * @return string - */ - public function getHost() - { - if (isset($this->env['HOST'])) { - if (strpos($this->env['HOST'], ':') !== false) { - $hostParts = explode(':', $this->env['HOST']); - - return $hostParts[0]; - } - - return $this->env['HOST']; - } else { - 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() - { - if (isset($this->env['REFERER'])) { - return $this->env['REFERER']; - } else { - return null; - } - } - - /** - * 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() - { - if (isset($this->env['USER_AGENT'])) { - return $this->env['USER_AGENT']; - } else { - return null; - } - } -} diff --git a/src/html/api/Slim/Http/Response.php b/src/html/api/Slim/Http/Response.php deleted file mode 100644 index 8e95b37..0000000 --- a/src/html/api/Slim/Http/Response.php +++ /dev/null @@ -1,459 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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 List of HTTP response headers - */ - protected $header; - - /** - * @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', - 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 $header The HTTP response headers - */ - public function __construct($body = '', $status = 200, $header = array()) - { - $this->status = (int) $status; - $headers = array(); - foreach ($header as $key => $value) { - $headers[$key] = $value; - } - $this->header = new Headers(array_merge(array('Content-Type' => 'text/html'), $headers)); - $this->body = ''; - $this->write($body); - } - - /** - * 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; - } - - /** - * 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[$name] = $value; - } - - return $this[$name]; - } - - /** - * Get headers - * @return \Slim\Http\Headers - */ - public function headers() - { - return $this->header; - } - - /** - * 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; - } - - /** - * 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; - } - - /** - * 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; - } - - /** - * 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() - { - if (in_array($this->status, array(204, 304))) { - unset($this['Content-Type'], $this['Content-Length']); - - return array($this->status, $this->header, ''); - } else { - return array($this->status, $this->header, $this->body); - } - } - - /** - * 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); - } - - /** - * 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 $value Properties for cookie including: value, expire, path, domain, secure, httponly - */ - public function deleteCookie($name, $value = array()) - { - 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->status = $status; - $this['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; - } - - /** - * Array Access: Offset Exists - */ - public function offsetExists( $offset ) - { - return isset($this->header[$offset]); - } - - /** - * Array Access: Offset Get - */ - public function offsetGet( $offset ) - { - if (isset($this->header[$offset])) { - return $this->header[$offset]; - } else { - return null; - } - } - - /** - * Array Access: Offset Set - */ - public function offsetSet($offset, $value) - { - $this->header[$offset] = $value; - } - - /** - * Array Access: Offset Unset - */ - public function offsetUnset($offset) - { - unset($this->header[$offset]); - } - - /** - * Countable: Count - */ - public function count() - { - return count($this->header); - } - - /** - * Get Iterator - * - * This returns the contained `\Slim\Http\Headers` instance which - * is itself iterable. - * - * @return \Slim\Http\Headers - */ - public function getIterator() - { - return $this->header; - } - - /** - * Get message for HTTP status code - * @return string|null - */ - public static function getMessageForCode($status) - { - if (isset(self::$messages[$status])) { - return self::$messages[$status]; - } else { - return null; - } - } -} diff --git a/src/html/api/Slim/Http/Util.php b/src/html/api/Slim/Http/Util.php deleted file mode 100644 index f7e99a9..0000000 --- a/src/html/api/Slim/Http/Util.php +++ /dev/null @@ -1,389 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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. - * - * @var array|string $rawData - * @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 - $settings = array_merge(array( - 'algorithm' => MCRYPT_RIJNDAEL_256, - 'mode' => MCRYPT_MODE_CBC - ), $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 - $settings = array_merge(array( - 'algorithm' => MCRYPT_RIJNDAEL_256, - 'mode' => MCRYPT_MODE_CBC - ), $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 = str_replace("\x0", '', $decryptedData); - mcrypt_generic_deinit($module); - - return $res; - } - - /** - * 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 unsecure 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 - * @param string - */ - public static function encodeSecureCookie($value, $expires, $secret, $algorithm, $mode) - { - $key = hash_hmac('sha1', $expires, $secret); - $iv = self::get_iv($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 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 - * @param 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::get_iv($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 string $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 requst'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 binary string with length 40 - */ - private static function get_iv($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/src/html/api/Slim/Log.php b/src/html/api/Slim/Log.php deleted file mode 100644 index 7706b2f..0000000 --- a/src/html/api/Slim/Log.php +++ /dev/null @@ -1,237 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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 ) - * info( mixed $object ) - * warn( mixed $object ) - * error( mixed $object ) - * fatal( mixed $object ) - * - * 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 FATAL = 0; - const ERROR = 1; - const WARN = 2; - const INFO = 3; - const DEBUG = 4; - - /** - * @var array - */ - protected static $levels = array( - self::FATAL => 'FATAL', - self::ERROR => 'ERROR', - self::WARN => 'WARN', - 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 - * @return mixed|false What the Logger returns, or false if Logger not set or not enabled - */ - public function debug($object) - { - return $this->write($object, self::DEBUG); - } - - /** - * Log info message - * @param mixed $object - * @return mixed|false What the Logger returns, or false if Logger not set or not enabled - */ - public function info($object) - { - return $this->write($object, self::INFO); - } - - /** - * Log warn message - * @param mixed $object - * @return mixed|false What the Logger returns, or false if Logger not set or not enabled - */ - public function warn($object) - { - return $this->write($object, self::WARN); - } - - /** - * Log error message - * @param mixed $object - * @return mixed|false What the Logger returns, or false if Logger not set or not enabled - */ - public function error($object) - { - return $this->write($object, self::ERROR); - } - - /** - * Log fatal message - * @param mixed $object - * @return mixed|false What the Logger returns, or false if Logger not set or not enabled - */ - public function fatal($object) - { - return $this->write($object, self::FATAL); - } - - /** - * Log message - * @param mixed The object to log - * @param int The message level - * @return int|false - */ - protected function write($object, $level) - { - if ($this->enabled && $this->writer && $level <= $this->level) { - return $this->writer->write($object, $level); - } else { - return false; - } - } -} diff --git a/src/html/api/Slim/LogWriter.php b/src/html/api/Slim/LogWriter.php deleted file mode 100644 index f26eb0f..0000000 --- a/src/html/api/Slim/LogWriter.php +++ /dev/null @@ -1,75 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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|false - */ - public function write($message, $level = null) - { - return fwrite($this->resource, (string) $message . PHP_EOL); - } -} diff --git a/src/html/api/Slim/Middleware.php b/src/html/api/Slim/Middleware.php deleted file mode 100644 index 641226a..0000000 --- a/src/html/api/Slim/Middleware.php +++ /dev/null @@ -1,114 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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 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 $application - */ - final public function setApplication($application) - { - $this->app = $application; - } - - /** - * Get application - * - * This method retrieves the application previously injected - * into this middleware. - * - * @return \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\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/src/html/api/Slim/Middleware/ContentTypes.php b/src/html/api/Slim/Middleware/ContentTypes.php deleted file mode 100644 index b11e460..0000000 --- a/src/html/api/Slim/Middleware/ContentTypes.php +++ /dev/null @@ -1,170 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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()) - { - $this->contentTypes = array_merge(array( - 'application/json' => array($this, 'parseJson'), - 'application/xml' => array($this, 'parseXml'), - 'text/xml' => array($this, 'parseXml'), - 'text/csv' => array($this, 'parseCsv') - ), $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 { - return new \SimpleXMLElement($input); - } 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/src/html/api/Slim/Middleware/Flash.php b/src/html/api/Slim/Middleware/Flash.php deleted file mode 100644 index 510bca3..0000000 --- a/src/html/api/Slim/Middleware/Flash.php +++ /dev/null @@ -1,202 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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 -{ - /** - * @var array - */ - protected $settings; - - /** - * @var array - */ - protected $messages; - - /** - * Constructor - * @param \Slim $app - * @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); - } -} diff --git a/src/html/api/Slim/Middleware/MethodOverride.php b/src/html/api/Slim/Middleware/MethodOverride.php deleted file mode 100644 index 6f5fffb..0000000 --- a/src/html/api/Slim/Middleware/MethodOverride.php +++ /dev/null @@ -1,96 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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 psuedo 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 \Slim $app - * @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. - * - * @param array $env - * @return array[status, header, body] - */ - public function call() - { - $env = $this->app->environment(); - if (isset($env['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['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/src/html/api/Slim/Middleware/PrettyExceptions.php b/src/html/api/Slim/Middleware/PrettyExceptions.php deleted file mode 100644 index e079e30..0000000 --- a/src/html/api/Slim/Middleware/PrettyExceptions.php +++ /dev/null @@ -1,114 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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) { - $env = $this->app->environment(); - $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/src/html/api/Slim/Middleware/SessionCookie.php b/src/html/api/Slim/Middleware/SessionCookie.php deleted file mode 100644 index 1747a86..0000000 --- a/src/html/api/Slim/Middleware/SessionCookie.php +++ /dev/null @@ -1,203 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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. - * - * If a secret key is provided with this middleware, the HTTP - * cookie will be checked for integrity to ensure the client-side - * cookie is not changed. - * - * You should NEVER store sensitive data in a client-side cookie - * in any format, encrypted 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 limtied 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()) - { - $this->settings = array_merge(array( - 'expires' => '20 minutes', - 'path' => '/', - 'domain' => null, - 'secure' => false, - 'httponly' => false, - 'name' => 'slim_session', - 'secret' => 'CHANGE_ME', - 'cipher' => MCRYPT_RIJNDAEL_256, - 'cipher_mode' => MCRYPT_MODE_CBC - ), $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 - * @param array $env - */ - protected function loadSession() - { - if (session_id() === '') { - session_start(); - } - - $value = \Slim\Http\Util::decodeSecureCookie( - $this->app->request()->cookies($this->settings['name']), - $this->settings['secret'], - $this->settings['cipher'], - $this->settings['cipher_mode'] - ); - if ($value) { - $_SESSION = unserialize($value); - } else { - $_SESSION = array(); - } - } - - /** - * Save session - */ - protected function saveSession() - { - $value = \Slim\Http\Util::encodeSecureCookie( - serialize($_SESSION), - $this->settings['expires'], - $this->settings['secret'], - $this->settings['cipher'], - $this->settings['cipher_mode'] - ); - if (strlen($value) > 4096) { - $this->app->getLog()->error('WARNING! Slim\Middleware\SessionCookie data size is larger than 4KB. Content save failed.'); - } else { - $this->app->response()->setCookie($this->settings['name'], array( - 'value' => $value, - 'domain' => $this->settings['domain'], - 'path' => $this->settings['path'], - 'expires' => $this->settings['expires'], - 'secure' => $this->settings['secure'], - 'httponly' => $this->settings['httponly'] - )); - } - session_destroy(); - } - - /******************************************************************************** - * Session Handler - *******************************************************************************/ - - public function open($savePath, $sessionName) - { - return true; - } - - public function close() - { - return true; - } - - public function read($id) - { - return ''; - } - - public function write($id, $data) - { - return true; - } - - public function destroy($id) - { - return true; - } - - public function gc($maxlifetime) - { - return true; - } -} diff --git a/src/html/api/Slim/Route.php b/src/html/api/Slim/Route.php deleted file mode 100644 index 445fbe9..0000000 --- a/src/html/api/Slim/Route.php +++ /dev/null @@ -1,416 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.0.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) - { - 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 - * @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 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; - } -} diff --git a/src/html/api/Slim/Router.php b/src/html/api/Slim/Router.php deleted file mode 100644 index 44979ea..0000000 --- a/src/html/api/Slim/Router.php +++ /dev/null @@ -1,235 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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; - - /** - * Constructor - */ - public function __construct() - { - $this->routes = 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)) { - continue; - } - - if ($route->matches($resourceUri)) { - $this->matchedRoutes[] = $route; - } - } - } - - return $this->matchedRoutes; - } - - /** - * Map a route object to a callback function - * @param string $pattern The URL pattern (ie. "/books/:id") - * @param mixed $callable Anything that returns TRUE for is_callable() - * @return \Slim\Route - */ - public function map($pattern, $callable) - { - $route = new \Slim\Route($pattern, $callable); - $this->routes[] = $route; - - return $route; - } - - /** - * Get URL for named route - * @param string $name The name of the route - * @param array 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 (array_keys($params) as $key) { - $search[] = '#:' . $key . '\+?(?!\w)#'; - } - $pattern = preg_replace($search, $params, $this->getNamedRoute($name)->getPattern()); - - //Remove remnants of unpopulated, trailing optional pattern segments - return preg_replace('#\(/?:.+\)|\(|\)#', '', $pattern); - } - - /** - * 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. - * - * @param \Slim\Route $route The route object - * @return bool Was route callable invoked successfully? - */ - public function dispatch(\Slim\Route $route) - { - $this->currentRoute = $route; - - //Invoke middleware - foreach ($route->getMiddleware() as $mw) { - call_user_func_array($mw, array($route)); - } - - //Invoke callable - call_user_func_array($route->getCallable(), array_values($route->getParams())); - - return true; - } - - /** - * 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/src/html/api/Slim/Slim.php b/src/html/api/Slim/Slim.php deleted file mode 100644 index 5e10c60..0000000 --- a/src/html/api/Slim/Slim.php +++ /dev/null @@ -1,1309 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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 - */ -class Slim -{ - /** - * @const string - */ - const VERSION = '2.2.0'; - - /** - * @var array[\Slim] - */ - protected static $apps = array(); - - /** - * @var string - */ - protected $name; - - /** - * @var array - */ - protected $environment; - - /** - * @var \Slim\Http\Request - */ - protected $request; - - /** - * @var \Slim\Http\Response - */ - protected $response; - - /** - * @var \Slim\Router - */ - protected $router; - - /** - * @var \Slim\View - */ - protected $view; - - /** - * @var array - */ - protected $settings; - - /** - * @var string - */ - protected $mode; - - /** - * @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($userSettings = array()) - { - // Setup Slim application - $this->settings = array_merge(static::getDefaultSettings(), $userSettings); - $this->environment = \Slim\Environment::getInstance(); - $this->request = new \Slim\Http\Request($this->environment); - $this->response = new \Slim\Http\Response(); - $this->router = new \Slim\Router(); - $this->middleware = array($this); - $this->add(new \Slim\Middleware\Flash()); - $this->add(new \Slim\Middleware\MethodOverride()); - - // Determine application mode - $this->getMode(); - - // Setup view - $this->view($this->config('view')); - - // Make default if first instance - if (is_null(static::getInstance())) { - $this->setName('default'); - } - - // Set default logger that writes to stderr (may be overridden with middleware) - $logWriter = $this->config('log.writer'); - if (!$logWriter) { - $logWriter = new \Slim\LogWriter($this->environment['slim.errors']); - } - $log = new \Slim\Log($logWriter); - $log->setEnabled($this->config('log.enabled')); - $log->setLevel($this->config('log.level')); - $this->environment['slim.log'] = $log; - } - - /** - * Get application instance by name - * @param string $name The name of the Slim application - * @return \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.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 { - $this->settings[$name] = $value; - } - } - - /******************************************************************************** - * 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() - { - if (!isset($this->mode)) { - if (isset($_ENV['SLIM_MODE'])) { - $this->mode = $_ENV['SLIM_MODE']; - } else { - $envMode = getenv('SLIM_MODE'); - if ($envMode !== false) { - $this->mode = $envMode; - } else { - $this->mode = $this->config('mode'); - } - } - } - - 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->environment['slim.log']; - } - - /******************************************************************************** - * Routing - *******************************************************************************/ - - /** - * Add GET|POST|PUT|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 = $this->router->map($pattern, $callable); - 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 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); - } - - /** - * 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, 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->setTemplatesDirectory($this->config('templates.path')); - $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['Last-Modified'] = date(DATE_RFC1123, $time); - if ($time === strtotime($this->request->headers('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('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['Expires'] = gmdate(DATE_RFC1123, $time); - } - - /******************************************************************************** - * HTTP Cookies - *******************************************************************************/ - - /** - * Set unencrypted HTTP cookie - * - * @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) - { - $this->response->setCookie($name, 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 - )); - } - - /** - * Get value of unencrypted HTTP cookie - * - * 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 - * @return string|null - */ - public function getCookie($name) - { - return $this->request->cookies($name); - } - - /** - * 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 = null, $httponly = null) - { - $expires = is_null($expires) ? $this->config('cookies.lifetime') : $expires; - if (is_string($expires)) { - $expires = strtotime($expires); - } - $secureValue = \Slim\Http\Util::encodeSecureCookie( - $value, - $expires, - $this->config('cookies.secret_key'), - $this->config('cookies.cipher'), - $this->config('cookies.cipher_mode') - ); - $this->setCookie($name, $secureValue, $expires, $path, $domain, $secure, $httponly); - } - - /** - * 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 - * @return string|false - */ - public function getEncryptedCookie($name, $deleteIfInvalid = true) - { - $value = \Slim\Http\Util::decodeSecureCookie( - $this->request->cookies($name), - $this->config('cookies.secret_key'), - $this->config('cookies.cipher'), - $this->config('cookies.cipher_mode') - ); - if ($value === false && $deleteIfInvalid) { - $this->deleteCookie($name); - } - - return $value; - } - - /** - * 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) - { - $this->response->deleteCookie($name, 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 - )); - } - - /******************************************************************************** - * 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['Content-Type'] = $type; - } - - /** - * Set the HTTP response status code - * @param int $status The HTTP response status code - */ - public function status($code) - { - $this->response->status($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 $hookArgs (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 - $this->add(new \Slim\Middleware\PrettyExceptions()); - - //Invoke middleware and application stack - $this->middleware[0]->call(); - - //Fetch status, header, and body - list($status, $header, $body) = $this->response->finalize(); - - //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 ($header as $name => $value) { - $hValues = explode("\n", $value); - foreach ($hValues as $hVal) { - header("$name: $hVal", false); - } - } - } - - //Send body - 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 = $this->router->dispatch($route); - $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 true - * @throws \ErrorException - */ - public static function handleErrors($errno, $errstr = '', $errfile = '', $errline = '') - { - if (error_reporting() & $errno) { - throw new \ErrorException($errstr, $errno, 0, $errfile, $errline); - } - - return true; - } - - /** - * 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 occured. The website administrator has been notified of the issue. Sorry for the temporary inconvenience.

'); - } -} diff --git a/src/html/api/Slim/View.php b/src/html/api/Slim/View.php deleted file mode 100644 index 0ce9568..0000000 --- a/src/html/api/Slim/View.php +++ /dev/null @@ -1,216 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.2.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 -{ - /** - * @var string Absolute or relative filesystem path to a specific template - * - * DEPRECATION WARNING! - * This variable will be removed in the near future - */ - protected $templatePath = ''; - - /** - * @var array Associative array of template variables - */ - protected $data = array(); - - /** - * @var string Absolute or relative path to the application's templates directory - */ - protected $templatesDirectory; - - /** - * Constructor - * - * This is empty but may be implemented in a subclass - */ - public function __construct() - { - - } - - /** - * Get data - * @param string|null $key - * @return mixed If key is null, array of template data; - * If key exists, value of datum with key; - * If key does not exist, null; - */ - public function getData($key = null) - { - if (!is_null($key)) { - return isset($this->data[$key]) ? $this->data[$key] : null; - } else { - return $this->data; - } - } - - /** - * Set data - * - * If two arguments: - * A single datum with key is assigned value; - * - * $view->setData('color', 'red'); - * - * If one argument: - * Replace all data with provided array keys and values; - * - * $view->setData(array('color' => 'red', 'number' => 1)); - * - * @param mixed - * @param mixed - * @throws InvalidArgumentException If incorrect method signature - */ - public function setData() - { - $args = func_get_args(); - if (count($args) === 1 && is_array($args[0])) { - $this->data = $args[0]; - } elseif (count($args) === 2) { - $this->data[(string) $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, ... ]);`'); - } - } - - /** - * Append new data to existing template data - * @param array - * @throws InvalidArgumentException If not given an array argument - */ - public function appendData($data) - { - if (!is_array($data)) { - throw new \InvalidArgumentException('Cannot append view data. Expected array argument.'); - } - $this->data = array_merge($this->data, $data); - } - - /** - * Get templates directory - * @return string|null Path to templates directory without trailing slash; - * Returns null if templates directory not set; - */ - public function getTemplatesDirectory() - { - return $this->templatesDirectory; - } - - /** - * Set templates directory - * @param string $dir - */ - public function setTemplatesDirectory($dir) - { - $this->templatesDirectory = rtrim($dir, '/'); - } - - /** - * Set template - * @param string $template - * @throws RuntimeException If template file does not exist - * - * DEPRECATION WARNING! - * This method will be removed in the near future. - */ - public function setTemplate($template) - { - $this->templatePath = $this->getTemplatesDirectory() . '/' . ltrim($template, '/'); - if (!file_exists($this->templatePath)) { - throw new \RuntimeException('View cannot render template `' . $this->templatePath . '`. Template does not exist.'); - } - } - - /** - * Display template - * - * This method echoes the rendered template to the current output buffer - * - * @param string $template Pathname of template file relative to templates directoy - */ - public function display($template) - { - echo $this->fetch($template); - } - - /** - * Fetch rendered template - * - * This method returns the rendered template - * - * @param string $template Pathname of template file relative to templates directory - * @return string - */ - public function fetch($template) - { - return $this->render($template); - } - - /** - * Render template - * - * @param string $template Pathname of template file relative to templates directory - * @return string - * - * DEPRECATION WARNING! - * Use `\Slim\View::fetch` to return a rendered template instead of `\Slim\View::render`. - */ - public function render($template) - { - $this->setTemplate($template); - extract($this->data); - ob_start(); - require $this->templatePath; - - return ob_get_clean(); - } -} diff --git a/src/html/api/index.php b/src/html/api/index.php deleted file mode 100644 index 5484c73..0000000 --- a/src/html/api/index.php +++ /dev/null @@ -1,216 +0,0 @@ -get('/entries/:account_id/:year/:month', 'getEntries'); -$app->get('/accounts', 'getAccounts'); -$app->get('/accounts/:account_id/months', 'getMonths'); -$app->delete('/entries/:id', 'removeEntry'); -$app->post('/entries/add', 'addEntry'); -$app->put('/entries/save/:id', 'saveEntry'); -$app->post('/accounts/add','addAccount'); -$app->put('/accounts/save/:id','saveAccount'); -$app->delete('/accounts/:id', 'removeAccount'); - -$app->run(); - -function getConnection() { - $db=new PDO("pgsql:host=localhost;dbname=accountant", "accountant", "accountant"); - $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - - return $db; -} - -// Return the entries -function getEntries($account_id, $year, $month) { - - $day=$year."-".$month."-01"; - - $connection=getConnection(); - - $sql = <<prepare($sql); - $statement->bindParam("day", $day); - $statement->bindParam("account_id", $account_id); - - $return=$statement->execute(); - - echo(json_encode($statement->fetchAll(PDO::FETCH_ASSOC))); -} - -// Add an entry -function addEntry() { - $request = \Slim\Slim::getInstance()->request(); - $entry = json_decode($request->getBody(), true); - - $connection=getConnection(); - - $statement=$connection->prepare("insert into entry (value_date, operation_date, label, value, account_id, category) values (:value_date, :operation_date, :label, :value, :account_id, :category)"); - - $statement->bindParam("value_date", $entry['value_date']); - $statement->bindParam("operation_date", $entry['operation_date']); - $statement->bindParam("label", $entry['label']); - $statement->bindParam("value", $entry['value']); - $statement->bindParam("account_id", $entry['account_id']); - $statement->bindParam("category", $entry["category"]); - - $return=$statement->execute(); - - echo("Entry saved."); -} - -// Saves an entry -function saveEntry($id) { - $request = \Slim\Slim::getInstance()->request(); - $entry = json_decode($request->getBody(), true); - - $connection=getConnection(); - - $statement=$connection->prepare("update entry set value_date=:value_date, operation_date=:operation_date, label=:label, value=:value, account_id=:account_id, category=:category where id=:id"); - - $statement->bindParam("value_date", $entry['value_date']); - $statement->bindParam("operation_date", $entry['operation_date']); - $statement->bindParam("label", $entry['label']); - $statement->bindParam("value", $entry['value']); - $statement->bindParam("account_id", $entry['account_id']); - $statement->bindParam("id", $entry['id']); - $statement->bindParam("category", $entry["category"]); - - $return=$statement->execute(); - - echo($entry['id'] . " saved."); -} - -// Remove an entry -function removeEntry($id) { - $connection=getConnection(); - - $statement=$connection->prepare("delete from entry where id=:id"); - $statement->bindParam("id", $id); - - $return=$statement->execute(); - - echo("Entry #" . $id . " removed."); -} - -// Return the accounts with their solds. -function getAccounts() { - $connection=getConnection(); - - $sql = <<prepare($sql); - - $return=$statement->execute(); - - echo(json_encode($statement->fetchAll(PDO::FETCH_ASSOC))); -} - -// Returns the months for an account. -function getMonths($account_id) { - $connection=getConnection(); - - $sql = <<prepare($sql); - $statement->bindParam("account_id", $account_id); - - $return=$statement->execute(); - - echo(json_encode($statement->fetchAll(PDO::FETCH_ASSOC))); -} - -function addAccount() { - $request = \Slim\Slim::getInstance()->request(); - $account = json_decode($request->getBody(), true); - - $connection=getConnection(); - - $statement=$connection->prepare("insert into account (name) values (:name)"); - - $statement->bindParam("name", $account['name']); - - $return=$statement->execute(); - - echo("Account saved."); -} - -function saveAccount($id) { - $request = \Slim\Slim::getInstance()->request(); - $account = json_decode($request->getBody(), true); - - $connection=getConnection(); - - $statement=$connection->prepare("update account set name=:name where id=:id"); - - $statement->bindParam("name", $account['name']); - $statement->bindParam("id", $id); - - $return=$statement->execute(); - - echo("Account #$id saved."); -} - -// Remove an account -function removeAccount($id) { - $connection=getConnection(); - - $statement=$connection->prepare("delete from account where id=:id"); - $statement->bindParam("id", $id); - - $return=$statement->execute(); - - echo("Account #$id removed."); -} - -?> - diff --git a/src/html/js/entries.js b/src/html/js/entries.js index c28230d..88916ad 100644 --- a/src/html/js/entries.js +++ b/src/html/js/entries.js @@ -90,17 +90,19 @@ var ListViewModel = function() { // Ajax call to save the entry. var type; - var url = "api/accounts/"; + var url = "api/accounts"; if(account.id()) { - type = "PUT"; - url += "save/" + account.id(); - } else { - type = "POST"; - url += "add"; + url += "/" + account.id(); } - $.ajax({url: url, type: type, data:ko.toJSON(account)}).success(function(data) { + $.ajax({ + url: url, + type: "PUT", + data: ko.toJSON(account), + dataType: "json", + contentType: "application/json" + }).success(function(data) { message("success", "Save", data); self.editingAccount(null); @@ -379,17 +381,19 @@ var ListViewModel = function() { // Ajax call to save the entry. var type; - var url = "api/entries/"; + var url = "api/entries"; if(item.id()) { - type = "PUT"; - url += "save/" + item.id(); - } else { - type = "POST"; - url += "add"; + url += "/" + item.id(); } - $.ajax({url: url, type: type, data:ko.toJSON(item)}).success(function(data) { + $.ajax({ + url: url, + type: "PUT", + contentType: "application/json", + data:ko.toJSON(item), + dataType: "json" + }).success(function(data) { message("success", "Save", data); self.selectedItem(null); @@ -422,7 +426,9 @@ var ListViewModel = function() { $.ajax("api/entries/" + ko.utils.unwrapObservable(item.id), {type: "DELETE"}).success(function (result) { // Reload accounts to update solds. self.loadAccounts(); - }).complete(function (result) { + }).success(function (data) { + message("success", "Delete", data); + }).complete(function (data) { // Reset removed item to null and hide the modal dialog. self.removedItem = null; $('#remove-confirm').modal('hide'); diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..dee56d2 --- /dev/null +++ b/src/main.py @@ -0,0 +1,10 @@ +from app import app + +from static import * + +from api.controller.entries import * +from api.controller.accounts import * + +if __name__ == '__main__': + app.run(debug=True) + diff --git a/src/static.py b/src/static.py new file mode 100644 index 0000000..6873d69 --- /dev/null +++ b/src/static.py @@ -0,0 +1,13 @@ +from app import app + +from flask import send_from_directory + +@app.route('/') +def index(): + return send_from_directory("html", "index.html") + +@app.route('//') +def static(path, filename): + return send_from_directory("html/%s" % path, filename) + +