Initial commit

This commit is contained in:
NightBits 2018-12-19 20:44:16 +01:00
parent b680b82039
commit 878eda33b8
92 changed files with 5819 additions and 0 deletions

13
.htaccess Normal file
View File

@ -0,0 +1,13 @@
<IfModule mod_rewrite.c>
RewriteEngine On
# Tell PHP that the mod_rewrite module is ENABLED.
SetEnv HTTP_MOD_REWRITE On
# Dont redirect direct links to files or directories to the index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Rewrite all other URLs to index.php/URL
RewriteRule ^(.*)$ index.php?url=$1 [PT,L]
</IfModule>

2
README Normal file
View File

@ -0,0 +1,2 @@
This is a test version of the upcoming SuperSmash Framework
This is a simple framework that works for everyone

BIN
SuperSmash_Framework.pdf Normal file

Binary file not shown.

14
applications/.htaccess Normal file
View File

@ -0,0 +1,14 @@
RewriteEngine on
# disable directory browsing
Options All -Indexes
<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
Order Allow,Deny
Deny from all
</FilesMatch>
# turn off magic_quotes_gpc for PHP enabled servers
<ifmodule mod_php4.c>
php_flag magic_quotes_gpc off
</ifmodule>

View File

@ -0,0 +1,14 @@
RewriteEngine on
# disable directory browsing
Options All -Indexes
<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
Order Allow,Deny
Deny from all
</FilesMatch>
# turn off magic_quotes_gpc for PHP enabled servers
<ifmodule mod_php4.c>
php_flag magic_quotes_gpc off
</ifmodule>

1
applications/start/cache/.htaccess vendored Normal file
View File

@ -0,0 +1 @@
deny from all

View File

@ -0,0 +1 @@
deny from all

View File

@ -0,0 +1,16 @@
<?php
$defaultController = 'introduction';
$defaultAction = 'start';
$language = 'english';
$controllerParameter = 'c';
$actionParameter = 'a';
$development = true;
$logErrors = true;
$urlParameters = false;
$sessionDatabase = false;
$libraries = array();
$helpers = array();
?>

View File

@ -0,0 +1,11 @@
<?php
$applicationName = 'start';
$websiteTitle = 'SuperSmash framework | Start';
$webmasterEmail = 'info@SuperSmash.nl';
// Include the database configuration file
include_once ('databaseconfiguration.php');
// Include the SuperSmash framework configuration file
include_once ('SuperSmashconfiguration.php');
?>

View File

@ -0,0 +1,10 @@
<?php
$database = array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'framework',
'username' => 'root',
'password' => '',
'port' => '3306'
);
?>

View File

@ -0,0 +1,28 @@
<?php
class Introduction extends System\SuperSmash\Controller {
// Create the constructor
function __construct() {
parent::__construct();
}
function _beforeAction() {
}
function start() {
// Load the introduction Model
$this->load->model('introduction');
// Load the data for the introduction model
$data = $this->IntroductionModel->introduction();
// Load the view and add the data
$this->load->view('introduction', $data);
}
function _afterAction() {
}
}
?>

View File

View File

View File

View File

@ -0,0 +1,17 @@
<?php
class IntroductionModel extends System\SuperSmash\Model {
// Create the constructor
public function __construct() {
parent::__construct();
}
public function introduction() {
return array('introductionMessage' =>
'Hello and welcome to the SuperSmash Framework! <br />
This framework will help you while developing your application <br /><br />
');
}
}
?>

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -0,0 +1,85 @@
body
{
margin:0 auto;
background-color:#000000;
}
h1 {
font-family: SuperSmash, serif;
text-transform: uppercase;
letter-spacing: 1px;
padding:10px;
}
#container
{
width:600px;
margin: 0 auto;
background: #F0C74D;
border: 1px solid #999;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
}
#header
{
width: auto;
height:100px;
text-align: center;
color : #F0C74D;
}
#content
{
width:600px;
padding: 20px 10px 20px 10px;
margin:0 auto;
text-align: center;
}
#footer
{
width:600px;
margin: 0 auto;
background: #F0C74D;
border: 1px solid #999;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
text-align: center;
}
#dynamic{
text-align: center;
}
#html5{
position:fixed;
top:20px;
right:5px;
}
#twitter{
position:fixed;
top:60px;
right:5px;
}
#w3c{
position:fixed;
top:100px;
right:5px;
}
pre
{
font-size: 12px;
padding-top: 10px;
background: #f0f0f0;
border: 1px solid #999;
width:400px;
margin: 0 auto;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 755 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

@ -0,0 +1,49 @@
<!DOCTYPE html>
<html>
<head>
<title><?php echo configuration('websiteTitle');?></title>
<link href="<?php echo $websiteURL . "/" . "applications" . "/" . configuration('applicationName') . $viewPath;?>/images/favicon.ico" rel="shortcut icon" type="image/x-icon"/>
<link rel="stylesheet" type="text/css" href="<?php echo $websiteURL . "/" . "applications" . "/" . configuration('applicationName') . $viewPath;?>/css/style.css"/>
</head>
<body>
<div id="header">
<h1>
<img src="<?php echo $websiteURL . "/" . "applications" . "/" . configuration('applicationName') . $viewPath;?>/images/logo.png" alt="SuperSmash Logo" />
Welcome to the SuperSmash Framework!
<img src="<?php echo $websiteURL . "/" . "applications" . "/" . configuration('applicationName') . $viewPath;?>/images/logo.png" alt="SuperSmash Logo" />
</h1>
</div>
<div id="container">
<div id="content">
<div id="dynamic"><?php echo $introductionMessage; ?></div>
You can edit the <b>Model</b> by going here:
<pre>applications/start/models/welcome.php
</pre>
<br />
You can edit the <b>View</b> by going here:
<pre>applications/start/views/welcome.php
</pre>
<br />
You can edit the <b>Controller</b> by going here:
<pre>applications/start/controllers/welcome.php
</pre>
<br /><img src="<?php echo $websiteURL . "/" . "applications" . "/" . configuration('applicationName') . $viewPath;?>/images/mvc.png" alt="MVC Model" /><br />
</div>
</div> <br /><br />
<div id="footer">
<small>
Page rendered in {elapsed} seconds, using {usage}<br />
</small>
</div>
<!-- Show some items -->
<a target="_blank" href="http://www.HTML5.com"><img id="html5" src="<?php echo $websiteURL . "/" . "applications" . "/" . configuration('applicationName') . $viewPath;?>/images/html5.png" alt="HTML5" /></a>
<a target="_blank" href="http://twitter.com/#!/SuperSmash007"><img id="twitter" src="<?php echo $websiteURL . "/" . "applications" . "/" . configuration('applicationName') . $viewPath;?>/images/twitter.png" alt="Twitter" /></a>
</body>
</html>

View File

@ -0,0 +1,14 @@
RewriteEngine on
# disable directory browsing
Options All -Indexes
<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
Order Allow,Deny
Deny from all
</FilesMatch>
# turn off magic_quotes_gpc for PHP enabled servers
<ifmodule mod_php4.c>
php_flag magic_quotes_gpc off
</ifmodule>

View File

@ -0,0 +1 @@
deny from all

View File

@ -0,0 +1 @@
deny from all

View File

@ -0,0 +1,16 @@
<?php
$defaultController = 'login';
$defaultAction = 'start';
$language = 'english';
$controllerParameter = 'c';
$actionParameter = 'a';
$development = false;
$logErrors = true;
$urlParameters = false;
$sessionDatabase = false;
$libraries = array();
$helpers = array();
?>

View File

@ -0,0 +1,12 @@
<?php
$applicationName = 'taskmanager';
$websiteTitle = 'SuperSmash Taskmanager';
$webmasterEmail = 'info@SuperSmash.nl';
$useDatabase = true;
// Include the database configuration file
include_once ('databaseconfiguration.php');
// Include the SuperSmash framework configuration file
include_once ('SuperSmashconfiguration.php');
?>

View File

@ -0,0 +1,10 @@
<?php
$database = array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'taskmanager',
'username' => 'root',
'password' => '',
'port' => '3306'
);
?>

View File

@ -0,0 +1,39 @@
<?php
class Login extends System\SuperSmash\Controller {
// Create the constructor
function __construct() {
parent::__construct();
}
function _beforeAction() {
}
function start($error = false) {
// Load the login Model
$this->load->model('login');
// Load the data for the login model
$data = $this->LoginModel->login($error);
// Load the view and add the data
$this->load->view('login', $data);
}
function check(){
// Load the login Model
$this->load->model('login');
if ($this->LoginModel->check()){
die("ingelogd");
} else {
$this->start(true);
}
}
function _afterAction() {
}
}
?>

View File

@ -0,0 +1,58 @@
<?php
class LoginModel extends System\SuperSmash\Model {
// Create the constructor
public function __construct() {
parent::__construct();
}
public function login($error = false) {
$array = array('loginMessage' =>
'Use this form to login into the application.'
);
if ($error) {
$error = array('errorMessage' =>
'Invalid username or password.'
);
$array = array_merge($array, $error);
}
return $array;
}
public function check(){
if ($_SERVER['REQUEST_METHOD'] == "POST"){
if (isset($_POST['username']) && isset($_POST['password'])){
// Get the database connection
$database = \System\SuperSmash\SuperSmash::database();
$password = $_POST['password'];
// Check if the username and password are valid
$query = $database->prepare("SELECT * FROM login WHERE username = ? LIMIT 1");
$query->execute(array($_POST['username']));
$result = $query->fetch();
$password = md5(sha1($password . $result['salt']));
$password = $this->encrypt_login($password, $result['salt']);
return $password == $result['password'];
}
}
}
private function encrypt_login($string, $key){
$r = 0;
for ($i = 0; $i < strlen($string); $i++)
$r .= substr((md5($key)), ($i % strlen(md5($key))),
1) . $string[$i];
for ($i = 1; $i < strlen($r); $i++)
$string[$i - 1] = chr(ord($r[$i - 1]) + ord(substr(md5
($key), ($i % strlen(md5($key))) - 1, 1)));
$value = 0;
$value = urlencode(base64_encode($string));
return stripslashes($value);
}
}
?>

View File

@ -0,0 +1,128 @@
body
{
margin:0 auto;
background-color:#000000;
}
#container
{
width:600px;
margin: 0 auto;
}
#header
{
margin: 0 auto;
height:100px;
text-align: center;
color : #FFFFFF;
font: bold 20px "SuperSmash", Arial;
}
#footer
{
width:600px;
margin: 0 auto;
background: #F0C74D;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
text-align: center;
}
#login-box {
width:333px;
height: 352px;
padding: 58px 76px 0 76px;
margin: 0 auto;
color: #ebebeb;
font: 12px Arial, Helvetica, sans-serif;
background: url("../images/background.png") no-repeat left top;
}
.loginButton{
margin-left:90px;
background: url("../images/button.png") no-repeat left top;
width:103px;
height:42px;
border:0px;
}
#login-box img {
border:none;
}
#login-box h2 {
padding:0;
margin:0;
color: #ebebeb;
font: bold 44px "Calibri", Arial;
}
#login-box-username {
float: left;
display:inline;
width:80px;
text-align: right;
padding: 14px 10px 0 0;
margin:0 0 7px 0;
}
#login-box-usernamefield {
float: left;
display:inline;
width:230px;
margin:0;
margin:0 0 7px 0;
}
#login-box-password {
float: left;
display:inline;
width:80px;
text-align: right;
padding: 14px 10px 0 0;
margin:0 0 7px 0;
}
#login-box-passwordfield {
float: left;
display:inline;
width:230px;
margin:0;
margin:0 0 7px 0;
}
.form-login {
width: 205px;
padding: 10px 4px 6px 3px;
border: 1px solid #0d2c52;
background-color:#1e4f8a;
font-size: 16px;
color: #ebebeb;
}
.login-box-options {
clear:both;
padding-left:87px;
font-size: 11px;
}
.login-box-options a {
color: #ebebeb;
font-size: 11px;
}
pre
{
font-size: 12px;
padding-top: 10px;
background: #f0f0f0;
border: 1px solid #999;
width:400px;
margin: 0 auto;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html>
<head>
<title><?php echo configuration('websiteTitle');?></title>
<link href="<?php echo $websiteURL . "/" . "applications" . "/" . configuration('applicationName') . $viewPath;?>/images/favicon.ico" rel="shortcut icon" type="image/x-icon"/>
<link rel="stylesheet" type="text/css" href="<?php echo $websiteURL . "/" . "applications" . "/" . configuration('applicationName') . $viewPath;?>/css/login.css"/>
</head>
<body>
<div id="header">
<br/><br/><h1>SuperSmash Task manager</h1>
</div>
<div id="container">
<div id="content">
<form action="<?php echo "$websiteURL/login/check"; ?>" method="post">
<div id="login-box">
<?php echo $loginMessage; ?>
<br />
<?php if(isset($errorMessage)) echo "<font color=\"red\">" . $errorMessage . "</font><br />"; ?>
<div id="login-box-username" style="margin-top:20px;">Username:</div>
<div id="login-box-usernamefield" style="margin-top:20px;">
<input name="username" class="form-login" title="Username" value="" size="30" maxlength="50" />
</div>
<div id="login-box-password">Password:</div>
<div id="login-box-passwordfield">
<input name="password" type="password" class="form-login" title="Password" value="" size="30" maxlength="50" />
</div>
<br />
<span class="login-box-options"><input type="checkbox" name="1" value="1"> Remember Me <a href="forget.php" style="margin-left:30px;">Forgot password?</a>
<br />
<br />
</span>
<button class="loginButton" type="submit">&nbsp;</button>
</div>
</form>
</div>
</div>
<div id="footer"></div>
</body>
</html>

22
index.php Normal file
View File

@ -0,0 +1,22 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
use settings\settings;
// We need to include all the custom editable settings // PLEASE DO NOT EDIT ANYTHING BUT FRAMEWORK CONTENT INSIDE THIS FOLDER !!!
require_once("system/editable/constants.php");
// We need to include all the available applications that are using the SuperSmash Framework
require_once ("system/SuperSmash/boot/applications.php");
// We need to bootstrap the SuperSmash Framework
require_once("system/SuperSmash/boot/bootstrap.php");
// Finally we need to start the SuperSmash Framework
$SuperSmash->start();
?>

View File

@ -0,0 +1,108 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\SuperSmash;
use settings\settings;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class SuperSmash
{
protected $Router;
protected $dispatch;
public static $database;
// This function will start the SuperSmash Framework
public function start()
{
// initialise the router
$this->Router = loadClass('Router');
// get the URL information to be used by the router
$routes = $this->Router->getUrlInformation();
// initialise some important routing variables
$controller = $GLOBALS['controller'] = $routes['controller'];
$action = $GLOBALS['action'] = $routes['action'];
$queryString = $GLOBALS['querystring'] = $routes['querystring'];
// Include the application controller
if(file_exists(settings::getFilePath() . DS . settings::getApp() . DS . 'controllers' . DS . strtolower($controller) . '.php'))
{
require_once (settings::getFilePath() . DS . settings::getApp() . DS . 'controllers' . DS . strtolower($controller) . '.php');
}
else
{
show_404();
}
// Create a new object for the controller
$this->dispatch = new $controller();
// Create a database connection object
if (configuration('useDatabase'))
{
if (self::$database == null)
{
self::$database = loadClass('Database','SuperSmash',configuration('database'));
self::$database = self::$database->open();
}
}
// Check if we need to put the session in the database
if (configuration('sessionDatabase'))
{
$config['database'] = self::$database;
new Session($config);
}
// After loading the controller, make sure the method exists, or we have a 404
if(method_exists($controller, $action))
{
// Call the beforeAction method in the controller.
$this->performAction($controller, "_beforeAction", $queryString);
// Call the actual action
$this->performAction($controller, $action, $queryString);
// Call the afterAction method in the controller.
$this->performAction($controller, "_afterAction", $queryString);
}
else
{
// If the method did not exist, then we have a 404
show_404();
}
}
// This function will perform an action on the specified controller
protected function performAction($controller, $action, $queryString = null)
{
if(method_exists($controller, $action))
{
return call_user_func_array( array($this->dispatch, $action), $queryString );
}
return false;
}
public static function database()
{
return self::$database;
}
public static function language()
{
// Load the language
$language = loadClass('Language');
$language->setLanguage(configuration('language', 'SuperSmash'));
$language->load('SuperSmash_errors');
$language->load('page_errors');
return $language;
}
}
?>

View File

@ -0,0 +1,14 @@
RewriteEngine on
# disable directory browsing
Options All -Indexes
<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
Order Allow,Deny
Deny from all
</FilesMatch>
# turn off magic_quotes_gpc for PHP enabled servers
<ifmodule mod_php4.c>
php_flag magic_quotes_gpc off
</ifmodule>

View File

@ -0,0 +1 @@
deny from all

View File

@ -0,0 +1 @@
deny from all

View File

@ -0,0 +1,16 @@
<?php
$defaultController = 'chooser';
$defaultAction = 'start';
$language = 'english';
$controllerParameter = 'c';
$actionParameter = 'a';
$development = true;
$logErrors = true;
$urlParameters = true;
$sessionDatabase = false;
$libraries = array();
$helpers = array();
?>

View File

@ -0,0 +1,11 @@
<?php
$applicationName = 'applicationChooser';
$websiteTitle = 'Choose your website';
$webmasterEmail = 'info@SuperSmash.nl';
// Include the database configuration file
include_once ('databaseconfiguration.php');
// Include the SuperSmash framework configuration file
include_once ('SuperSmashconfiguration.php');
?>

View File

@ -0,0 +1,10 @@
<?php
$database = array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'framework',
'username' => 'root',
'password' => '',
'port' => '3306'
);
?>

