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; + } + } + +} 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']); diff --git a/Middleware/Cache.php b/Middleware/Cache.php new file mode 100644 index 0000000..fe59719 --- /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/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 @@ +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/cache.sql b/Middleware/Cache/cache.sql new file mode 100644 index 0000000..547779a --- /dev/null +++ b/Middleware/Cache/cache.sql @@ -0,0 +1,6 @@ +CREATE TABLE `cache` ( + `key` CHAR(40) NOT NULL PRIMARY KEY, + `content_type` VARCHAR(100) NOT NULL, + `body` TEXT NOT NULL, + `tstamp` INTEGER UNSIGNED NOT NULL +); 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 +} 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.php b/Middleware/Newrelic.php new file mode 100644 index 0000000..a5de153 --- /dev/null +++ b/Middleware/Newrelic.php @@ -0,0 +1,201 @@ + + * @version 1.0 + * @copyright 2013 Alex Soban + * + * USAGE + * + * 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 +{ + /** + * Extension status + * + * @var boolean + */ + protected static $_extensionLoaded; + + /** + * Middleware configuration + * + * @var array + */ + protected static $_options = array( + 'newrelic.appname' => null, + 'transaction.method' => false, + ); + + /** + * Constructor. + * + * @param array $config Configuration options + * @return void + */ + public function __construct(array $config = array()) + { + static::$_options = array_merge(static::$_options, $config); + } + + /** + * Call middleware. + * + * @return void + */ + public function call() + { + // Attach hooks. + $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 + * + * @return void + */ + public function nameTransaction() + { + if ($this->extensionLoaded() && $this->option('transaction.name')) { + newrelic_name_transaction($this->option('transaction.name')); + } + } + + /** + * Newrelic browser timing header (RUM) API + * + * @param boolean $scriptTag Should the API return with + * @return mixed + */ + public function getRumHeader($scriptTag = true) + { + if (static::extensionLoaded()) { + return newrelic_get_browser_timing_header($scriptTag); + } + + return null; + } + + /** + * Newrelic browser timing footer (RUM) API + * + * @param boolean $scriptTag Should the API return with + * @return mixed + */ + public function getRumFooter($scriptTag = true) + { + if (static::extensionLoaded()) { + return newrelic_get_browser_timing_footer($scriptTag); + } + + 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()); + } + } + + /** + * Check if Newrelic extension is loaded + * + * @return boolean + */ + public function extensionLoaded() + { + // Check if the extension is loaded and store the result + if (null === static::$_extensionLoaded) { + static::$_extensionLoaded = extension_loaded('newrelic'); + } + + return static::$_extensionLoaded; + } + +} diff --git a/Middleware/README.markdown b/Middleware/README.markdown index e19a5a5..c6d76da 100644 --- a/Middleware/README.markdown +++ b/Middleware/README.markdown @@ -1,5 +1,24 @@ # Slim Authentication and XSS Middlewares +## Cache + +Provides basic Caching functionality. + +### How to use + + use \Slim\Slim; + use \Slim\Extras\Middleware\Cache; + use \Slim\Extras\Middleware\Cache\PDOCacheHandler; + + $db = ... + $app = new Slim(); + $handler = new PDOCacheHandler($db); + $app->add(new Cache($handler)); + +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. + ## CsrfGuard This is used to protect your website from CSRF attacks. diff --git a/Views/Mustache.php b/Views/Mustache.php index 6b14b2d..190602c 100644 --- a/Views/Mustache.php +++ b/Views/Mustache.php @@ -49,6 +49,26 @@ 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 = 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. * @@ -58,10 +78,38 @@ class Mustache extends \Slim\View */ public function render($template) { - 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); + return $this->getEngine()->render($template, $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)); + } + + $options = self::$mustacheOptions; + + // Autoload templates from the templates directory. + if (!isset($options['loader'])) { + $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); + } + + return $this->engine; } }