From 6e12a6481f42368a3b78e25ba7c0533d22fe3ce2 Mon Sep 17 00:00:00 2001 From: Soban Vuex Date: Sat, 22 Dec 2012 02:57:44 -0500 Subject: [PATCH 01/16] Newrelic Middleware --- Middleware/Newrelic.php | 109 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 Middleware/Newrelic.php diff --git a/Middleware/Newrelic.php b/Middleware/Newrelic.php new file mode 100644 index 0000000..17b0a99 --- /dev/null +++ b/Middleware/Newrelic.php @@ -0,0 +1,109 @@ +add(new \Slim\Extras\Middleware\Newrelic()); + * + */ +namespace Slim\Extras\Middleware; + +class Newrelic extends \Slim\Middleware +{ + /** + * Newrelic extension status + * + * @var boolean + */ + private $_extensionLoaded = null; + + /** + * Newrelic variable + * + * @var string + */ + private $_transaction = null; + /** + * Constructor. + * + * @return void + */ + public function __construct() + { + } + + /** + * Call middleware. + * + * @return void + */ + public function call() + { + // Attach hooks. + $this->app->hook("slim.after.router", array($this, "setTransactionName")); + $this->app->hook("slim.after", array($this, "nameTransaction")); + + // Call next middleware. + $this->next->call(); + } + + /** + * Newrelic transaction name API + * + * @return void + */ + public function nameTransaction() + { + if ($this->extensionLoaded()) { + newrelic_name_transaction($this->getTransactionName()); + } + } + + /** + * Set transaction name + * + * @return void + */ + public function setTransactionName() + { + // Set the transaction name based on the path info + // TODO: Handle route parameters + $this->_transaction = $this->app->request()->getPathInfo(); + } + + /** + * Get transaction name + * + * @return void + */ + public function getTransactionName() + { + if (null === $this->_transaction) { + $this->setTransactionName(); + } + + return $this->_transaction; + } + + /** + * Check if Newrelic extension is loaded + * + * @return boolean + */ + public function extensionLoaded() + { + // Check if the extension is loaded and store the result + if (null === $this->_extensionLoaded) { + $this->_extensionLoaded = extension_loaded("newrelic"); + } + + // Return + return $this->_extensionLoaded; + } + +} From ccdee8ed1f2470e5785ed35ee241a1027fdf1879 Mon Sep 17 00:00:00 2001 From: Soban Vuex Date: Sat, 22 Dec 2012 03:02:06 -0500 Subject: [PATCH 02/16] Newrelic Middleware --- Middleware/README.markdown | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Middleware/README.markdown b/Middleware/README.markdown index 6a9b0f1..de46fcc 100644 --- a/Middleware/README.markdown +++ b/Middleware/README.markdown @@ -29,6 +29,19 @@ This will provide you with basic user Authentication based on username and passw $app->add(new HttpBasicAuth('theUsername', 'thePassword')); +## Newrelic + +This will provde basic transaction tracking for newrelic.com users + +### How to use + + use \Slim\Slim; + use \Slim\Extras\Middleware\Newrelic; + + $app = new Slim(); + $app->add(new Newrelic()); + + ## Strong ### How to use From 06dae952488e398119bcc44af0765d781b490f84 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Sat, 19 Jan 2013 17:22:20 -0800 Subject: [PATCH 03/16] Mustache_Autoloader should only be used as fallback. If Composer is already handling autoloading the Mustache library, no need to require and register Mustache_Autoloader. --- Views/Mustache.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Views/Mustache.php b/Views/Mustache.php index 6b14b2d..1368ddf 100644 --- a/Views/Mustache.php +++ b/Views/Mustache.php @@ -58,8 +58,12 @@ class Mustache extends \Slim\View */ public function render($template) { - require_once self::$mustacheDirectory . '/Autoloader.php'; - \Mustache_Autoloader::register(dirname(self::$mustacheDirectory)); + // Check for Composer autoloading + if (!class_exists('\Mustache_Engine')) { + require_once self::$mustacheDirectory . '/Autoloader.php'; + \Mustache_Autoloader::register(dirname(self::$mustacheDirectory)); + } + $m = new \Mustache_Engine(); $contents = file_get_contents($this->getTemplatesDirectory() . '/' . ltrim($template, '/')); return $m->render($contents, $this->data); From 0bfda87e8f814535cd7bf4122a286fffcead0156 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Sat, 19 Jan 2013 17:29:47 -0800 Subject: [PATCH 04/16] Only instantiate a single Mustache_Engine. --- Views/Mustache.php | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/Views/Mustache.php b/Views/Mustache.php index 1368ddf..065b75b 100644 --- a/Views/Mustache.php +++ b/Views/Mustache.php @@ -49,6 +49,11 @@ class Mustache extends \Slim\View */ public static $mustacheDirectory = null; + /** + * @var \Mustache_Engine A Mustache engine instance for this view + */ + private $engine; + /** * Renders a template using Mustache.php. * @@ -58,14 +63,28 @@ class Mustache extends \Slim\View */ public function render($template) { - // Check for Composer autoloading - if (!class_exists('\Mustache_Engine')) { - require_once self::$mustacheDirectory . '/Autoloader.php'; - \Mustache_Autoloader::register(dirname(self::$mustacheDirectory)); - } - - $m = new \Mustache_Engine(); + $m = $this->getEngine(); $contents = file_get_contents($this->getTemplatesDirectory() . '/' . ltrim($template, '/')); return $m->render($contents, $this->data); } + + /** + * Get a \Mustache_Engine instance. + * + * @return \Mustache_Engine + */ + private function getEngine() + { + if (!isset($this->engine)) { + // Check for Composer autoloading + if (!class_exists('\Mustache_Engine')) { + require_once self::$mustacheDirectory . '/Autoloader.php'; + \Mustache_Autoloader::register(dirname(self::$mustacheDirectory)); + } + + $this->engine = new \Mustache_Engine(); + } + + return $this->engine; + } } From 80f68f0d801536f4e9777310ee2a85bbec1e8134 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Sat, 19 Jan 2013 17:33:45 -0800 Subject: [PATCH 05/16] Don't manually load template contents. Use a \Mustache_Loader_FilesystemLoader instance instead. This saves us some code, and makes it so loading partials works too :) --- Views/Mustache.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Views/Mustache.php b/Views/Mustache.php index 065b75b..200feeb 100644 --- a/Views/Mustache.php +++ b/Views/Mustache.php @@ -63,9 +63,7 @@ class Mustache extends \Slim\View */ public function render($template) { - $m = $this->getEngine(); - $contents = file_get_contents($this->getTemplatesDirectory() . '/' . ltrim($template, '/')); - return $m->render($contents, $this->data); + return $this->getEngine()->render($template, $this->data); } /** @@ -82,7 +80,10 @@ private function getEngine() \Mustache_Autoloader::register(dirname(self::$mustacheDirectory)); } - $this->engine = new \Mustache_Engine(); + $this->engine = new \Mustache_Engine(array( + // Autoload templates (and partials) from the templates directory. + 'loader' => new \Mustache_Loader_FilesystemLoader($this->getTemplatesDirectory()), + )); } return $this->engine; From 541897c94afb4bfc87ed814059bc5b53a5aa5282 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Sat, 19 Jan 2013 17:47:16 -0800 Subject: [PATCH 06/16] Allow specifying \Mustache_Engine configuration. --- Views/Mustache.php | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/Views/Mustache.php b/Views/Mustache.php index 200feeb..1ab84ae 100644 --- a/Views/Mustache.php +++ b/Views/Mustache.php @@ -49,10 +49,25 @@ class Mustache extends \Slim\View */ public static $mustacheDirectory = null; + /** + * @var array An array of \Mustache_Engine options + */ + public static $mustacheOptions = array(); + /** * @var \Mustache_Engine A Mustache engine instance for this view */ - private $engine; + private $engine = null; + + /** + * @param array $options \Mustache_Engine configuration options + */ + public function __construct(array $options = null) + { + if ($options !== null) { + self::$mustacheOptions = $options; + } + } /** * Renders a template using Mustache.php. @@ -80,10 +95,14 @@ private function getEngine() \Mustache_Autoloader::register(dirname(self::$mustacheDirectory)); } - $this->engine = new \Mustache_Engine(array( - // Autoload templates (and partials) from the templates directory. - 'loader' => new \Mustache_Loader_FilesystemLoader($this->getTemplatesDirectory()), - )); + $options = self::$mustacheOptions; + + // Autoload templates from the templates directory. + if (!isset($options['loader'])) { + $options['loader'] = new \Mustache_Loader_FilesystemLoader($this->getTemplatesDirectory()); + } + + $this->engine = new \Mustache_Engine($options); } return $this->engine; From b12fdd069062a0d30d1584aad3aa5bd76c275c5e Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Sat, 19 Jan 2013 17:47:52 -0800 Subject: [PATCH 07/16] Use default loader for partials if none specified. --- Views/Mustache.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Views/Mustache.php b/Views/Mustache.php index 1ab84ae..190602c 100644 --- a/Views/Mustache.php +++ b/Views/Mustache.php @@ -102,6 +102,11 @@ private function getEngine() $options['loader'] = new \Mustache_Loader_FilesystemLoader($this->getTemplatesDirectory()); } + // If a partials loader is not specified, fall back to the default template loader. + if (!isset($options['partials_loader']) && !isset($options['partials'])) { + $options['partials_loader'] = $options['loader']; + } + $this->engine = new \Mustache_Engine($options); } From 4dc6d1b476c7f347fcafbc1ace55eda8e1d86318 Mon Sep 17 00:00:00 2001 From: SobanVuex Date: Wed, 23 Jan 2013 16:18:30 -0500 Subject: [PATCH 08/16] Newrelic.md --- Middleware/Newrelic.md | 11 +++++++++++ Middleware/README.markdown | 13 ------------- 2 files changed, 11 insertions(+), 13 deletions(-) create mode 100644 Middleware/Newrelic.md diff --git a/Middleware/Newrelic.md b/Middleware/Newrelic.md new file mode 100644 index 0000000..56245c5 --- /dev/null +++ b/Middleware/Newrelic.md @@ -0,0 +1,11 @@ +## Newrelic + +This will provde basic transaction tracking for newrelic.com users + +### How to use + + use \Slim\Slim; + use \Slim\Extras\Middleware\Newrelic; + + $app = new Slim(); + $app->add(new Newrelic()); diff --git a/Middleware/README.markdown b/Middleware/README.markdown index 0432d9a..e19a5a5 100644 --- a/Middleware/README.markdown +++ b/Middleware/README.markdown @@ -29,19 +29,6 @@ This will provide you with basic user Authentication based on username and passw $app->add(new HttpBasicAuth('theUsername', 'thePassword')); -## Newrelic - -This will provde basic transaction tracking for newrelic.com users - -### How to use - - use \Slim\Slim; - use \Slim\Extras\Middleware\Newrelic; - - $app = new Slim(); - $app->add(new Newrelic()); - - ## Strong ### How to use From d8d0d11a2030d054e04acf6c1d7525faec743f63 Mon Sep 17 00:00:00 2001 From: SobanVuex Date: Wed, 23 Jan 2013 18:32:06 -0500 Subject: [PATCH 09/16] Newrelic.md > Newrelic.markdown --- Middleware/Newrelic.markdown | 52 ++++++++++++++++++++++++++++++++++++ Middleware/Newrelic.md | 11 -------- 2 files changed, 52 insertions(+), 11 deletions(-) create mode 100644 Middleware/Newrelic.markdown delete mode 100644 Middleware/Newrelic.md diff --git a/Middleware/Newrelic.markdown b/Middleware/Newrelic.markdown new file mode 100644 index 0000000..1376d2b --- /dev/null +++ b/Middleware/Newrelic.markdown @@ -0,0 +1,52 @@ +## Newrelic + +Basic integration for [NewRelic](http://newrelic.com) + +How to use +---------- + + - Basic + ``` php + use \Slim\Slim; + use \Slim\Extras\Middleware\Newrelic; + + $app = new Slim(); + $app->add(new Newrelic()); + ``` + + - Custom Application name + ``` php + $app->add(new Newrelic(array( + 'newrelic.appname' => 'New Application Name', + ))); + ``` + + - Custom Transaction name + ``` php + $app->get('/index', function() use ($app) + { + Newrelic::option('transaction.name', 'myIndex'); + ))); + ``` + + - Insert Newrelic browser timing headers + ``` php + $app->get('/index', function() use ($app) + { + $view = $app->view(); + $view->setData(array( + 'rumHeader', Newrelic::getRumHeader(), + 'rumFooter', Newrelic::getRumFooter(), + ); + ))); + ``` + + ``` php + + + + ... +
+ +
+ ``` diff --git a/Middleware/Newrelic.md b/Middleware/Newrelic.md deleted file mode 100644 index 56245c5..0000000 --- a/Middleware/Newrelic.md +++ /dev/null @@ -1,11 +0,0 @@ -## Newrelic - -This will provde basic transaction tracking for newrelic.com users - -### How to use - - use \Slim\Slim; - use \Slim\Extras\Middleware\Newrelic; - - $app = new Slim(); - $app->add(new Newrelic()); From af9835b24a38b1a5488d9386a632fdb2740633d5 Mon Sep 17 00:00:00 2001 From: SobanVuex Date: Wed, 23 Jan 2013 18:34:37 -0500 Subject: [PATCH 10/16] Newrelic Middleware --- Middleware/Newrelic.php | 148 ++++++++++++++++++++++++++++++++-------- 1 file changed, 120 insertions(+), 28 deletions(-) diff --git a/Middleware/Newrelic.php b/Middleware/Newrelic.php index 17b0a99..a5de153 100644 --- a/Middleware/Newrelic.php +++ b/Middleware/Newrelic.php @@ -5,36 +5,71 @@ * Use this middleware with your Slim Framework application * to track your transactions with newrelic.com * + * @author Alex Soban + * @version 1.0 + * @copyright 2013 Alex Soban + * * USAGE * - * $app = new \Slim\Slim(); - * $app->add(new \Slim\Extras\Middleware\Newrelic()); + * use \Slim\Slim; + * use \Slim\Extras\Middleware\Newrelic; + * + * $app = new Slim(); + * $app->add(new Newrelic(array( + * "newrelic.appname" => ini_get("newrelic.appname") | "AppName", + * ))); + * + * 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\Extras\Middleware; class Newrelic extends \Slim\Middleware { /** - * Newrelic extension status + * Extension status * * @var boolean */ - private $_extensionLoaded = null; + protected static $_extensionLoaded; /** - * Newrelic variable + * Middleware configuration * - * @var string + * @var array */ - private $_transaction = null; + protected static $_options = array( + 'newrelic.appname' => null, + 'transaction.method' => false, + ); + /** * Constructor. * + * @param array $config Configuration options * @return void */ - public function __construct() + public function __construct(array $config = array()) { + static::$_options = array_merge(static::$_options, $config); } /** @@ -45,13 +80,48 @@ public function __construct() public function call() { // Attach hooks. - $this->app->hook("slim.after.router", array($this, "setTransactionName")); - $this->app->hook("slim.after", array($this, "nameTransaction")); + $this->app->hook('slim.before', array($this, 'setAppName'), 0); + $this->app->hook('slim.before.dispatch', array($this, 'setTransactionName'), 0); + $this->app->hook('slim.after.dispatch', array($this, 'nameTransaction'), 0); // Call next middleware. $this->next->call(); } + /** + * Get/Set Options + * + * @param string $key Option name + * @param mixed $value (Optional) Value of the option + * @return mixed + */ + public function option($key, $value = null) + { + // Set option + if (!empty($value)) { + static::$_options[$key] = $value; + } + + // Get option + if (array_key_exists($key, static::$_options)) { + return static::$_options[$key]; + } + + return null; + } + + /** + * Newrelic application name API + * + * @return void + */ + public function setAppName() + { + if ($this->extensionLoaded() && $this->option('newrelic.appname')) { + newrelic_set_appname($this->option('newrelic.appname')); + } + } + /** * Newrelic transaction name API * @@ -59,35 +129,58 @@ public function call() */ public function nameTransaction() { - if ($this->extensionLoaded()) { - newrelic_name_transaction($this->getTransactionName()); + if ($this->extensionLoaded() && $this->option('transaction.name')) { + newrelic_name_transaction($this->option('transaction.name')); } } /** - * Set transaction name + * Newrelic browser timing header (RUM) API * - * @return void + * @param boolean $scriptTag Should the API return with + * @return mixed */ - public function setTransactionName() + public function getRumHeader($scriptTag = true) { - // Set the transaction name based on the path info - // TODO: Handle route parameters - $this->_transaction = $this->app->request()->getPathInfo(); + if (static::extensionLoaded()) { + return newrelic_get_browser_timing_header($scriptTag); + } + + return null; } /** - * Get transaction name + * Newrelic browser timing footer (RUM) API * - * @return void + * @param boolean $scriptTag Should the API return with + * @return mixed */ - public function getTransactionName() + public function getRumFooter($scriptTag = true) { - if (null === $this->_transaction) { - $this->setTransactionName(); + if (static::extensionLoaded()) { + return newrelic_get_browser_timing_footer($scriptTag); } - return $this->_transaction; + return null; + } + + /** + * Set transaction name + * + * @return void + */ + public function setTransactionName() + { + if ($this->option('transaction.method')) { + // Set the transaction name using Method and PathInfo + $this->option( + 'transaction.name', + $this->app->request()->getMethod() . $this->app->request()->getPathInfo() + ); + } else { + // Set the transaction name PathInfo + $this->option('transaction.name', $this->app->request()->getPathInfo()); + } } /** @@ -98,12 +191,11 @@ public function getTransactionName() public function extensionLoaded() { // Check if the extension is loaded and store the result - if (null === $this->_extensionLoaded) { - $this->_extensionLoaded = extension_loaded("newrelic"); + if (null === static::$_extensionLoaded) { + static::$_extensionLoaded = extension_loaded('newrelic'); } - // Return - return $this->_extensionLoaded; + return static::$_extensionLoaded; } } From 19d10d7c43b4a135ffeb12f03ea25bfaee8aa08c Mon Sep 17 00:00:00 2001 From: Mika Tuupola Date: Sun, 17 Feb 2013 00:32:49 +0200 Subject: [PATCH 11/16] Allow passing format string for log date format. Allows you to initialize logger with something like following: $app = new \Slim\Slim(array( "log.writer" => new \Slim\Extras\Log\DateTimeFileWriter(array( "path" => "./logs", "name_format" => "Y-m-d", "date_format" => "Y-m-d H:i:s", "message_format" => "%label% [%date%] %message%" )) )); --- Log/DateTimeFileWriter.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) mode change 100755 => 100644 Log/DateTimeFileWriter.php diff --git a/Log/DateTimeFileWriter.php b/Log/DateTimeFileWriter.php old mode 100755 new mode 100644 index 9f5e587..60eb023 --- a/Log/DateTimeFileWriter.php +++ b/Log/DateTimeFileWriter.php @@ -86,6 +86,7 @@ public function __construct($settings = array()) $this->settings = array_merge(array( 'path' => './logs', 'name_format' => 'Y-m-d', + 'date_format' => 'c', 'extension' => 'log', 'message_format' => '%label% - %date% - %message%' ), $settings); @@ -127,7 +128,7 @@ public function write($object, $level) '%message%' ), array( $label, - date('c'), + date($this->settings['date_format']), (string)$object ), $this->settings['message_format']); From e930e67172c2548dbc302b05370851862020fb0d Mon Sep 17 00:00:00 2001 From: Timothy Boronczyk Date: Tue, 19 Feb 2013 19:28:36 -0500 Subject: [PATCH 12/16] Committing cache middleware --- Middleware/Cache.php | 75 ++++++++++++++++++++++++++++++ Middleware/Cache/CacheHandler.php | 74 +++++++++++++++++++++++++++++ Middleware/Cache/ICacheHandler.php | 55 ++++++++++++++++++++++ Middleware/Cache/cache.sql | 6 +++ Middleware/README.markdown | 19 ++++++++ 5 files changed, 229 insertions(+) create mode 100644 Middleware/Cache.php create mode 100644 Middleware/Cache/CacheHandler.php create mode 100644 Middleware/Cache/ICacheHandler.php create mode 100644 Middleware/Cache/cache.sql diff --git a/Middleware/Cache.php b/Middleware/Cache.php new file mode 100644 index 0000000..eb101fe --- /dev/null +++ b/Middleware/Cache.php @@ -0,0 +1,75 @@ +add(new Cache($handler)); + * + * 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\Extras\Middleware; +use \Slim\Extras\Middleware\Cache\ICacheHandler; + +class Cache extends \Slim\Middleware +{ + protected $handler; + + public function __construct(ICacheHandler $handler) + { + $this->handler = $handler; + } + + public function call() + { + $req = $this->app->request(); + $resp = $this->app->response(); + $handler = $this->handler; + + $key = $req->getResourceUri(); + $data = $handler->fetch($key); + if ($data) { + $resp['Content-Type'] = $data['content_type']; + $resp->body($data['body']); + return; + } + + $this->next->call(); + + if ($resp->status() == 200) { + $handler->save($key, $resp['Content-Type'], $resp->body()); + } + } +} diff --git a/Middleware/Cache/CacheHandler.php b/Middleware/Cache/CacheHandler.php new file mode 100644 index 0000000..983af11 --- /dev/null +++ b/Middleware/Cache/CacheHandler.php @@ -0,0 +1,74 @@ +db = $db; + $this->ttl = $ttl; + } + + public function fetch($key) + { + $query = sprintf( + 'SELECT `content_type`, `body` FROM `cache` + WHERE `key` = %s AND `tstamp` > %d', + $this->db->quote(md5($key)), + time() - $this->ttl + ); + $result = $this->db->query($query); + $row = $result->fetch(\PDO::FETCH_ASSOC); + $result->closeCursor(); + return $row; + } + + public function save($key, $contentType, $body) + { + $query = sprintf( + 'INSERT INTO `cache` (`key`, `content_type`, `body`, `tstamp`) + VALUES (%s, %s, %s, %d) + ON DUPLICATE KEY UPDATE + `content_type` = %2$s, `body` = %3$s, `tstamp` = %4$d', + $this->db->quote(md5($key)), + $this->db->quote($contentType), + $this->db->quote($body), + time() + ); + $this->db->query($query); + } +} diff --git a/Middleware/Cache/ICacheHandler.php b/Middleware/Cache/ICacheHandler.php new file mode 100644 index 0000000..80c7350 --- /dev/null +++ b/Middleware/Cache/ICacheHandler.php @@ -0,0 +1,55 @@ +add(new Cache($handler)); + +The example implementation `CacheHandler` uses a PDO connection to a MySQL +database and the table structure included in `Cache/cache.sql`. You can write +your own handler by implementing the `ICacheHandler` interface. + ## CsrfGuard This is used to protect your website from CSRF attacks. From 2ee0e12a92b6b0cc9331618e8ff9a043468fd9ff Mon Sep 17 00:00:00 2001 From: Timothy Boronczyk Date: Tue, 19 Feb 2013 19:32:04 -0500 Subject: [PATCH 13/16] fixed formatting of addition to Middleware/README.markdown --- Middleware/README.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Middleware/README.markdown b/Middleware/README.markdown index dac5ca3..e3e1fcd 100644 --- a/Middleware/README.markdown +++ b/Middleware/README.markdown @@ -6,14 +6,14 @@ Provides basic Caching functionality. ### How to use - use \Slim\Slim; - use \Slim\Extras\Middleware\Cache; - use \Slim\Extras\Middleware\Cache\CacheHandler; - - $db = ... - $app = new Slim(); - $handler = new CacheHandler($db); - $app->add(new Cache($handler)); + use \Slim\Slim; + use \Slim\Extras\Middleware\Cache; + use \Slim\Extras\Middleware\Cache\CacheHandler; + + $db = ... + $app = new Slim(); + $handler = new CacheHandler($db); + $app->add(new Cache($handler)); The example implementation `CacheHandler` uses a PDO connection to a MySQL database and the table structure included in `Cache/cache.sql`. You can write From 9953260a7acfc5c789d1c0cf6db355f5270970d9 Mon Sep 17 00:00:00 2001 From: Timothy Boronczyk Date: Thu, 28 Feb 2013 10:25:48 -0500 Subject: [PATCH 14/16] Rename example CacheHandler class to PDOCacheHandler to be more informative. --- Middleware/Cache.php | 4 ++-- Middleware/Cache/{CacheHandler.php => PDOCacheHandler.php} | 2 +- Middleware/README.markdown | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) rename Middleware/Cache/{CacheHandler.php => PDOCacheHandler.php} (98%) diff --git a/Middleware/Cache.php b/Middleware/Cache.php index eb101fe..fe59719 100644 --- a/Middleware/Cache.php +++ b/Middleware/Cache.php @@ -12,11 +12,11 @@ * * use \Slim\Slim; * use \Slim\Extras\Middleware\Cache; - * use \Slim\Extras\Middleware\Cache\CacheHandler; + * use \Slim\Extras\Middleware\Cache\PDOCacheHandler; * * $db = ... * $app = new Slim(); - * $handler = new CacheHandler($db); + * $handler = new PDOCacheHandler($db); * $app->add(new Cache($handler)); * * MIT LICENSE diff --git a/Middleware/Cache/CacheHandler.php b/Middleware/Cache/PDOCacheHandler.php similarity index 98% rename from Middleware/Cache/CacheHandler.php rename to Middleware/Cache/PDOCacheHandler.php index 983af11..7e1fc58 100644 --- a/Middleware/Cache/CacheHandler.php +++ b/Middleware/Cache/PDOCacheHandler.php @@ -32,7 +32,7 @@ */ namespace Slim\Extras\Middleware\Cache; -class CacheHandler implements ICacheHandler +class PDOCacheHandler implements ICacheHandler { protected $db; protected $ttl; diff --git a/Middleware/README.markdown b/Middleware/README.markdown index e3e1fcd..c6d76da 100644 --- a/Middleware/README.markdown +++ b/Middleware/README.markdown @@ -8,14 +8,14 @@ Provides basic Caching functionality. use \Slim\Slim; use \Slim\Extras\Middleware\Cache; - use \Slim\Extras\Middleware\Cache\CacheHandler; + use \Slim\Extras\Middleware\Cache\PDOCacheHandler; $db = ... $app = new Slim(); - $handler = new CacheHandler($db); + $handler = new PDOCacheHandler($db); $app->add(new Cache($handler)); -The example implementation `CacheHandler` uses a PDO connection to a MySQL +The example implementation `PDOCacheHandler` uses a PDO connection to a MySQL database and the table structure included in `Cache/cache.sql`. You can write your own handler by implementing the `ICacheHandler` interface. From d2d2ca5d0e6ac8994111a8fee6ebe640101a448f Mon Sep 17 00:00:00 2001 From: Brian Phillips Date: Fri, 26 Apr 2013 12:56:04 -0400 Subject: [PATCH 15/16] look for CSRF token in HTTP headers as well as POST parameters --- Middleware/CsrfGuard.php | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/Middleware/CsrfGuard.php b/Middleware/CsrfGuard.php index 05277af..927db74 100644 --- a/Middleware/CsrfGuard.php +++ b/Middleware/CsrfGuard.php @@ -22,19 +22,31 @@ class CsrfGuard extends \Slim\Middleware */ protected $key; + /** + * CSRF token header name. + * + * @var string + */ + protected $header; + /** * Constructor. * * @param string $key The CSRF token key name. + * @param string $header The CSRF token header name. * @return void */ - public function __construct($key = 'csrf_token') + public function __construct($key = 'csrf_token', $header = 'X-CSRFToken') { if (! is_string($key) || empty($key) || preg_match('/[^a-zA-Z0-9\-\_]/', $key)) { throw new \OutOfBoundsException('Invalid CSRF token key "' . $key . '"'); } + if (! is_string($header) || empty($header) || preg_match('/[^a-zA-Z0-9\-\_]/', $header)) { + throw new \OutOfBoundsException('Invalid CSRF token header "' . $header . '"'); + } - $this->key = $key; + $this->key = $key; + $this->header = $header; } /** @@ -71,7 +83,8 @@ public function check() { // Validate the CSRF token. if (in_array($this->app->request()->getMethod(), array('POST', 'PUT', 'DELETE'))) { - $userToken = $this->app->request()->post($this->key); + $normalized_header = str_replace('-', '_', strtoupper($this->header)); + $userToken = $this->app->request()->post($this->key) ?: $this->app->environment()[$normalized_header]; if ($token !== $userToken) { $this->app->halt(400, 'Invalid or missing CSRF token.'); } @@ -79,8 +92,9 @@ public function check() { // Assign CSRF token key and value to view. $this->app->view()->appendData(array( - 'csrf_key' => $this->key, - 'csrf_token' => $token, + 'csrf_key' => $this->key, + 'csrf_token' => $token, + 'csrf_header' => $this->header )); } -} \ No newline at end of file +} From a466f6958bd8ab5e5becc35bf830321ef5987a4f Mon Sep 17 00:00:00 2001 From: Mika Tuupola Date: Thu, 23 May 2013 15:46:49 +0300 Subject: [PATCH 16/16] PHP ActiveRecord logging via Slim logger. --- Log/ActiveRecordAdapter.php | 85 +++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 Log/ActiveRecordAdapter.php diff --git a/Log/ActiveRecordAdapter.php b/Log/ActiveRecordAdapter.php new file mode 100644 index 0000000..7bfdd3d --- /dev/null +++ b/Log/ActiveRecordAdapter.php @@ -0,0 +1,85 @@ + new \Slim\Extras\Log\DateTimeFileWriter() + * )); + * + * $connections = array( + * "development" => "mysql://example:example@mysql.example.com/example_slim;charset=utf8", + * "production" => "mysql://example:example@localhost/example_slim;charset=utf8" + * ); + * + * ActiveRecord\Config::initialize(function($cfg) use ($connections, $app) { + * $cfg->set_connections($connections); + * $cfg->set_logging(true); + * $cfg->set_logger(new \Slim\Extras\Log\ActiveRecordAdapter($app->getLog(), \Slim\Log::DEBUG)); + * }); + * + * @author Mika Tuupola + * + * 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\Extras\Log; + +class ActiveRecordAdapter { + + private $logger; + private $level; + + function __construct($logger, $level = \Slim\Log::DEBUG) { + $this->logger = $logger; + $this->level = $level; + } + + public function log($message) { + /* $this->logger->log($message, $this->level); */ + + /* \Slim\Log::log() is protected so have to do this the hard way. */ + switch($this->level) { + case \Slim\Log::FATAL: + $this->logger->fatal($message); + break; + case \Slim\Log::ERROR: + $this->logger->error($message); + break; + case \Slim\Log::WARN: + $this->logger->warn($message); + break; + case \Slim\Log::INFO: + $this->logger->info($message); + break; + case \Slim\Log::DEBUG: + $this->logger->debug($message); + break; + } + } + +}