View File

@ -0,0 +1,34 @@
<?php
class Chooser extends system\SuperSmash\Controller
{
// Create the constructor
function __construct()
{
parent::__construct();
}
function _beforeAction()
{
}
function start()
{
// Load the chooser Model
$this->load->model('chooser');
// Load the data for the chooser model
$data = array_merge($this->ChooserModel->denyList());
$data += $this->ChooserModel->chooser();
// Load the view and add the data
$this->load->view('chooser', $data);
}
function _afterAction()
{
}
}
?>

View File

@ -0,0 +1,26 @@
<?php
class ChooserModel extends system\SuperSmash\Model
{
// Create the constructor
public function __construct()
{
parent::__construct();
}
public function chooser()
{
return array('chooserMessage' =>
'This portal contains several websites <br />
Please click on the website that you would like to visit <br /><br />
');
}
public function denyList()
{
return array('denyList' =>
'.htaccess');
}
}
?>

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

View File

@ -0,0 +1,93 @@
body
{
margin:0 auto;
}
h1 {
font-family: SuperSmash, serif;
text-transform: uppercase;
letter-spacing: 1px;
padding:10px;
}
#container
{
width:600px;
margin: 0 auto;
background: gray;
border: 1px solid #999;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
}
.button{
font-size:16px;
font-family:Arial,sans-serif;
height:100px;
width:100px;
border-width:0px;
cursor:pointer;
}
#header
{
width: auto;
height:100px;
text-align: center;
color : #F0C74D;
}
#content
{
width:600px;
padding: 20px 10px 20px 10px;
margin:0 auto;
text-align: center;
}
#footer
{
width:600px;
margin: 0 auto;
background: white;
border: 1px solid #999;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
text-align: center;
}
#dynamic{
text-align: center;
}
#html5{
position:fixed;
top:20px;
right:5px;
}
#twitter{
position:fixed;
top:60px;
right:5px;
}
#w3c{
position:fixed;
top:100px;
right:5px;
}
pre
{
font-size: 12px;
padding-top: 10px;
background: #f0f0f0;
border: 1px solid #999;
width:400px;
margin: 0 auto;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html>
<head>
<title><?php echo configuration('websiteTitle');?></title>
<link href="<?php echo $websitePath . $viewPath;?>/images/favicon.ico" rel="shortcut icon" type="image/x-icon"/>
<link rel="stylesheet" type="text/css" href="<?php echo $websitePath . $viewPath;?>/css/style.css"/>
</head>
<body style="background:transparent url(<?php echo $websitePath . $viewPath;?>/images/background.png) scroll; background-color:#0a0a0a; text-align:center; margin:0px; padding:0px;">
<div id="header"></div>
<div id="container">
<div id="content">
<div id="dynamic"><?php echo $chooserMessage; ?></div>
<?php
foreach ($applications as &$application){
$application = str_replace(" ", "&nbsp", $application);
// Check if there is an application in the denyList
if (strlen(strstr($denyList,$application))>0)
{
continue;
}
echo " <form action=\"$websiteURL/index.php\" method=\"POST\">";
if (file_exists(ROOT . "/applications/$application/portal.png")){
echo "<button class=\"button\" name=\"changepage\" type=\"submit\" style=\"background-color:transparent; background-image:url($websiteURL/applications/" . "$application" . "/portal.png)\" value=\"$application\" title=\"$application\"></button>";
} else {
echo "<button class=\"button\" name=\"changepage\" type=\"submit\" style=\"background-color:transparent; background-image:url($websitePath/portal.png)\" value=\"$application\" title=\"$application\"></button>";
}
echo " <br />$application
</form>
<br />";
};
?>
</div>
</div> <br /><br />
<div id="footer">
<small>
Page rendered in {elapsed} seconds, using {usage}<br />
</small>
</div>
</body>
</html>

View File

@ -0,0 +1,69 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\SuperSmash;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class Benchmark
{
// Create the arrays that holds the timers
protected $start = array();
protected $stop = array();
// This function will start a new timer
public function start($key)
{
$this->start[$key] = microtime(true);
}
// This function will stop the specified timer
public function stop($key)
{
$this->stop[$key] = microtime(true);
}
// This function will show the specified timer
public function elapsed($key, $round = 3, $stop = false)
{
if(!isset($this->start[$key]))
{
return false;
}
else
{
if(!isset($this->stop[$key]) && $stop == true)
{
$this->stop[$key] = microtime(true);
}
return round((microtime(true) - $this->start[$key]), $round);
}
}
// This function will return the amount of memory the page uses while loading
public function usage()
{
$returnValue = '';
$usage = memory_get_usage(true);
if($usage < 1024)
{
$returnValue = $usage." bytes";
}
elseif($usage < 1048576)
{
$returnValue = round($usage/1024, 2)." kilobytes";
}
else
{
$returnValue = round($usage/1048576, 2)." megabytes";
}
return $returnValue;
}
}
?>

View File

@ -0,0 +1,135 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace settings;
// Define the directory seperator (Check for Linux or Windows)
$operatingSystem = PHP_OS;
switch($operatingSystem)
{
case "Linux": define("DS", "/"); break;
case "Windows": define("DS", "\\"); break;
default: define("DS", "/"); break;
}
// Define the root path
define('ROOT', dirname(dirname(dirname(dirname(__FILE__)))));
class settings
{
private static $application;
private static $applications = array();
private static $filePath;
private static $applicationPath;
static function getApplicationPath()
{
return self::$applicationPath;
}
static function getFilePath()
{
return self::$filePath;
}
static function getApps()
{
return self::$applications;
}
static function getApp()
{
return self::$application;
}
static function setApps($value)
{
self::$applications = $value;
}
static function set($value)
{
if ($value == "applicationchooser")
{
self::$filePath = ROOT . DS . "system" . DS . 'SuperSmash';
self::$applicationPath = DS . "system" . DS . 'SuperSmash';
}
else
{
self::$filePath = ROOT . DS . "applications";
self::$applicationPath = DS . "applications";
}
self::$application = $value;
if (!is_dir(self::$filePath . DS . self::$application))
{
self::$filePath = ROOT . DS . "system" . DS . 'SuperSmash';
self::$applicationPath = DS . "system" . DS . 'SuperSmash';
self::$application = "applicationchooser";
}
}
}
// Create a constant for the debug FileName
define("DEBUG", $debugLog);
// Create a constant for the error FileName
define("ERROR", $errorLog);
// Scan all the available applications
$temporary = scandir(ROOT . DS . "applications");
$applications = array();
foreach ($temporary as $application)
{
if ($application == "." || $application == "..")
continue;
array_push($applications, $application);
}
settings::setApps($applications);
require_once(dirname(dirname(dirname(__FILE__))) . DS . "SuperSmash" . DS . "cookie.php");
if (isset($_POST['changepage']))
{
ob_start();
include dirname(__FILE__) . DS . "SuperSmash" . DS . "applicationchooser" . DS . "configuration" . DS . "SuperSmashconfiguration.php";
ob_end_clean();
if (isset($sessionDatabase))
{
$_SESSION['changedPage'] = $_POST['changepage'];
}
else
{
\system\SuperSmash\Cookie::set("changedPage", $_POST['changepage'], false, 3600);
header("Location: index.php");
}
}
if (\system\SuperSmash\Cookie::exists("changedPage"))
{
settings::set(\system\SuperSmash\Cookie::get("changedPage"));
}
else if (isset($_SESSION['changedPage']))
{
settings::set($_SESSION['changedPage']);
}
else if ($applicationChooser)
{
settings::set("applicationchooser");
}
// Define the system path
define('SYSTEM', ROOT . DS . 'system');
// Define the access variable
define('SUPERSMASH_FRAMEWORK', true);
// Load the default application
if (!$applicationChooser)
{
settings::set($applications[$applicationNumber]);
}
?>

View File

@ -0,0 +1,25 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
// Require the global settings
require (SYSTEM . DS . 'SuperSmash' . DS . 'global.php');
// Require the registry
require (SYSTEM . DS . 'SuperSmash' . DS . 'registry.php');
// Register the SuperSmash framework to process errors through a custom error handling system
set_error_handler( 'errorHandler' , E_ALL | E_STRICT );
// Initiate the system start time
$Benchmark = loadClass('Benchmark');
$Benchmark->start('system');
// Load the SuperSmash Framework
$SuperSmash = loadClass('SuperSmash');
?>

View File

@ -0,0 +1,176 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\SuperSmash;
use settings\settings;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class Configuration {
// This array will hold all the settings
protected $data = array();
// Create the constructor
public function __construct()
{
// Load the default configuration file
$this->load(settings::getFilePath() . DS . settings::getApp() . DS . 'configuration' . DS . 'configuration.php', 'SuperSmash');
}
// This function will get the specified variable from the configuration file
public function get($key, $type = 'SuperSmash')
{
// Check if the variable exists
if(isset($this->data[$type][$key]))
{
return $this->data[$type][$key];
}
return null;
}
// This function will return all the variables that where set in the data array
public function getAll($type = 'SuperSmash')
{
// Check if the variable exists
if(isset($this->data[$type]))
{
return $this->data[$type];
}
return null;
}
// This function will set a variable in the data array
public function set($key, $value = false, $name = 'SuperSmash')
{
// If we have array, loop through and set each
if(is_array($item))
{
foreach($item as $key => $value)
{
$this->data[$name][$key] = $value;
}
}
else
{
$this->data[$name][$item] = $value;
}
}
// This function will load a specific configuration file and will add its defined variables to the array
public function load($file, $name, $array = false)
{
// Include file and add it to the $files array
if(!file_exists($file))
{
return;
}
require_once ($file);
$this->files[$name]['filePath'] = $file;
$this->files[$name]['config_key'] = $array;
if($array)
{
$variables = $variables[$array];
}
else
{
$variables = get_defined_vars();
}
// Unset the passed variables
unset($variables['file'], $variables['name'], $variables['array']);
// Add the variables to the $data[$name] array
if(count($variables) > 0)
{
foreach($variables as $key => $value)
{
if($key != 'this' && $key != 'data')
{
$this->data[$name][$key] = $value;
}
}
}
return;
}
// This function will save all config variables to the config file,
// and makes a backup of the current config file
public function save($name)
{
// Convert everything to lowercase
$name = strtolower($name);
// Check to see if we need to put this in an array
$configKey = $this->files[$name]['config_key'];
if($configKey != false)
{
$Old_Data = $this->data[$name];
$this->data[$name] = array("$configKey" => $this->data[$name]);
}
// Create the new configuration file
$configurationContent = "<?php\n\n";
$configurationContent .= "
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
/**** This file has been generated ****/
/***** by the SuperSmash Framework ****/
/**************************************/
\n\n
";
// Loop through each var and write it
foreach($this->data[$name] as $key => $value)
{
if(is_numeric($value))
{
$configurationContent .= "\$$key = " . $value . ";\n";
}
elseif(is_array($value))
{
$val = var_export($value, true);
$configurationContent .= "\$$key = " . $value . ";\n";
}
else
{
$configurationContent .= "\$$key = '" . addslashes( $value ) . "';\n";
}
}
// Close the php tag
$configurationContent .= "?>";
// Add the back to non array if we did put it in one
if($configKey != false)
{
$this->data[$name] = $Old_Data;
}
// Copy the current config file for backup,
// and write the new config values to the new config
copy($this->files[$name]['filePath'], $this->files[$name]['filePath'].'.bak');
return file_put_contents($this->files[$name]['filePath'], $configurationContent);
}
// This function will revert the last saved configurationFile
public function restore($name)
{
// Copy the backup config file nd write the config values to the current config
return copy($this->files[$name]['filePath'].'bak', $this->files[$name]['filePath']);
}
}
?>

View File

@ -0,0 +1,84 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\SuperSmash;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class Controller
{
// This variable will hold the controllerName
public $controller;
// This variable will hold the action taken
public $action;
// This variable will hold the queryString
public $queryString;
// This variable will hold the queryString
public static $database;
// This variable will hold the instance of the class
private static $instance;
// Create the constructor
public function __construct()
{
// Set the instance of the controller
self::$instance = $this;
// Set our controller, action and queryString
$this->controller = $GLOBALS['controller'];
$this->action = $GLOBALS['action'];
$this->queryString = $GLOBALS['querystring'];
// Initiate the loader
$this->load = loadClass('Loader');
// Initiate the autoloader Helpers
$helpers = configuration('helpers', 'SuperSmash');
if(count($helpers) > 0)
{
foreach($helpers as $helper)
{
$this->load->helpers($helper);
}
}
// Intiate the autoloader Libraries
$libraries = configuration('libraries', 'SuperSmash');
if(count($libraries) > 0)
{
foreach($libraries as $library)
{
$this->load->libraries($library);
}
}
}
// This function will get the controller instance
public static function getInstance()
{
return self::$instance;
}
// This function will be called before an action is taken
public function _beforeAction()
{
// We can write some custom code here that will be taken before an action is made
}
// This function will be called after an action is taken
public function _afterAction()
{
// We can write some custom code here that will be taken after an action is made
}
}
?>

View File

@ -0,0 +1,106 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\SuperSmash;
class Cookie
{
private static $expire = 0;
private static $path;
private static $domain;
private static $secure;
private static $httponly = true;
public static function init($domain = '', $path = '/', $secure = false, $httponly = false) {
// Set the domain name to the current domain unless a domain name is given
if (strlen($domain) == 0) $domain = self::getDomain($_SERVER['HTTP_HOST']);
self::$domain = $domain;
self::$path = $path;
self::$secure = $secure;
self::$httponly = $httponly;
}
private static function getDomain($url)
{
$myurl = str_replace('www.','',$url);
$domain = parse_url($myurl);
if(!empty($domain["host"]))
{
return $domain["host"];
}
else
{
return $domain["path"];
}
}
// Set the cookie
public static function set($name, $value = '', $force = false, $expire = NULL, $path = NULL, $domain = NULL, $secure = false, $httponly = false)
{
// Check if the $value is an integer
if ($value === true || $value === false)
{
$value = (int) $value;
}
// Set the cookie value
if ($value)
{
$value = base64_encode(serialize($value));
// Check the allowed cookie size
if (strlen($value) > (4 * 1024))
{
trigger_error( "The cookie {$name} exceeds the specification for the maximum cookie size. Some data may be lost", E_USER_WARNING );
}
}
// Force value into superglobal
if ($force)
{
$_COOKIE[$name] = $value;
}
// Set the cookie
return setcookie($name, $value, (($expire) ? (time() + (int) $expire) : self::$expire), ($path) ? $path : self::$path, ($domain) ? $domain : self::$domain, ($secure) ? $secure : self::$secure, ($httponly) ? $httponly : self::$httponly);
}
// Check if the cookie exists
public static function exists($name)
{
return isset($_COOKIE[$name]);
}
// Get a cookie value
public static function get($name)
{
return (isset($_COOKIE[$name])) ? unserialize(base64_decode($_COOKIE[$name])) : NULL;
}
// Remove a cookie
public static function remove($name, $force = false)
{
// Check if the cookie isset
if (isset($_COOKIE[$name]))
{
// Remove from superglobal
if ($force)
{
unset($_COOKIE[$name]);
}
// Remove the cookie
return setcookie($name, '', time() - (3600 * 25), self::$path, self::$domain, self::$secure, self::$httponly);
}
}
}
Cookie::init();
?>

View File

@ -0,0 +1,852 @@
<?php
/* PDO Database connection class
*
* @author: SuperSmash
* @copyright: SuperSmash
* @version: 1.0
*
*/
/*
* How to use this class :
*
* Create a database connection:
*
* $database = new database("databaseType","serverIP","databaseName","userName","password","(optional) port");
* Example : $database = new database ("mysql","localhost","school","root","myPassword","");
*
* Check if the database connection was successfull
*
* if (!$database) {
* die ("Database connection cannot be established");
* }
*
* Get the latest database error
*
* echo $database->getError();
*
* Execute a query to the database:
*
* $database->query("SELECT * FROM databaseName WHERE id = '1'";)
*
* You can also get the inserted ID of the query you executed:
*
* $insertedId = $database->insert("TABLE", "record1,record2,record3", "value1,value2,value3";)
* Example: INSERT INTO USERS,firstname,lastname,VALUES('Amber','Heard') WHERE ADDRESS = 'Dark avenue 2';
* Example: $insertedID = $database->insert("USERS","ADDRESS='Dark avenue 2','Amber',Heard'");
*
* Get the rowCount of an execute query
*
* echo $database->rowcount();
*
* Delete a row in the database
*
* $database->query("DELETE FROM USERS WHERE ID=1;");
*
* Get the affected rows affected by the delete statement
*
* $affectedRows = $database->delete("USERS", "ID=1");
*
* Update rows in the database
*
* Example: $database->query("UPDATE USERS SET firstname='Joyce' WHERE ID=1;");
* Example 2: $affectedRows = $database->update("USERS", "FIRSTNAME='Joyce'", "ID=1");
*
* Get the ID that was inserted last in the database
*
* $lastID = $database->getLatestId("Table","recordName");
*
* Example: $lastID = $database->getLatestId("USERS","Firstname");
*
* Create a Anti-SQL injection statement to the database
*
* $parameters = array(":id@0@INT", ":firstname@amber@STR");
* $ID = $database->query_secure("INSERT INTO USERS (id,firstname) VALUES(:id,:firstname);", $parameters, false);
* (If the last false statement in the query above is set to true the class will return the resultset of the record)
* (else if the last false statement in the query above is set to false you will get a true of false idenitifying if * the query was executed successfully to the database).
*
* The $ID variable will now hold the last inserted ID.
*
* Show all the table that are in your database
*
* $result = $database->ShowTables("databaseName");
* Example: $result = $database->ShowTables("school");
*
* Output the result to the screen in a clean way:
*
* foreach($result as $row){
* $i++;
* echo "$row[$i]" . "<br />";
*
* Show all the databases this class holds (get all the databases you got permissions for)
*
* $result = $database->showDatabases();
*
* Output the result to the screen in a clean way:
*
* foreach($result as $row){
* $i++;
* echo "$row[$i]" . "<br />";
*
* close the database connection;
*
* $database->close();
*/
class Database
{
// Create an array with all the database types this class can connect to
private $database_types = array("databaselibrary", // Database Library (used by PHP)
"firebird", // firebird
"ibm", // IBM
"informix", // Informix
"mssql", // Microsoft SQL (<= 2000)
"mysql", // mysql
"odbc", // Open database connectivity (Microsoft Access)
"oracle", // Oracle
"postgre", // Postgre SQL
"sqlite2", // SQLite 2
"sqlite3", // SQLite 3
"sql", // Microsoft SQL
);
private $server; // This variable holds the host name of the server (serverName) used by the application
private $database; // This variable holds the databaseName of the database used by the application
private $user; // This variable holds the userName of the database used by the application
private $password; // This variable holds the password of the database used by the application
private $port; // This variable holds the port of the database used by the application
private $database_type; // This variable holds the database type of the database used by the application
private $root_mdb; // This variable holds the root mdb of the database used by the application
private $debug = false; // This variable holds the debugging state of the class
private $sql; // This variable holds all the sql connection parameters
private $con; // This variable holds the connection of the database used by the application
private $err_msg = ""; // This variable holds the error message that was trown by the database (if exists)
/**
* Create the constructor
* @param string $database_types (specify the database connection)
*
* These are the database connection that are accepted by this class:
*
* connection name - connection description
* --------------------------------------------
* databaselibrary Database Library database (used by PHP)
* firebird firebird database
* ibm IBM database
* informix Informix database
* mssql Microsoft SQL Server database (V. 2000 and lower)
* mysql mysql database
* odbc Open database connectivity (Microsoft Access)
* oracle Oracle database
* postgre postgre SQL database
* sqlite2 SQLite 2 database
* sqlite3 SQLite 3 database
* sql Microsoft SQL
*
* @param string $server (The server where the database is located)
* @param string $database (The name of the database)
* @param string $user (The userName of the connection to the database)
* @param string $password (The password of the connection to the database)
*
*/
// Create the constructor and initialise the connection to the specified server
public function __construct($database_type,$server,$database,$user,$password,$port)
{
$this->database_type = strtolower($database_type);
$this->server = $server;
$this->database = $database;
$this->user = $user;
$this->password = $password;
$this->port = $port;
}
// initialise class and connects to the database
public function open()
{
if(in_array($this->database_type, $this->database_types))
{
try {
switch ($this->database_type)
{
// Database Library connection
case "databaselibrary": // default port used by database => 10060
$this->con = new PDO("dblib:host=".$this->server.
":".$this->port.";
dbname=".$this->database,$this->user,$this->password
);
break;
// firebird connection
case "firebird": // default port used by database => 3050
$this->con = new PDO("firebird:dbname=".$this->server.
":".$this->database, $this->user, $this->password
);
break;
// ibm connection
case "ibm":
$this->con = new PDO("ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=".$this->database."; HOSTNAME=".$this->host.";
PORT=".$this->port.";
PROTOCOL=TCPIP;",
$this->user, $this->password
);
break;
// informix connection
case "informix":
$this->con = new PDO("informix:DSN=InformixDB", $this->user, $this->password);
break;
// mssql connection
case "mssql":
$this->con = new PDO("mssql:host=".$this->server.";
dbname=".$this->database, $this->user, $this->password
);
break;
// mysql connection
case "mysql":
if ($this->port != "") {
$this->con = new PDO("mysql:host=".$this->server.";
port=".$this->port.";
dbname=".$this->database, $this->user, $this->password
);
}else{
$this->con = new PDO("mysql:host=".$this->server.";
dbname=".$this->database, $this->user, $this->password
);
}
break;
// open database connectivity
case "odbc":
$this->con = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};
Dbq=C:\accounts.mdb;Uid=".$this->user
);
break;
// oracle connection
case "oracle":
$this->con = new PDO("OCI:dbname=".$this->database.";
charset=UTF-8", $this->user, $this->password
);
break;
// postgre connection
case "postgre":
if($this->port!="")
{
$this->con = new PDO("pgsql:dbname=".$this->database.";
port=".$this->port.";
host=".$this->server, $this->user, $this->password
);
}
else
{
$this->con = new PDO("pgsql:dbname=".$this->database.";
host=".$this->server, $this->user, $this->password
);
}
break;
// sqlite2 connection
case "sqlite2":
$this->con = new PDO("sqlite:".$this->server);
break;
// sqlite3 connection
case "sqlite3":
$this->con = new PDO("sqlite::memory");
break;
// sql connection
case "sql":
$this->con = new PDO("sqlsrv:server=".$this->server.";
database=".$this->database, $this->user, $this->password
);
}
if ($this->debug)
{
$this->showDebugInformation();
}
else
{
// Create the exception that will be thrown by the PDO if there is an error
$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return $this->con;
}
catch(PDOException $e)
{
$this->log ("Error: ". $e->getMessage());
return false;
}
}
else
{
$this->log("The parameters that are given are invalid. <br />
Possible reasons: <br /><br />
1. The parameters that are given are invalid for the class. <br />
2. The database connection is not supported by the class.<br /><br />
Please contact the administrator of the application. => info@SuperSmash.nl"
);
return false;
}
}
private function log($message)
{
$this->err_msg = "SuperSmash Database Connection class:<br />
=====================================<br /><br />
$message";
}
private function showDebugInformation(){
// Create the exception that will be thrown by the PDO if there is an error
$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// The following extra attributes will only be shown in debugging mode
// Create the exception that will be thrown by the PDO if there is a warning
$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
// Create the exception that will be thrown by the PDO if there is an error (silent mode)
$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
// Log all database connection information (for debugging)
echo "SuperSmash Database debug information:<br />
============================<br /><br />";
echo "Status: " . $this->con->getAttribute(PDO::ATTR_CONNECTION_STATUS) . "<br />";
echo "Drivername: " . $this->con->getAttribute(PDO::ATTR_DRIVER_NAME) . "<br />";
echo "Serverversion: " . $this->con->getAttribute(PDO::ATTR_SERVER_VERSION) . "<br />";
echo "Clientversion: " . $this->con->getAttribute(PDO::ATTR_CLIENT_VERSION) . "<br />";
echo "Serverinfo: " . $this->con->getAttribute(PDO::ATTR_SERVER_INFO) . "<br />";
die();
}
// Print all the available drivers to the screen (for instant debugging off supported drivers)
public function drivers()
{
print_r(PDO::getAvailableDrivers());
}
//Execute the query to the database
public function query($sql_statement)
{
$this->err_msg = "";
if($this->con!=null)
{
try
{
$this->sql=$sql_statement;
return $this->con->query($this->sql);
}
catch(PDOException $e)
{
$this->log("Error: ". $e->getMessage());
return false;
}
}
else
{
$this->log("Error: Connection to database lost.");
return false;
}
}
//Execute queries with Anti SQL injection
public function query_secure($sql_statement, $params, $fetch_rows=false)
{
$this->err_msg = "";
if($this->con!=null)
{
$obj = $this->con->prepare($sql_statement);
for($i=0;$i<count($params);$i++)
{
$params_split = explode("@",$params[$i]);
if($params_split[2]=="INT")
$obj->bindParam($params_split[0], $params_split[1], PDO::PARAM_INT);
else
$obj->bindParam($params_split[0], $params_split[1], PDO::PARAM_STR);
}
try
{
$obj->execute();
}
catch(PDOException $e)
{
$this->log("Error: ". $e->getMessage());
return false;
}
if($fetch_rows)
return $obj->fetchAll();
if(is_numeric($this->con->lastInsertId()))
return $this->con->lastInsertId();
return true;
}
else
{
$this->log("Error: Connection to database lost.");
return false;
}
}
// Get the first row of a query in the database
public function query_first($sql_statement)
{
$this->err_msg = "";
if($this->con!=null)
{
try
{
$sttmnt = $this->con->prepare($sql_statement);
$sttmnt->execute();
return $sttmnt->fetch();
}
catch(PDOException $e)
{
$this->log("Error: ". $e->getMessage());
return false;
}
}
else
{
$this->log("Error: Connection to database lost.");
return false;
}
}
// Get the first tableCell from a query in the database
public function query_single($sql_statement)
{
$this->err_msg = "";
if($this->con!=null)
{
try
{
$sttmnt = $this->con->prepare($sql_statement);
$sttmnt->execute();
return $sttmnt->fetchColumn();
}
catch(PDOException $e)
{
$this->log("Error: ". $e->getMessage());
return false;
}
}
else
{
$this->log("Error: Connection to database lost.");
return false;
}
}
// Return the rowcount of a query in the database
public function rowcount()
{
$this->err_msg = "";
if($this->con!=null)
{
try
{
$stmnt_tmp = $this->stmntCount($this->sql);
if($stmnt_tmp!=false && $stmnt_tmp!="")
{
return $this->query_single($stmnt_tmp);
}
else
{
$this->log("Error: A few data required.");
return -1;
}
}
catch(PDOException $e)
{
$this->log("Error: ". $e->getMessage());
return -1;
}
}
else
{
$this->log("Error: Connection to database lost.");
return false;
}
}
// Return all the colum names in the database (as an array)
public function columns($table)
{
$this->err_msg = "";
$this->sql="Select * From $table";
if($this->con!=null)
{
try
{
$q = $this->con->query($this->sql);
$column = array();
foreach($q->fetch(PDO::FETCH_ASSOC) as $key=>$val)
{
$column[] = $key;
}
return $column;
}
catch(PDOException $e)
{
$this->log("Error: ". $e->getMessage());
return false;
}
}
else
{
$this->log("Error: Connection to database lost.");
return false;
}
}
// Insert the query and get the new ID from the database
public function insert($table, $data){
$this->err_msg = "";
if($this->con!=null)
{
try
{
$texto = "Insert Into $table (";
$texto_extra = ") Values (";
$texto_close = ")";
$data_column = explode(",", $data);
for($x=0;$x<count($data_column);$x++)
{
$data_content = explode("=", $data_column[$x]); //0=Field, 1=Value
if($x==0)
{
$texto.= $data_content[0];
}
else
{
$texto.= "," . $data_content[0]; }
if($x==0)
{
$texto_extra.= $data_content[1];
}
else
{
$texto_extra.= "," . $data_content[1];
}
}
$this->con->exec("$texto $texto_extra $texto_close");
return $this->con->lastInsertId();
}
catch(PDOException $e)
{
$this->log("Error: ". $e->getMessage());
return false;
}
}
else
{
$this->log("Error: Connection to database lost.");
return false;
}
}
// Update the tables in the database
public function update($table, $data, $condition="")
{
$this->err_msg = "";
if($this->con!=null)
{
try
{
return (trim($condition)!="") ? $this->con->exec("update $table set $data where $condition") : $this->con->exec("update $table set $data");
}
catch(PDOException $e)
{
$this->err_msg = "Error: ". $e->getMessage();
return false;
}
}
else
{
$this->log("Error: Connection to database lost.");
return false;
}
}
// Delete a record from the database
public function delete($table, $condition="")
{
$this->err_msg = "";
if($this->con!=null)
{
try
{
return (trim($condition)!="") ? $this->con->exec("delete from $table where $condition") : $this->con->exec("delete from $table");
}
catch(PDOException $e)
{
$this->log("Error: ". $e->getMessage());
return false;
}
}
else
{
$this->log("Error: Connection to database lost.");
return false;
}
}
//Execute Store Procedures
public function execute($sp_query)
{
$this->err_msg = "";
if($this->con!=null)
{
try
{
$this->con->exec("$sp_query");
return true;
}
catch(PDOException $e)
{
$this->log("Error: ". $e->getMessage());
return false;
}
}
else
{
$this->log("Error: Connection to database lost.");
return false;
}
}
// Get the latest ID from the specified table in the database
public function getLatestId($db_table, $table_field)
{
$this->err_msg = "";
$sql_statement = "";
$dbtype = $this->database_type;
if($dbtype=="sql" || $dbtype=="mssql" || $dbtype=="ibm" || $dbtype=="databaselibrary" || $dbtype=="odbc")
{
$sql_statement = "select top 1 $table_field from $db_table order by $table_field desc";
}
if($dbtype=="oracle")
{
$sql_statement = "select $table_field from $db_table where ROWNUM<=1 order by $table_field desc";
}
if($dbtype=="informix" || $dbtype=="firebird")
{
$sql_statement = "select first 1 $table_field from $db_table order by $table_field desc";
}
if($dbtype=="mysql" || $dbtype=="sqlite2" || $dbtype=="sqlite3")
{
$sql_statement = "select $table_field from $db_table order by $table_field desc limit 1";
}
if($dbtype=="postgre")
{
$sql_statement = "select $table_field from $db_table order by $table_field desc limit 1 offset 0";
}
if($this->con!=null)
{
try
{
return $this->query_single($sql_statement);
}
catch(PDOException $e)
{
$this->log("Error: ". $e->getMessage());
return false;
}
}
else
{
$this->log("Error: Connection to database lost.");
return false;
}
}
//Get all the tables from a specified database
public function ShowTables($database)
{
$this->err_msg = "";
$complete = "";
$sql_statement = "";
$dbtype = $this->database_type;
if($dbtype=="sql" || $dbtype=="mssql" || $dbtype=="ibm" || $dbtype=="databaselibrary" || $dbtype=="odbc" || $dbtype=="sqlite2" || $dbtype=="sqlite3")
{
$sql_statement = "select name from sysobjects where xtype='U'";
}
if($dbtype=="oracle")
{
//If the query statement fail, try with uncomment the next line:
//$sql_statement = "SELECT table_name FROM tabs";
$sql_statement = "SELECT table_name FROM cat";
}
if($dbtype=="informix" || $dbtype=="firebird")
{
$sql_statement = "SELECT RDB$RELATION_NAME FROM RDB$RELATIONS WHERE RDB$SYSTEM_FLAG = 0 AND RDB$VIEW_BLR IS NULL ORDER BY RDB$RELATION_NAME";
}
if($dbtype=="mysql")
{
if($database!="")
{
$complete = " from $database";
}
$sql_statement = "show tables $complete";
}
if($dbtype=="postgre")
{
$sql_statement = "select relname as name from pg_stat_user_tables order by relname";
}
if($this->con!=null)
{
try
{
$this->sql=$sql_statement;
return $this->con->query($this->sql);
}
catch(PDOException $e)
{
$this->log("Error: ". $e->getMessage());
return false;
}
}
else
{
$this->log("Error: Connection to database lost.");
return false;
}
}
//Get all databases that exists on the server (and where you got permission to use them)
public function showDatabases()
{
$this->err_msg = "";
$sql_statement = "";
$dbtype = $this->database_type;
if($dbtype=="sql" || $dbtype=="mssql" || $dbtype=="ibm" || $dbtype=="databaselibrary" || $dbtype=="odbc" || $dbtype=="sqlite2" || $dbtype=="sqlite3")
{
$sql_statement = "SELECT name FROM sys.Databases";
}
if($dbtype=="oracle")
{
//If the query statement fail, try with uncomment the next line:
//$sql_statement = "select * from user_tablespaces";
$sql_statement = "select * from v$database";
}
if($dbtype=="informix" || $dbtype=="firebird")
{
$sql_statement = "";
}
if($dbtype=="mysql")
{
$sql_statement = "SHOW DATABASES";
}
if($dbtype=="postgre")
{
$sql_statement = "select datname as name from pg_database";
}
if($this->con!=null)
{
try
{
$this->sql=$sql_statement;
return $this->con->query($this->sql);
}
catch(PDOException $e)
{
$this->log("Error: ". $e->getMessage());
return false;
}
}
else
{
$this->log("Error: Connection to database lost.");
return false;
}
}
//Get the latest error ocurred in the connection
public function getError()
{
return trim($this->err_msg)!="" ? "<span style='color:#FF0000;background:#FFEDED;font-weight:bold;border:2px solid #FF0000;padding:2px 4px 2px 4px;'>".$this->err_msg."</span><br />" : "";
}
//Disconnect from database
public function close()
{
$this->err_msg = "";
if($this->con)
{
$this->con = null;
return true;
}
else
{
$this->log("Error: Connection to database lost.");
return false;
}
}
//Build the query neccesary for the count(*) in rowcount method
private function stmntCount($query_stmnt)
{
if(trim($query_stmnt)!="")
{
$query_stmnt = trim($query_stmnt);
$query_split = explode(" ",$query_stmnt);
$query_flag = false;
$query_final = "";
for($x=0;$x<count($query_split);$x++)
{
//Checking "SELECT"
if($x==0 && strtoupper(trim($query_split[$x]))=="SELECT")
$query_final = "SELECT count(*) ";
if($x==0 && strtoupper(trim($query_split[$x]))!="SELECT")
return false;
//Checking "FROM"
if(strtoupper(trim($query_split[$x]))=="FROM")
{
$query_final .= "FROM ";
$query_flag = true;
continue;
}
//Building the query
if(trim($query_split[$x])!="" && $query_flag)
$query_final .= " " . trim($query_split[$x]) . " ";
}
return trim($query_final);
}
return false;
}
}
?>

