<commit_before><?php
/**
 * Slim
 *
 * A simple PHP framework for PHP 5 or newer
 *
 * @author		<NAME> <<EMAIL>>
 * @link		http://slim.joshlockhart.com
 * @copyright	2010 <NAME>
 *
 * 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.
 */

//Ensure expected constants are available
if ( !defined('MCRYPT_RIJNDAEL_256') ) {
	define('MCRYPT_RIJNDAEL_256', 0);
}
if ( !defined('MCRYPT_MODE_CBC') ) {
	define('MCRYPT_MODE_CBC', 0);
}
	
//Set which errors are reported by PHP and logged by Slim
error_reporting(E_ALL | E_STRICT);

//This will handle errors
set_error_handler(array('Slim', 'handleErrors'));

//This will handle uncaught exceptions
set_exception_handler(array('Slim', 'handleExceptions'));

//Slim will auto-load class files in the same directory as Slim.php
spl_autoload_register(array('Slim', 'autoload'));

//Ensure a valid TimeZone is set
if ( @date_default_timezone_set(date_default_timezone_get()) === false ) {
	date_default_timezone_set('UTC');
}

/**
 * Slim
 *
 * This is the primary class for the Slim framework that organizes
 * requests, responses, views, and the routers. This also provides
 * helper methods to control the flow of your Slim application.
 *
 * @package	Slim
 * @author	<NAME> <<EMAIL>>
 * @since	Version 1.0
 */
class Slim {

	//Constants helpful when triggering errors or calling Slim::log()
	const ERROR = 256;
	const WARNING = 512;
	const NOTICE = 1024;

	/**
	 * @var Slim The application instance
	 */
	protected static $app;

	/**
	 * @var Request
	 */
	private $request;

	/**
	 * @var Response
	 */
	private $response;

	/**
	 * @var Router
	 */
	private $router;

	/**
	 * @var View
	 */
	private $view;
	
	/**
	 * @var mixed The Logger
	 */
	private $logger;

	/**
	 * @var array Before callbacks
	 */
	private $before;

	/**
	 * @var array After callbacks
	 */
	private $after;

	/**
	 * @var array Application settings
	 */
	private $settings = array();

	/**
	 * @var array Plugin hooks
	 */
	private $hooks = array(
		'slim.before' => array(),
		'slim.before.router' => array(),
		'slim.before.dispatch' => array(),
		'slim.after.dispatch' => array(),
		'slim.after.router' => array(),
		'slim.after' => array()
	);

	/**
	 * Slim auto-loader
	 *
	 * This method allows Slim to lazy-load class files as
	 * the classes are first instantiated. This method expects
	 * the class files to exist in the same directory as the
	 * primary Slim class definition.
	 *
	 * @return void
	 */
	public static function autoload( $className ) {
		if ( file_exists($file = dirname(__FILE__) . '/' . $className . '.php') ) {
			require_once($file);
		}
	}

	/**
	 * Handle errors
	 *
	 * This is the global Error handler that will catch uncaught errors
	 * and display a nice-looking page with details about the error.
	 *
	 * @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  void
	 */
	public static function handleErrors( $errno, $errstr = '', $errfile = '', $errline = '' ) {
		if ( !(error_reporting() & $errno) ) {
			return;
		}
		Slim::log(sprintf("Message: %s | File: %s | Line: %d", $errstr, $errfile, $errline), $errno);
		if ( self::config('debug') === true ) {
			Slim::halt(500, self::generateErrorMarkup($errstr, $errfile, $errline));
		} else {
			self::error();
		}
		die();
	}

	/**
	 * Handle exceptions
	 *
	 * This is the global Exception handler that will catch uncaught exceptions
	 * and display a nice-looking page with details about the exception.
	 *
	 * @param   Exception $e
	 * @return  void
	 */
	public static function handleExceptions( Exception $e ) {
		if ( $e instanceof SlimStopException === false ) {
			Slim::log(sprintf("Message: %s | File: %s | Line: %d", $e->getMessage(), $e->getFile(), $e->getLine()));
			if ( self::config('debug') === true ) {
				Slim::halt(500, self::generateErrorMarkup($e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString()));
			} else {
				self::error();
			}
		}
		die();
	}

