diff --git a/class-DB.php b/class-DB.php index 3c530c8..a7ab419 100644 --- a/class-DB.php +++ b/class-DB.php @@ -1,478 +1,493 @@ . /* * 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; + /** + * Singleton instance + * + * @var self + */ + private static $_instance; + /** * Get an instance of this class * * @return self */ public function instance() { - static $me = null; - if( ! $me ) { - $me = new self(); + if( ! self::$_instance ) { + self::$_instance = new self(); } - return $me; + return self::$_instance; + } + + /** + * Check if ::instance() was called + * + * @return boolean + */ + public 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' ) { 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

Errore:
%s
"), $this->numQueries, $SQL, esc_html($this->mysqli->error) ); } } diff --git a/class-DynamicQuery.php b/class-DynamicQuery.php index ba9883e..e3808ff 100644 --- a/class-DynamicQuery.php +++ b/class-DynamicQuery.php @@ -1,169 +1,168 @@ . /** * @deprecated use Query instead */ class DynamicQuery { private $db; private $selectFields = []; private $tables = []; private $conditions = null; private $offset; private $rowCount; private $orders = null; function __construct(& $db = null) { if(!$db) { - expect('db'); - $db = & $GLOBALS['db']; + $db = DB::instance(); } $this->db = $db; // Dipendency injection } public function useTable($t) { self::appendInArray($t, $this->tables); return $this; } public function uniqueTables() { $this->tables = array_unique($this->tables); return $this; } public function selectField($f) { self::appendInArray($f, $this->selectFields); return $this; } public function appendCondition($c, $glue = 'AND') { if($this->conditions !== null) { $this->conditions .= " $glue "; } $this->conditions .= $c; return $this; } public function setLimit($row_count, $offset = null) { $this->rowCount = $row_count; $this->offset = $offset; return $this; } public function appendConditionSomethingIn($heystack, $needles, $glue = 'AND', $not_in = false) { force_array($needles); $n_needles = count($needles); if( $n_needles === 1 ) { $symbol = ($not_in) ? '!=' : '='; $this->appendCondition( sprintf("$heystack $symbol '%s'", esc_sql( $needles[0] ) ), $glue ); return $this; } $values = ''; for($i=0; $i<$n_needles; $i++) { if($i != 0) { $values .= ', '; } $values .= single_quotes( esc_sql($needles[ $i ]) ); } if( $values !== '') { if($not_in) { $this->appendCondition("$heystack NOT IN ($values)", $glue); } else { $this->appendCondition("$heystack IN ($values)", $glue); } } return $this; } public function appendConditionSomethingNotIn($heystack, $needles, $glue = 'AND') { $this->appendConditionSomethingIn($heystack, $needles, $glue, true); // See true return $this; } private static function appendInArray($values, & $array) { force_array($values); foreach($values as $value) { if( $value && ! in_array($value, $array, true) ) { $array[] = $value; } } } public function getTables() { return $this->db->getTables( $this->tables ); } public function getSelectFields() { if( count( $this->selectFields ) === 0 ) { return '*'; } return implode(', ', $this->selectFields); } public function getConditions() { return $this->conditions; } public function appendOrderBy($order_by) { if($this->orders !== null) { $this->orders .= ', '; } $this->orders .= $order_by; return $this; } public function getQuery() { $sql = "SELECT {$this->getSelectFields()} FROM {$this->getTables()}"; if($this->conditions) { $sql .= " WHERE {$this->getConditions()}"; } if($this->orders) { $sql .= " ORDER BY {$this->orders}"; } if($this->rowCount) { $sql .= ' LIMIT '; if( $this->offset ) { $sql .= "{$this->offset}, "; } $sql .= $this->rowCount; } return $sql; } public function query() { return $this->db->query( $this->getQuery() ); } public function getResults($class_name = null, $params = [] ) { return $this->db->getResults( $this->getQuery(), $class_name, $params ); } public function getRow($class_name = null, $params = []) { return $this->db->getRow( $this->getQuery(), $class_name, $params ); } public function getValue($column_name) { return $this->db->getValue( $this->getQuery(), $column_name ); } } diff --git a/class-G.php b/class-G.php deleted file mode 100644 index db56871..0000000 --- a/class-G.php +++ /dev/null @@ -1,73 +0,0 @@ -. - -/** - * Allows you to be sure that a global object exists. - * - * @deprecated - */ -class G { - /** - * Associative array of: expected global variable name => it's class - */ - private $added = []; - - /** - * Register an expected global variable name to it's class. - * - * If it doesn't exists it will be created as global and istantiated. - */ - public function add($name, $class) { - $this->added[ $name ] = $class; - } - - /** - * Be sure that a global object exists. - * - * This method allows you to use the power of PHP and spl_audoload() - * loading resources only when you request them. - * - * E.g. if you create a database connection using something as - * $GLOBAL['db'] = new DB(), and we do it, you can avoid starting a - * database connection even in pages that don't require database connections - * simply saying that you "expect" an initialized global '$db' object. - * Let's say expect('db'). - * - * As you can see, in the best case it's only an isset() away from your code. - * - * @param string $name A global var name. - */ - public function expect($name) { - if( ! isset( $GLOBALS[ $name ] ) ) { - // Die if class was not registered - isset( $this->added[ $name ] ) || error_die( sprintf( - __("Variabile globale '%s' attesa ma mai registrata. L'hai scritta correttamente?"), - esc_html($name) - ) ); - - $class_name = $this->added[ $name ]; - - class_exists($class_name, true) || error_die( sprintf( - __("La classe '%s' non esiste!"), - esc_html($class_name) - ) ); - - $GLOBALS[ $name ] = new $class_name(); - } - - return $GLOBALS[ $name ]; - } -} diff --git a/class-Menu.php b/class-Menu.php index 6656c58..293907a 100644 --- a/class-Menu.php +++ b/class-Menu.php @@ -1,110 +1,116 @@ . /** * Handle a menu tree. */ class Menu { private $menuEntries = []; 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() { + static $me = false; + if( ! $me ) { + $me = new self(); + } + return $me; + } + /** * Append a single or an array of menu entries. * * @param array|MenuEntry $menuEntries */ public function add($menuEntries) { force_array($menuEntries); foreach($menuEntries as $menuEntry) { $this->menuEntries[ $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. * * @param string $uid Menu entry identifier. * @return MenuEntry */ public function getMenuEntry($uid) { if( isset( $this->menuEntries[ $uid ] ) ) { return $this->menuEntries[ $uid ]; } - - DEBUG && error( sprintf( - __("La voce di menu '%s' non è stata ancora creata."), - esc_html($uid) - ) ); - - return null; + error( "the menu entry $uid was not found" ); } /** * 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; } $menuEntries = []; if( isset( $this->tree[ $parentUid ] ) ) { foreach($this->tree[ $parentUid ] as $uid) { $menuEntries[] = $this->menuEntries[ $uid ]; } } return $menuEntries; } } diff --git a/class-MimeTypes.php b/class-MimeTypes.php index 85622ad..9c1f0b3 100644 --- a/class-MimeTypes.php +++ b/class-MimeTypes.php @@ -1,266 +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) { - $defaults && $this->loadDefaults(); + 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; } /** * * @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 ] ) ) { - DEBUG && self::printErrorUnknownCategory( $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 ] ) ) { - DEBUG && self::printErrorUnknownCategory($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 ) { - DEBUG && error( sprintf( - __("Errore aprendo il database fileinfo situato in '%s'."), + return error( sprintf( + 'error opening the fileinfo database expected in %s', MAGIC_MIME_FILE ) ); - return false; } $mime = finfo_file( $finfo, $filepath ); if( ! $mime ) { - DEBUG && error( sprintf( - __("Impossibile ottenere il MIME del file '%s'."), - esc_html( $filepath ) + return error( sprintf( + "can't detect the mime of the file %s", + $filepath ) ); - return false; } if( ! $pure ) { $mime = explode(';', $mime, 2); // Split "; charset" $mime = $mime[0]; } return $mime; } - private static function printErrorUnknownCategory($category) { + private static function errorUnknownCategory($category) { error( sprintf( - __("Categoria di MIME %s non registrata."), - esc_html( $category ) + 'the MIME category %s is not registered"), + $category ) ); } } diff --git a/class-Queried.php b/class-Queried.php index 6de6f20..ad437bf 100644 --- a/class-Queried.php +++ b/class-Queried.php @@ -1,186 +1,185 @@ . /** * This class handles a database table result * * Very often this database table has an ID and an UID. */ class Queried { /** * Maximum UID length */ const MAXLEN_UID = 256; /** * Empty constructor */ public function __construct() {} /** * Obtain a property that can be null (but can't be undefined). * * @param string $property * @return mixed */ public function get( $property ) { if( property_exists( $this, $property ) ) { return $this->$property; } error_die( sprintf( - __("Impossibile ottenere %s->%s"), + 'cannot obtain %s->%s', get_class( $this ), $property ) ); } /** * Check if a property is not NULL * * @param string $property * @return bool */ public function has( $property ) { return null !== $this->get( $property ); } /** * Obtain a property that can't be null (and can't be undefined). * * @param string $property * @return mixed */ public function nonnull($property) { if( isset( $this->$property ) ) { return $this->$property; } - error_die( sprintf( - __("Impossibile ottenere %s->%s"), + 'cannot obtain %s->%s', get_class( $this ), $property ) ); } function integers() { foreach( func_get_args() as $p) { isset( $this->$p ) and $this->$p = (int) $this->$p; } return $this; } function booleans() { foreach( func_get_args() as $p) { isset( $this->$p ) and $this->$p = (bool) (int) $this->$p; } return $this; } function dates() { foreach( func_get_args() as $p) { isset( $this->$p ) and $this->$p = DateTime::createFromFormat('Y-m-d', $this->$p); } } function datetimes() { foreach( func_get_args() as $p) { isset( $this->$p ) and $this->$p = DateTime::createFromFormat('Y-m-d H:i:s', $this->$p); } return $this; } function floats() { foreach( func_get_args() as $p) { isset( $this->$p ) and $this->$p = (float) $this->$p; } } /** * Query factory * * The class constant 'T' is expected as table name * * @return Query */ public static function factory() { return Query::factory( static::class ) ->from( static::T ); } /** * Factory from an ID column * * The class constant 'ID' is expected * * @param $ID int * @return Queried */ public static function factoryFromID( $ID ) { $field = defined( static::class . '::ID' ) ? static::ID : static::T . '_ID'; $field = static::T . DOT . $field; return self::factory() ->whereInt( $field, $ID ); } /** * Factory from an UID column * * The class constant 'UID' is expected * * @param $uid string * @return Queried */ public static function factoryFromUID( $uid ) { $field = defined( static::class . '::UID' ) ? static::UID : static::T . '_uid'; $uid = static::sanitizeUID( $uid ); return self::factory() ->whereStr( $field, $uid ); } /** * Sanitize the UID * * @return string * @use luser_input() */ public static function sanitizeUID( $uid ) { return luser_input( $uid, static::MAXLEN_UID ); } /** * Alias of self::factoryFromID() * * @deprecated */ public static function factoryByID( $ID ) { return self::factoryFromID( $ID ); } /** * Alias of self::factoryFromUID() * * @deprecated */ public static function factoryByUID( $uid ) { return self::factoryFromUID( $uid ); } } diff --git a/class-Query.php b/class-Query.php index eb44dd7..956f1f9 100644 --- a/class-Query.php +++ b/class-Query.php @@ -1,449 +1,449 @@ . /** * Class useful to build a database query */ class Query { private $db; private $class_name; private $selectFields = []; private $tables = []; private $from = []; private $groups = []; private $having; private $conditions; private $offset; private $rowCount; private $orders; - public function __construct( &$db = null ) { - $this->db = $db ? $db : expect( 'db' ); // Dipendency injection + public function __construct( $db = null ) { + $this->db = $db ? $db : DB::instance(); // Dipendency injection } /** * Construct shortcut. * * @param string $class_name Class to encapsulate the database result * @return self */ public static function factory( $class_name = null ) { $t = new self(); $class_name and $t->defaultClass( $class_name ); return $t; } /** * Selected fields (SELECT). * * @param string|array $fields * @return self */ public function select() { return $this->appendInArray( func_get_args(), $this->selectFields ); } /** * Selected tables * * @param string|array $tables Table/tables without database prefix * @return self */ public function from() { return $this->appendInArray( func_get_args(), $this->tables ); } /** * Set a custom from value * * @param string e.g. "(SELECT * ...) as t1" * @return self */ public function fromCustom( $from ) { $this->from[] = $from; return $this; } /** * Intendeed to be used for PRIMARY KEY joins. * * @param string $one Result set field * @param string $two Result set field * @return self */ public function equals( $one, $two ) { return $this->where( "$one = $two" ); } /** * Append a query condition * * @param string $condition something as 'field = 1' * @param string $glue condition glue such as 'OR' * @return self */ public function where( $condition, $glue = 'AND' ) { if( null !== $this->conditions ) { $this->conditions .= " $glue "; } $this->conditions .= $condition; return $this; } /** * Intended to compare a property with a number. * * @param string $one Column name * @param int $value Value */ public function whereInt( $column, $value ) { return $this->equals( $column, (int)$value ); } /** * Intended to compare a property with a string. * * @param string $one Column name * @param string $value Value */ public function whereStr( $column, $value ) { $value = esc_sql( $value ); return $this->equals( $column, "'$value'" ); } /** * Filter by a LIKE command * * @param $column string Column name * @param $value string Value to be liked * @param $left string To have whatever before the value * @param $right string To have whatever after the value */ public function whereLike( $column, $value, $left = true, $right = true ) { $left = $left ? '%' : ''; $right = $right ? '%' : ''; return $this->where( sprintf( '`%s` LIKE \'%s%s%s\'', $column, $left, esc_sql_like( $value ), $right ) ); } /** * Append a custom join from the latest selected table * * @param $type string join type e.g. LEFT, RIGHT, LEFT OUTHER * @param $table string table name * @param $a string column name * @param $b string column name */ public function joinOn( $type, $table, $a, $b ) { if( $this->tables ) { $latest_table = $this->db->getTable( array_pop( $this->tables ), true ); } elseif( $this->from ) { $latest_table = array_pop( $this->from ); } else { throw new InvalidArgumentException( 'not enough tables' ); } $this->from[] = sprintf( '%s %s JOIN %s ON (%s = %s)', $latest_table, $type, $this->db->getTable( $table ), $a, $b ); return $this; } /** * Group by * * @param string|array $groups Group by * @return self */ public function groupBy() { return $this->appendInArray( func_get_args(), $this->groups ); } /** * You have double-selected a table but that wasn't your goal. * * @return self */ public function uniqueTables() { $this->tables = array_unique( $this->tables ); return $this; } /** * LIMIT count, offset. * * @param int $row_count Max numbers of elements. * @param int $offset Starting offset * @return self */ public function limit( $row_count, $offset = null ) { $this->rowCount = $row_count; $this->offset = $offset; return $this; } /** * Handy shortcut for `something IN (values)` condition. * * @param string $heystack Field. * @param string|array $needles Values to compare. * @return self */ public function whereSomethingIn( $heystack, $needles, $glue = 'AND', $not_in = false ) { force_array($needles); $n_needles = count($needles); if( $n_needles === 1 ) { $needle = array_pop( $needles ); $this->where( sprintf("%s %s '%s'", $heystack, $not_in ? '!=' : '=', esc_sql( $needle ) ), $glue ); return $this; } $escaped_needles = []; $is_int = is_int( reset( $needles ) ); foreach( $needles as $needle ) { $escaped_needles[] = $is_int ? (int) $needle : "'" . esc_sql( $needle ) . "'"; } if( $escaped_needles ) { $values = implode(', ', $escaped_needles); if($not_in) { $this->where("$heystack NOT IN ($values)", $glue); } else { $this->where("$heystack IN ($values)", $glue); } } return $this; } /** * Handy shortcut for `something NOT IN (values)` condition. * * @param string $heystack Field. * @param string|array $needles Values to compare. */ public function whereSomethingNotIn( $heystack, $needles, $glue = 'AND' ) { $this->appendConditionSomethingIn($heystack, $needles, $glue, true); // See true return $this; } /** * Get the FROM clause * * @return string */ public function getFrom() { $tables = $this->db->getTables( $this->tables ); if( $this->from ) { if( $tables ) { $tables .= ' JOIN '; } $tables .= implode( ' JOIN ', $this->from ); } return $tables; } public function getSelect() { if( $this->selectFields ) { return implode( ', ', $this->selectFields ); } return '*'; } public function getWhere() { return $this->conditions; } public function getGroupBy() { return implode(', ', $this->groups); } public function having( $having ) { $this->having = $having; return $this; } /** * Order by * * @param $order_by string Field to sort * @param $how string DESC|ASC, failing to ASC * @return self */ public function orderBy( $order_by, $how = null ) { if( null !== $this->orders ) { $this->orders .= ', '; } $this->orders .= $order_by; if( $how ) { $this->orders .= ' ' . self::filterDirection( $how ); } return $this; } /** * @return string SQL query */ public function getQuery() { $sql = "SELECT {$this->getSelect()} FROM {$this->getFrom()}"; if( $this->conditions ) { $sql .= " WHERE {$this->getWhere()}"; } if( $this->groups ) { $sql .= " GROUP BY {$this->getGroupBy()}"; } if( $this->having ) { $sql .= " HAVING {$this->having}"; } if( $this->orders ) { $sql .= " ORDER BY {$this->orders}"; } if( null !== $this->rowCount ) { $sql .= ' LIMIT '; if( $this->offset ) { $sql .= "{$this->offset}, "; } $sql .= $this->rowCount; } return $sql; } /** * Set the default class to incapsulate the result set. * * @param string $class_name Class name * @return self */ public function defaultClass( $class_name ) { $this->class_name = $class_name; return $this; } /** * Get the specified class name or the default one * * @TODO: rename to getClassName() * @param $class_name string * @return string */ public function getDefaultClass( $class_name = null ) { return $class_name ? $class_name : $this->class_name; } /** * @see DB#query() */ public function query() { return $this->db->query( $this->getQuery() ); } /** * Get the array of result sets encapsulated in the specified class. * * @param string $class_name * @see DB#getResults() * @return array */ public function queryResults( $class_name = null, $params = [] ) { return $this->db->getResults( $this->getQuery(), $this->getDefaultClass( $class_name ), $params ); } /** * Get a generator of $class_name objects. * * @param string $class_name * @see DB#getResults() * @return array */ public function queryGenerator( $class_name = null, $params = [] ) { return $this->db->getGenerator( $this->getQuery(), $this->getDefaultClass( $class_name ), $params ); } /** * Get the result set encapsulated in the specified class. * * @param string $class_name * @see DB#getRow() * @return null|Object */ public function queryRow( $class_name = null, $params = [] ) { return $this->db->getRow( $this->getQuery(), $this->getDefaultClass( $class_name ), $params ); } /** * Get the specified column from the first result set. * @param string $column_name * @see DB#getValue() * @return mixed */ public function queryValue( $column_name ) { return $this->db->getValue( $this->getQuery(), $column_name ); } private function appendInArray( $values, & $array ) { // Retrocompatibility patch if( isset( $values[ 0 ] ) && is_array( $values[ 0 ] ) ) { $values = $values[ 0 ]; } foreach( $values as $value ) { $array[] = $value; } return $this; } /** * Filter a direction * * The fallback is ASC. * * @param $dir string * @return string DESC|ASC */ public static function filterDirection( $dir ) { $dir = strtoupper( $dir ); return $dir === 'DESC' ? 'DESC' : 'ASC'; } } diff --git a/class-RegisterLanguage.php b/class-RegisterLanguage.php index 4683ad2..8e91cf5 100644 --- a/class-RegisterLanguage.php +++ b/class-RegisterLanguage.php @@ -1,319 +1,332 @@ . /** * 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() { + 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 ) { DEBUG && error( sprintf( ___("Non hai specificato una codifica per la lingua '%s' e non ce n'è una predefinita. Impostala con la costante %s."), esc_html($code), 'GETTEXT_DEFAULT_ENCODE' ) ); return false; } $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( sprintf( ___("Default language '%s' have to be registered previously"), esc_html($default) ) ); } $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::getInstance(); $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 ) { DEBUG && error( sprintf( ___("Can't guess the ISO language from language code '%s'. Falling on default '%s'."), esc_html($code), $fallback ) ); return $fallback; } return substr($code, 0, $p); } } diff --git a/functions.php b/functions.php index 9ac0356..eba3d74 100644 --- a/functions.php +++ b/functions.php @@ -1,795 +1,774 @@ . -// Useful e.g. in Table::NAME . DOT . STAR query. +// unuseful shortcuts when you want a SELECT * 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) ) { + 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); +function enfatize_substr( $heystack, $needle, $pre = '', $post = '' ) { + return EnfatizeSubstr::get( $heystack, $needle, $pre, $post ); } /** * SQL query escape string * @see DB#escapeString() */ function esc_sql($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 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 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 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 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 DB::instance()->getValue($query, $value, $class); } /** * Executes one or multiple queries which are concatenated by a semicolon * @see DB#multiQuery() */ function 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 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 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 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?") ); - + if( ! DB::instanced() ) { + error_die( 'cannot obtain last inserted ID without database connection' ); + } 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 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 = '') { 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); + MimeTypes::instance()->registerMimetypes($category, $mimetypes); } function get_mimetypes($category = null) { - return expect('mimeTypes')->getMimetypes($category); + return MimeTypes::instance()->getMimetypes($category); } /** * @param string $role User role * @param string|string[] $permissions Permissions */ function register_permissions($role, $permissions) { - expect('permissions')->registerPermissions($role, $permissions); + Permissions::instance()->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); + Permissions::instance()->inheritPermissions($role_to, $role_from, $other_permissions); } function register_js($javascript_uid, $url, $position = null) { - return expect('javascript')->register( $javascript_uid, $url, $position ); + return RegisterJS::instance()->register( $javascript_uid, $url, $position ); } function enqueue_js($javascript_uid, $position = null) { - expect('javascript'); - return $GLOBALS['javascript']->enqueue( $javascript_uid, $position ); + return RegisterJS::instance()->enqueue( $javascript_uid, $position ); } function register_css($css_uid, $url) { - return expect('css')->register($css_uid, $url); + return RegisterCSS::instance()->register($css_uid, $url); } function enqueue_css($css_uid) { - return expect('css')->enqueue($css_uid); + return RegisterCSS::instance()->enqueue($css_uid); } function add_menu_entries($menuEntries) { - expect('menu')->add($menuEntries); + Menu::instance()->add($menuEntries); } function get_menu_entry($uid) { - return expect('menu')->getMenuEntry($uid); + return Menu::instance()->getMenuEntry($uid); } function get_children_menu_entries($parentUid) { - return expect('menu')->getChildrenMenuEntries($parentUid); + return Menu::instance()->getChildrenMenuEntries($parentUid); } function register_module($module_uid) { - return expect('module')->register($module_uid); + return RegisterModule::instance()->register($module_uid); } function inject_in_module($module_uid, $callback) { - return expect('module')->injectFunction($module_uid, $callback); + return RegisterModule::instance()->injectFunction($module_uid, $callback); } function load_module($module_uid) { - return expect('module')->loadModule($module_uid); + return RegisterModule::instance()->loadModule($module_uid); } function get_table_prefix() { return DB::instance()->getPrefix(); } function register_option($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 = 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 Session::instance()->login($status, $user_uid, $user_password); } function logout() { return Session::instance()->destroy(); } function register_language($code, $aliases = [], $encode = null, $iso = null, $human = null) { - return expect('registerLanguage')->registerLanguage($code, $aliases, $encode, $iso, $human); + return RegisterLanguage::instance()->registerLanguage($code, $aliases, $encode, $iso, $human); } function register_default_language($default) { - return expect('registerLanguage')->setDefaultLanguage($default); + return RegisterLanguage::instance()->setDefaultLanguage($default); } function find_language($language_alias) { - return expect('registerLanguage')->getLanguage($language_alias); + return RegisterLanguage::instance()->getLanguage($language_alias); } function apply_language($language_alias = null) { - return expect('registerLanguage')->applyLanguage($language_alias); + return RegisterLanguage::instance()->applyLanguage($language_alias); } function latest_language() { - return expect('registerLanguage')->getLatestLanguageApplied(); + return RegisterLanguage::instance()->getLatestLanguageApplied(); } function all_languages() { - return expect('registerLanguage')->getAll(); + return RegisterLanguage::instance()->getAll(); } function get_num_queries() { - if( isset( $GLOBALS['db'] ) ) { - return $GLOBALS['db']->getNumQueries(); + if( DB::instanced() ) { + return DB::instance()->getNumQueries(); } return 0; } function is_logged() { return Session::instance()->isLogged(); } /** * @param string $permission Permission uid * @param User|null $user Specified user * @return bool */ function has_permission($permission, $user = null) { - $session = Session::instance(); - - if( $user === null ) { - $user = $session->getUser(); + if( ! $user ) { + $user = Session::instance()->getUser(); } - $user_role = false; - if($user) { - $user_role = $user->user_role; - } - if( ! $user_role ) { - $user_role = DEFAULT_USER_ROLE; + $role = $user + ? $user->get( 'user_role' ) + : false; + + if( ! $role ) { + $role = DEFAULT_USER_ROLE; } - return expect('permissions')->hasPermission($user_role, $permission); + return Permissions::instance()->hasPermission($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']; + return isset( $_SERVER[ 'SERVER_NAME' ] ) + ? $_SERVER[ 'SERVER_NAME' ] + : php_uname( 'n' ); } /** * 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 ); return $data ? "$url?$data" : $url; } /** * HTTP 503 headers */ function http_503() { return Shit::header503(); } /** * It scares the user with an error message (and dies). */ function error_die( $msg ) { Shit::WSOD( $msg ); } /** * It logs an error message and eventually prints it when DEBUG * * @return void */ function error( $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(); + $native = RegisterLanguage::instance()->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 ); + return MoLoader::instance()->getTranslator()->gettext( $msgid ); } /** * Shortcut for echoing a translated string */ function _e( $s ) { echo __( $s ); } function http_json_header($charset = null) { - if( $charset === null ) { + if( null === $charset ) { $charset = CHARSET; } - header('Content-Type: application/json; 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 ); + $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); + return MimeTypes::instance()->isMimetypeInCategory($mime , $category); } /** * Get the file extension */ function get_file_extension_from_expectations($filename, $category) { - return expect('mimeTypes')->getFileExtensionFromExpectations($filename, $category); + return MimeTypes::instance()->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; } 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, ''); + return mb_strimwidth( trim($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 0e7805d..6da797e 100644 --- a/load.php +++ b/load.php @@ -1,102 +1,93 @@ . /* * Start the boz-php framework */ // URL slash defined('_') or define('_', '/'); // directory separator defined('__') or define('__', DIRECTORY_SEPARATOR); // boz-php directory define('BOZ_PHP', __DIR__ ); // load the functions require BOZ_PHP . __ . 'functions.php'; // start stopwatch get_page_load(); // 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' ); // trailing JavaScript / CSS parameter e.g. 'v=1' (will be automatically prefixed with &/?) 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; } } ); -$GLOBALS['G'] = new G(); -$GLOBALS['G']->add('mimeTypes', 'MimeTypes'); -$GLOBALS['G']->add('javascript', 'RegisterJS'); -$GLOBALS['G']->add('css', 'RegisterCSS'); -$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 ABSPATH or at least disable REQUIRE_LOAD_POST" ); } } if( REQUIRE_LOAD_POST ) { require REQUIRE_LOAD_POST; }