419
system/SuperSmash/debug.php Normal file
View File

@ -0,0 +1,419 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\SuperSmash;
use settings\settings;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class Debug
{
// This variable will hold the instance of the class
private static $instance;
// This variable will hold the errorMessage
protected $errorMessage;
// This variable will hold the file that contains the error
protected $errorFile;
// This variable will hold the line the error is on
protected $errorLine;
// This variable will hold the level of the error
protected $errorLevel;
// This variable will hold the backTrace of the error
protected $errorTrace;
// This variable will hold check if we need to log the error
protected $logErrors;
// This variable will hold the error development level
protected $development;
// This variable will hold the original settings
protected $originalSettings;
// This variable will hold the the url Information
protected $urlInformation;
// This variable will hold the current language
protected $language;
// Create the constructor
public function __construct()
{
// Set the error reporting
$this->logErrors = configuration('logErrors', 'SuperSmash');
$this->development = configuration('development', 'SuperSmash');
// Save our original settings incase we change them midscript
$this->originalSettings['logErrors'] = $this->logErrors;
$this->originalSettings['development'] = $this->development;
// Get our URL info
$this->urlInformation = getUrlInformation();
}
// This function will trigger the error
public function triggerError($errorNumber, $message = '', $file = '', $line = 0, $backtrace = null)
{
// Language setup
$this->language = strtolower(configuration('language', 'SuperSmash'));
// fill in the attributes
$this->errorMessage = $message;
$this->errorFile = $file;
$this->errorLine = $line;
$this->errorTrace = $backtrace;
// Get the error Level
switch($errorNumber)
{
case E_USER_ERROR:
$this->errorLevel = 'Error';
$severity = 2;
break;
case E_USER_WARNING:
$this->errorLevel = 'Warning';
$severity = 1;
break;
case E_USER_NOTICE:
$this->errorLevel = 'Notice';
$severity = 1;
break;
case E_ERROR:
$this->errorLevel = 'Error';
$severity = 2;
break;
case E_WARNING:
$this->errorLevel = 'Warning';
$severity = 1;
break;
case E_NOTICE:
$this->errorLevel = 'Notice';
$severity = 1;
break;
case E_STRICT:
$this->errorLevel = 'Strict';
$severity = 1;
break;
default:
$this->errorLevel = 'Error Code: '.$errorNumber;
$severity = 2;
break;
}
// Check if the error Logging is enabled
if ($this->logErrors)
{
$this->logError();
}
// Check if the error is important or the development environment is active
if($this->development || $severity == 2)
{
// create the error page
$this->createErrorPage();
}
}
// This function will show a specific error page
public function showError($type)
{
if (ob_get_level() != 0)
{
ob_end_clean();
}
// Get the language
$language = strtolower (configuration('language', 'SuperSmash'));
// Get the site url
$websiteURL = $this->urlInformation['websiteURL'];
// See if there is a custom page in the app folder
if(file_exists(settings::getFilePath() . DS . settings::getApp() . 'pages' . DS . $this->language . DS . $type .'.php'))
{
ob_start();
require_once(settings::getFilePath() . DS . settings::getApp() . 'pages' . DS . $this->language . DS . $type .'.php');
$page = ob_get_contents();
$page = str_replace("<head>","<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">
<meta name=\"generator\" content=\"SuperSmash Framework\" />"
,$page);
// Replace some footer values
$Benchmark = loadClass('Benchmark');
$page = str_replace('{elapsed}', $Benchmark->elapsed('system', 4), $page);
$page = str_replace('{usage}', $Benchmark->usage(), $page);
ob_end_clean();
die($page);
}
else
{
ob_start();
require_once(SYSTEM . DS . "SuperSmash" . DS . 'pages' . DS . $this->language . DS . $type .'.php');
$page = ob_get_contents();
$page = str_replace("<head>","<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">
<meta name=\"generator\" content=\"SuperSmash Framework\" />"
,$page);
// Replace some footer values
$Benchmark = loadClass('Benchmark');
$page = str_replace('{elapsed}', $Benchmark->elapsed('system', 4), $page);
$page = str_replace('{usage}', $Benchmark->usage(), $page);
ob_end_clean();
die($page);
}
}
// This function will log the error to the log file
protected function logError()
{
// Get the site url
$url = $this->urlInformation;
// Create the log message
$err_message = "| Logging started at: ". date('Y-m-d H:i:s') ."\n";
$err_message .= "| Error Level: ".$this->errorLevel ."\n";
$err_message .= "| Message: ".$this->errorMessage ."\n";
$err_message .= "| Reporting File: ".$this->errorFile."\n";
$err_message .= "| Error Line: ".$this->errorLine."\n";
$err_message .= "| URL When Error Occured: ". $url['websiteURL'] ."/". $url['uri'] ."\n\n";
$err_message .= "--------------------------------------------------------------------\n\n";
// Write to the log file
$log = @fopen(SYSTEM . DS . 'editable' . DS . 'logs' . DS . ERROR, 'a');
@fwrite($log, $err_message);
@fclose($log);
}
// This function will log the message to the debugging log
public function log($message, $filename = DEBUG)
{
// Create the log message
$logMessage = "(".date('Y-m-d H:i:s') .") ".$message ."\n";
// Write to the log file
if (file_exists(settings::getFilePath() . DS . settings::getApp() . DS . "logs"))
{
$log = @fopen(settings::getFilePath() . DS . settings::getApp() . DS . "logs" . DS . $filename, 'a');
}
else
{
$log = @fopen(SYSTEM . DS . 'editable' . DS . 'logs' . DS . $filename, 'a');
}
@fwrite($log, $logMessage);
@fclose($log);
}
// This function will enable or disable errorReporting
public function errorReporting($report = true)
{
if($report)
{
// Set the error reporting back to the original state
$this->logErrors = $this->originalSettings['logErrors'];
$this->development = $this->originalSettings['development'];
}
else
{
// Use the custom error reporting
$this->logErrors = 0;
$this->development = 0;
}
return true;
}
// This function will build the error page
protected function createErrorPage()
{
if (ob_get_level() != 0)
{
ob_end_clean();
}
// Get the site url
$websiteURL = $this->urlInformation['websiteURL'];
// Get the correct error message
ob_start();
if(!$this->development)
{
require_once(SYSTEM . DS . "SuperSmash" . DS . 'pages' . DS . 'error.php');
}
else
{
require_once(SYSTEM . DS . "SuperSmash" . DS . 'pages' . DS . 'debug_error.php');
}
$page = ob_get_contents();
// Replace some footer values
$Benchmark = loadClass('Benchmark');
$page = str_replace('{elapsed}', $Benchmark->elapsed('system', 4), $page);
$page = str_replace('{usage}', $Benchmark->usage(), $page);
ob_end_clean();
// If we are debugging, build the debug block
if($this->development)
{
// Create the regex, and search for it
$regex = "{DEBUG}(.*){/DEBUG}";
while(preg_match("~". $regex ."~iUs", $page, $match))
{
$blocks = '';
// We dont need the first trace because its in the error message
unset($this->errorTrace[0]);
$i = 1;
// Make sure we have at least 1 backtrace!
if(count($this->errorTrace) > 0)
{
// Loop through each level and add it to the $blocks var.
foreach($this->errorTrace as $key => $value)
{
$block = $match[1];
$block = str_replace('{#}', $key++, $block);
// Loop though each variable in the Trace level
foreach($value as $key => $value)
{
// Upper case the key
$key = strtoupper($key);
// If $v is an object, then go to next loop
if(is_object($value))
{
continue;
}
// If $v is an array, we need to dump it
if(is_array($value))
{
$value = "<pre>" . $this->var_dump($value, $key) . "</pre>";
}
$block = str_replace("{".$key."}", $value, $block);
}
// Add to blocks
$blocks .= $block;
// We only want to do this no more then 3 times
if($i == 2)
{
break;
}
$i++;
}
}
// Finally replace the whole thing with $blocks
$page = str_replace($match[0], $blocks, $page);
}
}
// add the error information to the page
$page = str_replace("{ERROR_COPYRIGHT}", "SuperSmash Framework &#169;" . date("Y") . " <a href=\"http://www.SuperSmash.nl\">SuperSmash</a>", $page);
$page = str_replace("{ERROR_LEVEL}", $this->errorLevel, $page);
$page = str_replace("{MESSAGE}", $this->errorMessage, $page);
$page = str_replace("{FILE}", $this->errorFile, $page);
$page = str_replace("{LINE}", $this->errorLine, $page);
die($page);
}
// This function will create a var dump
protected function var_dump($variable, $var_name = null, $indent = null)
{
// create an empty html variable
$html = '';
// Create the tabIndentation style
$tab_line = "<span style='color:red;'>|</span> &nbsp;&nbsp;&nbsp;&nbsp ";
// Grab our variable type and get our text color
$type = ucfirst(gettype($variable));
switch($type)
{
case "Array":
// Count our number of keys in the array
$count = count($variable);
$html .= "$indent" . ($var_name ? "$var_name => ":"") . "<span style='color:red'>$type ($count)</span><br />$indent(<br />";
$keys = array_keys($variable);
// Foreach array key, we need to get the value.
foreach($keys as $name)
{
$value = $variable[$name];
$html .= $this->var_dump($value, "['$name']", $indent.$tab_line);
}
$html .= "$indent)<br />";
break;
case "String":
$type_color = "<span style='color:green'>";
$html .= "$indent$var_name = <span style='color:orange'>$type(".strlen($variable).")</span> $type_color\"$variable\"</span><br />";
break;
case "Integer":
$type_color = "<span style='color:red'>";
$html .= "$indent$var_name = <span style='color:blue'>$type(".strlen($variable).")</span> $type_color$variable</span><br />";
break;
case "Double":
$type_color = "<span style='color:red'>";
$type = "Float";
$html .= "$indent$var_name = <span style='color:blue'>$type(".strlen($variable).")</span> $type_color$variable</span><br />";
break;
case "Boolean":
$type_color = "<span style='color:blue'>";
$html .= "$indent$var_name = <span style='color:brown'>$type(".strlen($variable).")</span> $type_color".($variable == 1 ? "true":"false")."</span><br />";
break;
case "null":
$type_color = "<span style='color:black'>";
$html .= "$indent$var_name = <span style='color:purple'>$type(".strlen($variable).")</span> ".$type_color."null</span><br />";
break;
case "Object":
$type_color = "<span style='color:black'>";
$html .= "$indent$var_name = <span style='color:yellow'>$type</span><br />";
break;
case "Resource":
$type_color = "<span style='color:black'>";
$html .= "$indent$var_name = <span style='color:yellow'>$type</span> ".$type_color."Resource</span><br />";
break;
default:
$html .= "$indent$var_name = <span style='color:red'>$type(".@strlen($variable).")</span> $variable<br />";
break;
}
return $html;
}
}
?>