	/**
	 * Generate markup for error message
	 *
	 * This method accepts details about an error or exception and
	 * generates HTML markup for the 500 response body that will
	 * be sent to the client.
	 *
	 * @param   string  $message    The error message
	 * @param   string  $file       The absolute file path to the affected file
	 * @param   int     $line       The line number in the affected file
	 * @param   string  $trace      A stack trace of the error
	 * @return  string
	 */
	private static function generateErrorMarkup( $message, $file = '', $line = '', $trace = '' ) {
		$body = '<p>The application could not run because of the following error:</p>';
		$body .= "<h2>Details:</h2><strong>Message:</strong> $message<br/>";
		if ( $file !== '' ) $body .= "<strong>File:</strong> $file<br/>";
		if ( $line !== '' ) $body .= "<strong>Line:</strong> $line<br/>";
		if ( $trace !== '' ) $body .= '<h2>Stack Trace:</h2>' . nl2br($trace);
		return self::generateTemplateMarkup('Slim Application Error', $body);
	}

	/**
	 * Generate default template markup
	 *
	 * This method accepts a title and body content to generate
	 * an HTML page. This is primarily used to generate the markup
	 * for Error handlers and Not Found handlers.
	 *
	 * @param	string	$title The title of the HTML template
	 * @param	string	$body The body content of the HTML template
	 * @return 	string
	 */
	private static function generateTemplateMarkup( $title, $body ) {
		$html = "<html><head><title>$title</title><style>body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}</style></head><body>";
		$html .= "<h1>$title</h1>";
		$html .= $body;
		$html .= '</body></html>';
		return $html;
	}


	/***** INITIALIZER *****/

