diff --git a/DEVELOPING.md b/DEVELOPING.md
index 4c69356..a8410bf 100644
--- a/DEVELOPING.md
+++ b/DEVELOPING.md
@@ -1,185 +1,185 @@
# Boz PHP - Another PHP Framework
## Project structure
* `load.php` - Should be unversioned (database credentials, `ROOT`, `ABSPATH` constants, etc.)
* `load-post.php` - Can be versioned (roles, permissions, JavaScript and CSS files, etc.)
## Sample page
Here an example of `index.php`:
```php
```
Long story short: just put a `require 'load.php'` in top of your template to access the framework.
## Query
Note that as default no database
### Query (declarative)
```php
query( "ALTER TABLE ADD COLUMN `hello` ..." );
```
### Select rows (full list)
```php
// results as a pure array
$posts = query_results( "SELECT post_title FROM wp_post" );
if( $posts ) {
json( $posts );
}
```
Note that `query_results()` is better over `query_generator()` if:
* You need the full list (e.g. to count, to convert as JSON, etc.)
* You want to read the list multiple times
### Select rows (generator)
```php
// generator of results
$posts = query_generator( "SELECT post_title FROM wp_post" );
if( $posts->valid() ) {
foreach( $posts as $post ) {
echo $post->post_title;
}
}
```
Note that `query_generator()` is better over `query_results()` if:
* You do not need the full list (but just one at time)
* You do not need to read the list multiple times.
### Query builder (object-oriented)
```php
// get a pure array
$posts = ( new Query() )
->from( 'post' )
->queryResults();
```
```php
// generator of results
$posts = ( new Query() )
->from( 'post' )
->queryGenerator();
```
```php
$posts = ( new Query() )
->from( 'post' )
->whereStr( 'post_title', $title )
->whereInt( 'post_author_id', $author )
->quereSomethingIn( 'post_status', [ 'private', 'stub', 'deleted' ] )
// implicit join + condition
->from( 'comment' )
->where( 'comment.user_ID = user.user_ID' )
// explicit JOIN ON
->joinOn( 'LEFT', 'user', 'user.user_ID', 'post.post_author_id' )
->queryResults();
```
## Insert
Declarative way:
```php
insert_row( 'post', [
new DBCol( 'post_ID', $id, 'd' ),
new DBCol( 'post_title', $title, 's' ),
new DBCol( 'post_creation_date', 'NOW()', '-' ),
] );
```
Object-oriented way:
```php
( new Query() )
->from( 'post' )
->insertRow( [
new DBCol( 'post_ID', $id, 'd' ),
new DBCol( 'post_title', $title, 's' ),
new DBCol( 'post_creation_date', 'NOW()', '-' ),
] );
```
## Delete
```php
( new Query() )
->from( 'post' )
->whereStr( 'post_author', 'jhon' )
->whereInt( 'post_stub, 1 )
->delete();
```
## Database row → object (mapping)
```php
/**
* Declaration of my custom class
*/
class Post extends Queried {
/**
* Table name without table prefix
*/
const T = 'post';
/**
* An example method
*
* @return string
*/
public function getTitle() {
return $this->post_title;
}
}
// retrieve a Post object or null
-$post = Post::factory()
+$post = ( new Post() )
->whereInt( 'post_ID', 1 )
->queryRow();
if( $post ) {
// do stuff
$title = $post->getTitle();
}
```
## CSRF protection
To both identify a form and secure it against [Cross-site request forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery) you can use `form_action()` and `is_action()`:
```php
-```
\ No newline at end of file
+```
diff --git a/README.md b/README.md
index 4f85cba..89bf034 100644
--- a/README.md
+++ b/README.md
@@ -1,135 +1,133 @@
# SucklessPHP - Another PHP framework that sucks less
This framework is my laser cannon that I used to develope dozen of very-different Content Management Systems made from scratch.
Note that I very often deprecate and kill stuff depending on how I feel in the morning.
## Benefits
I can create a RDBMS CMS with these features:
* stateless
* efficient (very tiny footprint)
* [CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery)-safe
* on demand resource loader (e.g. DB connection is instantiated only if you use it, etc.)
* query builder
* associative options
* database table prefix
* login and user capabilities (WITHOUT the need of PHP sessions)
* secure file uploads with MIME type checks etc.
* multilanguage (using the widely used GNU Gettext native or high-level)
## Requirements
Obviously a webserver with PHP and MySQL or MariaDB working. Personally I have a simple GLAMP machine (GNU/Linux + Apache + PHP + MySQL or MariaDB). Extra packages suggested:
* `libmagic-dev`
The `libmagic-dev` package is in the main Debian GNU/Linux repository and so I think it is in all other GNU/Linux distributions. It is needed only if you need to upload files.
## Simplest shared installation
As a shared library: one can serve many sites with a simple `require`. Start cloning the source-code in a shared folder as `/usr/share`:
sudo git clone https://github.com/valerio-bozzolan/suckless-php.git /usr/share/php/suckless-php
That's it! Leave that folder as is, you don't have to touch it anymore.
## Use it
Go to your website folder (e.g. `/var/www/blog`), and create your friendly config file. I use to call it `load.php` and please do so. Write in something as:
```php
time;
echo "If you see the datetime, the database works!";
```
## Database installation
You can add support for user *autentication* / user *permissions* and *associative options* importing the database schema into your database. To do it you should have received a file called `example-schema.sql` in the `examples` framework folder. Import it into your database. Actually there are only two tables.
## Stuff in `load.php`
Have to specify these:
* `$username` (`string`) The database username.
* `$password` (`string`) The password of the database username.
* `$database` (`string`) The database name.
* `$location` (`string`) The database location.
* `$prefix` (`string`) The database table prefix.
* `ABSPATH` (`string`) The absolute pathname of your site (`__DIR__` is your friend). No trailing slash.
* `ROOT` (`string`) The absolute request pathname (something as `/blog` or simply an empty string). No trailing slash.
Definibles (as (`type`) `default`):
* `DEBUG` (`bool`) `false`: Enable verbose debugging.
* `DEBUG_QUERIES` (`bool`) `false`: The queries are logged, and also printed when also `DEBUG`.
* `PROTOCOL` (`string`): Default is the protocol of the request (`http://` / `https://`). It builds the `URL` constant.
* `DOMAIN` (`string`): Default is your domain name. You can override it. It builds the `URL` constant.
* `URL` (`string`): Default is `PROTOCOL . DOMAIN . ROOT`.
* `REQUIRE_LOAD_POST` (`string|false`) `string`: As default it's `ABSPATH . '/load-post.php` and it's a file that describes your CMS.
-## What you have then
-Well. I hope to auto-document it with inline comments. For now you can just see `functions.php` in the framework folder.
+## Website configuration
-## Own functions / stuff
It's normal to have your own custom configuration of this framework. So the `load-post.php` file is made for you. Create it and write in it what you want:
+
```php
'pdf',
'application/x-pdf' => 'pdf',
'application/x-bzpdf' => 'pdf',
'application/x-gzpdf' => 'pdf'
] );
-// Custom menu tree declaration
+// my menu tree
add_menu_entries( [
+ // UID URL NAME PARENT
new MenuEntry( 'index', 'home.php', __("Home") ),
new MenuEntry( 'services', 'services.php', __("Our services") ),
new MenuEntry( 'contact', 'meet.php', __("Meet us"), 'services'),
new MenuEntry( 'fsf', 'https://fsf.org/', __("Meet us in Colorado"), 'contact'),
] );
-
-// Use of custom associative options
-// $visits = get_option('visits', 0);
-// set_option('visits', ++$visits);
```
## Hacking
See [DEVELOPING.md](./DEVELOPING.md).
## License
Copyright (c) 2015-2019 [Valerio Bozzolan](http://boz.reyboz.it/)
This is a **Free** as in **Freedom** project. It comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under the terms of the **GNU General Public License v3+**.
diff --git a/class-Query.php b/class-Query.php
index a6ccd48..d2b3375 100644
--- a/class-Query.php
+++ b/class-Query.php
@@ -1,613 +1,612 @@
.
/**
* 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;
}
/**
* 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. 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.
*
* @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;
}
/**
* 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" );
}
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
*
- * @TODO: rename to getClassName()
- * @param $class_name string
+ * @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" );
}
error_die( "for security reasons you cannot build this kind of query without a condition" );
}
return $this->db->query( $query );
}
}
diff --git a/functions.php b/functions.php
index 5a1cb5f..7798bbe 100644
--- a/functions.php
+++ b/functions.php
@@ -1,1143 +1,1143 @@
.
/**
* 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 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