View File

@ -0,0 +1,281 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
use settings\settings;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
// This function will autoload the classes that are not yet included/loaded in the SuperSmash Framework
function __autoload($className)
{
// We will need to lowercase everything
$parts = explode(DS, strtolower($className));
// We need to remove the first part of the array (if the value is empty)
// (This can happen because you came from the root namespace)
if (empty($parts[0]))
{
array_shift($parts);
};
// Build the filePath
$classPath = implode(DS, $parts);
$classPath = str_replace('\\', DS, $classPath);
// We need to assign our filePath as the root (so php looks there when looking for files)
$file = ROOT . DS . $classPath .'.php';
$file = str_replace('supersmash', 'SuperSmash', $file);
// If the file exists, then include it else show an error
if (!file_exists($file))
{
// Failed to load the class we where looking for.
showError('autoLoad', array(addslashes($className)), E_ERROR);
}
require_once($file);
}
// This function will handle all the errors that where given by PHP (this will be the default error handler)
function errorHandler($errorNumber, $errorMessage, $errorFile, $errorLine) {
if(!$errorNumber)
{
return;
}
// Get the debug instance
$debug = loadClass('Debug');
// Trigger the error
$debug->triggerError($errorNumber, $errorMessage, $errorFile, $errorLine, debug_backtrace());
// Don't execute PHP internal error handler
return true;
}
// This function will show the errorMessage
function showError($errorMessage = 'none', $arguments = null, $level = E_ERROR)
{
// Let get a backtrace for deep debugging
$backtrace = debug_backtrace();
$calling = $backtrace[0];
$language = system\SuperSmash\SuperSmash::language();
$message = $language->get($errorMessage);
// Allow custom messages
if(!$message)
{
$message = $errorMessage;
}
// check if there are any arguments
if(is_array($arguments))
{
// Add the arguments to the message
$message = vsprintf($message, $arguments);
}
// Get the debug instance
$debug = loadClass('Debug');
// Add a break to the errorMessage
$message = "<br>" . $message;
// Trigger the error
$debug->triggerError($level, $message, $calling['file'], $calling['line'], $backtrace);
}
// This function will show an 404 error page
function show_404()
{
// Get the debug instance
$debug = loadClass('Debug');
// Show the error
$debug->showError(404);
}
// This function will log a message to a specified filename log
function logMessage($message, $filename = DEBUG)
{
// Get the debug instance
$debug = loadClass('Debug');
// Log the error
$debug->log($message, $filename);
}
// This function returns an item of the configuration file
function configuration($item, $type = 'SuperSmash')
{
// Get the config instance
$configuration = loadClass('Configuration');
// Return the specific item
return $configuration->get($item, $type);
}
// This function will set an item in the configuration file
function configurationSet($item, $value, $name = 'SuperSmash')
{
// Get the config instance
$configuration = loadClass('Configuration');
// Set the specific configuration item in the configuration file
$configuration->set($item, $value, $name);
}
// This function will save a configuration to the configuration.php file
function configurationSave($name)
{
// Get the config instance
$configuration = loadClass('Configuration');
// Save the configuration to the configuration.php file
return $configuration->save($name);
}
// This function will load the specific configuration in the configuration.php
function configurationLoad($file, $name, $array = false)
{
$configuration = loadClass('Configuration');
$configuration->load($file, $name, $array);
}
// This function will get an instance of the controller
function getInstance()
{
if (class_exists('application\\SuperSmash\\Controller', false))
{
return application\SuperSmash\Controller::getInstance();
}
elseif (class_exists('system\\SuperSmash\\Controller', false))
{
return system\SuperSmash\Controller::getInstance();
}
else
{
return false;
}
}
// This function will return the website URL and the URL information
function getUrlInformation()
{
return loadClass('Router')->getUrlInformation();
}
// This function will load a specific className
function loadClass($className, $type = 'SuperSmash', $parameters = array())
{
// We need to create a className path for the correct class
if(strpos($className, '\\') === false)
{
$className = $type . DS . $className;
}
// We will need to lowercase everything
$class = strtolower($className);
// We will need to change the SuperSmash directory to its capital case
$class = str_replace('supersmash', 'SuperSmash', $class);
// Create a storageName for the class
$store_name = str_replace('\\', '_', $class);
// Check if the class exists in the registry
$loaded = \system\SuperSmash\Registry::singleton()->load($store_name);
if($loaded !== null)
{
return $loaded;
}
// The class was not found in the registry so we need to look for the classFile ourself
// Split the class path in parts
$parts = explode('\\', $class);
// Build our filepath
$file = str_replace('\\', DS, implode('\\', $parts));
// If we dont have the full path, we need to create it
if($parts[0] !== 'system' && $parts[0] !== 'application')
{
// Check for needed classes in the Application library folder
if(file_exists(settings::getFilePath() . DS . settings::getApp() . DS . $file . '.php'))
{
$file = settings::getFilePath() . DS . settings::getApp() . DS . $file .'.php';
$className = DS . 'application' . DS . $className;
}
else
{
$file = SYSTEM . DS . $file .'.php';
$className = DS .'system' . DS . $className;
}
}
else
{
$file = ROOT . $file .'.php';
}
require_once ($file);
if (!class_exists($className))
{
// We only want the className and dont need the parent paths
if (strlen(strstr($className, DS . "system" . DS . "SuperSmash" . DS))>0) $className = str_replace(DS . "system" . DS . "SuperSmash" . DS, "", $className);
// Check if the class needs parameters
if (!empty($parameters))
{
try
{
$newClass = new ReflectionClass($className);
$newClass = $newClass->newInstanceArgs($parameters);
}
catch (Exception $exception)
{
die("The class $className could not be loaded >>> <br/><br/> $exception");
}
}
else
{
// Create an object of the new class
$newClass = '\system\\SuperSmash\\' . $className;
$newClass = new $newClass;
}
}
// Store the new object in the registry
\system\SuperSmash\Registry::singleton()->store($store_name, $newClass);
// return the new class.
return $newClass;
}
// This function will redirect you to a specified URL after a specified waiting time
function redirect($url, $wait = 0)
{
// Check if the URL is valid. If not then add our current websiteURL to it.
if(!preg_match('@^(mailto|ftp|http(s)?)://@i', $url))
{
$websiteURL = getUrlInformation();
$url = $websiteURL['websiteURL'] .'/'. $url;
}
// Check if we need to wait a few seconds before we can redirect the user
if($wait >= 1)
{
header("Refresh:". $wait .";url=". $url);
}
else
{
header("Location: ".$url);
die();
}
}
?>