	/**
	 * Constructor
	 *
	 * This method instantiates the Slim application
	 * instance, the Request, the Response, the Router,
	 * the before callbacks, the after callbacks, and the
	 * default application settings.
	 *
	 * @param array $userSettings
	 */
	private function __construct( $userSettings = array() ) {
		$this->settings = array_merge(array(
			//Logging
			'log.enable' => false,
			'log.logger' => null,
			'log.path' => './logs',
			'log.level' => 4,
			//Debugging
			'debug' => true,
			//View
			'templates_dir' => './templates',
			'view' => 'View',
			//Settings for all cookies
			'cookies.lifetime' => '20 minutes',
			'cookies.path' => '/',
			'cookies.domain' => '',
			'cookies.secure' => false,
			'cookies.httponly' => false,
			//Settings for encrypted cookies
			'cookies.secret_key' => 'CHANGE_ME',
			'cookies.cipher' => MCRYPT_RIJNDAEL_256,
			'cookies.cipher_mode' => MCRYPT_MODE_CBC,
			'cookies.encrypt' => true,
			'cookies.user_id' => 'DEFAULT'
		), $userSettings);
		$this->request = new Request();
		$this->response = new Response();
		$this->router = new Router( $this->request );
		$this->response->setCookieJar(new CookieJar($this->settings['cookies.secret_key'], array(
			'high_confidentiality' => $this->settings['cookies.encrypt'],
			'mcrypt_algorithm' => $this->settings['cookies.cipher'],
			'mcrypt_mode' => $this->settings['cookies.cipher_mode'],
			'enable_ssl' => $this->settings['cookies.secure']
		)));
		if ( $this->settings['log.enable'] ) {
			if ( empty($this->settings['log.logger']) ) {
				$this->logger = new Logger($this->settings['log.path'], $this->settings['log.level']);
			} else {
				$this->logger = $this->settings['log.logger'];<commit_msg>Integrating Log adapdapter into Slim::init<commit_after><?php
/**
 * Slim
 *
 * A simple PHP framework for PHP 5 or newer
 *
 * @author		<NAME> <<EMAIL>>
 * @link		http://slim.joshlockhart.com
 * @copyright	2010 <NAME>
 *
 * 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.
 */

//Ensure expected constants are available
if ( !defined('MCRYPT_RIJNDAEL_256') ) {
	define('MCRYPT_RIJNDAEL_256', 0);
}
if ( !defined('MCRYPT_MODE_CBC') ) {
	define('MCRYPT_MODE_CBC', 0);
}
	
//Set which errors are reported by PHP and logged by Slim
error_reporting(E_ALL | E_STRICT);

//This will handle errors
set_error_handler(array('Slim', 'handleErrors'));

//This will handle uncaught exceptions
set_exception_handler(array('Slim', 'handleExceptions'));

//Slim will auto-load class files in the same directory as Slim.php
spl_autoload_register(array('Slim', 'autoload'));

//Ensure a valid TimeZone is set
if ( @date_default_timezone_set(date_default_timezone_get()) === false ) {
	date_default_timezone_set('UTC');
}

/**
 * Slim
 *
 * This is the primary class for the Slim framework that organizes
 * requests, responses, views, and the routers. This also provides
 * helper methods to control the flow of your Slim application.
 *
 * @package	Slim
 * @author	<NAME> <<EMAIL>>
 * @since	Version 1.0
 */
class Slim {

	//Constants helpful when triggering errors or calling Slim::log()
	const ERROR = 256;
	const WARNING = 512;
	const NOTICE = 1024;

	/**
	 * @var Slim The application instance
	 */
	protected static $app;

	/**
	 * @var Request
	 */
	private $request;

	/**
	 * @var Response
	 */
	private $response;

	/**
	 * @var Router
	 */
	private $router;

	/**
	 * @var View
	 */
	private $view;
	
	/**
	 * @var mixed The Logger
	 */
	private $logger;

	/**
	 * @var array Before callbacks
	 */
	private $before;

	/**
	 * @var array After callbacks
	 */
	private $after;

	/**
	 * @var array Application settings
	 */
	private $settings = array();

	/**
	 * @var array Plugin hooks
	 */
	private $hooks = array(
		'slim.before' => array(),
		'slim.before.router' => array(),
		'slim.before.dispatch' => array(),
		'slim.after.dispatch' => array(),
		'slim.after.router' => array(),
		'slim.after' => array()
	);

	/**
	 * Slim auto-loader
	 *
	 * This method allows Slim to lazy-load class files as
	 * the classes are first instantiated. This method expects
	 * the class files to exist in the same directory as the
	 * primary Slim class definition.
	 *
	 * @return void
	 */
	public static function autoload( $className ) {
		if ( file_exists($file = dirname(__FILE__) . '/' . $className . '.php') ) {
			require_once($file);
		}
	}

	/**
	 * Handle errors
	 *
	 * This is the global Error handler that will catch uncaught errors
	 * and display a nice-looking page with details about the error.
	 *
	 * @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  void
	 */
	public static function handleErrors( $errno, $errstr = '', $errfile = '', $errline = '' ) {
		if ( !(error_reporting() & $errno) ) {
			return;
		}
		Slim::log(sprintf("Message: %s | File: %s | Line: %d", $errstr, $errfile, $errline), $errno);
		if ( self::config('debug') === true ) {
			Slim::halt(500, self::generateErrorMarkup($errstr, $errfile, $errline));
		} else {
			self::error();
		}
		die();
	}

	/**
	 * Handle exceptions
	 *
	 * This is the global Exception handler that will catch uncaught exceptions
	 * and display a nice-looking page with details about the exception.
	 *
	 * @param   Exception $e
	 * @return  void
	 */
	public static function handleExceptions( Exception $e ) {
		if ( $e instanceof SlimStopException === false ) {
			Slim::log(sprintf("Message: %s | File: %s | Line: %d", $e->getMessage(), $e->getFile(), $e->getLine()));
			if ( self::config('debug') === true ) {
				Slim::halt(500, self::generateErrorMarkup($e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString()));
			} else {
				self::error();
			}
		}
		die();
	}

	/**
	 * Generate markup for error message
	 *
	 * This method accepts details about an error or exception and
	 * generates HTML markup for the 500 response body that will
	 * be sent to the client.
	 *
	 * @param   string  $message    The error message
	 * @param   string  $file       The absolute file path to the affected file
	 * @param   int     $line       The line number in the affected file
	 * @param   string  $trace      A stack trace of the error
	 * @return  string
	 */
	private static function generateErrorMarkup( $message, $file = '', $line = '', $trace = '' ) {
		$body = '<p>The application could not run because of the following error:</p>';
		$body .= "<h2>Details:</h2><strong>Message:</strong> $message<br/>";
		if ( $file !== '' ) $body .= "<strong>File:</strong> $file<br/>";
		if ( $line !== '' ) $body .= "<strong>Line:</strong> $line<br/>";
		if ( $trace !== '' ) $body .= '<h2>Stack Trace:</h2>' . nl2br($trace);
		return self::generateTemplateMarkup('Slim Application Error', $body);
	}

	/**
	 * Generate default template markup
	 *
	 * This method accepts a title and body content to generate
	 * an HTML page. This is primarily used to generate the markup
	 * for Error handlers and Not Found handlers.
	 *
	 * @param	string	$title The title of the HTML template
	 * @param	string	$body The body content of the HTML template
	 * @return 	string
	 */
	private static function generateTemplateMarkup( $title, $body ) {
		$html = "<html><head><title>$title</title><style>body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}</style></head><body>";
		$html .= "<h1>$title</h1>";
		$html .= $body;
		$html .= '</body></html>';
		return $html;
	}


	/***** INITIALIZER *****/

	/**
	 * Constructor
	 *
	 * This method instantiates the Slim application
	 * instance, the Request, the Response, the Router,
	 * the before callbacks, the after callbacks, and the
	 * default application settings.
	 *
	 * @param array $userSettings
	 */
	private function __construct( $userSettings = array() ) {
		$this->settings = array_merge(array(
			//Logging
			'log.enable' => false,
			'log.logger' => null,
			'log.path' => './logs',
			'log.level' => 4,
			//Debugging
			'debug' => true,
			//View
			'templates_dir' => './templates',
			'view' => 'View',
			//Settings for all cookies
			'cookies.lifetime' => '20 minutes',
			'cookies.path' => '/',
			'cookies.domain' => '',
			'cookies.secure' => false,
			'cookies.httponly' => false,
			//Settings for encrypted cookies
			'cookies.secret_key' => 'CHANGE_ME',
			'cookies.cipher' => MCRYPT_RIJNDAEL_256,
			'cookies.cipher_mode' => MCRYPT_MODE_CBC,
			'cookies.encrypt' => true,
			'cookies.user_id' => 'DEFAULT'
		), $userSettings);
		$this->request = new Request();
		$this->response = new Response();
		$this->router = new Router( $this->request );
		$this->response->setCookieJar(new CookieJar($this->settings['cookies.secret_key'], array(
			'high_confidentiality' => $this->settings['cookies.encrypt'],
			'mcrypt_algorithm' => $this->settings['cookies.cipher'],
			'mcrypt_mode' => $this->settings['cookies.cipher_mode'],
			'enable_ssl' => $this->settings['cookies.secure']
		)));
		if ( $this->settings['log.enable'] === true ) {
			if ( empty($this->settings['log.logger']) ) {
				Log::setLogger(new Logger($this->settings['log.path'], $this->settings['log.level']));
			} else {
				Log::setLogger($this->settings['log.logger']);
{'fraction_non_alphanumeric': 0.14656060432642784, 'fraction_numerical': 0.007096257296554881, 'mean_word_length': 3.619349722442506, 'pattern_counts': {'":': 0, '<': 73, '<?xml version=': 0, '>': 175, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6666461', 'n_tokens_mistral': 5954, 'n_tokens_neox': 5333, 'n_words': 1734}