diff --git a/class-DB.php b/class-DB.php index 798e6dc..dc0b597 100644 --- a/class-DB.php +++ b/class-DB.php @@ -1,468 +1,468 @@ . /* * Use: esc_html(), error_die(), DEBUG, force_array() */ /** * Database class * * This class was forked from my defunct project called Open Student. */ class DB { /** * MySQL connection link */ private $mysqli; /** * Table prefix * * @var string */ private $prefix; /** * Number of executed queries * * @var int */ private $queries = 0; /** * Last query result * * @var query-result */ private $last = false; /** * Singleton instance * * @var self */ private static $_instance; /** * Get the singleton instance of this class * * @return self */ - public function instance() { + public static function instance() { if( ! self::$_instance ) { self::$_instance = new self(); } return self::$_instance; } /** * Check if ::instance() was called * * @return boolean */ - public function instanced() { + public static function instanced() { return isset( self::$_instance ); } /** * 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' ) { // default credentials usually defined from your load.php if( ! func_num_args() ) { $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->mysqli->connect_errno ) { if( DEBUG ) { $length = strlen( $password ); error_die( "unable to connect to the database '$database' using user '$username' and password ($length characters) on MySQL/MariaDB host '$location'" ); } else { error_die( "error in establishing a database connection" ); } } else { $this->mysqli->set_charset( $charset ); } } /** * Execute an SQL query * * @param string $query The SQL query to execute */ public function query( $query ) { $this->queries++; if( $this->last !== false && $this->last !== true) { $this->last->free(); } $this->last = $this->mysqli->query( $query ); if( !$this->last ) { error_die( $this->getQueryErrorMessage( $query ) ); } elseif( DEBUG_QUERIES ) { error( "query n. {$this->queries}: $query" ); } return $this->last; } /** * Select only a row from the database */ public function getRow( $query, $class_name = null, $params = [] ) { $results = $this->getResults( $query, $class_name, $params ); return isset( $results[ 0 ] ) ? $results[ 0 ] : null; } /** * 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 isset( $row->{ $column_name } ) ? $row->{ $column_name } : null; } /** * 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->last->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( !$class_name ) { $class_name = 'Queried'; } $result = $this->query( $query ); $this->last = 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])) { 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); } /** * Get the last inserted ID * * @return string */ 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 getqueries() { return $this->queries; } 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 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'); } /** * Get the number of affected rows * * @return int */ public function affectedRows() { $this->mysqli->affected_rows(); } /** * Please close the door when you leave a room */ public function closeConnection() { if( $this->mysqli ) { @$this->mysqli->close(); } } /** * Automatically close the door when you leave the room */ public function __destruct() { $this->closeConnection(); } /** * 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->queries, $SQL, esc_html($this->mysqli->error) ); } } diff --git a/class-Menu.php b/class-Menu.php index f767209..df9838c 100644 --- a/class-Menu.php +++ b/class-Menu.php @@ -1,109 +1,109 @@ . /** * Handle a menu tree */ class Menu { private $entries = []; private $tree = []; private $rootUid; /** * Specify the default root identifier. * * @param string $rootUid The default menu entry root identifier. */ function __construct( $rootUid = 'root' ) { $this->rootUid = $rootUid; } /** * Get the singleton instance * * @return self */ - public function instance() { + public static function instance() { static $me = false; if( ! $me ) { $me = new self(); } return $me; } /** * Append a single or an array of menu entries. * * @param array|MenuEntry $entries */ public function add( $entries ) { force_array( $entries ); foreach( $entries as $menuEntry ) { $this->entries[ $menuEntry->uid ] = $menuEntry; force_array( $menuEntry->parentUid ); foreach( $menuEntry->parentUid as $parentUid ) { if( $parentUid === null ) { $parentUid = $this->rootUid; } $this->setParent( $menuEntry->uid, $parentUid ); } } } /** * Force a parent->children relation. * * @param string $uid Children menu entry identifier. * @param string $parentUid Parent menu entry identifier. */ public function setParent($uid, $parentUid) { if( ! isset( $this->tree[ $parentUid ] ) || ! is_array( $this->tree[ $parentUid ] ) ) { $this->tree[ $parentUid ] = []; } $this->tree[ $parentUid ][] = $uid; } /** * Get a single menu entry if registered * * @param string $uid Menu entry identifier * @return MenuEntry */ public function getMenuEntry( $uid ) { if( isset( $this->entries[ $uid ] ) ) { return $this->entries[ $uid ]; } } /** * Get an array of menu entries. * * @param string|null $parentUid Parent menu entry identifier of the parent. The default menu entry root identifier as default. * @return array */ public function getChildrenMenuEntries( $parentUid = null ) { if( $parentUid === null ) { $parentUid = $this->rootUid; } $entries = []; if( isset( $this->tree[ $parentUid ] ) ) { foreach( $this->tree[ $parentUid ] as $uid ) { $entries[] = $this->entries[ $uid ]; } } return $entries; } } diff --git a/class-MimeTypes.php b/class-MimeTypes.php index 9c1f0b3..0e6cb67 100644 --- a/class-MimeTypes.php +++ b/class-MimeTypes.php @@ -1,279 +1,279 @@ . /** * Handle MIME and file types (extensions). * * @use MAGIC_MIME_FILE, functions.php */ class MimeTypes { /** * [ * 'category-1' => [ * 'mime' => ['filetype1', 'filetype2'], * ... * ], * ... * ] * * @var array */ private $mimeTypes; function __construct( $defaults = true ) { if( $defaults ) { $this->loadDefaults(); } } /** * Get the singleton instance * * @return self */ - public function instance() { + public static function instance() { static $me = false; if( ! $me ) { $me = new self(); } return $me; } /** * * @param string $category Category e.g. 'audio' * @param mixed $mimeTypes Array of MIME => file types. * E.g.: * [ * 'image/png' => 'png', * 'image/jpeg' => array['jpg', 'jpeg'], * ... * ] */ public function registerMimetypes($category, $mimeTypes) { // Register category if not exists if( ! isset( $this->mimeTypes[ $category ] ) ) { $this->mimeTypes[ $category ] = []; } foreach($mimeTypes as $mime => $filetypes) { force_array( $filetypes ); if( ! isset( $this->mimeTypes[ $category ][ $mime ] ) ) { $this->mimeTypes[ $category ][ $mime ] = $filetypes; continue; // No need next lines. } $this->mimeTypes[ $category ][ $mime ] = array_merge( $this->mimeTypes[ $category ][ $mime ], $filetypes ); } } /** * Load default MIME types */ private function loadDefaults() { $this->registerMimetypes('image', [ 'image/jpeg' => ['jpg', 'jpeg'], 'image/png' => 'png', 'image/gif' => 'gif' ] ); $this->registerMimetypes('audio', [ 'audio/x-flac' => 'flac', 'audio/ogg' => 'ogg', 'audio/vorbis' => 'ogg', 'audio/vorbis-config' => 'ogg', 'audio/mpeg' => 'mp3', 'audio/MPA' => 'mp4', 'audio/mpa-robust' => 'mp4' ] ); $this->registerMimetypes('video', [ 'video/mp4' => 'mp4', 'application/ogg' => 'ogg' ] ); $this->registerMimetypes('document', [ 'application/pdf' => 'pdf', 'application/x-pdf' => 'pdf', 'application/x-bzpdf' => 'pdf', 'application/x-gzpdf' => 'pdf', 'application/vnd.oasis.opendocument.text' => 'odt', 'application/vnd.oasis.opendocument.presentation' => 'odp', 'application/vnd.oasis.opendocument.spreadsheet' => 'ods', 'application/vnd.oasis.opendocument.graphics' => 'odg', 'application/msword' => 'doc', 'application/vnd.ms-excel' => 'xls', 'application/vnd.ms-powerpoint' => 'ppt', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => ['docx', 'xlsx', 'pptx'] ] ); } /** * Get an array of MIME of the selected category. If category is NULL, all the MIME are returned. * * @param array|string|null $category Category e.g. 'audio' * @return array Array of MIME. */ public function getMimetypes($categories = null) { $allMimeTypes = []; if( $categories === null ) { // All MIME types foreach($this->mimeTypes as $mimeTypes) { foreach($mimeTypes as $mime => $filetypes) { $allMimeTypes[] = $mime; } } } else { force_array( $categories ); // MIME types from selected categories foreach($categories as $category) { if( ! isset( $this->mimeTypes[ $category ] ) ) { self::errorUnknownCategory( $category ); continue; } foreach($this->mimeTypes[ $category ] as $mime => $filetypes) { $allMimeTypes[] = $mime; } } if( count($categories) > 0 ) { $allMimeTypes = array_unique( $allMimeTypes ); } } return $allMimeTypes; } /** * Check if a MIME belongs to a certain category. * * @param string $mime_value E.g.: 'audio/vorbis'. * @param mixed $category E.g.: 'document' * @return bool */ public function isMimetypeInCategory($mimetype, $category = null ) { return in_array($mimetype, $this->getMimetypes($category), true); } /** * Get the file types of a MIME. * * @param string|null $category * If NULL it search in all the categories. * @param string|null $mimetype The MIME type. * @return mixed FALSE if the MIME is not registered or an array of file types. */ public function getFiletypes($categories = null, $mimetype = null) { $all_types = []; if( $categories === null ) { // Search in all the categories. foreach($this->mimeTypes as $mimeTypes) { foreach($mimeTypes as $mime => $types) { if($mimetype === null || $mime === $mimetype) { $all_types = array_merge($all_types, $types); } } } } else { force_array( $categories ); // Search *that* category if exists foreach($categories as $category) { if( ! isset( $this->mimeTypes[ $category ] ) ) { self::errorUnknownCategory($category); continue; } foreach($this->mimeTypes[ $category ] as $mime => $types) { if($mimetype === null || $mime === $mimetype) { $all_types = array_merge($all_types, $types); } } } } return array_unique( $all_types ); } /** * Check (and get) the known file extension. * * @param string $filename The file name. * @param array|string|null $categories MIME categories. * @param string|null $mimetype The MIME type. * @return string|false FALSE or the file extension e.g.: 'png' */ public function getFileExtensionFromExpectations($filename, $categories = null, $mimetype = null) { // Have to insert an arg to enable this feature? // ASD.JPEG => asd.jpeg // @TODO $filename = strtolower($filename); $expected_filetypes = $this->getFiletypes($categories, $mimetype); foreach($expected_filetypes as $filetype) { $dotted = ".$filetype"; $strlen = strlen($dotted); if( substr( $filename, -$strlen, $strlen) === $dotted ) { return $filetype; } } return false; } /** * Get the MIME type from a file. * * @param string $filepath The file path. * @param bool $pure * true for 'image/png; something'; * false for 'image/png'. * @return string|false */ public static function fileMimetype( $filepath, $pure = false ) { $finfo = finfo_open( FILEINFO_MIME, MAGIC_MIME_FILE ); if( ! $finfo ) { return error( sprintf( 'error opening the fileinfo database expected in %s', MAGIC_MIME_FILE ) ); } $mime = finfo_file( $finfo, $filepath ); if( ! $mime ) { return error( sprintf( "can't detect the mime of the file %s", $filepath ) ); } if( ! $pure ) { $mime = explode(';', $mime, 2); // Split "; charset" $mime = $mime[0]; } return $mime; } private static function errorUnknownCategory($category) { error( sprintf( 'the MIME category %s is not registered"), $category ) ); } } diff --git a/class-Permissions.php b/class-Permissions.php index 2501899..12d9bf5 100644 --- a/class-Permissions.php +++ b/class-Permissions.php @@ -1,128 +1,128 @@ . /** * Handle roles and their permissions */ class Permissions { /** * Permissions indexed by user roles */ public $roles = []; /** * Get the singleton instance */ - public function instance() { + public static 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->roles[ $role ] = []; } $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 ) ) { return in_array( $permission, $this->roles[ $role ], true ); } else { error( "unknown role $role" ); } return false; } /** * 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' ); } $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->roles[ $role ] ); } /** * Get all the known permissions * * @return array */ public function getPermissions() { $all = []; 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->roles ); } /** * 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->roles as $role => $permissions ) { $this->roles[ $role ] = array_unique( $permissions ); } return $this; } } diff --git a/class-RegisterCSS.php b/class-RegisterCSS.php index 96cda38..6ae9041 100644 --- a/class-RegisterCSS.php +++ b/class-RegisterCSS.php @@ -1,92 +1,92 @@ . class RegisterCSS { /** * Stylesheets */ private $css = []; /** * Get the singleton instance * * @return self */ - public function instance() { + public static function instance() { static $me = false; if( ! $me ) { $me = new self(); } return $me; } /** * Register a new style name * * @param string $name CSS name, like: "jquery-ui". * @param string $url CSS url, like "http://example.org/styles/jquery-ui.css". */ public function register( $uid, $url ) { $this->css[ $uid ] = new CSS( $url ); } /** * Enqueue a previous registered CSS name * * @param string $uid CSS name. */ public function enqueue( $uid ) { if( empty( $this->css[ $uid ] ) ) { error( "unknown stylesheet $uid" ); } else { $this->css[ $uid ]->enqueue = true; } } /** * Enqueue all registered style that are not registered as private use */ public function printAll( $force = false ) { foreach( $this->css as $uid => $css ) { if( $css->enqueue && !$css->enqueued ) { self::link( $css->url, $uid ); $this->css[ $uid ]->enqueued = true; } } } /** * Print the CSS link tag */ public static function link( $url, $uid ) { if( CACHE_BUSTER ) { $url .= false === strpos( $url, '?' ) ? '?' : '&'; $url .= CACHE_BUSTER; } echo "\n\t"; } } class CSS { public $url; public $enqueue = false; public $enqueued = false; public function __construct( $url ) { $this->url = $url; } } diff --git a/class-RegisterJS.php b/class-RegisterJS.php index 159093e..338551b 100644 --- a/class-RegisterJS.php +++ b/class-RegisterJS.php @@ -1,124 +1,124 @@ . /** * To enqueue JS libraries */ class RegisterJS { /** * Script names */ private $javascript = []; private $generated = [ false, false ]; /** * Get the singleton instance * * @return self */ - public function instance() { + public static function instance() { static $me = false; if( ! $me ) { $me = new self(); } return $me; } /** * Register a new script name * * @param string $name JS name, like: "jquery" * @param string $url Script url, like "http://example.org/lib/jquery.js" */ public function register( $uid, $url ) { if( isset( $this->javascript[ $uid ] ) ) { $this->javascript[ $uid ]->url = $url; } else { $this->javascript[ $uid ] = new JS( $url ); } } /** * Enqueue a previous registered JS name * * @param string $name JS name * @param bool $position Place it in the head of the page or not */ public function enqueue( $uid, $position = null ) { $position = JS::filterPosition( $position ); if( isset( $this->javascript[ $uid ] ) ) { $this->javascript[ $uid ]->enqueue( $position ); } else { error( "unregistered JS $uid" ); } } public function printAll( $position ) { $cache_burster = CACHE_BUSTER; foreach( $this->javascript as $uid => $javascript ) { if( $javascript->enqueue && $javascript->position === $position ) { echo "\n"; if( $position === JS::HEADER ) { echo "\t"; } $url = $javascript->url; if( CACHE_BUSTER ) { $url .= false === strpos( $url, '?' ) ? '?' : '&'; $url .= CACHE_BUSTER; } echo ""; if( DEBUG ) { echo ""; } } } $this->generated[ (int) $position ] = true; } public function isGenerated( $position ) { return $this->generated[ (int) $position ]; } } class JS { const HEADER = true; const FOOTER = false; public $url; public $position = self::HEADER; public $enqueue = false; public function __construct( $url ) { $this->url = $url; } /** * @param boolean $in_head {JS::HEADER, JS::FOOTER} */ public function enqueue( $position = self::HEADER ) { $this->position = self::filterPosition( $position ); $this->enqueue = true; } public static function filterPosition( $position ) { if( $position === null ) { return self::HEADER; } return $position; } } diff --git a/class-RegisterLanguage.php b/class-RegisterLanguage.php index 994dfde..3e637c7 100644 --- a/class-RegisterLanguage.php +++ b/class-RegisterLanguage.php @@ -1,320 +1,320 @@ . /** * Handle languages using standard GNU Gettext functionalities * * @use error_die(), esc_html() */ class RegisterLanguage { private $i = -1; private $languages = []; /** * Associative map of alias=>index of $this->languages */ private $aliases = []; private $gettextDomain; private $gettextDirectory; private $gettextDefaultEncode; /** * Use native GNU Gettext (lot of quicker but more unreliable) * * @var bool */ private $native; /** * Latest language applied */ private $latest = null; /** * Default language (don't apply GNU Gettext in this case). * * Index of self#languages[] */ private $default = null; /** * Get the singleton instance * * @return self */ - public function instance() { + public static function instance() { static $me = false; if( ! $me ) { $me = new self(); } return $me; } /** * Constructor * * @param string $domain GNU Gettext domain * @param string $directory GNU Gettext directory * @param string $default_encode GNU Gettext default language encode */ public function __construct( $domain = null, $directory = null, $default_encode = null, $native = null ) { if( ! $domain ) { $domain = GETTEXT_DOMAIN; } if( ! $directory ) { $directory = GETTEXT_DIRECTORY; } if( ! $default_encode ) { $default_encode = GETTEXT_DEFAULT_ENCODE; } if( null === $native ) { $native = defined( 'GETTEXT_NATIVE' ) ? GETTEXT_NATIVE : false; } $this->gettextDomain = $domain; $this->gettextDirectory = $directory; $this->gettextDefaultEncode = $default_encode; $this->native = $native; } /** * Register a language * * @param $code string GNU Gettext code language * @param $aliases array You can specify language aliases (in lower case) * @param $encode string Override the default GNU Gettext language encode * @param $iso string * @param $human string e.g. 'English' */ public function registerLanguage( $code, $aliases = [], $encode = null, $iso = null, $human = null, $humanL10n = null ) { if( ! $encode ) { $encode = $this->gettextDefaultEncode; } if( ! $encode ) { return error( 'please specify encoding for language $code, or define GETTEXT_DEFAULT_ENCODE' ); } $this->languages[ ++$this->i ] = new BozPHPLanguage( $code, $encode, $iso, $human, $humanL10n ); // Yes, the language code it's an alias to itself. That's a lazy hack! $this->aliases[ self::normalize($code) ] = $this->i; // Each alias is associated to it's language code force_array( $aliases ); foreach( $aliases as $alias ) { $this->aliases[ $alias ] = $this->i; } } /** * Set the default language. * * A default language allow less high-level pain. * * @param string $default */ public function setDefaultLanguage( $default ) { $code = self::normalize( $default ); if( ! isset( $this->aliases[ $code ] ) ) { error_die( "the default language $default have to be registered previously" ); } $this->default = $this->languages[ $this->aliases[ $code ] ]; } /** * Get a Language object from a language alias. * * @param string $language_alias Language alias, null for browser preferences * @return false|object Language object or false if it isn't registered */ public function getLanguage( $language_alias = null ) { if( $language_alias ) { $language_alias = self::normalize( $language_alias ); if( isset( $this->aliases[ $language_alias ] ) ) { return $this->languages[ $this->aliases[ $language_alias ] ]; } } else { return $this->getLanguageFromHTTP(); } return false; } /** * Is a native GETTEXT implementation? * * @return bool */ public function isNative() { return $this->native; } /** * Set the GNU Gettext environment from a language alias or from browser preferences. * * @param string $language_alias Language alias, null for browser preferences * @return mixed */ public function applyLanguage( $language_alias = null ) { $language = $this->getLanguage( $language_alias ); if( ! $language ) { return false; } $this->latest = $language; self::GNUGettextEnvironment( $language->getCode(), $language->getEncode(), $this->gettextDomain, $this->gettextDirectory, $this->isNative() ); return $language->getCode(); } /** * @return BozPHPLanguage|null */ function getLatestLanguageApplied() { return $this->latest ? $this->latest : $this->default; } /** * Determine browser language in preference order, respecting RFC. * * @see http://stackoverflow.com/a/11161193 */ function getLanguageFromHTTP() { if( ! isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) { return false; } // Create an associative array of priority=>language preg_match_all( '/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER[ 'HTTP_ACCEPT_LANGUAGE' ], $langs ); if( 0 === count( $langs[ 1 ] ) ) { return false; } $langs = array_combine( $langs[ 1 ], $langs[ 4 ] ); // To respect RFC if no priority is specified (q=;) foreach( $langs as $lang => $val ){ $langs[ $lang ] = ( '' === $val ) ? 1.0 : (float) $val; } // Order by priority arsort( $langs, SORT_NUMERIC ); // Search and use a known language foreach( $langs as $lang => $val ) { $language = $this->getLanguage( $lang ); if( false !== $language ) { // Found a language that match browser preferences! return $language; } } return false; } /** * Get all the registered languages * * @return array */ public function getAll() { return $this->languages; } /** * Fill the GNU Gettext Environment * * @param $native bool Use or not the native implementation */ public static function GNUGettextEnvironment( $code, $encode, $domain, $directory, $native = false ) { if( $native ) { putenv( "LANG=$code.$encode" ); $ok = setlocale( LC_MESSAGES, "$code.$encode" ); bindtextdomain( $domain, $directory ); textdomain( $domain ); bind_textdomain_codeset( $domain, $encode ); } else { $loader = MoLoader::instance(); $loader->setlocale( "$code.$encode" ); $loader->textdomain( $domain ); $loader->bindtextdomain( $domain, $directory ); } } /** * Normalize a language code for internal use * * @param $code string * @return string */ private static function normalize( $code ) { return strtolower( $code ); } } class BozPHPLanguage { private $code; private $encode; private $iso; private $human; private $humanL10n; public function __construct( $code, $encode, $iso, $human, $humanL10n ) { $this->code = $code; $this->encode = $encode; $this->iso = $iso; $this->human = $human; $this->humanL10n = $humanL10n; } public function getCode() { return $this->code; } public function getEncode() { return $this->encode; } public function getISO() { if($this->iso === null) { $this->iso = self::guessISO($this->iso); } return $this->iso; } public function getHuman() { return $this->human; } public function getHumanL10n() { return $this->humanL10n; } /** * Gets 'it' from 'it_IT', 'it_IT.utf8' etc. * * Can be called statically */ public function guessISO( $code = null, $fallback = 'en' ) { if( $code === null ) { $code = $this->code; } $p = strpos( $code, '_' ); if( false === $p ) { error( "can't guess the ISO language from $code, falling on $fallback" ); return $fallback; } return substr( $code, 0, $p ); } } diff --git a/class-RegisterModule.php b/class-RegisterModule.php index f7845ba..297d577 100644 --- a/class-RegisterModule.php +++ b/class-RegisterModule.php @@ -1,109 +1,109 @@ . /** * Dynamically inject functions in modules ("places"). * * @require DEBUG, error(), esc_html() */ class RegisterModule { /** * Assoc functions to modules */ private $module = []; /** * 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() { + public static 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' ); // Append scripts and styles $this->injectFunction( 'header', function () { RegisterJS ::instance()->printAll( JS::HEADER ); RegisterCSS::instance()->printAll(); } ); $this->injectFunction( 'footer', function () { RegisterJS::instance()->printAll( JS::FOOTER ); } ); } /** * Formally register a module (a place where you can inject functions) * * @param string $name */ public function register( $name ) { if( ! isset( $this->module[ $name ] ) ) { $this->module[ $name ] = []; } } /** * Inject a callback into a module * * @param string $name Module name * @param string $callback The callback */ public function injectFunction( $name, $callback ) { if( ! isset( $this->module[ $name ] ) ) { return error( "can't inject in unknown module $name" ); } $this->module[ $name ][] = $callback; } /** * Load all the functions related to this module name. * * @param string $name Module name */ public function loadModule( $name ) { if( ! isset( $this->module[ $name ] ) ) { return error( "can't load unregistered module $name" ); } $status = true; foreach( $this->module[ $name ] as $callback ) { $status = $status && $callback(); } return $status; } } diff --git a/class-Session.php b/class-Session.php index a107fcc..b459cd7 100644 --- a/class-Session.php +++ b/class-Session.php @@ -1,221 +1,221 @@ . // 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() { + public static 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; 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() ) { 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; } }