463
system/SuperSmash/input.php Normal file
View File

@ -0,0 +1,463 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\SuperSmash;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class Input
{
// This variable will hold the cookie expiration time
protected $time;
// This variable will hold the cookie path
protected $cookiePath;
// This variable will hold the cookie domain
protected $cookieDomain;
// This variable will hold the user agent of the user
protected $userAgent = false;
// This variable will hold the ipaddress of the user
protected $ipAddress = false;
// This variable will hold the Array of tags and attributes
protected $tagsArray = array();
protected $attributesArray = array();
// This variable will hold the tagging methods
protected $tagsMethod = 0;
protected $attributesMethod = 0;
// This variable will hold the activation of the xss autocleaner
protected $xssAuto = 1;
// This variable will hold an array with the Blacklisting of tags and attributes
protected $tagBlackList = array('applet', 'body', 'bgsound',
'base', 'basefont', 'embed', 'frame', 'frameset', 'head', 'html', 'id', 'iframe',
'ilayer', 'layer', 'link', 'meta', 'name', 'object', 'script', 'style', 'title', 'xml'
);
protected $attributesBlackList = array('action', 'background', 'codebase', 'dynsrc', 'lowsrc');
// Create the constructor
public function __construct()
{
// Set the cookie defaults
$this->time = ( time() + (60 * 60 * 24 * 365) ); // Default: 1 year
$this->cookiePath = "/";
$this->cookieDomain = rtrim($_SERVER['HTTP_HOST'], '/');
}
// This function will return the post variable
public function post($var, $xss = false)
{
if(isset($_POST[$var]))
{
if(!$xss)
{
return $_POST[$var];
}
return $this->clean($_POST[$var]);
}
return false;
}
// This function will return the get variable
public function get($var, $xss = false)
{
if(isset($_GET[$var]))
{
if(!$xss)
{
return $this->cleanElement($_GET[$var]);
}
return $this->cleanElement($this->clean($_GET[$var]));
}
return false;
}
public function cleanElement($variable)
{
if(!is_array($variable))
$variable = htmlentities($variable,ENT_QUOTES,"UTF-8");
else
foreach ($variable as $key => $value)
$variable[$key] = $this->clean($value);
return $variable;
}
// This function will return the cookie variable
public function cookie($name, $xss = false)
{
if (\system\SuperSmash\Cookie::exists($name)){
if(!$xss) {
return \system\SuperSmash\Cookie::get($name);
}
return $this->clean(\system\SuperSmash\Cookie::get($name));
}
return false;
}
// This function will set the cookie variable
function setCookie($cookieName, $cookieValue, $cookieTime = null)
{
if($cookieTime === null)
{
$cookieTime = $this->time;
}
\system\SuperSmash\Cookie::set($cookieName, $cookieValue, false, $cookieTime,$this->cookiePath);
}
// This function will return the user agent of the user
public function userAgent()
{
if(!$this->userAgent)
{
$this->userAgent = (isset($_SERVER['HTTP_userAgent']) ? $_SERVER['HTTP_userAgent'] : false);
}
return $this->userAgent;
}
// This function will return the ipAddress of the user
public function ipAddress()
{
// Return it if we already determined the IP
if(!$this->ipAddress)
{
// Check to see if the server has the IP address
if(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] != '')
{
$this->ipAddress = $_SERVER['REMOTE_ADDR'];
}
elseif(isset($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != '')
{
$this->ipAddress = $_SERVER['HTTP_CLIENT_IP'];
}
// If we still have a false IP address, then set to 0's
if (!$this->ipAddress)
{
$this->ipAddress = '0.0.0.0';
}
}
return $this->ipAddress;
}
// This function will set the cleaning rules
public function setRules($tagsArray = array(), $attributesArray = array(), $tagsMethod = 0, $attributesMethod = 0, $xssAuto = 1)
{
// Count how many are in each for out loops
$countTags = count($tagsArray);
$countAttributes = count($attributesArray);
// Loop through and lowercase all Tags
for($i = 0; $i < $countTags; $i++)
{
$tagsArray[$i] = strtolower($tagsArray[$i]);
}
// Loop through and lowercase all attributes
for($i = 0; $i < $countAttributes; $i++)
{
$attributesArray[$i] = strtolower($attributesArray[$i]);
}
// Set the class variables
$this->tagsArray = $tagsArray;
$this->attributesArray = $attributesArray;
$this->tagsMethod = $tagsMethod;
$this->attributesMethod = $attributesMethod;
$this->xssAuto = $xssAuto;
}
// This function will clean the given input
public function clean($source)
{
// If in array, clean each value
if(is_array($source))
{
foreach($source as $key => $value)
{
if(is_string($value))
{
// filter element for XSS and other 'bad' code etc.
$source[$key] = $this->remove($this->decode($value));
}
}
return $source;
}
elseif(is_string($source))
{
// filter element for XSS and other 'bad' code etc.
return $this->remove($this->decode($source));
}
return $source;
}
// This function will remove unwanted tags
protected function remove($source)
{
$loopCounter = 0;
while($source != $this->filterTags($source))
{
$source = $this->filterTags($source);
$loopCounter++;
}
return $source;
}
// This function will strip certain tags of the string
protected function filterTags($source)
{
$preTag = null;
$postTag = $source;
// find initial tag's position
$tagOpen_start = strpos($source, '<');
// interate through string until no tags left
while($tagOpen_start !== false)
{
// process tag interatively
$preTag .= substr($postTag, 0, $tagOpen_start);
$postTag = substr($postTag, $tagOpen_start);
$fromTagOpen = substr($postTag, 1);
$tagOpen_end = strpos($fromTagOpen, '>');
if($tagOpen_end === false)
{
break;
}
// next start of tag (for nested tag assessment)
$tagOpen_nested = strpos($fromTagOpen, '<');
if(($tagOpen_nested !== false) && ($tagOpen_nested < $tagOpen_end))
{
$preTag .= substr($postTag, 0, ($tagOpen_nested + 1));
$postTag = substr($postTag, ($tagOpen_nested + 1));
$tagOpen_start = strpos($postTag, '<');
continue;
}
$tagOpen_nested = (strpos($fromTagOpen, '<') + $tagOpen_start + 1);
$currentTag = substr($fromTagOpen, 0, $tagOpen_end);
$tagLength = strlen($currentTag);
if(!$tagOpen_end)
{
$preTag .= $postTag;
$tagOpen_start = strpos($postTag, '<');
}
// iterate through tag finding attribute pairs - setup
$tagLeft = $currentTag;
$attributeSet = array();
$currentSpace = strpos($tagLeft, ' ');
// is end tag
if(substr($currentTag, 0, 1) == "/")
{
$isCloseTag = true;
list($tagName) = explode(' ', $currentTag);
$tagName = substr($tagName, 1);
}
else
{
$isCloseTag = false;
list($tagName) = explode(' ', $currentTag);
}
// excludes all "non-regular" tagnames OR no tagname OR remove if xssauto is on and tag is blacklisted
if((!preg_match("/^[a-z][a-z0-9]*$/i", $tagName)) || (!$tagName) || ((in_array(strtolower($tagName),
$this->tagBlackList)) && ($this->xssAuto)))
{
$postTag = substr($postTag, ($tagLength + 2));
$tagOpen_start = strpos($postTag, '<');
continue;
}
// this while is needed to support attribute values with spaces in!
while($currentSpace !== false)
{
$fromSpace = substr($tagLeft, ($currentSpace+1));
$nextSpace = strpos($fromSpace, ' ');
$openQuotes = strpos($fromSpace, '"');
$closeQuotes = strpos(substr($fromSpace, ($openQuotes+1)), '"') + $openQuotes + 1;
// another equals exists
if(strpos($fromSpace, '=') !== false)
{
// opening and closing quotes exists
if(($openQuotes !== false) && (strpos(substr($fromSpace, ($openQuotes+1)), '"') !== false))
{
$attr = substr($fromSpace, 0, ($closeQuotes+1));
}
else
{
$attr = substr($fromSpace, 0, $nextSpace);
}
}
else
{
$attr = substr($fromSpace, 0, $nextSpace);
}
if(!$attr)
{
$attr = $fromSpace;
}
// add to attribute pairs array
$attributeSet[] = $attr;
// next inc
$tagLeft = substr($fromSpace, strlen($attr));
$currentSpace = strpos($tagLeft, ' ');
}
// appears in array specified by user
$tagFound = in_array(strtolower($tagName), $this->tagsArray);
// remove this tag on condition
if((!$tagFound && $this->tagsMethod) || ($tagFound && !$this->tagsMethod))
{
// reconstruct tag with allowed attributes
if(!$isCloseTag)
{
$attributeSet = $this->filterAttribute($attributeSet);
$preTag .= '<' . $tagName;
for($i = 0; $i < count($attributeSet); $i++)
{
$preTag .= ' ' . $attributeSet[$i];
}
// reformat single tags to XHTML
if(strpos($fromTagOpen, "</" . $tagName))
{
$preTag .= '>';
}
else
{
$preTag .= ' />';
}
}
else
{
$preTag .= '</' . $tagName . '>';
}
}
// find next tag's start
$postTag = substr($postTag, ($tagLength + 2));
$tagOpen_start = strpos($postTag, '<');
}
// append any code after end of tags
$preTag .= $postTag;
return $preTag;
}
// This function will strip certain tags off attributes
protected function filterAttribute($attributeSet)
{
$newSet = array();
// process attributes
for($i = 0; $i <count($attributeSet); $i++)
{
// skip blank spaces in tag
if(!$attributeSet[$i])
{
continue;
}
// split into attr name and value
$attrSubSet = explode('=', trim($attributeSet[$i]));
list($attrSubSet[0]) = explode(' ', $attrSubSet[0]);
// removes all "non-regular" attr names AND also attr blacklisted
if ((!preg_match("/^[a-z]*$/i", $attrSubSet[0])) || (($this->xssAuto) && ((in_array(strtolower($attrSubSet[0]),
$this->attributesBlackList)) || (substr($attrSubSet[0], 0, 2) == 'on'))))
{
continue;
}
// xss attr value filtering
if($attrSubSet[1])
{
// strips unicode, hex, etc
$attrSubSet[1] = str_replace('&#', '', $attrSubSet[1]);
// strip normal newline within attr value
$attrSubSet[1] = preg_replace('/\s+/', '', $attrSubSet[1]);
// strip double quotes
$attrSubSet[1] = str_replace('"', '', $attrSubSet[1]);
// [requested feature] convert single quotes from either side to doubles (Single quotes shouldn't be used to pad attr value)
if ((substr($attrSubSet[1], 0, 1) == "'") && (substr($attrSubSet[1], (strlen($attrSubSet[1]) - 1), 1) == "'"))
{
$attrSubSet[1] = substr($attrSubSet[1], 1, (strlen($attrSubSet[1]) - 2));
}
// strip slashes
$attrSubSet[1] = stripslashes($attrSubSet[1]);
}
// auto strip attr's with "javascript:
if(((strpos(strtolower($attrSubSet[1]), 'expression') !== false) && (strtolower($attrSubSet[0]) == 'style'))
|| (strpos(strtolower($attrSubSet[1]), 'javascript:') !== false)
|| (strpos(strtolower($attrSubSet[1]), 'behaviour:') !== false)
|| (strpos(strtolower($attrSubSet[1]), 'vbscript:') !== false)
|| (strpos(strtolower($attrSubSet[1]), 'mocha:') !== false)
|| (strpos(strtolower($attrSubSet[1]), 'livescript:') !== false)
) continue;
// if matches user defined array
$attrFound = in_array(strtolower($attrSubSet[0]), $this->attributesArray);
// keep this attr on condition
if((!$attrFound && $this->attributesMethod) || ($attrFound && !$this->attributesMethod))
{
// attr has value
if($attrSubSet[1])
{
$newSet[] = $attrSubSet[0] . '="' . $attrSubSet[1] . '"';
}
// attr has decimal zero as value
elseif($attrSubSet[1] == "0")
{
$newSet[] = $attrSubSet[0] . '="0"';
}
// reformat single attributes to XHTML
else
{
$newSet[] = $attrSubSet[0] . '="' . $attrSubSet[0] . '"';
}
}
}
return $newSet;
}
// This function will decode the source to a clean string
protected function decode($source)
{
$source = html_entity_decode($source, ENT_QUOTES, "ISO-8859-1");
$source = preg_replace('/&#(\d+);/me',"chr(\\1)", $source);
$source = preg_replace('/&#x([a-f0-9]+);/mei',"chr(0x\\1)", $source);
return $source;
}
}
?>

View File

