diff --git a/class-DB.php b/class-DB.php index bfe612b..3c530c8 100644 --- a/class-DB.php +++ b/class-DB.php @@ -1,465 +1,478 @@ . /* * Use: esc_html(), error_die(), DEBUG, force_array() */ /** * The database class from the Open Student project. * Some functions to run MySQL queries and analyze results. */ class DB { /** * MySQL connection link. * @var MySQLi->link MySQLi connection link */ private $mysqli; /** * Table prefix. * @var string */ private $prefix; /** * Number of executed queries. * @var int */ private $numQueries = 0; /** * Last query result. * @var query-result */ private $lastResult = false; + /** + * Get an instance of this class + * + * @return self + */ + public function instance() { + static $me = null; + if( ! $me ) { + $me = new self(); + } + return $me; + } + /** * Prepare the DB object. * * @param type $username Database username * @param type $password Database password * @param type $location Database location * @param type $database Database name * @param type $prefix Table Prefix */ - function __construct($username = null, $password = null, $location = null, $database = null, $prefix = '', $charset = 'utf8') { + function __construct( $username = null, $password = null, $location = null, $database = null, $prefix = '', $charset = 'utf8' ) { if( func_num_args() === 0 ) { $username = @$GLOBALS['username']; $password = @$GLOBALS['password']; $location = @$GLOBALS['location']; $database = @$GLOBALS['database']; $prefix = @$GLOBALS['prefix']; } $this->prefix = $prefix; @$this->mysqli = new mysqli($location, $username, $password, $database); if( $this->errorConnection() ) { if(DEBUG) { $password_shown = ($password === '') ? __("nessuna") : sprintf( __("di %d caratteri"), strlen( $password ) ); error_die( sprintf( __("Impossibile connettersi al database '%s' tramite l'utente '%s' e password (%s) sul server MySQL/MariaDB '%s'. Specifica correttamente queste informazioni nel file di configurazione del tuo progetto (usualmente '%s'). %s."), $database, $username, $password_shown, $location, 'load.php', HTML::a( 'https://github.com/valerio-bozzolan/boz-php-another-php-framework/blob/master/README.md#use-it', __("Documentazione") ) ) ); } else { error_die( __("Errore nello stabilire una connessione al database.") ); } } @$this->mysqli->set_charset($charset); } function __destruct() { $this->closeConnection(); } /** * Lock the door when you leave a room. */ public function closeConnection() { $this->mysqli && @$this->mysqli->close(); } /** * To execute a query. * * @param string $SQL The SQL query to execute * @param boolean $tagReplace Use tag sobstitution, or no */ public function query($query) { $this->numQueries++; if( $this->lastResult !== false && $this->lastResult !== true) { $this->lastResult->free(); } $this->lastResult = $this->mysqli->query($query); if( ! $this->lastResult ) { error_die( $this->getQueryErrorMessage($query) ); } elseif(DEBUG && SHOW_EVERY_SQL) { $this->showSQL($query); } return $this->lastResult; } private function showSQL($SQL) { echo "
" . sprintf( __("Query numero %d:
%s"), $this->numQueries, $SQL ) . "\n"; } /** * Select only a row from the database */ public function getRow($query, $class_name = null, $params = [] ) { $results = $this->getResults($query, $class_name, $params); return @$results[0]; } /** * Select only a column from a single row */ public function getValue($query, $column_name, $class_name = null, $params = [] ) { $row = $this->getRow($query, $class_name, $params); return @$row->{$column_name}; } /** * Execute a query and return an array of $class_name objects. * * @param string $query Database SQL query. * @param string $class_name The name of the class to instantiate. * @param array $params Optional data for the $class_name constructor. * @See http://php.net/manual/en/mysqli-result.fetch-object.php */ public function getResults($query, $class_name = null, $params = [] ) { // IS_ARRAY() IS SHIT FOR HISTORICAL REASONS if( $class_name === null || is_array( $class_name ) ) { $class_name = 'Queried'; } // IS_ARRAY() IS SHIT FOR HISTORICAL REASONS $this->query($query); $res = []; while( $row = $this->lastResult->fetch_object($class_name, $params) ) { $res[] = $row; } return $res; } /** * Execute a query and return a generator of $class_name objects. * * @param string $query Database SQL query. * @param string $class_name The name of the class to instantiate. * @param array $params Optional data for the $class_name constructor. * @See http://php.net/manual/en/mysqli-result.fetch-object.php */ public function getGenerator( $query, $class_name = null, $params = [] ) { if( null === $class_name ) { $class_name = 'Queried'; } $result = $this->query( $query ); $this->lastResult = true; // to don't be killed from another query() call while( $row = $result->fetch_object( $class_name, $params ) ) { yield $row; } $result->free(); } /** * To insert a single row. * I have not time to check if $dbCols are DBCol objects. * * @param string $table_name * @param DBCol[] $cols * @param $args arguments like 'replace-into */ public function insertRow( $table_name, $cols, $args = [] ) { $SQL_columns = ''; $n = count($cols); for($i=0; $i<$n; $i++) { if($i !== 0) { $SQL_columns .= ', '; } $SQL_columns .= "`{$cols[$i]->column}`"; } $values = ''; for($i=0; $i<$n; $i++) { if($i !== 0) { $values .= ', '; } $values .= $this->forceType($cols[$i]->value, $cols[$i]->forceType); } $args = array_replace( [ 'replace-into' => false, ], $args ); $what = $args[ 'replace-into' ] ? 'REPLACE' : 'INSERT'; return $this->query("$what INTO {$this->getTable($table_name)} ($SQL_columns) VALUES ($values)"); } /** * Executes one or multiple queries which are concatenated by a semicolon * * @param $queries string */ public function multiQuery( $queries ) { return $this->mysqli->multi_query( $queries ); } /** * To execute clean insert SQL queries. * * @param string $table_name Table Name without prefix * @param array $columns Assoc array of types ('ID' => 'null', 'name' => 's', ..) * @param array $rows Array of rows * @param array $args Extra arguments */ public function insert($table_name, $columns, $rows, $args = []) { $args = array_replace( [ 'replace-into' => false ], $args ); force_array($rows); if( ! @is_array($rows[0]) ) { $rows = [ $rows ]; // array_columns('value col 1', '..') => array_rows( array_columns( 'value col 1', ..) ) } $n_columns = count($columns); $n_rows = count($rows); $SQL_columns = ''; $first = key($columns); foreach($columns as $column => $type) { if($column !== $first) { $SQL_columns .= ', '; } $SQL_columns .= "`$column`"; } $insert = ($args['replace-into']) ? 'REPLACE' : 'INSERT'; $SQL = "$insert INTO {$this->getTable($table_name)} ($SQL_columns) VALUES"; for($i=0; $i<$n_rows; $i++) { $SQL .= ($i === 0) ? ' (' : ', ('; $SQL_values = []; if($n_columns != count($rows[$i])) { DEBUG && error( sprintf( __("Errore inserendo nella tabella %s. Colonne: %d. Colonne values[%d]: %d"), esc_html($table_name), $n_columns, $i, count($rows[$i]) ) ); return false; } $j = 0; foreach($columns as $column => $type) { $SQL_values[] = $this->forceType($rows[$i][$j], $type); $j++; } $SQL .= implode(', ', $SQL_values) . ')'; } return $this->query($SQL); } /** * To execute update queries. */ public function update($table_name, $dbCols, $conditions, $after = '') { force_array($dbCols); $SQL = "UPDATE {$this->getTable($table_name)} SET "; $n_cols = count($dbCols); for($i=0; $i<$n_cols; $i++) { if($i !== 0) { $SQL .= ', '; } $val = $this->forceType($dbCols[$i]->value, $dbCols[$i]->forceType); $SQL .= "`{$dbCols[$i]->column}` = $val"; } if($after !== '') { $after = " $after"; } $SQL .= " WHERE {$conditions}{$after}"; return $this->query($SQL); } public function getLastInsertedID() { return $this->mysqli->insert_id; } /** * Escape a string * * @param string $s String to be escaped * @return string String escaped. */ public function escapeString($s) { return $this->mysqli->real_escape_string($s); } public function getNumQueries() { return $this->numQueries; } public function getPrefix() { return $this->prefix; } /** * Return a table name with it's school prefix * * @param string $name Table name * @param boolean $as True if you want to access to the table $name in the SQL * @return string Table $name with the prefix */ public function getTable($name, $as = false) { if($this->prefix === '') { $as = false; } $r = "`{$this->prefix}$name`"; if($as) { $r .= " AS `$name`"; } return $r; } /** * Return the list of every table name inserted as arguments or as an [] */ public function getTables($args = []) { $tables = []; if( ! is_array( $args ) ) { $args = func_get_args(); } foreach( $args as $arg ) { $tables[] = $this->getTable( $arg, true ); } return implode( ' JOIN ', $tables ); } /** * Force a string to a defined type. * * @param string $s String to be forced. * @param string $type Type ('d' for integer, 's' for string, 'f' for float, 'null' for autoincrement values or for "don't care" values). * @see http://news.php.net/php.bugs/195815 * @return string Forced string */ private function forceType($s, $type) { if( $type === 'd' ) return (int) $s; // Integer if( $type === 'f' ) return (float) $s; // Float if( $type === 'dnull' ) return ($s === null) ? 'NULL' : (int) $s; // Integer - or NULL if( $type === 'fnull' ) return ($s === null) ? 'NULL' : (float) $s; // Float - or NULL if( $type === 's' ) return "'{$this->escapeString($s)}'"; // String escaped if( $type === 'snull' ) return ($s === null) ? 'NULL' : "'{$this->escapeString($s)}'"; // String escaped - or NULL if( $type === 'f' ) return (float) $s; // Float value if( $type === '-' ) return $s; // Float value if( $type === null || $type === 'null' ) return 'NULL'; // 'NULL' literally for indexes DEBUG && error( sprintf( "Tipo '%s' non concesso in DB::forceType(). Vedi la documentazione (esiste?). Sarà usato l'escape 's'.", esc_html($type) ) ); return $this->forceType($s, 's'); } /** * Check if there is an error in the connection * * @return boolean */ private function errorConnection() { return @mysqli_connect_errno(); } /** * You have to check the result before use this! * * @deprecated */ private function fetch_row($fetch) { if($fetch === 'object' || $fetch === 'assoc') { return $this->lastResult->{'fetch_' . $fetch}(); } error_die('Fetch row cannot be ' . $fetch); } public function affectedRows() { return @$this->mysqli->affected_rows(); } /** * Used to show "friendly" error. * * @param string $SQL SQL query executed during the error. * @return string Kind message. */ private function getQueryErrorMessage($SQL) { return sprintf( __("Errore eseguendo una query SQL: Query n. %d:
%s
%s"), $this->numQueries, $SQL, esc_html($this->mysqli->error) ); } } diff --git a/class-Permissions.php b/class-Permissions.php index a46de36..2ee269b 100644 --- a/class-Permissions.php +++ b/class-Permissions.php @@ -1,90 +1,128 @@ . +/** + * Handle roles and their permissions + */ class Permissions { - var $rolePermissions = []; - public function __construct() { - // expect('session'); it is unnecessary at this time + /** + * Permissions indexed by user roles + */ + public $roles = []; + + /** + * Get the singleton instance + */ + public function instance() { + static $me = false; + if( ! $me ) { + $me = new self(); + } + return $me; } + /** + * Register specific permissions to the wanted role + * + * @param $role string + * @param $permissions array + */ public function registerPermissions( $role, $permissions ) { force_array( $permissions ); if( ! $this->roleExists( $role ) ) { - $this->rolePermissions[ $role ] = []; + $this->roles[ $role ] = []; } - $this->rolePermissions[ $role ] = array_merge( $this->rolePermissions[ $role ], $permissions ); + $this->roles[ $role ] = array_merge( $this->roles[ $role ], $permissions ); } + /** + * Check if a role has a permission + * + * @param $role string + * @param $permissions string + * @return boolean + */ public function hasPermission( $role, $permission ) { if( $this->roleExists( $role ) ) { - foreach( $this->rolePermissions[ $role ] as $rolePermission ) { - if( $rolePermission === $permission ) { - return true; - } - } + return in_array( $this->roles[ $role ], $permission, true ); + } else { + error( "unknown role $role" ); } return false; } - public function inheritPermissions( $new_role, $existing_role, $new_role_permissions = [] ) { - if( ! $this->roleExists( $existing_role ) ) { - self::errorRole( $existing_role ); - return false; - } - $this->registerPermissions( $new_role, $this->rolePermissions[ $existing_role ] ); - if( $new_role_permissions ) { - $this->registerPermissions( $new_role, $new_role_permissions ); + /** + * Inherit permissions from an existing role, and extend it + * + * @param $new_role string + * @param $existing string + * @param $permissions array + */ + public function inheritPermissions( $new_role, $existing, $permissions = [] ) { + if( ! $this->roleExists( $existing ) ) { + throw new InvalidArgumentException( 'unknown role' ); } - return true; + $this->registerPermissions( $new_role, $this->roles[ $existing ] ); + $this->registerPermissions( $new_role, $permissions ); } + /** + * Check if a role formally exists + * + * @param $role string + * @return boolean + */ public function roleExists( $role ) { - return isset( $this->rolePermissions[ $role ] ); + return isset( $this->roles[ $role ] ); } + /** + * Get all the known permissions + * + * @return array + */ public function getPermissions() { $all = []; - foreach( $this->rolePermissions as $permissions ) { + foreach( $this->roles as $permissions ) { $all = array_merge( $all, $permissions ); } return array_unique( $permissions ); } + /** + * Get all the roles + * + * @return array + */ public function getRoles() { - return array_keys( $this->rolePermissions ); + return array_keys( $this->roles ); } /** - * To avoid duplicate permissions - * Only useful when someone want to list all the permissions. + * Avoid duplicate permissions + * + * Well, it's only useful when you want to list all the permissions without duplicates. * * @return self */ public function clean() { - foreach( $this->rolePermissions as $role => $permissions ) { - $this->rolePermissions[ $role ] = array_unique( $permissions ); + foreach( $this->roles as $role => $permissions ) { + $this->roles[ $role ] = array_unique( $permissions ); } return $this; } - - private static function errorRole( $role ) { - DEBUG && error( sprintf( - __("Il ruolo %s non è stato ancora registrato"), - esc_html( $role ) - ) ); - } } diff --git a/class-RegisterModule.php b/class-RegisterModule.php index a688c47..f802beb 100644 --- a/class-RegisterModule.php +++ b/class-RegisterModule.php @@ -1,121 +1,109 @@ . /** - * Dinamically inject functions in modules ("places"). + * Dynamically inject functions in modules ("places"). * * @require DEBUG, error(), esc_html() */ class RegisterModule { /** * Assoc functions to modules */ private $module = []; - function __construct($defaults = true) { - $defaults && $this->loadDefaults(); + /** + * Constructor + * + * @param $defaults boolean Load the defaults modules + */ + function __construct( $defaults = true ) { + if( $defaults ) { + $this->loadDefaults(); + } } + /** + * Get the singleton instance + * + * @return self + */ + public function instance() { + static $me = false; + if( ! $me ) { + $me = new self(); + } + return $me; + } + + /** + * Load the default modules + */ private function loadDefaults() { - $this->register('header'); - $this->register('footer'); + $this->register( 'header' ); + $this->register( 'footer' ); // Append scripts and styles - $this->injectFunction('header', function() { - expect('css'); - expect('javascript'); - $GLOBALS['css']->printAll(); - $GLOBALS['javascript']->printAll( JS::HEADER ); - }); - $this->injectFunction('footer', function() { - expect('javascript'); - $GLOBALS['javascript']->printAll( JS::FOOTER ); - }); + $this->injectFunction( 'header', function () { + CSS ::instance()->printAll(); + JavaScript::instance()->printAll( JS::HEADER ); + } ); + $this->injectFunction( 'footer', function () { + JavaScript::instance()->printAll( JS::FOOTER ); + } ); } /** * Formally register a module (a place where you can inject functions) * - * @param string $module_uid + * @param string $name */ - public function register($module_uid) { - if( isset( $this->module[ $module_uid ] ) ) { - DEBUG && error( sprintf( - __("Il modulo %s è già stato registrato."), - "
" . esc_html($module_uid) . ""
- ) );
+ public function register( $name ) {
+ if( ! isset( $this->module[ $name ] ) ) {
+ $this->module[ $name ] = [];
}
- $this->module[ $module_uid ] = [];
}
/**
- * @param string $module_uid The place name (e.g. 'footer')
+ * Inject a callback into a module
+ *
+ * @param string $name Module name
* @param string $callback The callback
*/
- public function injectFunction($module_uid, $callback) {
- if( ! isset( $this->module[ $module_uid ] ) ) {
- $this->module[$module_uid] = [];
- DEBUG && error( sprintf(
- __("Il modulo %s non è stato ancora creato. Hai sbagliato a scriverlo?"),
- "" . esc_html($module_uid) . ""
- ) );
+ public function injectFunction( $name, $callback ) {
+ if( ! isset( $this->module[ $name ] ) ) {
+ return error( "can't inject in unknown module $name" );
}
- $this->module[ $module_uid ][] = $callback;
+ $this->module[ $name ][] = $callback;
}
/**
* Load all the functions related to this module name.
*
- * @param string $callback
+ * @param string $name Module name
*/
- public function loadModule($module_uid) {
- if( ! isset( $this->module[ $module_uid ] ) ) {
- DEBUG && error( sprintf(
- __("Il modulo %s è già stato registrato."),
- "" . esc_html($module_uid) . ""
- ) );
- return false;
+ public function loadModule( $name ) {
+ if( ! isset( $this->module[ $name ] ) ) {
+ return error( "can't load unregistered module $name" );
}
-
- // Short form
- $module = & $this->module[$module_uid];
-
- // Load every callback
- $tot_status = true;
- $n = count($module);
- for($i=0; $i<$n; $i++) {
- if( is_closure( $module[$i] ) ) {
- $status = $module[$i]();
- if(DEBUG && $status === false) {
- error( sprintf(
- __("Errore caricando il modulo %s (callback %s°)."),
- "" . esc_html($module_uuid) . "",
- "" . $i . ""
- ) );
- }
- } else {
- $status = false;
- DEBUG && error( sprintf(
- __("Il callback richiesto per il modulo %s non esiste."),
- "" . esc_html($module_uuid) . ""
- ) );
- }
- $tot_status = $tot_status && $status;
+ $status = true;
+ foreach( $this->module[ $name ] as $callback ) {
+ $status = $status && $callback();
}
- return $tot_status;
+ return $status;
}
}
diff --git a/class-Session.php b/class-Session.php
index 138dac5..a107fcc 100644
--- a/class-Session.php
+++ b/class-Session.php
@@ -1,191 +1,221 @@
.
-defined('SESSION_DURATION') || define('SESSION_DURATION', 604800); // Just something 60s * 60m * 24h * 7d
-defined('SESSIONUSER_CLASS') || define('SESSIONUSER_CLASS', 'Sessionuser');
+// 60s * 60m * 24h * 7d
+define_default( 'SESSION_DURATION', 604800 );
+
+// the default user logged-in class
+define_default( 'SESSIONUSER_CLASS', 'Sessionuser' );
/**
* Session handler class
*/
class Session {
/**
* Is the login verified?
*
* @var bool
*/
private $loginVerified = false;
/**
* User currently logged
*
* @var Sessionuser
*/
private $user = null;
+ /**
+ * Get the singleton instance
+ *
+ * @return self
+ */
+ public function instance() {
+ static $me = false;
+ if( ! $me ) {
+ $me = new self();
+ }
+ return $me;
+ }
+
/**
* Constructor
*/
public function __construct() {
$this->validate();
}
/**
* Is the user logged?
*
* @return bool
*/
public function isLogged() {
return null !== $this->getUser();
}
/**
* Get the currently logged-in user
*
* @return Sessionuser
*/
public function getUser() {
if( ! $this->loginVerified ) {
$this->validate();
}
return $this->user;
}
/*
* Login statuses
*/
const OK = 0;
const LOGIN_FAILED = 1;
const ALREADY_LOGGED = 2;
const EMPTY_USER_UID = 4;
const EMPTY_USER_PASSWORD = 8;
const USER_DISABLED = 64;
/**
* Do a login
*
* @param $status int Login status
* @param $user_uid User UID
* @param $user_password User password
* @return bool
*/
public function login( & $status = null, $user_uid = null, $user_password = null ) {
if( $this->isLogged() ) {
$status = self::ALREADY_LOGGED;
return true;
}
if( null === $user_uid && isset( $_POST['user_uid'] ) ) {
$user_uid = $_POST['user_uid'];
}
if( null === $user_password && isset( $_POST['user_password'] ) ) {
$user_password = $_POST['user_password'];
}
if( empty( $user_uid ) ) {
$status = self::EMPTY_USER_UID;
return false;
}
if( empty( $user_password ) ) {
$status = self::EMPTY_USER_PASSWORD;
return false;
}
// PHP bug
$userClass = SESSIONUSER_CLASS;
$user = $userClass::factoryFromLogin( $user_uid, $user_password )
->queryRow();
if( ! $user ) {
$status = self::LOGIN_FAILED;
- error_log( sprintf( "Login failed by '%s' using POST", $userClass::sanitizeUID( $user_uid ) ) );
- return false;
+ return self::failed( $userClass::sanitizeUID( $user_uid ), 'POST' );
}
if( ! $user->isSessionuserActive() ) {
$status = self::USER_DISABLED;
return false;
}
$this->loginVerified = true;
$this->user = $user;
$time = time();
$duration = $time + SESSION_DURATION;
$force_https = is_https();
setcookie( 'user_uid', $user->getSessionuserUID(), $duration, ROOT, '', $force_https, false );
setcookie( 'token', $user->generateSessionuserCookieToken(), $duration, ROOT, '', $force_https, true );
$status = self::OK;
return true;
}
/**
* Validate the user session
*
* @return bool
*/
private function validate() {
if( $this->loginVerified ) {
return true;
}
if( ! isset( $_COOKIE['user_uid'], $_COOKIE['token'] ) ) {
return false;
}
// PHP Bug
$userClass = SESSIONUSER_CLASS;
$user = $userClass::factoryFromUID( $_COOKIE['user_uid'] )
->queryRow();
$this->loginVerified = true;
if( ! $user ) {
$this->user = null;
return false;
}
if( ! $user->isSessionuserActive() ) {
return false;
}
if( $_COOKIE['token'] !== $user->generateSessionuserCookieToken() ) {
- error_log( sprintf( "Login failed by '%s' using cookies", $userClass::sanitizeUID( $_COOKIE['user_uid'] ) ) );
- return false;
+ return self::failed( $userClass::sanitizeUID( $_COOKIE['user_uid'] ), 'cookies' );
}
$this->user = $user;
return true;
}
/**
* Destroy the session
*/
public function destroy() {
$invalidate = time() - 8000;
setcookie( 'user_uid', 'asd', $invalidate );
setcookie( 'token', 'asd', $invalidate );
$this->loginVerified = true;
$this->user = null;
}
+
+ /**
+ * Log in syslog a login fail
+ *
+ * @param $uid string
+ * @param $from string
+ * @return false
+ */
+ public static function failed( $uid, $from ) {
+ error_log( sprintf(
+ "Login failed by '%s' using %s",
+ $uid,
+ $from
+ ) );
+ return false;
+ }
}
diff --git a/class-Shit.php b/class-Shit.php
index d4d2612..715744e 100644
--- a/class-Shit.php
+++ b/class-Shit.php
@@ -1,66 +1,76 @@
.
/**
- * This file is completly full of shit.
+ * This file is completly full of shit
*/
class Shit {
- /**
- * A shitty phrase.
- */
- static function getErrorMessage( $msg ) {
- return "\n\n\t\n\tError: $msg
\n\n"; - } - - /** - * Soap of 503 headers. - */ - static function header503() { - if( headers_sent() ) { - return false; - } - header('HTTP/1.1 503 Service Temporarily Unavailable'); - header('Status: 503 Service Temporarily Unavailable'); - header('Retry-After: 300'); - } /** - * Spawn the white screen of death. + * Spawn the white screen of death + * + * @param $msg string */ - static function WSOD( $msg ) { + public static function WSOD( $msg ) { self::header503(); ?>« »
- + + \n"; + echo '' . esc_html( $msg ) . '
'; + } + } + } diff --git a/functions.php b/functions.php index 9f396f5..9ac0356 100644 --- a/functions.php +++ b/functions.php @@ -1,801 +1,795 @@ . // Useful e.g. in Table::NAME . DOT . STAR query. define('DOT', '.'); define('STAR', '*'); function define_default( $constant_name, $default_value ) { defined( $constant_name ) or define( $constant_name, $default_value ); } function selected( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { return html_property_when_matching( 'selected', 'selected', $helper, $current, $force); } function checked( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { return html_property_when_matching( 'checked', 'checked', $helper, $current, $force); } function disabled( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { return html_property_when_matching( 'disabled', 'disabled', $helper, $current, $force ); } function _checked( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { echo checked( $helper, $current, $force ); } function _selected( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { echo selected( $helper, $current, $force ); } function _disabled( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { echo disabled( $helper, $current, $force ); } function html_property_when_matching( $property, $value, $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { if( $helper === $current || $helper && PHP_INT_MAX === $current || $force ) { return HTML::property( $property, $value ); } return ''; } function _value( $v ) { echo HTML::property( 'value', $v ); } /** * Retrieve a required global object. * @see G::expect() */ function expect( $global_var ) { return $GLOBALS['G']->expect( $global_var ); } /** * Register a required global object. * @see G::add() */ function register_expected( $global_var, $class_name ) { $GLOBALS['G']->add( $global_var, $class_name ); } /** * Force something to be an array. * * @return mixed|array * @return array */ function force_array( & $a ) { if( ! is_array($a) ) { $a = [ $a ]; } } /** * Enfatize a substring. * @see EnfatizeSubstr::get() */ function enfatize_substr($heystack, $needle, $pre = '', $post = '') { if( ! $needle ) { return $heystack; } return EnfatizeSubstr::get($heystack, $needle, $pre, $post); } /** * SQL query escape string * @see DB#escapeString() */ function esc_sql($s) { - return expect('db')->escapeString($s); + return DB::instance()->escapeString($s); } /** * Same as esc_sql() but also avoid '%'s. * * @param string $s * @return string */ function esc_sql_like($s) { $s = str_replace('%', '\%', $s); return esc_sql($s); } /** * HTML escape * * @param string $s * @return string */ function esc_html($s) { return htmlspecialchars($s); } /** * HTML escape print * * @param string * @return void */ function _esc_html($s) { echo htmlentities($s); } /** * Execute a simple query. * @see DB#getResults() */ function query($query) { - return expect('db')->query($query); + return DB::instance()->query($query); } /** * Execute a query and return an array of objects. * * @param string $query SQL query * @param string $class Class name to encapsulate the result set * @return array * @see DB#getResults() */ function query_results($query, $class = null, $args = [] ) { - return expect('db')->getResults($query, $class, $args); + return DB::instance()->getResults($query, $class, $args); } /** * Execute a query and return a Generator * * @param string $query SQL query * @param string $class Class name to encapsulate the result set * @generator * @see DB#getGenerator() */ function query_generator( $query, $class = null, $args = [] ) { - return expect( 'db' )->getGenerator( $query, $class, $args ); + return DB::instance()->getGenerator( $query, $class, $args ); } /** * Execute a query and return an object. * * @param string $query SQL query * @param string $class Class name to encapsulate the result set * @return null|Object * @see DB#getRow() */ function query_row($query, $class = null, $args = [] ) { - return expect('db')->getRow($query, $class, $args); + return DB::instance()->getRow($query, $class, $args); } /** * Execute a query and return a single value. * @see DB#getValue() */ function query_value($query, $value, $class = null) { - return expect('db')->getValue($query, $value, $class); + return DB::instance()->getValue($query, $value, $class); } /** * Executes one or multiple queries which are concatenated by a semicolon * @see DB#multiQuery() */ function multiquery( $queries ) { - return expect('db')->multiQuery( $queries ); + return DB::instance()->multiQuery( $queries ); } /** * Database table full with prefix. * * @param string $t Table name (as 'test') * @return string Table name with prefix (as '`site01_test`') * @see DB#getTable() */ function T($t, $as = false) { - return expect('db')->getTable($t, $as); + return DB::instance()->getTable($t, $as); } define('T', 'T'); define('JOIN', 'JOIN'); // Stupid shurtcut for string context $GLOBALS[T] = function($t, $as = false) { return T($t, $as = false); }; // Stupid shortcut for string context for listing tables $GLOBALS[JOIN] = function($t) { - return expect('db')->getTables( func_get_args() ); + return DB::instance()->getTables( func_get_args() ); }; /** * Insert a row in the specified database table. * @param string $table * @param DBCols[] * @param $args array * @see DB#insertRow() */ function insert_row( $table, $cols, $args = [] ) { - return expect('db')->insertRow( $table, $cols, $args ); + return DB::instance()->insertRow( $table, $cols, $args ); } /** * If the table has an AUTOINCREMENT you can get the last inserted index * after an insert_row(). * @return int * @see DB#getLastInsertedID() */ function last_inserted_ID() { isset( $GLOBALS['db'] ) || error_die( __("Manca la connessione al database. Come ottenere l'ultimo indice?") ); - return expect('db')->getLastInsertedID(); + return DB::instance()->getLastInsertedID(); } /** * Insert multiple values in the specified database table * @param string $table * @param array $cols * @param array $values * @see DB#insert() */ function insert_values($table, $cols, $values) { - return expect('db')->insert($table, $cols, $values); + return DB::instance()->insert($table, $cols, $values); } /** * Update rows in the specified database table * @param string $table * @param DBCol[] $cols * @param string $condition * @see DB#update() */ function query_update($table, $cols, $condition, $after = '') { - expect('db')->update($table, $cols, $condition, $after); + DB::instance()->update($table, $cols, $condition, $after); } /** * Alias for htmlspecialchars(). * @param string $s * @return string */ function esc_attr($s) { return htmlspecialchars($s); } /** * @param string * @return void */ function _esc_attr($s) { echo htmlspecialchars($s); } /* * Friendly symlinks */ function register_mimetypes($category, $mimetypes) { expect('mimeTypes')->registerMimetypes($category, $mimetypes); } function get_mimetypes($category = null) { return expect('mimeTypes')->getMimetypes($category); } /** * @param string $role User role * @param string|string[] $permissions Permissions */ function register_permissions($role, $permissions) { expect('permissions')->registerPermissions($role, $permissions); } /** * @param string $role_to New role * @param string $role_from Existing role */ function inherit_permissions($role_to, $role_from, $other_permissions = []) { expect('permissions')->inheritPermissions($role_to, $role_from, $other_permissions); } function register_js($javascript_uid, $url, $position = null) { return expect('javascript')->register( $javascript_uid, $url, $position ); } function enqueue_js($javascript_uid, $position = null) { expect('javascript'); return $GLOBALS['javascript']->enqueue( $javascript_uid, $position ); } function register_css($css_uid, $url) { return expect('css')->register($css_uid, $url); } function enqueue_css($css_uid) { return expect('css')->enqueue($css_uid); } function add_menu_entries($menuEntries) { expect('menu')->add($menuEntries); } function get_menu_entry($uid) { return expect('menu')->getMenuEntry($uid); } function get_children_menu_entries($parentUid) { return expect('menu')->getChildrenMenuEntries($parentUid); } function register_module($module_uid) { return expect('module')->register($module_uid); } function inject_in_module($module_uid, $callback) { return expect('module')->injectFunction($module_uid, $callback); } function load_module($module_uid) { return expect('module')->loadModule($module_uid); } function get_table_prefix() { - return expect('db')->getPrefix(); + return DB::instance()->getPrefix(); } function register_option($option_name) { - return expect('db')->registerOption($option_name); + return DB::instance()->registerOption($option_name); } function get_option( $name, $default = '' ) { return Options::instance()->get( $name, $default ); } function set_option( $name, $value, $autoload = true ) { return Options::instance()->set( $name, $value, $autoload ); } function remove_option( $name ) { return Options::instance()->remove( $name ); } /** * Get the current logged user. * * @param null|string $property Property name * @return mixed|Sessionuser Property, or entire Sessionuser object. */ function get_user( $property = null ) { - $user = expect('session')->getUser(); + $user = Session::instance()->getUser(); if( null === $property ) { return $user; } return $user ? $user->get( $property ) : null; } /** * Try to login using $_POST['user_uid'] and $_POST['user_password']. * * @param int $status * @see Session::login() */ function login(& $status = null, $user_uid = null, $user_password = null) { - return expect('session')->login($status, $user_uid, $user_password); + return Session::instance()->login($status, $user_uid, $user_password); } function logout() { - return expect('session')->destroy(); + return Session::instance()->destroy(); } function register_language($code, $aliases = [], $encode = null, $iso = null, $human = null) { return expect('registerLanguage')->registerLanguage($code, $aliases, $encode, $iso, $human); } function register_default_language($default) { return expect('registerLanguage')->setDefaultLanguage($default); } function find_language($language_alias) { return expect('registerLanguage')->getLanguage($language_alias); } function apply_language($language_alias = null) { return expect('registerLanguage')->applyLanguage($language_alias); } function latest_language() { return expect('registerLanguage')->getLatestLanguageApplied(); } function all_languages() { return expect('registerLanguage')->getAll(); } function get_num_queries() { if( isset( $GLOBALS['db'] ) ) { return $GLOBALS['db']->getNumQueries(); } return 0; } function is_logged() { - return expect('session')->isLogged(); + return Session::instance()->isLogged(); } -defined('DEFAULT_USER_ROLE') - or define('DEFAULT_USER_ROLE', 'UNREGISTERED'); - /** * @param string $permission Permission uid * @param User|null $user Specified user * @return bool */ function has_permission($permission, $user = null) { - $session = expect('session'); + $session = Session::instance(); if( $user === null ) { $user = $session->getUser(); } $user_role = false; if($user) { $user_role = $user->user_role; } if( ! $user_role ) { $user_role = DEFAULT_USER_ROLE; } return expect('permissions')->hasPermission($user_role, $permission); } /** * Add a directory to a base URL or a pathname. * If the base URL it is not defined, a slash ('/') is appended to the URL. * The base URL could end with a slash ('/') or not. * * @param string $base_URL Base URL with/without any slash at start * @param string $dir Directory without any slash * @return string URL / Pathname */ function append_dir( $base_URL, $dir = '/' ) { $base_URL = rtrim( $base_URL, '/' ); $dir = ltrim( $dir, '/' ); return $base_URL . _ . $dir; } /** * Normalize a site page * * @param $page string Whatever, a full URL, a relative pathname e.g. 'page', an absolute one, etc. * @param $full_url boolean As default it try to avoid full URLs */ function site_page( $page, $full_url = false ) { $first = @$page[ 0 ]; if( $first === '#' ) { return $page; // '#anchor' } if( $first === '/' ) { if( @$page[ 1 ] === '/' ) { return $page; // "//example.org" } return append_dir( $full_url ? BASE_URL : '', $page ); } elseif( preg_match( '#^[a-z]+://#', $page ) === 1 ) { return $page; // "ftp://example.org" } return append_dir( $full_url ? URL : ROOT, $page ); } function single_quotes($s) { return "'$s'"; } function double_quotes($s) { return '"' . $s . '"'; } function this_folder() { return dirname( $_SERVER['PHP_SELF'] ); } /** * Truncate a string if it's over a specific length. * You can specify the end of the string if it's truncated. * * @param string %s Input string * @param int $max_length Max string length * @param string $blabla Optional. If string length is over $max_length, $blabla it's appended after $string * @deprecated Use mb_strimwidth */ function str_truncate($s, $max_length, $blabla = '', $encoding = null ) { if( ! $encoding ) { $encoding = mb_internal_encoding(); } return mb_strimwidth($s, 0, $max_length, $blabla, $encoding); } /** * Choose the appropriate string. * '%' will be replaced with the input number. * * @param int $n Input number. * @param string $text_multi Text displayed if n > 1 * @param string $text_one Text displayed if n == 1 * @param string $text_no Text displayed if n < 1 */ function multi_text($n, $text_multi, $text_one, $text_no = '') { if($n > 1) { return str_replace('%', $n, $text_multi); } elseif($n == 1) { return $text_one; } return $text_no; } /** * Simple HTTP redirects. */ function http_redirect($url, $http_response_code = 0) { header("Location: $url", true, $http_response_code); exit; } /** * Check if the request is under HTTPS */ function is_https() { return ! empty( $_SERVER['HTTPS'] ); } /** * Get the protocol of the request * @see use PROTOCOL */ function URL_protocol() { return is_https() ? 'https://' : 'http://'; } /** * Get the domain of the request * @see DOMAIN */ function URL_domain() { return empty( $_SERVER['SERVER_NAME'] ) ? 'localhost' : $_SERVER['SERVER_NAME']; } /** * Get the explicit port of the request * @see PORT * @return string */ function URL_port() { if( isset( $_SERVER[ 'SERVER_PORT' ] ) ) { $p = (int) $_SERVER[ 'SERVER_PORT' ]; if( 80 !== $p && 443 !== $p ) { return ":$p"; } } return ''; } function URL_root() { $root = this_folder(); if( $root === _ ) { return ''; } return $root; } /** * Get a secured version of a string */ function generate_slug($s, $max_length = -1, $glue = '-', & $truncated = false) { return Slug::get($s, $max_length, $glue, $truncated); } -function http_build_get_query($url, $data) { - $data = http_build_query($data); - if( $data ) { - return "$url?$data"; - } - return $url; +function http_build_get_query( $url, $data ) { + $data = http_build_query( $data ); + return $data ? "$url?$data" : $url; } /** - * HTTP 503 headers. - * @see Shit::header503() + * HTTP 503 headers */ function http_503() { return Shit::header503(); } /** * It scares the user with an error message (and dies). - * @see Shit::SWOD() */ function error_die( $msg ) { Shit::WSOD( $msg ); } +/** + * It logs an error message and eventually prints it when DEBUG + * + * @return void + */ function error( $msg ) { - echo Shit::getErrorMessage( $msg ); + Shit::error( $msg ); } /** * Translates a string * * @param string $msgid String to be translated * @return string translated string (or original, if not found) */ function __( $msgid ) { // does the user want a native GNU GETTEXT implementation? cache it. static $native = null; if( null === $native ) { $native = expect( 'registerLanguage' )->isNative(); } if( $native ) { // low-level GNU Gettext call (quicker but the locales must be installed by a sysadmin, and other cache problems) return _( $msgid ); } // high-level GNU Gettext (simpler but slower) return MoLoader::getInstance()->getTranslator()->gettext( $msgid ); } /** * Shortcut for echoing a translated string */ function _e( $s ) { echo __( $s ); } function http_json_header($charset = null) { if( $charset === null ) { $charset = CHARSET; } header('Content-Type: application/json; charset=' . $charset); } /** * Unset the empty values in an array or an object as well recursively * * @param $data mixed * @return array */ function array_unset_empty( $data ) { $is_array = is_array( $data ); if( $is_array || is_object( $data ) ) { foreach( $data as $k => $v ) { if( is_array( $v ) || is_object( $v ) ) { if( $is_array ) { $data [ $k ] = array_unset_empty( $v ); } else { $data->{ $k } = array_unset_empty( $v ); } } elseif( empty( $v ) && ! is_int( $v ) ) { if( $is_array ) { unset( $data [ $k ] ); } else { unset( $data->{ $k } ); } } } } return $data; } /** * Send a JSON (stripping out unuseful values) and quit * * Falsy elements are not returned * * @param $data mixed */ function json( $data ) { http_json_header(); echo json_encode( array_unset_empty( $data ) ); exit; } /** * Send a JSON error and quit * * @param $http_code int HTTP response code * @param $code string Error code * @param $msg string Error human message */ function json_error( $http_code, $code, $msg ) { http_response_code( $http_code ); json( [ 'error' => [ 'code' => $code, 'message' => $msg, ] ] ); } /** * Get the MIME type of a file. * @see MimeTypes::fileMimetype() */ function get_mimetype($filepath, $pure = false) { return MimeTypes::fileMimetype( $filepath, $pure = false ); } /** * Know if a file belongs to a certain category * @see MimeTypes::isMimetypeInCategory() */ function is_file_in_category($filepath, $category) { $mime = get_mimetype($filepath); return expect('mimeTypes')->isMimetypeInCategory($mime , $category); } /** * Get the file extension */ function get_file_extension_from_expectations($filename, $category) { return expect('mimeTypes')->getFileExtensionFromExpectations($filename, $category); } function is_image($filepath) { return is_file_in_category($filepath, 'image'); } function is_audio($filepath) { return is_file_in_category($filepath, 'audio'); } function is_video($filepath) { return is_file_in_category($filepath, 'video'); } function is_document($filepath) { return is_file_in_category($filepath, 'document'); } function is_closure($t) { return is_object($t) && ($t instanceof Closure); } /* * From http://php.net/manual/en/features.file-upload.php#88591 */ function human_filesize($filesize, $separator = ' '){ if( ! is_numeric($filesize) ) { return __("NaN"); } $decr = 1024; $step = 0; $prefix = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB']; while(($filesize / $decr) > 0.9) { $filesize /= $decr; $step++; } return round($filesize, 2) . $separator . $prefix[$step]; } /* * Create a pathname in the filesystem */ function create_path($path, $chmod = CHMOD_WRITABLE_DIRECTORY) { if( file_exists($path) || mkdir($path, $chmod, true) ) { return true; } - DEBUG && error( sprintf( - __("Impossibile scrivere il percorso '%s'."), - esc_html( $path ) - ) ); + error( "unable to create path $path" ); return false; } /** * @see FileUploader::searchFreeFilename() */ function search_free_filename( $filepath, $filename, $ext, $args, $build_filename = null ) { return FileUploader::searchFreeFilename( $filepath, $filename, $ext, $args, $build_filename = null ); } /** * I use this to clean user input before DB#insert() * * @param string $s Input string * @param int $max Max length */ function luser_input($s, $max) { $s = trim($s); return mb_strimwidth($s, 0, $max, ''); } /** * Used to know much is the page load * * @return mixed Execution time * @deprecated */ function get_page_load($decimals = 6) { static $start_microtime = 0; // Please let me take advantage of PHP features if($start_microtime == 0) { $start_microtime = microtime(true); } return substr(microtime(true) - $start_microtime, 0, 2 + $decimals); } diff --git a/load.php b/load.php index b52be29..ddac717 100644 --- a/load.php +++ b/load.php @@ -1,77 +1,102 @@ . /* - * Start the framework + * Start the boz-php framework */ // URL slash defined('_') or define('_', '/'); -// Directory separator +// directory separator defined('__') or define('__', DIRECTORY_SEPARATOR); -define('BOZ_PHP', __DIR__ ); // Here -require BOZ_PHP . __ . 'functions.php'; // Some functions +// boz-php directory +define('BOZ_PHP', __DIR__ ); -// Start stopwatch +// load the functions +require BOZ_PHP . __ . 'functions.php'; + +// start stopwatch get_page_load(); -// Lot of constants with default values -defined('DEBUG') or define('DEBUG', false); -defined('PROTOCOL') or define('PROTOCOL', URL_protocol() ); -defined('DOMAIN') or define('DOMAIN', URL_domain() ); -defined('PORT') or define('PORT', URL_port() ); -defined('ROOT') or define('ROOT', URL_root() ); -defined('BASE_URL') or define('BASE_URL', PROTOCOL . DOMAIN . PORT); -defined('URL') or define('URL', BASE_URL . ROOT); -defined('SHOW_EVERY_SQL') or define('SHOW_EVERY_SQL', false); -defined('CHMOD_WRITABLE_DIRECTORY') or define('CHMOD_WRITABLE_DIRECTORY', 0777); -defined('CHMOD_WRITABLE_FILE') or define('CHMOD_WRITABLE_FILE', 0666); -defined('CHARSET') or define('CHARSET', 'utf-8'); -defined('CACHE_BUSTER') or define('CACHE_BUSTER', ''); - -// On demand requests class-$php ... it's f****** amazing! -spl_autoload_register( function($c) { +// default anonymous user role +define_default( 'DEFAULT_USER_ROLE', 'UNREGISTERED' ); + +// in debug mode you see errors in HTML +define_default( 'DEBUG', false ); + +// log every SQL query and eventually print them in HTML whenever DEBUG is also enabled +define_default( 'DEBUG_QUERIES', false ); + +// HTTP protocol e.g. 'https' +define_default( 'PROTOCOL', URL_protocol() ); + +// domain name e.g. 'reyboz.it' +define_default( 'DOMAIN', URL_domain() ); + +// HTTP port e.g. ':8080' +define_default( 'PORT', URL_port() ); + +// absolute URL directory without trailing slash e.g. '/myapp' or '' +define_default( 'ROOT', URL_root() ); + +// URL without the ROOT +define_default( 'BASE_URL', PROTOCOL . DOMAIN . PORT ); + +// URL with the ROOT +define_default( 'URL', BASE_URL . ROOT ); + +// default permissions for new directories +define_default( 'CHMOD_WRITABLE_DIRECTORY', 0777 ); + +// default permissions for new files +define_default( 'CHMOD_WRITABLE_FILE', 0666 ); + +// request charset +define_default( 'CHARSET', 'utf-8' ); + +// JavaScript / CSS additional GET parameter e.g. '?v=1' +define_default( 'CACHE_BUSTER', '' ); + +// autoload boz-php classes +spl_autoload_register( function( $c ) { $path = BOZ_PHP . __ . "class-$c.php"; if( is_file( $path ) ) { require $path; } } ); -// This is a really stupid thing but it's f****** amazing! $GLOBALS['G'] = new G(); -$GLOBALS['G']->add('db', 'DB'); $GLOBALS['G']->add('mimeTypes', 'MimeTypes'); $GLOBALS['G']->add('javascript', 'RegisterJS'); $GLOBALS['G']->add('css', 'RegisterCSS'); -$GLOBALS['G']->add('session', 'Session'); $GLOBALS['G']->add('permissions', 'Permissions'); $GLOBALS['G']->add('menu', 'Menu'); $GLOBALS['G']->add('module', 'RegisterModule'); $GLOBALS['G']->add('registerLanguage', 'RegisterLanguage'); if( ! defined( 'REQUIRE_LOAD_POST' ) ) { if( defined( 'ABSPATH' ) ) { define( 'REQUIRE_LOAD_POST', ABSPATH . __ . 'load-post.php' ); } else { - error_die( "Please define your ABSPATH or disable REQUIRE_LOAD_POST" ); + error_die( "Please define ABSPATH or at least disable REQUIRE_LOAD_POST" ); } } if( REQUIRE_LOAD_POST ) { require REQUIRE_LOAD_POST; }