Page MenuHomeGitPull.it

No OneTemporary

Authored By
Unknown
Size
69 KB
Referenced Files
None
Subscribers
None
diff --git a/class-DB.php b/class-DB.php
index 5261d7f..ccac1d7 100644
--- a/class-DB.php
+++ b/class-DB.php
@@ -1,490 +1,490 @@
<?php
# Copyright (C) 2015, 2018, 2019 Valerio Bozzolan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
- * Use: esc_html(), error_die(), DEBUG, force_array()
+ * Use: esc_html(), DEBUG, force_array()
*/
/**
* A simple but effective 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
*
* Read by get_num_queries()
*
* @var int
*/
public $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 static function instance() {
if( ! self::$_instance ) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Check if ::instance() was called
*
* @return boolean
*/
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 ) {
$length = strlen( $password );
- error_die( "unable to connect to the database '$database' using user '$username' and password ($length characters) on MySQL/MariaDB host '$location'" );
+ throw new SucklessException( "unable to connect to the database '$database' using user '$username' and password ($length characters) on MySQL/MariaDB host '$location'" );
} 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 ) );
+ throw new SucklessException( $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();
}
/**
* Run an INSERT query for a single row
*
* @param string $table
* @param DBCol[] $cols
* @param $args arguments like 'replace-into
*/
public function insertRow( $table, $cols, $args = [] ) {
// build column names
$columns = [];
foreach( $cols as $col ) {
$columns[] = "`{$col->column}`";
}
// sanitize values
$values = [];
foreach( $cols as $col ) {
$values[] = $this->forceType( $col->value, $col->forceType );
}
// default arguments
$args = array_replace( [
'replace-into' => false,
], $args );
$what = $args[ 'replace-into' ] ? 'REPLACE' : 'INSERT';
$table = $this->getTable( $table, false );
$columns_comma = implode( ', ', $columns );
$values_comma = implode( ', ', $values );
return $this->query("$what INTO $table ($columns_comma) VALUES ($values_comma)");
}
/**
* Executes one or multiple queries which are concatenated by a semicolon
*
* @param $queries string
*/
public function multiQuery( $queries ) {
$i = 1;
if( !$this->mysqli->multi_query( $queries ) ) {
- error_die( "error in MySQLi#multi_query() with statement n. $i (starting from 1): {$this->mysqli->error}" );
+ throw new SucklessException( "error in MySQLi#multi_query() with statement n. $i (starting from 1): {$this->mysqli->error}" );
}
while( $this->mysqli->more_results() ) {
$i++;
if( !$this->mysqli->next_result() ) {
- error_die( "error in MySQLi#multi_query() with statement n. $i (starting from 1): {$this->mysqli->error}" );
+ throw new SucklessException( "error in MySQLi#multi_query() with statement n. $i (starting from 1): {$this->mysqli->error}" );
}
}
}
/**
* Run an INSERT query for multiple rows
*
* @param string $table Table Name without prefix
* @param array $columns Assoc array of types ('ID' => 'null', 'name' => 's', ..)
* @param array $rows Array of rows (or just a row)
* @param array $args Extra arguments
*/
public function insert( $table, $columns, $rows, $args = [] ) {
// default arguments
$args = array_replace( [
'replace-into' => false,
], $args );
// backticked column names
$column_names = [];
foreach( $columns as $column => $type ) {
$column_names[] = "`$column`";
}
$columns_comma = implode( ', ', $column_names );
// backward compatibility
force_array( $rows );
if( ! @is_array( $rows[0] ) ) {
$rows = [$rows];
}
// just the types (in order to be indexed numerically)
$types = array_values( $columns );
$n_columns = count( $types );
$value_groups = [];
foreach( $rows as $i => $row ) {
$query_values = [];
if( $n_columns !== count( $row ) ) {
- error_die( sprintf(
+ throw new SucklessException( sprintf(
"error using insert() in table %s: %d columns but %d values in row %d",
$table,
$n_columns,
count( $row ),
$i
) );
}
$values_escaped = [];
foreach( $types as $j => $type ) {
$values_escaped[] = $this->forceType( $row[ $j ], $type );
}
$values_grouped = implode( ', ', $values_escaped );
$value_groups[] = "($values_grouped)";
}
$value_groups_comma = implode( ', ', $value_groups );
$action = $args['replace-into'] ? 'REPLACE' : 'INSERT';
$table = $this->getTable( $table, false );
return $this->query( "$action INTO $table ($columns_comma) VALUES $value_groups_comma" );
}
/**
* Run an UPDATE query
*
* @param string $table Table name without prefix and backticks
* @param array $columns array of DBCol(s)
* @param string $conditions part after WHERE
* @param string $after
*/
public function update( $table, $columns, $conditions, $after = '' ) {
// backward compatibility
force_array( $columns );
$table = $this->getTable( $table, false );
$sets = [];
foreach( $columns as $column ) {
$name = $column->column;
$value = $this->forceType( $column->value, $column->forceType );
$sets[] = "`$name` = $value";
}
$sets_comma = implode( ', ', $sets );
return $this->query( "UPDATE $table SET $sets_comma WHERE $conditions $after" );
}
/**
* Get the last inserted ID
*
* @return string
*/
public function getLastInsertedID() {
return $this->mysqli->insert_id;
}
/**
* Get the last number of rows retrieved
*
* @return int
*/
public function getLastNumRows() {
return $this->last->num_rows;
}
/**
* 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 );
}
/**
* Get the table prefix
*
* @return string
*/
public function getPrefix() {
return $this->prefix;
}
/**
* Get table name with it's prefix (if any)
*
* @param string $name Table name
* @param mixed $as True to create an alias without the table prefix, or specify your alias
* @return string Table eventually with the alias
*/
public function getTable( $name, $as = true ) {
$table = "`{$this->prefix}$name`";
if( $as ) {
if( $as === true ) {
$as = $name;
}
$table .= " AS `$as`";
}
return $table;
}
/**
* Get the list of every table name inserted as arguments or as an array
*
* @return string
*/
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
*/
public 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( "type $type unexpected in DB::forceType() and so it will be seen as 's'" );
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.
+ * Show a friendly error about last MySQL query
*
- * @param string $query SQL query executed during the error
+ * @param string $query SQL query executed during the error
* @return string
*/
private function getQueryErrorMessage( $query ) {
return sprintf(
"error executing the query n. %d |%s| error: %s",
$this->queries,
$query,
- esc_html( $this->mysqli->error )
+ $this->mysqli->error
);
}
}
diff --git a/class-Queried.php b/class-Queried.php
index 338eb4d..0a83511 100644
--- a/class-Queried.php
+++ b/class-Queried.php
@@ -1,185 +1,185 @@
<?php
# Copyright (C) 2017, 2018, 2019 Valerio Bozzolan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
/**
* 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;
}
- throw new Exception( sprintf(
+ throw new SucklessException( sprintf(
'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;
}
- throw new Exception( sprintf(
+ throw new SucklessException( sprintf(
'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 2eabd77..4298ae7 100644
--- a/class-Query.php
+++ b/class-Query.php
@@ -1,626 +1,626 @@
<?php
# Copyright (C) 2017, 2018, 2019 Valerio Bozzolan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
/**
* 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;
/**
* Constructor
*
* @param object $db Database object (class DB)
* @param string $class_name Class to encapsulate the database result
*/
public function __construct( $db = null, $class_name = null ) {
$this->db = $db ? $db : DB::instance(); // Dependency injection
if( $class_name ) {
$this->defaultClass( $class_name );
}
}
/**
* Constructor shortcut from class name
*
* @param string $class_name Class to encapsulate the database result
* @param object $db Database object (class DB)
* @return self
*/
public static function factory( $class_name = null, $db = null ) {
return new self( $db, $class_name );
}
/**
* 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;
}
/**
* To compare two columns somehow
*
* @param string $one Something (NOT SANITIZED)
* @param string $verb Comparison method
* @param string $two Something (NOT SANITIZED)
* @param string $glue Conditions glue
* @return self
*/
public function compare( $one, $verb, $two, $glue = 'AND' ) {
return $this->where( "$one $verb $two", $glue );
}
/**
* To be used for PRIMARY KEY joins
*
* @param string $one Something (NOT SANITIZED)
* @param string $two Something (NOT SANITIZED)
* @return self
*/
public function equals( $one, $two ) {
return $this->compare( $one, '=', $two );
}
/**
* Append a query condition
*
* @param string $condition Something as 'field = 1'
* @param string $glue Conditions glue
* @return self
*/
public function where( $condition, $glue = 'AND' ) {
if( null !== $this->conditions ) {
$this->conditions .= " $glue ";
}
$this->conditions .= $condition;
return $this;
}
/**
* Intended to compare a column with a number
*
* @param string $one Column name
* @param int $value Value
* @param string $verb Compare method
* @return self
*/
public function whereInt( $column, $value, $verb = '=' ) {
return $this->compare( $column, $verb, (int)$value );
}
/**
* Intended to compare a column with a string
*
* @param string $one Column name
* @param string $value Value
* @param string $verb Compare method
* @return self
*/
public function whereStr( $column, $value, $verb = '=' ) {
$value = esc_sql( $value );
return $this->compare( $column, $verb, "'$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 ? '%' : '';
$value = $left . esc_sql_like( $value ) . $right;
return $this->whereStr( $column, $value, 'LIKE' );
}
/**
* Append a custom join from the latest selected table
*
* @param $type string Join type e.g. INNER, LEFT, RIGHT, etc.
* @param $table string Table name
* @param $a string First column name for the ON clause (or complete ON condition if $b is empty)
* @param $b string Second column name for the ON clause (or complete ON condition if $a is empty)
* @param $alias mixed Table alias. As default is true, and the table prefix is removed.
*/
public function joinOn( $type, $table, $a, $b = null, $alias = true ) {
if( $this->tables ) {
$previous = array_pop( $this->tables );
$previous = $this->db->getTable( $previous, true );
} elseif( $this->from ) {
$previous = array_pop( $this->from );
} else {
throw new InvalidArgumentException( 'not enough tables' );
}
$table = $this->db->getTable( $table, $alias );
$conditions = [];
if( $a ) {
$conditions[] = $a;
}
if( $b ) {
$conditions[] = $b;
}
$on = implode( '=', $conditions );
$this->from[] = "$previous $type JOIN $table ON ($on)";
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;
}
/**
* Get the LIMIT SQL clause (if any)
*
* @return string
*/
public function getLimitClause() {
if( $this->rowCount !== null ) {
$query = ' LIMIT ';
if( $this->offset ) {
$query .= "{$this->offset}, ";
}
return $query . $this->rowCount;
}
}
/**
* Handy shortcut for `something IN (values)` condition.
*
* Actually the type (int or string) is inherited from the first value.
*
* @param string $heystack Column name
* @param string|array $needles Values to compare
* @return self
*/
public function whereSomethingIn( $heystack, $needles, $glue = 'AND', $not_in = false ) {
force_array( $needles );
// no needles no filter
$n_needles = count( $needles );
if( !$n_needles ) {
return $this;
}
// the type is inherited from the first value
$is_int = is_int( reset( $needles ) );
// case with just one element
if( $n_needles === 1 ) {
$needle = array_pop( $needles );
$verb = $not_in ? '!=' : '=';
return $is_int
? $this->whereInt( $heystack, $needle, $verb )
: $this->whereStr( $heystack, $needle, $verb );
}
// collect the series
$escaped_needles = [];
$force_type = $is_int ? 'd' : 's';
foreach( $needles as $needle ) {
$escaped_needles[] = $this->db->forceType( $needle, $force_type );
}
// build the condition
$values = implode( ', ', $escaped_needles );
$values = "($values)";
$verb = $not_in ? 'NOT IN' : 'IN';
return $this->compare( $heystack, $verb, $values, $glue );
}
/**
* 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' ) {
return $this->appendConditionSomethingIn( $heystack, $needles, $glue, true ); // See true
}
/**
* 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;
}
/**
* Get the SELECT clause
*
* @return string
*/
public function getSelect() {
if( $this->selectFields ) {
return implode( ', ', $this->selectFields );
}
return '*';
}
/**
* Get the WHERE clause body
*
* @return string
*/
public function getWhere() {
return $this->conditions;
}
/**
* Get the GROUP BY clause body
*
* @return string
*/
public function getGroupBy() {
return implode(', ', $this->groups);
}
/**
* Set the HAVING clause
*
* @param string $having
* @return self
*/
public function having( $having ) {
$this->having = $having;
return $this;
}
/**
* Order by a field
*
* @param string $order_by Field to sort
* @param string $how Choose 'DESC' or '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;
}
/**
* Mark a SELECT query as needed for an UPDATE
*
* «If you use FOR UPDATE with a storage engine that uses page or row locks,
* rows examined by the query are write-locked until the end of the current transaction.»
*
* @return self
*/
public function forUpdate() {
$this->forUpdate = true;
return $this;
}
/**
* Build an SQL SELECT query
*
* @return string SQL query
* @see https://dev.mysql.com/doc/refman/8.0/en/select.html
*/
public function getQuery() {
$sql = "SELECT {$this->getSelect()} FROM {$this->getFrom()}";
if( $this->conditions ) {
$sql .= " WHERE {$this->conditions}";
}
if( $this->groups ) {
$sql .= " GROUP BY {$this->getGroupBy()}";
}
if( $this->having ) {
$sql .= " HAVING {$this->having}";
}
if( $this->orders ) {
$sql .= " ORDER BY {$this->orders}";
}
$sql .= $this->getLimitClause();
if( isset( $this->forUpdate ) ) {
$sql .= " FOR UPDATE";
}
return $sql;
}
/**
* Get a DELETE query
*
* Note that you MUST specify a condition.
*
* Note that the SQL DELETE query has a strange syntax for
* table aliases. See https://stackoverflow.com/a/11005244
*
* @return string SQL DELETE query
*/
public function getDeleteQuery() {
$table = reset( $this->tables ); // just the only one
$table_full = $this->db->getTable( $table, true );
return "DELETE `$table` FROM $table_full WHERE {$this->conditions} {$this->getLimitClause()}";
}
/**
* Run an SQL DELETE query
*
* @see https://dev.mysql.com/doc/refman/8.0/en/delete.html
*/
public function delete() {
return $this->runDangerousQuery( $this->getDeleteQuery() );
}
/**
* Build and run an SQL UPDATE query
*
* Note that you MUST specify a condition.
*
* @param array $columns
* @return array
*/
public function update( $columns ) {
force_array( $columns );
$sets = [];
foreach( $columns as $column ) {
$name = $column->column;
$value = $this->db->forceType( $column->value, $column->forceType );
$sets[] = "`$name` = $value";
}
$sets_comma = implode( ', ', $sets );
$query = "UPDATE {$this->getFrom()} SET $sets_comma WHERE {$this->conditions}";
$query .= $this->getLimitClause();
return $this->runDangerousQuery( $query );
}
/**
* Run an INSERT query
*
* @param array $data Array of DBCol sanitized data
* @param array $args Associative array of arguments
* 'replace-into' boolean Run this query as a REPLACE INTO
*/
public function insertRow( $data, $args = [] ) {
if( empty( $this->tables[0] ) ) {
- error_die( "cannot insert without a table" );
+ throw new SucklessException( "cannot insert without a table" );
}
return $this->db->insertRow( $this->tables[0], $data, $args );
}
/**
* 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
*
* @param string $class_name
* @return string
*/
public function getDefaultClass( $class_name = null ) {
return $class_name ? $class_name : $this->class_name;
}
/**
* Run the SELECT query
*
* @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 );
}
/**
* Append a value or some values into an array
*
* @param array|string $values An array of values or just a value
* @param array $array Array that will be modified
* @return self
*/
private function appendInArray( $values, & $array ) {
// retro-compatibility feature
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';
}
/**
* Check if this query is involving just a single table
*
* @return bool
*/
private function isSimpleFrom() {
return count( $this->from ) + count( $this->tables ) === 1;
}
/**
* Run a query that MUST involve just a single table and have a condition
*
* @param string $query SQL query
* @param string $kind Kind of query (just for the debug message)
*/
private function runDangerousQuery( $query ) {
if( !$this->conditions || !$this->isSimpleFrom() ) {
if( DEBUG_QUERIES ) {
error( $query );
}
if( $this->conditions ) {
- error_die( "for security reasons you cannot build this kind of query involving multiple tables" );
+ throw new SucklessException( "for security reasons you cannot build this kind of query involving multiple tables" );
}
- error_die( "for security reasons you cannot build this kind of query without a condition" );
+ throw new SucklessException( "for security reasons you cannot build this kind of query without a condition" );
}
return $this->db->query( $query );
}
}
diff --git a/class-RegisterJS.php b/class-RegisterJS.php
index 77b920f..ad30481 100644
--- a/class-RegisterJS.php
+++ b/class-RegisterJS.php
@@ -1,189 +1,189 @@
<?php
# Copyright (C) 2015, 2017, 2019 Valerio Bozzolan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
/**
* Register and enqueue JS libraries
*/
class RegisterJS {
/**
* Default position
*/
public static $DEFAULT = 'header';
/**
* Script names
*/
private $js = [];
/**
* Get the singleton instance
*
* @return self
*/
public static function instance() {
static $me = false;
if( ! $me ) {
$me = new self();
}
return $me;
}
/**
* Register a new script name
*
* @param string $name Script name, like: "jquery"
* @param mixed $url Script url, like "http://example.org/lib/jquery.js"
* @param string $position header|footer
* @param array $dependencies Dependent script names
*/
public function register( $uid, $url, $position = null, $dependencies = [] ) {
if( ! $position ) {
$position = self::$DEFAULT;
}
$this->js[ $uid ] = new JS( $uid, $url, $position, $dependencies );
}
/**
* Register an inline script
*
* @param string $uid Script name, like: "jquery"
* @param array $data Inline JavaScript content (without <script> tags)
* @param string $position before|after
*/
public function registerInline( $uid, $data, $position ) {
if( isset( $this->js[ $uid ] ) ) {
$this->js[ $uid ]->inline[ $position ][] = $data;
} else {
- throw new Exception( "missing script '$uid'" );
+ throw new SucklessException( "missing script '$uid'" );
}
}
/**
* Enqueue a previous registered JS name
*
* Note that if there is a stylesheet with the same UID, it will be
* enqueued as well.
*
* @param $name string JS name
* @param $position string Place it in the head of the page or not
*/
public function enqueue( $uid, $position = null ) {
$js = $this->js[ $uid ];
// eventually override script position
if( $position ) {
$js->position = $position;
}
// eventually mark to be enqueued with also its dependencies
if( !$js->enqueue ) {
// also enqueue the stylesheet with the same UID (if it exists)
RegisterCSS::instance()->enqueue( $uid, false );
$js->enqueue = true;
foreach( $js->dependencies as $dependency_uid ) {
$this->enqueue( $dependency_uid );
}
}
}
/**
* Print all the JS from a specified position
*
* @param $position string
*/
public function printAll( $position ) {
$glue = $position === 'header' ? "\n\t" : "\n";
foreach( $this->js as $js ) {
if( $js->enqueue && $js->position === $position ) {
$js->printInline( 'before', $glue );
$js->printNormal( $glue );
$js->printInline( 'after', $glue );
}
}
}
}
class JS {
public $uid;
public $url;
public $position;
public $enqueue = false;
public $inline;
public $dependencies;
/**
* Construct
*
* @param $uid string
* @param $url string
* @param $position string header|footer
*/
public function __construct( $uid, $url, $position, $dependencies ) {
$this->uid = $uid;
$this->url = $url;
$this->position = $position;
$this->dependencies = $dependencies;
$this->inline = [
'after' => [],
'before' => [],
];
}
/**
* Print inline JavaScript parts
*
* @param $position before|after
* @param $glue string
*/
public function printInline( $position, $glue ) {
$parts = $this->inline[ $position ];
if( $parts ) {
echo "$glue<script>$glue" .
implode( $parts, $glue ) .
"$glue</script>";
if( DEBUG ) {
echo "<!-- {$this->uid} - $position -->";
}
}
}
/**
* Print the normal JS inclusion
*
* @param $glue string
*/
public function printNormal( $glue ) {
$url = $this->url;
if( CACHE_BUSTER ) {
$url .= false === strpos( $url, '?' ) ? '?' : '&amp;';
$url .= CACHE_BUSTER;
}
echo "$glue<script src=\"$url\"></script>";
if( DEBUG ) {
echo "<!-- {$this->uid} -->";
}
}
}
diff --git a/class-SucklessException.php b/class-SucklessException.php
new file mode 100644
index 0000000..19f75f1
--- /dev/null
+++ b/class-SucklessException.php
@@ -0,0 +1,22 @@
+<?php
+# Copyright (C) 2019 Valerio Bozzolan
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Exception thrown by sucklessPHP
+ */
+class SucklessException extends Exception {
+
+}
diff --git a/functions.php b/functions.php
index 628d339..4db3dd1 100644
--- a/functions.php
+++ b/functions.php
@@ -1,1122 +1,1122 @@
<?php
# Copyright (C) 2015, 2016, 2017, 2018, 2019 Valerio Bozzolan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
/**
* Check if the user do not want to be tracked
*
* See the HTTP 'DNT' header.
*
* @return boolean
*/
function do_not_track() {
return isset( $_SERVER['HTTP_DNT'] )
&& $_SERVER['HTTP_DNT'] === '1';
}
/*
* Configuration helpers
*
* Shortcuts useful when you declare a configuration file.
*/
/**
* Define a constant if it does not exist
*
* @param string $name Constant name
* @param string $value Constant value
*/
function define_default( $name, $value ) {
defined( $name ) or
define( $name, $value );
}
/*
* Template helpers
*
* Shortcuts useful when you build a page
*/
/**
* Return a ' selected="selected"' HTML attribute under some circumstances
*
* @param mixed $helper If this is the only arg, return
* @param mixed $current If this matches $helper, return
* @param bool $force If this is true, return
*/
function selected( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) {
return html_attribute_when_matching( 'selected', 'selected', $helper, $current, $force);
}
/**
* Return a ' checked="checked"' HTML attribute under some circumstances
*
* This is useful for the <input type="checkbox" /> HTML tag.
*
* @param mixed $helper If this is the only arg, return
* @param mixed $current If this matches $helper, return
* @param bool $force If this is true, return
*/
function checked( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) {
return html_attribute_when_matching( 'checked', 'checked', $helper, $current, $force);
}
/**
* Return a ' disabled="disabled"' HTML attribute under some circumstances
*
* @param mixed $helper If this is the only arg, return
* @param mixed $current If this matches $helper, return
* @param bool $force If this is true, return
*/
function disabled( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) {
return html_attribute_when_matching( 'disabled', 'disabled', $helper, $current, $force );
}
/**
* Return an HTML attribute under some circumstances
*
* @param string $attribute HTML attribute name e.g. 'disabled'
* @param string $value HTML attribute value e.g.
* @param mixed $helper If this is the only arg, return
* @param mixed $current If this matches $helper, return
* @param bool $force If this is true, return
*/
function html_attribute_when_matching( $attribute, $value, $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) {
if( $helper === $current || $helper && PHP_INT_MAX === $current || $force ) {
return HTML::property( $attribute, $value );
}
return '';
}
/**
* Get an HTML attribute ' value="$v"'
*
* The value will be sanitized.
*
* @param string $v
* @return string
*/
function value( $v ) {
return HTML::property( 'value', $v );
}
/**
* Shortcut for htmlentities()
*
* Return an HTML-sanitized untrusted string to be safe from XSS.
*
* @param string $s e.g. 'Hello<script>...'
* @return string e.g. 'Hello&lt;script&gt;...'
*/
function esc_html( $s ) {
return htmlentities( $s );
}
/**
* Enfatize a sub-string
*
* This is helpful when highlighting search results
*
* @param string $heystack e.g. 'The quick brown fox'
* @param string $needle e.g. 'quick'
* @param string $pre HTML markup put before the found $needle
* @param string $post HTML markup put after fhe found $needle
* @return string e.g. 'The <b>quick</b> brown fox'
*/
function enfatize_substr( $heystack, $needle, $pre = '<b>', $post = '</b>' ) {
return OutputUtilities::enfatizeSubstr( $heystack, $needle, $pre, $post );
}
/*
* Conversion shortcuts
*/
/**
* Force a variable to be an array
*
* @return mixed|array $a
*/
function force_array( & $a ) {
if( ! is_array( $a ) ) {
$a = [ $a ];
}
}
/*
* Database shourtcuts
*/
/**
* Sanitize an SQL value to be safe from SQL injections
*
* @param string $s
* @return string
*/
function esc_sql( $s ) {
return DB::instance()->escapeString( $s );
}
/**
* Sanitize an SQL value to be safe from SQL injections and escape also '%'
*
* @param string $s
* @return string
*/
function esc_sql_like( $s ) {
$s = str_replace( '%', '\%', $s );
return esc_sql( $s );
}
/**
* Execute whatever query
*
* @param string $query SQL query
* @see DB#query()
* @return object
*/
function query( $query ) {
return DB::instance()->query( $query );
}
/**
* Execute a query and return an array of objects
*
* Note: Use query_generator() if you do not need the entire array.
*
* @param string $query SQL query
* @param string $class_name Class name to encapsulate the result set
* @param array $args Arguments to be passed to the constructor of $class_name
* @return array
*/
function query_results( $query, $class_name = null, $args = [] ) {
return DB::instance()->getResults( $query, $class_name, $args );
}
/**
* Execute a query and return a generator
*
* Note: Use query_results() if you need the entire array.
*
* @param string $query SQL query
* @param string $class_name Class name to encapsulate the result set
* @param array $args Arguments to be passed to the constructor of $class_name
* @return array
*/
function query_generator( $query, $class_name = null, $args = [] ) {
return DB::instance()->getGenerator( $query, $class_name, $args );
}
/**
* Execute a query and return a single row, as an object
*
* @param string $query SQL query
* @param string $class_name Class name to encapsulate the result set
* @return object|null Arguments to be passed to the constructor of $class_name
*/
function query_row( $query, $class_name = null, $args = [] ) {
return DB::instance()->getRow( $query, $class_name, $args );
}
/**
* Execute a query and return a single column from a single row
*
* @param string $query SQL query
* @param string $field Field to be returned
* @see DB#getValue()
*/
function query_value( $query, $field, $class_name = null ) {
return DB::instance()->getValue( $query, $field, $class_name );
}
/**
* Executes multiple queries concatenated by a semicolon
*
* @param string $queries SQL queries
*/
function multiquery( $queries ) {
return DB::instance()->multiQuery( $queries );
}
/**
* Get a database table name, full with its prefix, eventually aliased
*
* Note that the prefix is declared in your configuration file as $prefix.
*
* @param string $table Table name e.g. 'test'
* @param boolean If true, eventually strip the prefix with an alias
* @return string Table name e.g. 'site01_test'
*/
function T( $table, $as = false ) {
return DB::instance()->getTable( $table, $as );
}
/**
* Insert a row in a database table
*
* @param string $table Table name
* @param DBCol[] $cols Array of DBCol objects (with column, value and type)
* @param array $args Associative arguments for the query
* * 'replace-into' boolean Run a REPLACE INTO instead of just an INSERT INTO
*/
function insert_row( $table, $cols, $args = [] ) {
return DB::instance()->insertRow( $table, $cols, $args );
}
/**
* Get the last AUTOINCREMENT value created after an INSERT query
*
* @return int
*/
function last_inserted_ID() {
if( ! DB::instanced() ) {
- error_die( 'cannot obtain last inserted ID without database connection' );
+ throw new SucklessException( 'cannot obtain last inserted ID without database connection' );
}
return DB::instance()->getLastInsertedID();
}
/**
* Insert multiple rows in a database table
*
* @param string $table Table name
* @param array $cols Array of columns with their escape e.g. [ 'id' => 'd', 'name' => 's' ]
* @param array $values Array of rows e.g. [ [ 1, 'stallman' ], [ 2, 'torvalds' ]
*/
function insert_values( $table, $cols, $values ) {
return DB::instance()->insert( $table, $cols, $values );
}
/**
* Update rows in the specified database table
*
* @param string $table Table name
* @param DBCol[] $cols Array of DBCol objects (with column, value and type)
* @param string $cond SQL condition (after the WHERE part)
* @see DB#update()
*/
function query_update( $table, $cols, $cond, $after = '' ) {
DB::instance()->update( $table, $cols, $cond, $after );
}
/**
* Shortcut for htmlspecialchars()
*
* Get a sanitized value for an HTML attribute value (in double quotes).
*
* @param string $s
* @return string
*/
function esc_attr( $s ) {
return htmlspecialchars( $s );
}
/**
* Shortcut for echoing htmlspecialchars()
*
* Print a sanitized value for an HTML attribute value (in double quotes).
*
* @param string $s
*/
function _esc_attr( $s ) {
echo htmlspecialchars( $s );
}
/**
* Associate some MIME types to a category
*
* @param string $category e.g. 'compressed'
* @param string $mimetypes e.g. [ 'tgz' => 'application/x-tar', 'gzip' => 'application/x-bzip', ]
*/
function register_mimetypes( $category, $mimetypes ) {
MimeTypes::instance()->registerMimetypes($category, $mimetypes);
}
/**
* Get the MIME types of a category, or all the accepteds
*
* @param string $category e.g. 'image'
* @return string
*/
function get_mimetypes( $category = null ) {
return MimeTypes::instance()->getMimetypes( $category );
}
/**
* Register permissions to a role
*
* @param string $role User role
* @param array|string $permissions Permissions
*/
function register_permissions($role, $permissions) {
Permissions::instance()->registerPermissions($role, $permissions);
}
/**
* Give some permissions to a role, inheriting from an old one
*
* @param string $role_to Role to give permissions
* @param string $role_from Role from inheriting permissions
* @param array|string $permissions Extra permissions to be add to $role_to
*/
function inherit_permissions( $role_to, $role_from, $permissions = [] ) {
Permissions::instance()->inheritPermissions( $role_to, $role_from, $permissions );
}
/**
* Register a JavaScript file to be enqueued later
*
* @param string $uid Script name e.g. 'jquery'
* @param string $url Script URL e.g. '/javascript/jquery/jquery.min.js'
* @param string $position Choose between 'header' or 'footer'
* @param array $dependencies Array of script names used as dependencies
*/
function register_js( $uid, $url, $position = null, $dependencies = [] ) {
RegisterJS::instance()->register( $uid, $url, $position, $dependencies );
}
/**
* Register an inline JavaScript script and attach to a registered script
*
* @param string $uid Dependent script name e.g. 'jquery'
* @param string $data Script body e.g. '$(document).find()...'
* @param string $position Choose between 'after' or 'before' related to $uid execution
*/
function register_js_inline( $uid, $data, $position = 'after' ) {
RegisterJS::instance()->registerInline($uid, $data, $position);
}
/**
* Register an inline JavaScript variable and attach to a registered script
*
* @param string $uid Dependent script name e.g. 'my-map'
* @param string $variable Variable declaration e.g. 'var coordinates'
* @param mixed $value Variable content (can be an array, an object, a callback, etc.)
* @param string $position Choose between 'after' or 'before' related to $uid execution
*/
function register_js_var( $uid, $variable, $value, $position = 'before' ) {
if( is_closure( $value ) ) {
$value = $value();
}
$data = json_encode( $value, DEBUG ? JSON_PRETTY_PRINT : 0 );
register_js_inline( $uid, "$variable = $data;", $position );
}
/**
* Mark a registered script for usage
*
* Note that if there is a related stylesheet, it will be enqueued as well.
*
* @param string $uid Dependent script name e.g. 'my-map'
* @param string $position Choose between 'header' or 'footer'
*/
function enqueue_js( $uid, $position = null ) {
return RegisterJS::instance()->enqueue( $uid, $position );
}
/**
* Register a CSS stylesheet
*
* @param string $uid Stylesheet name e.g. 'materializecss'
* @param string $url Stylesheet URL
*/
function register_css( $uid, $url ) {
return RegisterCSS::instance()->register( $uid, $url );
}
/**
* Mark a registered stylesheet for usage
*
* @param string $uid Stylesheet name e.g. 'materializecss'
*/
function enqueue_css( $uid ) {
return RegisterCSS::instance()->enqueue( $uid );
}
/**
* Register some menu entries
*
* @param MenuEntry[] $entries
*/
function add_menu_entries( $entries ) {
Menu::instance()->add( $entries );
}
/**
* Get a menu entry
*
* @param string $uid
* @return MenuEntry
*/
function menu_entry( $uid ) {
return Menu::instance()->getMenuEntry( $uid );
}
function get_children_menu_entries($uid) {
return Menu::instance()->getChildrenMenuEntries($uid);
}
/**
* Register a module
*
* @param string $uid Module position
*/
function register_module( $uid ) {
return RegisterModule::instance()->register($uid);
}
/**
* Inject a closure into a module
*
* @param string $uid
* @param closure $callback
*/
function inject_in_module( $uid, $callback ) {
return RegisterModule::instance()->injectFunction($uid, $callback);
}
/**
* Run the actions registered in the specified module
*
* @param string $uid
*/
function load_module( $uid ) {
return RegisterModule::instance()->loadModule($uid);
}
/**
* Get the database table prefix
*
* @return string
*/
function get_table_prefix() {
return DB::instance()->getPrefix();
}
/**
* Register an option to be used later
*
* The options are stored in the database.
*
* @param string $name
*/
function register_option( $name ) {
return DB::instance()->registerOption( $name );
}
/**
* Get the value of an option
*
* The options are stored in the database.
*
* @param string $name Option name
* @param string $default Option default value
* @return string Option value
*/
function get_option( $name, $default = '' ) {
return Options::instance()->get( $name, $default );
}
/**
* Set the value of an option
*
* The options are stored in the database.
*
* @param string $name Option name
* @param string $value Option value
* @param boolean $autoload Set to false if this option is not used on the majority of the requests
*/
function set_option( $name, $value, $autoload = true ) {
return Options::instance()->set( $name, $value, $autoload );
}
/**
* Remove an option
*
* The options are stored in the database.
*
* @param string $name Option name
*/
function remove_option( $name ) {
return Options::instance()->remove( $name );
}
/**
* Get the current logged user, or just a property
*
* @param string $property Property name or NULL to retrieve the whole object
* @return object Value of $property, or entire user (Sessionuser) object if $property is NULL
*/
function get_user( $property = null ) {
$user = Session::instance()->getUser();
if( $property === null ) {
return $user;
}
return $user ? $user->get( $property ) : null;
}
/**
* Try to login using POST 'user_uid' and 'user_password' fields
*
* Note that this will not involve sessions.
*
* @param int $status Login status code
* @param string $uid User uid
* @param string $pwd Password
* @return boolean Login successful or not
*/
function login(& $status = null, $uid = null, $pwd = null) {
return Session::instance()->login($status, $uid, $pwd);
}
/**
* Destroy user cookies
*/
function logout() {
return Session::instance()->destroy();
}
/**
* To be used inside a form with POST method to contrast CSRF attacks
*
* @param string $action Your action name e.g. 'save-user'
*/
function form_action( $action ) {
Session::instance()->formActionWithCSRF( $action );
}
/**
* Check if a POST action is the specified one
*
* @param string $action Your action name e.g. 'save-user'
* @return boolean
*/
function is_action( $action ) {
return Session::instance()->validateActionAndCSRF( $action );
}
/**
* Register a language
*
* @param string $code Language code e.g. 'en_US'
* @param array $aliases Language aliases e.g. [ 'en_GB' ]
* @param string $iso Language iso code e.g. 'en'
* @param string $human Human language name e.g. 'English'
*/
function register_language( $code, $aliases = [], $encode = null, $iso = null, $human = null ) {
return RegisterLanguage::instance()->registerLanguage( $code, $aliases, $encode, $iso, $human );
}
/**
* Register the default language
*
* @param string $lang Language code, language alias, etc. e.g. 'en'
*/
function register_default_language( $lang ) {
return RegisterLanguage::instance()->setDefaultLanguage( $lang );
}
/**
* Find a language
*
* @param string $lang Language code, language alias, etc. e.g. 'en'
*/
function find_language( $lang ) {
return RegisterLanguage::instance()->getLanguage( $lang );
}
/**
* Apply a language to the next translations
*
* @param string $lang Language code, language alias, etc e.g. 'en'
* @return object Language object
*/
function apply_language( $lang = null ) {
return RegisterLanguage::instance()->applyLanguage( $lang );
}
/**
* Retrieve the latest language applied
*
* @return object
*/
function latest_language() {
return RegisterLanguage::instance()->getLatestLanguageApplied();
}
/**
* Get a list of all the registered languages
*
* @return array
*/
function all_languages() {
return RegisterLanguage::instance()->getAll();
}
/**
* Get the number of queries run
*
* @return int
*/
function get_num_queries() {
if( DB::instanced() ) {
return DB::instance()->queries;
}
return 0;
}
/**
* Check if the user is authenticated
*
* @return boolean
*/
function is_logged() {
return Session::instance()->isLogged();
}
/**
* Check if the user has a permission
*
* @param string $permission Permission code
* @param object $user An user object, different from the current one
* @return bool
*/
function has_permission( $permission, $user = null ) {
return Permissions::instance()->userHasPermission( $permission, $user );
}
/**
* 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 Base URL with/without any slash at start
* @param string $dir Directory without any slash
* @return string URL / Pathname
*/
function append_dir( $base, $dir = '/' ) {
$base = rtrim( $base, '/' );
$dir = ltrim( $dir, '/' );
return $base . _ . $dir;
}
/**
* Normalize a partial URI to a complete one, or an absolute one
*
* Few examples:
* * If the URI is an anchor, keep it as-is
* * If the URI starts with a protocol, keep it as-is
* * If the URI starts with a slash, keep it as-is or, if $full_url, append protocol and domain
* * If the URI it's a word like 'page.html', prepend ROOT or, if $full_url, append also protocol and domain
*
* @param $page string Whatever, a full URL, a relative pathname e.g. 'page.html', an absolute one, etc.
* @param $full_url boolean Set to true if you want an URI with it's protocol and domain, and not just the pathname
*/
function site_page( $page, $full_url = false ) {
$first = @$page[ 0 ];
if( $first === '#' ) {
return $page; // an anchor e.g. '#contacts'
}
if( $first === '/' ) {
if( @$page[ 1 ] === '/' ) {
return $page; // URI with relative protocol e.g. '//example.org'
}
return append_dir( $full_url ? BASE_URL : '', $page );
} elseif( preg_match( '#^[a-z]+://#', $page ) === 1 ) {
return $page; // URI with full protocol e.g. 'ftp://example.org'
}
// URI not starting with a slash e.g. 'contact.html'
return append_dir( $full_url ? URL : ROOT, $page );
}
/**
* 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 );
}
return $n == 1 ? $text_one : $text_no;
}
/**
* Do an HTTP redirects and die
*
* @param string $url URL (can be relative)
* @param string $response_code HTTP response code (PHP's default it's 302)
*/
function http_redirect( $url, $response_code = 0 ) {
$url = site_page( $url, true );
header( "Location: $url", true, $response_code );
exit;
}
/**
* Get a search-engine friendly version of any string
*
* @param string $s Input string
* @param int $max_length Maximum string length (or zero for no limit)
* @param string $glue Word separator
* @param boolean $truncated Flag to know if the string was truncated
* @return string
*/
function generate_slug( $s, $max_length = 0, $glue = '-', & $truncated = false ) {
return OutputUtilities::slug( $s, $max_length, $glue, $truncated );
}
/**
* Build an HTTP GET URL from an associative array of arguments
*
* Note that NULL arguments will be automatically stripped out.
*
* @param string $url Input URL e.g. 'https://example.com/page.html'
* @param array $data Associative array of parameters e.g. [ 'p' => '1' ]
* @return string URL with GET data e.g. 'https://example.com/page.html?p=1'
*/
function http_build_get_query( $url, $data ) {
$data = http_build_query( $data );
return $data ? "$url?$data" : $url;
}
/**
* HTTP 503 header
*
* Spawn a 503 HTTP status code
*/
function http_503() {
OutputUtilities::header503();
}
/**
* Scare the user with an error message and die
*
* @param string $msg
*/
function error_die( $msg ) {
OutputUtilities::WSOD( $msg );
}
/**
* Log an error message and eventually print it when DEBUG
*
* @param string $msg
* @return void
*/
function error( $msg ) {
OutputUtilities::error( $msg );
}
/**
* Translate a string
*
* You should understand the amazing GNU Gettext workflow.
*
* @param string $msgid String to be translated
* @param string $domain Translation domain
* @return string Translated string (or original one)
*/
function __( $msgid, $domain = '' ) {
// is native GNU GETTEXT implementation?
static $native = null;
if( null === $native ) {
$native = RegisterLanguage::instance()->isNative();
}
// low-level GNU Gettext call
if( $native ) {
return _( $msgid );
}
// high-level GNU Gettext (simpler but slower)
return MoLoader::instance()->getTranslator( $domain )->gettext( $msgid );
}
/**
* Shortcut for echoing a translated string
*
* @param string $msgid String to be translated
* @param string $domain Translation domain
* @return string Translated string (or original one)
*/
function _e( $msgid, $domain = '' ) {
echo __( $msgid, $domain );
}
/**
* Declare a JSON document
*
* @param string $charset Document charset, if different from the default one
*/
function http_json_header( $charset = null ) {
if( !$charset ) {
$charset = CHARSET;
}
header( "Content-Type: application/json; charset=$charset" );
}
/**
* Send a JSON (stripping out unuseful values) and die
*
* For performance related to data transfer, falsy elements are stripped out.
*
* @param $data mixed
*/
function json( $data, $flags = 0 ) {
http_json_header();
$data = OutputUtilities::compressData( $data );
echo json_encode( $data, $flags );
exit;
}
/**
* Send a JSON error and die
*
* Note that in the real world it does not exist a JSON error,
* this method is just a way to standardize it a bit.
*
* @param int $http_code HTTP response status code e.g. '403'
* @param string $code Human error code e.g. 'unauthorized'
* @param string $msg Human error message e.g. 'You are not authorized to....'
* @param int $flags Flags passed to json_encode()
*/
function json_error( $http_code, $code, $msg = null, $flags = 0 ) {
http_response_code( $http_code );
json( [ 'error' => [
'code' => $code,
'message' => $msg,
] ], $flags );
}
/**
* Get the MIME type of a file
*
* @param string $filepath Filesystem file path
* @see MimeTypes::fileMimetype()
*/
function get_mimetype( $filepath, $pure = false ) {
return MimeTypes::fileMimetype( $filepath, $pure = false );
}
/**
* Check if a file belongs to a certain category
*
* @param string $filepath Filesystem file path
* @param string $category File category e.g. 'image'
* @see MimeTypes::isMimetypeInCategory()
*/
function is_file_in_category( $filepath, $category ) {
$mime = get_mimetype( $filepath );
return MimeTypes::instance()->isMimetypeInCategory( $mime , $category );
}
/**
* Get a file extension
*
* @param string $filename Filesystem file path
*/
function get_file_extension_from_expectations( $filename, $category ) {
return MimeTypes::instance()->getFileExtensionFromExpectations( $filename, $category );
}
/**
* Check if a file is an image
*
* @param string $filepath
* @return boolean
*/
function is_image( $path ) {
return is_file_in_category( $path, 'image' );
}
/**
* Check if a file is an audio
*
* @param string $path
* @return boolean
*/
function is_audio( $path ) {
return is_file_in_category( $path, 'audio' );
}
/**
* Check if a file is a video
*
* @param string $path
* @return boolean
*/
function is_video( $path ) {
return is_file_in_category( $path, 'video' );
}
/**
* Check if a file is a document
*
* @param string $path
*/
function is_document( $path ) {
return is_file_in_category( $path, 'document' );
}
/**
* Validate a closure
*
* @param mixed $t
* @return boolean
*/
function is_closure( $t ) {
return is_object( $t ) && $t instanceof Closure;
}
/**
* Get the human filesize from bytes
*
* @param $filesize int bytes
* @param $glue string
* @return string
*/
function human_filesize( $filesize, $glue = ' ' ) {
return OutputUtilities::humanFilesize( $filesize, $glue );
}
/*
* Create a directory
*
* @param $path string
* @param $chmod string
*/
function create_path( $path, $chmod = null ) {
return FileUploader::createPath( $path, $chmod );
}
/**
* @see FileUploader::searchFreeFilename()
*/
function search_free_filename( $filepath, $filename, $ext, $args, $build_filename = null ) {
return FileUploader::searchFreeFilename( $filepath, $filename, $ext, $args, $build_filename );
}
/**
* I use this to clean user input before DB#insert()
*
* This does not mean that it sanitizes the string.
*
* @param string $s Input string
* @param int $max Max length
* @return string
*/
function luser_input( $s, $max ) {
return mb_strimwidth( trim( $s ), 0, $max, '' );
}
/**
* Get the number of milliseconds of this request age
*
* @param int $precision number of decimal digits to round to
* @return Execution time
*/
function get_page_load( $decimals = 6 ) {
return round( microtime( true ) - $_SERVER[ 'REQUEST_TIME_FLOAT' ], $decimals );
}
// shortcuts to build SELECT * query
define('DOT', '.');
define('STAR', '*');
/*
* Deprecated zone
*
* @TODO remove the shit below this line
*/
/**
* 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 $s length is over $max_length, $blabla it's appended after $s
* @deprecated Use mb_strimwidth
*/
function str_truncate($s, $max_length, $blabla = '', $encoding = null ) {
error( "deprecated str_truncate() use mb_strimwidth() instead" );
if( ! $encoding ) {
$encoding = mb_internal_encoding();
}
return mb_strimwidth($s, 0, $max_length, $blabla, $encoding);
}
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() );
};
function get_menu_entry( $uid ) {
error( "deprecated get_menu_entry() use menu_entry() instead" );
return menu_entry( $uid );
}
function _esc_html( $s ) {
error( 'deprecated _esc_html' );
echo htmlentities( $s );
}
function _checked( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) {
error( 'deprecated _checked() use echo checked()' );
echo checked( $helper, $current, $force );
}
function _selected( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) {
error( 'deprecated _selected() use echo selected()' );
echo selected( $helper, $current, $force );
}
function _disabled( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) {
error( 'deprecated _disabled() use echo disabled()' );
echo disabled( $helper, $current, $force );
}
function _required( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) {
error( 'deprecated _required() print it instead' );
echo html_attribute_when_matching( 'required', 'required', $helper, $current, $force );
}
function _value( $v ) {
error( 'deprecated _value() use echo value() insted' );
echo value( $v );
}

File Metadata

Mime Type
text/x-diff
Expires
Thu, Nov 19, 03:27 (21 h, 5 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2264472
Default Alt Text
(69 KB)

Event Timeline