@ -0,0 +1,181 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\SuperSmash;
use settings\settings;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class Language
{
// This variable will contain an array of supported languages
protected $supportedLanguages = array();
// This variable will contain an array of loaded language files
protected $loadedLanguages = array();
// This variable will contain an array of supported system and application languages
protected $languages = array();
// This variable will hold our language
public $language;
// Create the constructor
public function __construct()
{
// Scan the languages folder
$this->scanLanguageFolders();
// Set the default Language
$this->language = configuration('language', 'SuperSmash');
}
// This function will set the specified language
public function setLanguage($language)
{
// Check if the language exists
$language = strtolower($language);
if(in_array($language, $this->languages['application']) || in_array($language, $this->languages['system']))
{
$this->language = $language;
return true;
}
return false;
}
// This function will load the specified language
public function load($file, $language = null)
{
// Set the language if specified
if($language != null)
{
$this->setLanguage($language);
}
// Add the extension, and create our tag
$language = $this->language;
$key = $file .'_'. $language;
$file = $file . '.php';
// Make sure we havent loaded this already
if(isset($this->supportedLanguages[$key]))
{
return $this->supportedLanguages[$key];
}
// Init our empty variable arrays
$vars = array();
$vars2 = array();
// Load the core language file if it exists
if(file_exists(SYSTEM . DS . 'editable' . DS . 'languages' . DS . $language . DS . $file))
{
$vars = include(SYSTEM . DS . 'editable' . DS . 'languages' . DS . $language . DS . $file);
if(!is_array($vars))
{
return false;
}
}
// Next we load the application file, allows overriding of the core one
if(file_exists(settings::getFilePath() . DS . settings::getApp() . DS . 'languages' . DS . $language . DS . $file))
{
$vars2 = include(settings::getFilePath() . DS . settings::getApp() . DS . 'languages' . DS . $language . DS . $file);
if(!is_array($vars2))
{
return false;
}
}
// Merge if both the app and core had the same filename
$vars = array_merge($vars, $vars2);
// Without a return, we need to store what we have here.
$this->loadedLanguages[] = $file;
$this->supportedLanguages[$key] = $vars;
// Init the return
return (!empty($vars)) ? $vars : false;
}
// This function gets the specified variable of the configuration array
public function get($variable, $file = null)
{
// Check to see that we loaded something first
if(empty($this->supportedLanguages))
{
return false;
}
// Determine our language variable filename if not givin
if($file == null)
{
foreach ($this->loadedLanguages as $key => $value) {
$file = $value;
// Build the language key (strip the .php extension)
$key = preg_replace('/\.php$/','',$file) . '_' . $this->language;
// check to see if our var is set... if not, try to load it first
if(!isset($this->supportedLanguages[$key]))
{
$this->load($file);
}
// Attempt to load the actual language var now
if(isset($this->supportedLanguages[$key][$variable]))
{
return $this->supportedLanguages[$key][$variable];
}
}
}
return false;
}
// This function will return an array of all the languages that where found in the language folder
public function getLanguages($type = null)
{
if($type == 'system')
{
return $this->languages['system'];
}
elseif($type == 'application')
{
return $this->languages['application'];
}
return $this->languages;
}
// This function will scan and find all the installed languages
protected function scanLanguageFolders()
{
// Load the system languages first
$path = SYSTEM . DS . 'editable' . DS . 'languages';
$list = opendir( $path );
while($file = readdir($list))
{
if($file[0] != "." && is_dir($path . DS . $file))
{
$this->languages['system'][] = $file;
}
}
closedir($list);
// Finally, Load app languages
$path = settings::getFilePath() . DS . settings::getApp() . DS . 'languages';
$list = opendir( $path );
while($file = readdir($list))
{
if($file[0] != "." && is_dir($path . DS . $file))
{
$this->languages['application'][] = $file;
}
}
closedir($list);
}
}
?>

View File

@ -0,0 +1,107 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\library;
use settings\settings;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class Cache
{
protected $path;
// Create the contructor
public function __construct()
{
$this->path = settings::getFilePath() . DS . settings::getApp() . DS . 'cache';
}
// This function will set the cache path
public function set_path($path)
{
// Remove any trailing slashes
$path = rtrim($path, '/');
$this->path = str_replace( array('\\', '/'), DS, $path );
}
// This function will read and returns the contents of the cached file
public function get($id)
{
// Define a file path
$file = $this->path . DS . $id . '.cache';
// check if our file exists
if(file_exists($file))
{
// Get our file contents and Unserialize our data
$data = file_get_contents($file);
$data = unserialize($data);
// Check out expire time, if expired, remove the file
if($data['expire_time'] < time())
{
unlink($file);
return false;
}
return $data['data'];
}
return false;
}
// This function will save the contents into the given file id.
public function save($id, $contents, $expire = 86400)
{
// Define a file path
$file = $this->path . DS . $id . '.cache';
// Create the files contents
$data = array(
'expire_time' => (time() + $expire),
'data' => $contents
);
// Save file and contents
if(file_put_contents( $file, serialize($data) ))
{
// Try to put read/write permissions on the new file
@chmod($file, 0777);
return true;
}
return false;
}
// This function will delete a cached file
public function delete($id)
{
// Define a file path
$file = $this->path . DS . $id . '.cache';
// Return the direct result of the deleting
return unlink($file);
}
// This function will delete all the cached files
public function clear()
{
// get a list of all files and directories
$files = scandir($this->path);
foreach($files as $file)
{
// Define a file path
$file = $this->path . DS . $file;
// We only want to delete the the cache files, not subfolders
if($file[0] != "." && $file != 'index.html')
{
unlink($file); //Remove the file
}
}
return true;
}
}

View File

@ -0,0 +1,280 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\library;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class Email
{
// This variable will hold the email recipient
protected $to = '';
// This variable will hold an Array of carbon copy's
protected $cc = array();
// This variable will hold an array of blind carbon copy's
protected $bcc = array();
// This variable will hold the email subject
protected $subject = '';
// This variable will hold the email message
protected $message = '';
// This variable will hold an array of attachment data
protected $attachment = array();
// This variable will hold the email character Set
protected $charset = 'ISO-8859-1';
// This variable will hold the email boundary
protected $boundary = '';
// This variable will hold the email header data
protected $header = '';
// This variable will hold the textHeader
protected $textheader = '';
// This variable will hold an array of errors
public $errors = array();
// Create the contructor
public function __construct()
{
// Set our email boundary
$this->boundary = uniqid(time());
}
// This function will send the email
public function send()
{
$this->build_header();
return mail($this->to, $this->subject, $this->message, $this->header);
}
// This function will add a to recipient to the email message
public function to($email, $name = null)
{
// Check if the email is valid before adding it
if(!$this->validate($email))
{
return false;
}
if($name == null)
{
$this->to = $email;
}
else
{
$this->to = $name." <".$email.">";
}
return true;
}
// This function will add a to sender to the email message
public function from($email, $name = null)
{
// Check if the email is valid before adding it
if(!$this->validate($email))
{
return false;
}
if($name == null)
{
$this->header .= "From: ".$email."\r\n";
}
else
{
$this->header .= "From: ".$name." <".$email.">\r\n";
}
return true;
}
// This function will add a reply to to the email message
public function reply_to($email, $name = null)
{
// Check if the email is valid before adding it
if(!$this->validate($email))
{
return false;
}
if($name == null)
{
$this->header .= "Reply-to: ".$email."\r\n";
}
else
{
$this->header .= "Reply-to: ".$name." <".$email.">\r\n";
}
return true;
}
// This function will add a cc to to the email message
public function cc($email)
{
// Check if the email is valid before adding it
if(!$this->validate($email))
{
return false;
}
$this->cc[] = $email;
return true;
}
// This function will add a bcc to to the email message
public function bcc($email)
{
// Check if the email is valid before adding it
if(!$this->validate($email))
{
return false;
}
$this->bcc[] = $email;
return true;
}
// This function will set the email subject
public function subject($subject)
{
$this->subject = strip_tags(trim($subject));
return true;
}
// This function will add the message to the headers so we can actually send the email
public function message($message = '', $type = 'html')
{
$textboundary = uniqid('textboundary');
$this->textheader = "Content-Type: multipart/alternative; boundary=\"".$textboundary."\"\r\n\r\n";
$this->message .= "--". $textboundary ."\r\n";
$this->message .= "Content-Type: text/plain; charset=\"". $this->charset ."\"\r\n";
$this->message .= "Content-Transfer-Encoding: quoted-printable\r\n\r\n";
$this->message .= strip_tags($message) ."\r\n\r\n";
$this->message .= "--". $textboundary ."\r\n";
$this->message .= "Content-Type: text/html; charset=\"".$this->charset ."\"\r\n";
$this->message .= "Content-Transfer-Encoding: quoted-printable\r\n\r\n";
$this->message .= $message ."\r\n\r\n";
$this->message .= "--". $textboundary ."--\r\n\r\n";
}
// This function will add an attachment to the email message
public function attachment($file)
{
// Make sure we are dealing with a real file here
if(is_file($file))
{
$basename = basename($file);
$attachmentheader = "--". $this->boundary ."\r\n";
$attachmentheader .= "Content-Type: ".$this->mime_type($file)."; name=\"".$basename."\"\r\n";
$attachmentheader .= "Content-Transfer-Encoding: base64\r\n";
$attachmentheader .= "Content-Disposition: attachment; filename=\"".$basename."\"\r\n\r\n";
$attachmentheader .= chunk_split(base64_encode(fread(fopen($file,"rb"),filesize($file))),72)."\r\n";
$this->attachment[] = $attachmentheader;
}
else
{
return false;
}
}
// This function builds the email header before being sent
protected function build_header()
{
// Add out Cc's
$count = count($this->cc);
if($count > 0)
{
$this->header .= "Cc: ";
for($i=0; $i < $count; $i++)
{
// Add a comma if we are not on our first!
if($i > 0)
{
$this->header .= ',';
}
$this->header .= $this->cc[$i];
}
$this->header .= "\r\n";
}
// Add out Bcc's
$count = count($this->bcc);
if($count > 0)
{
$this->header .= "Bcc: ";
for($i=0; $i < $count; $i++)
{
// Add comma if we are not on our first!
if($i > 0)
{
$this->header .= ',';
}
$this->header .= $this->bcc[$i];
}
$this->header .= "\r\n";
}
// Add our MINE version and X-Mailer
$this->header .= "X-Mailer: SuperSmash Framework\r\n";
$this->header .= "MIME-Version: 1.0\r\n";
// Add attachments
$attachcount = count($this->attachment);
if($attachcount > 0)
{
$this->header .= "Content-Type: multipart/mixed; boundary=\"". $this->boundary ."\"\r\n\r\n";
$this->header .= "--". $this->boundary ."\r\n";
$this->header .= $this->textheader;
if($attachcount > 0)
{
$this->header .= implode("", $this->attachment);
}
$this->header .= "--". $this->boundary ."--\r\n\r\n";
}
else
{
$this->header .= $this->textheader;
}
}
// This function will check if the emailAddress specified is a valid email address
public function validate($email)
{
// Use PHP's built in email validator
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$this->errors[] = "Invalid Email: <". $email .">";
return false;
}
return true;
}
// This function will get the mime type of a file for attachments
public function mime_type($file)
{
$fileInfo = new finfo();
return $fileInfo->file($file, FILEINFO_MIME);
}
// This function will clear the current email
public function clear()
{
$this->header = null;
$this->to = null;
$this->subject = null;
return true;
}
}
?>

View File

@ -0,0 +1,193 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\library;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class Validation
{
// Our fields
protected $fields;
// Our field rules
protected $field_rules;
// A bool of whether we are debugging
protected $debug;
// Our running list of errors
protected $errors;
// Create the constructor
public function __construct()
{
// Init the default values
$this->fields = $_POST;
$this->field_rules = array();
$this->errors = array();
}
// This function is used to set the rules of certain $_POST vars
public function set($rules)
{
if(!is_array($rules))
{
showError('no_array', array('rules', 'Validation::set'), E_ERROR);
}
// Add the current rules
$this->field_rules = array_merge($this->field_rules, $rules);
// Allow chaining here
return $this;
}
// This function validates all the POST data that has rules set
public function validate($debug = false)
{
// before we begin, make sure we have post data
if(!empty($this->field_rules))
{
// Set our debugging
$this->debug = $debug;
// Validate each of the fields that have rules
foreach($this->field_rules as $field => $rules)
{
// Get our array of rules to process
$rules = explode('|', $rules);
// Make sure that the field we are looking at exists
if(isset($this->fields[$field]))
{
// Process each rule for this post var
foreach($rules as $rule)
{
$result = null;
// We will define the param as false, if preg_match
// finds a second value, then it will overwrite this
$param = false;
if (preg_match("/^(.*?)\[(.*?)\]$/", $rule, $match))
{
$rule = $match[1];
$param = $match[2];
}
// Call the function that corresponds to the rule
if (!empty($rule))
{
$result = $this->$rule($this->fields[$field], $param);
}
// Handle errors
if ($result === false)
{
$this->set_error($field, $rule);
}
}
}
}
return (empty($this->errors));
}
}
// This function returns an array of all the errors by field name
public function get_errors() {
if(count($this->errors) == 0)
{
return array();
}
return $this->errors;
}
// This function sets an error for the $field
protected function set_error($field, $rule)
{
// If debugging, we want an array of all failed validations
if($this->debug)
{
if(isset($this->errors[$field]))
{
$this->errors[$field] .= "|".$rule;
return;
}
$this->errors[$field] = $rule;
return;
}
$this->errors[$field] = true;
}
// This function determines if the string passed has any values
public function required($string, $value = false)
{
if (!is_array($string))
{
// Trim white space and see if its still empty
$string = trim($string);
}
return (!empty($string));
}
// This function determines if the string is a valid email
public function email($string)
{
if(filter_var($string, FILTER_VALIDATE_EMAIL))
{
return true;
}
return false;
}
// This function determines if the string passed is numeric
public function number($string)
{
return (is_numeric($string));
}
// This function determines if the string passed is valid URL
public function url($string)
{
return (!preg_match('@^(mailto|ftp|http(s)?)://(.*)$@i', $string)) ? false : true;
}
// This function determines if the string passed is a float
public function float($string)
{
return (is_float($string));
}
// This function determines if the string passed has a minimum value of $value
public function min($string, $value)
{
if(!is_numeric($string))
{
return (strlen($string) >= $value);
}
return ($string >= $value);
}
// This function determines if the string passed has a maximum value of $value
public function max($string, $value)
{
if(!is_numeric($string))
{
return (strlen($string) <= $value);
}
return ($string <= $value);
}
// This function determines if the string passed contains the specified pattern
public function pattern($string, $pattern)
{
return (!preg_match("/".$pattern."/", $string)) ? false : true;
}
}
?>

View File

