diff --git a/DEVELOPING.md b/DEVELOPING.md deleted file mode 100644 index f177efa..0000000 --- a/DEVELOPING.md +++ /dev/null @@ -1,208 +0,0 @@ -# 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. - -In the next examples the `require 'load.php'` part is implicit. - -## JSON - -An example of a JSON API page could be this: - -```php -// do some pre-conditions -if( !isset( $_GET['ping'] ) ) { - - // die with an HTTP status code 400 (Bad Request) and show a message - json_error( 400, 'missing-ping', "Please specify the 'ping' GET argument" ); -} - -json( [ - 'success' => true, - 'pong' => $_GET['ping'], -] ); -``` - -Note that to optimize the data transfer, `false` and `null` values and empty objects will be automagically removed from the JSON. - -## Query - -Note that the database connection is established automagically only if you need it. Now some examples. - -### 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" ); - -// as example, let's expose them in JSON -json( $posts ); -``` - -Note that `query_results()` is better over `query_generator()` if: -* You need the full list (e.g. to count them, 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 ) - ->whereSomethingIn( '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', [ - // quick sanitize an integer - 'post_ID' => 2, - - // quick sanitize a string - 'post_title' => 'Title unsafe', - - // assign a MySQL function to a column - 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; - } -} - - -// now you have a query builder -$post = Post::factory() - ->whereInt( 'post_ID', 1 ) - ->queryRow(); - -// do stuff -if( $post ) { - - // this method exists - $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 - - -
- - -
-``` diff --git a/README.md b/README.md index 5420fee..dcc9bd2 100644 --- a/README.md +++ b/README.md @@ -1,134 +1,10 @@ # 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. +Follow this documentation: -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. - -## Website configuration - -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' -] ); - -// 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'), -] ); -``` - -## Hacking - -See [DEVELOPING.md](./DEVELOPING.md). +https://gitpull.it/w/suckless-php/ ## 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-Session.php b/class-Session.php index f64bc27..7ce408b 100644 --- a/class-Session.php +++ b/class-Session.php @@ -1,315 +1,311 @@ . // 60s * 60m * 24h * 7d define_default( 'SESSION_DURATION', 604800 ); // the default user logged-in class define_default( 'SESSIONUSER_CLASS', 'Sessionuser' ); // the default algorithm for the User fingerprint define_default( 'SESSION_FINGERPRINT_ALGO', 'sha256' ); /** * Session handler * * Note that actually we do NOT need server sessions <3 */ class Session { /** * User currently logged * * @var Sessionuser */ private $user = null; /** * Are the cookies tobe validated? * * @var bool */ private $mustValidate = true; /** * Last CSRF generated * * @var string */ private $csrf; /** * Constructor */ public function __construct() { // remember the existing CSRF if available if( isset( $_COOKIE['csrf'] ) ) { $this->csrf = $_COOKIE['csrf']; } } /** * Get the singleton instance * * @return self */ public static function instance() { static $me = false; if( ! $me ) { $me = new self(); } return $me; } /** * Is the user logged? * * @return boolean */ public function isLogged() { return is_object( $this->getUser() ); } /** * Get the currently logged-in user * * @return Sessionuser */ public function getUser() { if( $this->mustValidate ) { $this->validate(); } return $this->user; } /* * Login statuses */ const OK = 0; const LOGIN_FAILED = 1; const ALREADY_LOGGED = 2; const EMPTY_USER_UID = 4; const EMPTY_USER_PASSWORD = 8; const USER_DISABLED = 64; /** * Do a login * * @param int $status int Login status * @param string $uid User UID (if not specified is the 'user_uid' POST field * @param string $pwd User password (if not specified is the 'user_password' POST field * @return bool */ public function login( & $status = null, $uid = null, $pwd = null ) { // already logged if( $this->isLogged() ) { $status = self::ALREADY_LOGGED; return true; } // UID from function or POST if( $uid === null && isset( $_POST['user_uid'] ) ) { $uid = $_POST['user_uid']; } // password from parameter or POST if( $pwd === null && isset( $_POST['user_password'] ) ) { $pwd = $_POST['user_password']; } // no uid no party if( empty( $uid ) ) { $status = self::EMPTY_USER_UID; return false; } // no password no party if( empty( $pwd ) ) { $status = self::EMPTY_USER_PASSWORD; return false; } // check if the user exists (note that the user class can be customized) $userClass = SESSIONUSER_CLASS; $user = $userClass::factoryFromLogin( $uid, $pwd ) ->queryRow(); // check if user exists if( ! $user ) { $status = self::LOGIN_FAILED; self::failed( $userClass::sanitizeUID( $uid ), 'POST' ); return false; } // check if user is active if( ! $user->isSessionuserActive() ) { $status = self::USER_DISABLED; return false; } // mark as logged $this->user = $user; // mark cookies as already validated $this->mustValidate = false; // pass login status $status = self::OK; // set cookies $this->setCookie( 'user_uid', $user->getSessionuserUID(), false ); $this->setCookie( 'token', $user->generateSessionuserCookieToken(), true ); // it's a good moment to renew the anti-CSRF token $this->renewCSRF(); return true; } /** * Set a cookie * * @param string $name Cookie name * @param string $value Cookie value * @param boolean $httponly When true do not expose via JavaScript */ private function setCookie( $name, $value, $httponly ) { $duration = time() + SESSION_DURATION; $path = ROOT . _; $force_https = PROTOCOL === 'https://'; setcookie( $name, $value, $duration, $path, '', $force_https, $httponly ); } /** * Validate the session */ private function validate() { // do not call this twice $this->mustValidate = false; // no cookies no party if( !isset( $_COOKIE['user_uid'], $_COOKIE['token'] ) ) { return; } // retrieve the user just from the username (then will check the password) $userClass = SESSIONUSER_CLASS; $user = $userClass::factoryFromUID( $_COOKIE['user_uid'] ) ->queryRow(); // missing user or inactive if( !$user || !$user->isSessionuserActive() ) { return $this->destroy(); } // check if the token is OK if( $_COOKIE['token'] !== $user->generateSessionuserCookieToken() ) { self::failed( $userClass::sanitizeUID( $_COOKIE['user_uid'] ), 'cookies' ); return $this->destroy(); } // now the user is logged $this->user = $user; } /** * Destroy the session */ public function destroy() { $invalidate = time() - 8000; $path = ROOT . _; - // try to destroy the cookies + // try to destroy the cookies (leave the csrf that is useful anyway) if( !headers_sent() ) { setcookie( 'user_uid', 'asd', $invalidate, $path ); setcookie( 'token', 'asd', $invalidate, $path ); - setcookie( 'csrf', 'asd', $invalidate, $path ); } // logout $this->user = null; $this->mustValidate = false; - - // unset accordingly to the cookie - $this->csrf = null; } /** * Get the CSRF token (or send a new one) * * @return string */ public function getCSRF() { if( empty( $this->csrf ) ) { $this->renewCSRF(); } return $this->csrf; } /** * Print a form action field with the anti-CSRF token * * @param string $action Form action (e.g. 'save-user') */ public function formActionWithCSRF( $action ) { echo HTML::input( 'hidden', 'csrf', $this->getCSRF() ); echo HTML::input( 'hidden', 'action', $action ); } /** * Check if a form action is valid (with the related anti-CSRF token) * * @param string $action * @return boolean */ public function validateActionAndCSRF( $action ) { $csrf = $this->getCSRF(); return isset( $_POST['action'], $_POST['csrf'] ) && $_POST['action'] === $action && $_POST['csrf'] === $csrf; } /** * Generate a new anti-CSRF token * * This will also send a new COOKIE. * * @param int $bytes How much random bytes for the anti-CSRF token * @return string */ public function renewCSRF( $bytes = 8 ) { $this->csrf = bin2hex( openssl_random_pseudo_bytes( $bytes ) ); $this->setCookie( 'csrf', $this->csrf, true ); return $this->csrf; } /** * Log in syslog a login fail * * @param $uid string * @param $from string */ public static function failed( $uid, $from ) { error_log( sprintf( "Login failed by '%s' using %s", $uid, $from ) ); } }