@ -0,0 +1,211 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\SuperSmash;
use settings\settings;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class Loader {
// This function will call the specified model
public function model($name, $additionalInstanceName = null)
{
// Check for path. We need to get the model file name
if(!strpos($name, '/'))
{
$paths = explode('/', $name);
$class = ucfirst(end($paths)) . "Model";
}
else
{
$class = ucfirst($name) . "Model";
$name = strtolower($name);
}
// Include the model page
require_once(settings::getFilePath() . DS . settings::getApp() . DS . 'models' . DS . $name .'.php');
// Get our class into a variable
$object = new $class();
// Get the instance
if($additionalInstanceName !== null)
{
getInstance()->$additionalInstanceName = $object;
}
else
{
getInstance()->$class = $object;
}
return $object;
}
// This function will load the view file and display it
public function view($viewName, $data, $displayView = false)
{
// Make sure our data is in an array format
if(!is_array($data))
{
showError('no_array', array('data', 'Loader::view'), E_WARNING);
$data = array();
}
// Set the filePath for the view
$filePath = settings::getFilePath() . DS . settings::getApp() . DS . 'views' . DS . $viewName . DS . 'index.php';
// Set the viewPath for the view
$viewPath = array('viewPath' => DS . 'views' . DS . $viewName);
// Get the websiteURL for the view
$websiteInformation = getUrlInformation();
$websiteInformation = array('websiteURL' => $websiteInformation['websiteURL']);
// Set the websitePath
$websitePath = array('websitePath' => $websiteInformation['websiteURL'] . settings::getApplicationPath() . "/" . settings::getApp());
// Get all the applications for the view
$applications = settings::getApps();
$data = array_merge($data,$viewPath, $websiteInformation, $websitePath, $applications);
// extract variables
extract($data);
// Get our page contents
if(file_exists($filePath))
{
ob_start();
include($filePath);
$page = ob_get_contents();
$page = str_replace("<head>","<head>
<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />
<meta name=\"generator\" content=\"SuperSmash Framework\" />"
,$page);
ob_end_clean();
// Replace some Global values
$Benchmark = loadClass("Benchmark");
$page = str_replace("{elapsed}", $Benchmark->elapsed('system', 4), $page);
$page = str_replace("{usage}", $Benchmark->usage(), $page);
$page = str_replace("</head>", "\t<link rel=\"stylesheet\" type=\"text/css\" href=\"". $websiteURL . "/" . "system" . "/" . "SuperSmash" . "/" . "pages" . "/css/footer.css\"/>\n</head>", $page);
preg_match('/<body[^>]*?[^>]*>/i', $page, $body);
$page = str_replace("$body[0]", "$body[0]\n<div class=\"SuperSmashFrameworkWrapper\">", $page);
$page = str_replace("</body>", "</div>\n</body>", $page);
$page = str_replace("</div>\n</body>", "\t\t<br />\n\t\t<div class=\"SuperSmashFramework\"><p>Running on SuperSmash Framework &#169; " . date("Y") . ", <a target=\"_blank\" href=\"http://www.SuperSmash.nl\">SuperSmash</a></p></div>\n\t</div>\n\t</body>", $page);
// Spit out the page
if(!$displayView)
{
echo $page;
}
return $page;
}
else
{
showError('view', array($viewName), E_ERROR);
return false;
}
}
// This function will be used to call in a class from either the APP library, or the system library folders
public function library($name, $instance = true)
{
// Make sure periods are replaced with slahes if there is any
if(strpos($name, "."))
{
$name = str_replace('.', '\\', $name);
}
// Load the Class
$class = loadClass($name, 'Library');
// Do we instance this class?
if($instance)
{
// Allow for custom class naming
(!$instance) ? $name = $instance : '';
// Instance
$FB = getInstance();
if($FB)
{
(!isset($FB->$name)) ? $FB->$name = $class : '';
}
}
return $class;
}
// This function will be used to setup a database connection
public function database($arguments, $instance = true)
{
// Load our connection settings. We can allow custom connection arguments
if(!is_array($arguments))
{
// Check our registry to see if we already loaded this connection
$object = \Registry::singleton()->load("database".$arguments);
if($object != null)
{
// Skip to the instancing part unless we set instance to false
if($instance)
{
goto Instance;
}
return $object;
}
// Get the DB connection information
$info = configuration($arguments, 'database');
if($info === null)
{
showError('db_key_not_found', array($arguments), E_ERROR);
}
}
// Not in the registry, so establish a new connection
$dispatch = $first ."Database\\Driver";
$object = new $dispatch($info);
// Store the connection in the registry
\Registry::singleton()->store("DBC_".$arguments, $object);
// Here is our instance goto
Instance:
{
// If user wants to instance this, then we do that
if($instance && !is_numeric($arguments))
{
if($instance) $instance = $arguments;
// Easy way to instance the connection is like this
$FB = getInstance();
if($FB)
{
(!isset($FB->$instance)) ? $FB->$instance = $object : '';
}
}
}
return $object;
}
// This function is used to load in a helper file from either the application/helpers, or the SuperSmash/helpers folders
public function helper($name)
{
// Check the application/helpers folder
if(file_exists(settings::getFilePath() . DS . settings::getApp() . DS . 'helpers' . DS . $name . '.php'))
{
require_once(settings::getFilePath() . DS . settings::getApp() . DS . 'helpers' . DS . $name . '.php');
}
// Check the core/helpers folder
else
{
require_once(SYSTEM . DS . 'helpers' . DS . $name . '.php');
}
}
}
?>

View File

@ -0,0 +1,21 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\SuperSmash;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class Model
{
// Create the contructor
public function __construct()
{
$this->load = loadClass('Loader');
}
}
?>

View File

@ -0,0 +1,29 @@
<!DOCTYPE html>
<html>
<head>
<title><?php echo configuration('websiteTitle');?> 404 - Not Found</title>
<link rel="stylesheet" href="<?php echo $websiteURL; ?>/system/SuperSmash/pages/css/main.css" type="text/css"/>
<link rel="shortcut icon" href="<?php echo $websiteURL; ?>/system/SuperSmash/pages/images/favicon.ico">
</head>
<body>
<div id="error-box">
<?php $language = system\SuperSmash\SuperSmash::language(); ?>
<img class="error" src="<?php echo $websiteURL; ?>/system/SuperSmash/pages/images/404.png" alt="404 error" />
<div class="header"><?php echo $language->get('notFoundTitle'); ?></div>
<div class="message">
<?php echo $language->get('notFoundMessage'); ?> <a href="mailto:<?php echo configuration('webmasterEmail');?>"><?php echo $language->get('notFoundEmail'); ?> </a>. <br /><br />
</div>
<div class="links">
<a href='<?php echo $websiteURL; ?>'><?php echo $language->get('startPage'); ?></a> | <a href='javascript: history.go(-1)'><?php echo $language->get('previousPage'); ?></a>
</div>
</div>
<br /><br />
<div id="footer">
<small>
<?php echo $language->get('footerRendered'); ?> {elapsed} <?php echo $language->get('footerSeconds'); ?> {usage}<br />
SuperSmash Framework &#169; <?php echo date("Y");?>, <a href="http://www.SuperSmash.nl">SuperSmash</a>
</small>
</div>
</body>
</html>

View File

@ -0,0 +1,47 @@
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
html,
body {
margin:0;
padding:0;
height:100%;
}
#header{
padding:10px;
}
.SuperSmashFrameworkWrapper {
min-height:10%;
height:100%;
}
.SuperSmashFramework {
position:relative;
float:bottom;
bottom:0px;
width:100%;
height:55px;
background: url(../images/footer.png) repeat-x;
background-position:center;
color: #fff;
font: 0.8em helvetica,arial,sans-serif;
}
.SuperSmashFramework a {
color: #fff;
}
.SuperSmashFramework p {
margin-bottom:10px;
font: 0.8em helvetica,arial,sans-serif;
position: absolute;
bottom: 15px;
width: 100%;
text-align:center;
}

View File

@ -0,0 +1,126 @@
body
{
background: #CCCCCC;
padding: 30px;
margin: 0;
font-family: "SuperSmash";
src: url(./font/SuperSmash.ttf)
}
#error-box
{
width: 800px;
background-color: #f8f8f8;
margin-left: auto;
margin-right: auto;
border: 1px solid #111;
border-radius: 6px;
box-shadow: 0 0 5px 5px #888;
}
div.error-copyright
{
text-align: center;
}
div.error-header
{
margin: 10px;
font-weight: bold;
font-size: 24px;
color: #CC0000;
border-bottom: 1px solid #666666;
}
div.error-message
{
margin:10px;
font-size: 16px;
}
div.debug-error-message
{
margin:10px;
font-size: 16px;
}
img.error
{
display: block;
margin-left: auto;
margin-right: auto;
}
div.header
{
margin: 10px;
font-weight: bold;
font-size: 24px;
color: #000000;
text-align: center;
padding-bottom: 5px;
border-bottom: 1px solid #666666;
}
div.links
{
border-top: 1px solid #666666;
padding-top: 3px;
margin:10px;
text-align: center;
font-size: 12px;
}
div.message
{
margin:10px;
text-align: center;
font-size: 14px;
}
#footer
{
width:600px;
margin: 0 auto;
background: #f8f8f8;
border: 1px solid #999;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
box-shadow: 0 0 5px 5px #888;
text-align: center;
}
pre
{
margin: 0px 0px 10px 0px;
display: block;
background: white;
color: black;
font-family: Verdana;
border: 1px solid #CC0000;
padding: 5px;
font-size: 11px;
line-height: 14px;
overflow:auto;
}
*
{
margin: 0;
}
html, body
{
height: 100%;
}
.wrapper
{
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.SuperSmashFramework, .bottom
{
height: 142px; /* .bottom must be the same height as .footer */
}

View File

@ -0,0 +1,39 @@
<!DOCTYPE html>
<html>
<head>
<title><?php echo configuration('websiteTitle');?> >> {ERROR_LEVEL}</title>
<link rel="stylesheet" href="<?php echo $websiteURL; ?>/system/SuperSmash/pages/css/main.css" type="text/css"/>
<link rel="shortcut icon" href="<?php echo $websiteURL; ?>/system/SuperSmash/pages/images/favicon.ico">
</head>
<body>
<div id="error-box">
<?php $language = system\SuperSmash\SuperSmash::language(); ?>
<div class="error-copyright"><small>{ERROR_COPYRIGHT}</small></div>
<div class="error-header">{ERROR_LEVEL}</div>
<div class="error-message">
<b><?php echo $language->get('debugMessage'); ?></b> {MESSAGE}<br /><br />
<b><?php echo $language->get('debugFile'); ?></b> <br />{FILE}<br /><br />
<b><?php echo $language->get('debugLine'); ?></b> {LINE} <br /><br />
</div>
<div class="debug-error-message">
{DEBUG}
<hr><b><?php echo $language->get('debugTrace'); ?> {#}:</b><br />
<b><?php echo $language->get('debugFile'); ?></b> <br />{FILE}<br /><br />
<b><?php echo $language->get('debugClass'); ?></b> {CLASS} <br />
<b><?php echo $language->get('debugLine'); ?></b> {LINE} <br /><br />
<b><?php echo $language->get('debugFunction'); ?></b> {FUNCTION} <br />
<b><?php echo $language->get('debugFunctionArguments'); ?></b> {ARGS}<hr> <br /><br />
{/DEBUG}
</div>
</div>
<br /><br />
<div id="footer">
<small>
<?php echo $language->get('footerRendered'); ?> {elapsed} <?php echo $language->get('footerSeconds'); ?> {usage}<br />
SuperSmash Framework &#169; <?php echo date("Y");?>, <a href="http://www.SuperSmash.nl">SuperSmash</a>
</small>
</div>
</body>
</html>

View File

@ -0,0 +1,29 @@
<!DOCTYPE html>
<html>
<head>
<title><?php echo configuration('websiteTitle');?> >> {ERROR_LEVEL}</title>
<link rel="stylesheet" href="<?php echo $websiteURL; ?>/system/SuperSmash/pages/css/main.css" type="text/css"/>
<link rel="shortcut icon" href="<?php echo $websiteURL; ?>/system/SuperSmash/pages/images/favicon.ico">
</head>
<body>
<div id="error-box">
<?php $language = system\SuperSmash\SuperSmash::language(); ?>
<div class="error-copyright"><small>{ERROR_COPYRIGHT}</small></div>
<div class="error-header">{ERROR_LEVEL}</div>
<div class="error-message">
<p>
<?php echo $language->get('notFoundErrorMessage'); ?><a href="mailto:<?php echo configuration('webmasterEmail');?>"> <?php echo $language->get('notFoundEmail'); ?></a>. <br/ > <br/ >
</p>
<b><?php echo $language->get('errorMessage'); ?></b> {MESSAGE}
</div>
</div>
<br /><br />
<div id="footer">
<small>
<?php echo $language->get('footerRendered'); ?> {elapsed} <?php echo $language->get('footerSeconds'); ?> {usage}<br />
SuperSmash Framework &#169; <?php echo date("Y");?>, <a href="http://www.SuperSmash.nl">SuperSmash</a>
</small>
</div>
</body>
</html>

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

View File

@ -0,0 +1,67 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\SuperSmash;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class Registry
{
// Registry array of objects
private static $objects = array();
// The instance of the registry
private static $instance;
// prevent cloning of the registry
public function __clone()
{
// Do nothing
}
// This function will create a singleton if it not has been created yet
public static function singleton()
{
if(!isset(self::$instance))
{
self::$instance = new self();
}
return self::$instance;
}
// This function will get a specified key and returns it
protected function get($key)
{
if(isset(self::$objects[$key]))
{
return self::$objects[$key];
}
return null;
}
// This function will set a specified key
protected function set($key,$value)
{
self::$objects[$key] = $value;
}
// This function will load a specified key and returns the singleton
static function load($key)
{
return self::singleton()->get($key);
}
// This function will store an object as a singleton
static function store($key, $instance)
{
return self::singleton()->set($key,$instance);
}
}
?>

View File

@ -0,0 +1,202 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
namespace system\SuperSmash;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class Router
{
// http protocol (https or http)
protected $protocol;
// hostname
protected $hostName;
// website URL
protected $websiteURL;
// requested URI
protected $uri;
// website directory
protected $websiteDir;
// controller name
protected $controler;
// action (sub page)
protected $action;
// querystring
protected $queryString;
// Create the contructor
public function __construct()
{
// Load the input class
$this->input = loadClass('Input');
// Start routing
$this->checkRoutingUrl();
}
// This function will check how the url should be loaded
protected function checkRoutingUrl()
{
// Determine our http hostname, and site directory
$this->hostName = rtrim($_SERVER['HTTP_HOST'], '/');
$this->websiteDir = dirname( $_SERVER['PHP_SELF'] );
// Detect our protocol
if(isset($_SERVER['HTTPS']))
{
if(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')
{
$this->protocol = 'https';
}
else
{
$this->protocol = 'http';
}
}
else
{
$this->protocol = 'http';
}
// Build our Full Base URL
$websiteURL = str_replace('//', '/', $this->hostName .'/'. $this->websiteDir);
$this->websiteURL = $this->protocol .'://' . rtrim($websiteURL, '/');
// Process the site URI
if (!configuration('urlParameters', 'SuperSmash'))
{
// Get our current url, which is passed on by the 'url' param
$this->uri = (isset($_GET['url']) ? $this->input->get('url', true) : '');
}
else
{
// Define our needed vars
$controllerParameter = configuration('controllerParameter', 'SuperSmash');
$actionParameter = configuration('actionParameter', 'SuperSmash');
// Make sure we have a controller at least
$controller = $this->input->get($controllerParameter, true);
if (!$controller)
{
$this->uri = '';
}
else
{
// Get our action
$action = $this->input->get($actionParameter, true);
if(!$action) $action = configuration('defaultAction', 'SuperSmash'); // Default Action
// initialise the uri
$this->uri = $controller .'/'. $action;
// Clean the query string
$queryString = $this->input->clean($_SERVER['QUERY_STRING']);
$queryString = explode('&', $queryString);
foreach($queryString as $string)
{
// Convert this segment to an array
$string = explode('=', $string);
// Dont add the controller / action twice ;)
if($string[0] == $controllerParameter || $string[0] == $actionParameter)
{
continue;
}
// Append the uri vraiable
$this->uri .= '/'. $string[1];
}
}
}
// If the URI is empty, then load defaults
if (empty($this->uri))
{
// Set our Controller / Action to the defaults
$controller = configuration('defaultController', 'SuperSmash'); // Default Controller
$action = configuration('defaultAction', 'SuperSmash'); // Default Action
$queryString = array(); // Default query string
}
// There is a URI, Lets load our controller and action
else
{
// Remove any left slashes or double slashes
$this->uri = ltrim( str_replace('//', '/', $this->uri), '/');
// We will start by bulding our controller, action, and querystring
$urlArray = array();
$urlArray = explode("/", $this->uri);
$controller = $urlArray[0];
// If there is an action, then lets set that in a variable
array_shift($urlArray);
if(isset($urlArray[0]) && !empty($urlArray[0]))
{
$action = $urlArray[0];
array_shift($urlArray);
}
// If there is no action, load the default action.
else
{
$action = configuration('defaultAction', 'SuperSmash'); // Default Action
}
// $queryString is what remains
$queryString = $urlArray;
}
// Make sure the first character of the controller is not an _ !
if( strncmp($controller, '_', 1) == 0 || strncmp($action, '_', 1) == 0 )
{
show_404();
}
// Set static Variables
$this->controller = $controller;
$this->action = $action;
$this->queryString = $queryString;
}
// This function returns all the url information
public function getUrlInformation()
{
$array = array(
'protocol' => $this->protocol,
'hostName' => $this->hostName,
'websiteURL' => $this->websiteURL,
'websiteDir' => $this->websiteDir,
'uri' => $this->uri,
'controller' => $this->controller,
'action' => $this->action,
'querystring' => $this->queryString
);
return $array;
}
// This function returns the specified URI segment
public function getUriSegment($index) {
// Return the URI
if(isset($this->uri[$index]))
{
return $this->uri[$index];
}
return false;
}
}
?>

View File

@ -0,0 +1,606 @@
<?php
/*
CREATE TABLE IF NOT EXISTS `sessions` (
`time_updated` text NOT NULL,
`session_id` text NOT NULL,
`data` blob NOT NULL,
`user_agent` text NOT NULL,
`ip_address` text NOT NULL,
`flagged_for_update` int(11) NOT NULL,
PRIMARY KEY (`session_id`(254))
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
*/
/*
$config['cookie_name'] = 'session_cookie'; // Name of the cookie
$config['table_name'] = 'sessions'; // Database table name
$config['seconds_till_expiration'] = 7200; // How many seconds it takes before the session expires. Default is 2 hours.
$config['renewal_time'] = 300; // How many seconds it takes before the session ID is renewed. Default is 5 minutes.
$config['expire_on_close'] = FALSE; // The session is terminated when the browser is closed.
$config['secure_cookie'] = FALSE; // Decides whether the cookie should only be set when a HTTPS connection exists.
$config['check_ip_address'] = $_SERVER['REMOTE_ADDR']; // Will check the user's IP address against the one stored in the database. Make sure this is a string which is a valid IP address. FALSE by default.
$config['check_user_agent'] = $_SERVER['HTTP_USER_AGENT']; // Will check the user's user agent against the one stored in the database. FALSE by default.
*/
namespace system\SuperSmash;
use settings\settings;
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
class Session
{
/**
* @description PDO database handle
* @access private
* @var PDO database resource
* */
private $_db = NULL;
/**
* @description Database table name where sessions are stored.
* @access private
* @var string
* */
private $_table_name = 'sessions';
/**
* @description Cookie name where the session ID is stored.
* @access private
* @var string
* */
private $_cookie_name = '_Session_cookie';
/**
* @description Number of seconds before the session expires. Default is 2 hours.
* @access private
* @var integer
* */
private $_seconds_till_expiration = 7200; // 2 hours
/**
* @description Number of seconds before the session ID is regenerated. Default is 5 minutes.
* @access private
* @var integer
* */
private $_renewal_time = 300; // 5 minutes
/**
* @description Closes the session when the browser is closed.
* @access private
* @var boolean
* */
private $_expire_on_close = FALSE;
/**
* @description IP address that will be checked against the database if enabled. Must be a valid IP address.
* @access private
* @var string
* */
private $_ip_address = FALSE;
/**
* @description User agent that will be checked against the database if enabled.
* @access private
* @var string
* */
private $_user_agent = FALSE;
/**
* @description Will only set the session cookie if a secure HTTPS connection is being used.
* @access private
* @var boolean
* */
private $_secure_cookie = FALSE;
/**
* @description A hashed string which is the ID of the session.
* @access private
* @var string
* */
private $_session_id = '';
/**
* @description Data stored by the user.
* @access private
* @var array
* */
private $_data = array();
/**
* @description Initializes the session handler.
* @access public
* @param array - configuration options
* @return void
* */
public function __construct(array $config)
{
// Set the cookiename
$this->_cookie_name = settings::getApp() . $this->_cookie_name;
// Sets user configuration
$this->_setConfig($config);
// Runs the session mechanism
if ($this->_read())
{
$this->_update();
}
else
{
$this->_create();
}
// Cleans expired sessions if necessary and writes cookie
$this->_cleanExpired();
$this->_setCookie();
}
/**
* @description Regenerates a new session ID for the current session.
* @access public
* @return void
* */
public function regenerateId()
{
// Acquires a new session ID
$old_session_id = $this->_session_id;
$this->_session_id = $this->_generateId();
// Updates session ID in the database
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET time_updated = ?, session_id = ? WHERE session_id = ?");
$stmt->execute(array(time(), $this->_session_id, $old_session_id));
// Updates cookie
$this->_setCookie();
}
/**
* @description Sets a specific item to the session data array.
* @access public
* @param string - session data array key
* @param string - data value
* @return void
* */
public function setData($key, $value)
{
$this->_data[$key] = $value;
$this->_write(); // Writes to database
}
/**
* @description Unsets a specific item from the session data array.
* @access public
* @param string - session data array key
* @return void
* */
public function unsetData($key)
{
if (isset($this->_data[$key])) unset($this->_data[$key]);
}
/**
* @description Returns a specific item from the session data array.
* @access public
* @param string - session data array key
* @return string - data value/FALSE
* */
public function getData($key)
{
return isset($this->_data[$key]) ? $this->_data[$key] : FALSE;
}
/**
* @description Returns all items in the session data array.
* @access public
* @return array
* */
public function getAllData()
{
return $this->_data;
}
/**
* @description Destroys the current session.
* @access public
* @return void
* */
public function destroy()
{
// Deletes session from the database
if (isset($this->_session_id))
{
$stmt = $this->_db->prepare("DELETE FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
}
// Destroy the cookie
\system\SuperSmash\Cookie::set($this->_cookie_name, '', false, time() - 31500000, NULL,NULL,NULL,NULL);
}
/**
* @description The main session mechanism:
* - Reads session cookie and retreives session data
* - Checks session expiration
* - Verifies IP address (if enabled)
* - Verifies user agent (if enabled)
* @access private
* @return void
* */
private function _read()
{
// Fetches session cookie
$session_id = \system\SuperSmash\Cookie::exists($this->_cookie_name) ? \system\SuperSmash\Cookie::get($this->_cookie_name) : FALSE;
// Cookie doesn't exist!
if (! $session_id) {
return FALSE;
}
$this->_session_id = $session_id;
// Fetches the session from the database
$stmt = $this->_db->prepare("SELECT data, time_updated, user_agent, ip_address FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
$result = $stmt->fetch();
// Did a session exist?
if ($result !== FALSE && count($result) > 0)
{
// Checks if the session has expired in the database
if (! $this->_expire_on_close)
{
if (($result['time_updated'] + $this->_seconds_till_expiration) < time())
{
$this->destroy();
return FALSE;
}
}
// Checks if the user's IP address matches the one saved in the database
if ($this->_ip_address)
{
if ($result['ip_address'] != $this->_ip_address)
{
$this->_flagForUpdate();
return FALSE;
}
}
// Checks if the user's user agent matches the one saved in the database
if ($this->_user_agent)
{
if ($result['user_agent'] != $this->_user_agent)
{
$this->_flagForUpdate();
return FALSE;
}
}
// Checks if the session has been requested to regenerate a new ID (hack attempt)
$this->_checkUpdateFlag();
// Checks if the session ID needs to be renewed (time exceeded)
$this->_checkIdRenewal();
// Sets user data
$user_data = unserialize($result['data']);
if ($user_data)
{
$this->_data = $user_data;
unset($user_data);
}
// All good!
return TRUE;
}
// No session found
return FALSE;
}
/**
* @description Creates a session.
* @access private
* @return void
* */
private function _create()
{
// Generates session ID
$this->_session_id = $this->_generateId();
// Inserts session into database
$stmt = $this->_db->prepare("INSERT INTO {$this->_table_name} (session_id, user_agent, ip_address, time_updated) VALUES (?, ?, ?, ?)");
$stmt->execute(array($this->_session_id, $_SERVER['HTTP_USER_AGENT'], $_SERVER['REMOTE_ADDR'], time()));
}
/**
* @description Updates a current session.
* @access private
* @return void
* */
private function _update()
{
// Updates session in database
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET time_updated = ? WHERE session_id = ?");
$stmt->execute(array(time(), $this->_session_id));
}
/**
* @description Writes session data to the database.
* @access private
* @return void
* */
private function _write()
{
// Custom data doesn't exist
if (count($this->_data) == 0)
{
$custom_data = '';
}
else
{
$custom_data = serialize($this->_data);
}
// Writes session data to database
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET data = ?, time_updated = ? WHERE session_id = ?");
$stmt->execute(array($custom_data, time(), $this->_session_id));
}
/**
* @description Sets session cookie.
* @access private
* @return void
* */
private function _setCookie()
{
\system\SuperSmash\Cookie::set($this->_cookie_name, $this->_session_id, false, ($this->_expire_on_close) ? 0 : time() + $this->_seconds_till_expiration,NULL,NULL,$this->_secure_cookie,TRUE);
}
/**
* @description Removes expired sessions from the database.
* @access private
* @return void
* */
private function _cleanExpired()
{
// 0.1 % chance to clean the database of expired sessions
if (mt_rand(1, 1000) == 1)
{
$stmt = $this->_db->prepare("DELETE FROM {$this->_table_name} WHERE (time_updated + {$this->_seconds_till_expiration}) < ?");
$stmt->execute(array(time()));
}
}
/**
* @description Creates a unique session ID.
* @access private
* @return string
* */
private function _generateId()
{
$salt = 'S34U7^%^&%P@%57E6F3R&*(+S_!@M#-AKOS++_-&^H';
$random_number = mt_rand(0, mt_getrandmax());
$ip_address_fragment = md5(substr($_SERVER['REMOTE_ADDR'], 0, 5));
$timestamp = md5(microtime(TRUE) . time());
$hash_data = $random_number . $ip_address_fragment . $salt . $timestamp;
$hash = hash('sha256', $hash_data);
return $hash;
}
/**
* @description Checks if the session ID needs to be regenerated and does so if necessary.
* @access private
* @return void
* */
private function _checkIdRenewal()
{
// Gets the last time the session was updated
$stmt = $this->_db->prepare("SELECT time_updated FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
$result = $stmt->fetch();
if ($result !== FALSE && count($result) > 0)
{
// Checks if the session ID has exceeded it's permitted lifespan.
if ((time() - $this->_renewal_time) > $result['time_updated'])
{
// Regenerates a new session ID
$this->regenerateId();
}
}
}
/**
* @description Flags a session so that it will receive a new ID on the next subsequent request.
* @access private
* @return void
* */
private function _flagForUpdate()
{
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET flagged_for_update = '1' WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
}
/**
* @description Checks if the session has been requested to regenerate a new ID and does so if necessary.
* @access private
* @return void
* */
private function _checkUpdateFlag()
{
// Gets flagged status
$stmt = $this->_db->prepare("SELECT flagged_for_update FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
$result = $stmt->fetch();
if ($result !== FALSE && count($result) > 0)
{
// Flagged?
if ($result['flagged_for_update'])
{
// Creates a new session ID
$this->regenerateId();
// Updates database
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET flagged_for_update = '0' WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
}
}
}
/**
* @description Sets configuration.
* @access private
* @param array - configuration options
* @return void
* */
private function _setConfig(array $config)
{
// Sets database handle
if (isset($config['database']) && $config['database'])
{
$this->_db = $config['database'];
}
else
{
showError('sessionTable');
}
// --------------------------------------------
// Cookie name
if (isset($config['cookie_name']))
{
// Checks if alpha-numeric
if (! ctype_alnum(str_replace(array('-', '_'), '', $config['cookie_name'])))
{
showError('invalidCookieName');
}
$this->_cookie_name = $config['cookie_name'];
}
// --------------------------------------------
// Database table name
if (isset($config['table_name']))
{
// Checks if alpha-numeric
if (! ctype_alnum(str_replace(array('-', '_'), '', $config['table_name'])))
{
showError('invalidTableName');
}
$this->_table_name = $config['table_name'];
}
// --------------------------------------------
// Expiration time in seconds
if (isset($config['seconds_till_expiration']))
{
// Anything else than digits?
if (! is_int($config['seconds_till_expiration']) || ! preg_match('#[0-9]#', $config['seconds_till_expiration']))
{
showError('invalidExpirationTime');
}
// Negative number or zero?
if ($config['seconds_till_expiration'] < 1)
{
showError('invalidSecondsTime');
}
$this->_seconds_till_expiration = (int) $config['seconds_till_expiration'];
}
// --------------------------------------------
// End the session when the browser is closed?
if (isset($config['expire_on_close']))
{
// Not TRUE or FALSE?
if (! is_bool($config['expire_on_close']))
{
showError('invalidExpirationOnClose');
}
$this->_expire_on_close = $config['expire_on_close'];
}
// --------------------------------------------
// How often should the session be renewed?
if (isset($config['renewal_time']))
{
// Anything else than digits?
if (! is_int($config['renewal_time']) || ! preg_match('#[0-9]#', $config['renewal_time']))
{
showError('invalidSessionRenewalTimeNumber');
}
// Negative number or zero?
if ($config['renewal_time'] < 1)
{
showError('invalidSessionRenewalTime');
}
$this->_renewal_time = (int) $config['renewal_time'];
}
// --------------------------------------------
// Check IP addresses?
if (isset($config['check_ip_address']))
{
// Not a string?
if (! is_string($config['check_ip_address']))
{
showError('invalidIPAddressFormat');
}
// Invalid IP?
if (! preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/', $config['check_ip_address']))
{
showError('invalidIPAddress');
}
$this->_ip_address = $config['check_ip_address'];
}
// --------------------------------------------
// Check user agent?
if (isset($config['check_user_agent']))
{
$this->_user_agent = substr($config['check_user_agent'], 0, 999);
}
// --------------------------------------------
// Send cookie only when HTTPS is enabled?
if (isset($config['secure_cookie']))
{
if (! is_bool($config['secure_cookie']))
{
showError('invalidSecureCookie');
}
$this->_secure_cookie = $config['secure_cookie'];
}
}
}

View File

@ -0,0 +1,63 @@
<?php
/**************************************/
/**** SuperSmash Framework ****/
/**** Created By SuperSmash ****/
/**** Started on: 25-04-2012 ****/
/**************************************/
// Please do not edit anything else then this file contents.
// Editing anything else can and may cause harm to the SuperSmash framework !!!
// Uncomment these two lines to display errors
// error_reporting(E_ALL);
// ini_set("display_errors", 1);
/*************************************************/
/* Set this variable to true if you want to have */
/* an application chooser when people visit your */
/* website. */
/* */
/* (The application choice will be stored in a */
/* cookie named: changedPage) */
/*************************************************/
// Show the applications chooser startup page //Default: true
$applicationChooser = true;
/*
/***************************************************/
/* Set this variable to which application you would*/
/* like to load as a default application. */
/* Your website would automatically go to this */
/* application and there is no way to choose */
/* another application. */
/* (Unless the applicationChooser is set to true) */
/* */
/* You can choose the application by specifying a */
/* number. For example if: */
/* the directory applications contain 4 apps named:*/
/* Application A */
/* Application B */
/* Application C */
/* Start */
/* Then you can choose an application by entering */
/* its application number: */
/* 0 = Application A */
/* 1 = Application B */
/* 2 = Application C */
/* 3 = Start */
/* */
/* All applications are ordered alfabetical */
/***************************************************/
// Load application number // Default: 0
$applicationNumber = 0;
// Here you can change the debug log filename // Default: debug.log
$debugLog = "debug.log";
// Here you can change the error log filename // Default: error.log
$errorLog = "error.log";

View File

@ -0,0 +1,21 @@
<?php
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
return array(
'autoLoad' => "Autoload failed to load class: %s",
'view' => "Unable to locate the view file \"%s\". Please make sure a view page is created and is correctly named.",
'no_array' => "Variable \$%s passed is a non-array format in method %s",
'db_key_not_found' => "The database key was not found",
'sessionTable' => "The session database does not exist<br>Please run the session SQL script",
'invalidCookieName' => "Invalid cookie name!",
'invalidTableName' => "Invalid table name!",
'invalidExpirationTime.' => "Seconds till expiration must be a valid number.",
'invalidSecondsTime' => "Seconds till expiration can not be zero or less. Enable session expiration when the browser closes instead.",
'invalidExpirationOnClose' => "Expire on close must be either TRUE or FALSE.",
'invalidSessionRenewalTimeNumber' => "Session renewal time must be a valid number.",
'invalidSessionRenewalTime' => "Session renewal time can not be zero or less.",
'invalidIPAddressFormat' => "The IP address must be a string similar to this: '192.168.10.200'",
'invalidIPAddress' => "Invalid IP address.",
'invalidSecureCookie' => "The secure cookie option must be either TRUE or FALSE.",
);

View File

@ -0,0 +1,25 @@
<?php
if (!defined("SUPERSMASH_FRAMEWORK")){die("You cannot access this page directly!");}
return array(
'debugMessage' => "Message:",
'debugFile' => "File that reports the error:",
'debugLine' => "Line:",
'debugTrace' => "Trace:",
'debugClass' => "Class:",
'debugFunction' => "Function:",
'debugFunctionArguments' => "Function arguments:",
'footerRendered' => "Page rendered in",
'footerSeconds' => "seconds, using",
'notFoundTitle' => "The page you are looking for is not at this location",
'notFoundMessage' => "The page you are looking for cannot be located. You may have mis-typed the URL, or the page was deleted.
Please check your spelling and try again. If you feel you have reached this page in an error, please",
'notFoundEmail' => "email us",
'startPage' => "Return to index",
'previousPage' => "Previous page",
'notFoundErrorMessage' => "We are sorry for the inconvenience, but an unrecoverable error has occured. <br/ >
If the problem persists, please",
'errorMessage' => "Error message:",
);