r20160202

This commit is contained in:
flash 2016-02-02 22:04:15 +01:00
parent 2c0bb382d2
commit ff025f978c
41 changed files with 2459 additions and 544 deletions

View file

@ -2,12 +2,21 @@
namespace Sakura;
/**
* Class ActionCode
* Used to generate one-time keys for user automatic user actions e.g. account activation.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class ActionCode
{
// Generating an action code
/**
* Generate an Action Code.
*
* @param string $action The identifier of the action.
* @param int $user The user this action code is intended for (leave 0 for universal).
*
* @return string The action code given to the user.
*/
public static function generate($action, $user = 0)
{
// Generate a code
@ -24,7 +33,16 @@ class ActionCode
return $code;
}
// Checking if a code is still valid
/**
* Validate an action code.
*
* @param string $action The action identifier.
* @param string $code The action code.
* @param int $user The id of the user validating this code.
* @param bool $invalidate Set if the code should be invalidated once validated.
*
* @return bool Boolean indicating success.
*/
public static function validate($action, $code, $user = 0, $invalidate = true)
{
// Fetch the code from the db
@ -43,7 +61,11 @@ class ActionCode
return $get[0] > 0;
}
// Make a code invalid
/**
* Make a code invalid.
*
* @param string $code The code that is being invalidated.
*/
public static function invalidate($code)
{
Database::delete('actioncodes', [

View file

@ -1,8 +1,4 @@
<?php
/*
* BBcode Wrapper
*/
namespace Sakura;
use JBBCode\Parser;
@ -10,15 +6,23 @@ use JBBCode\DefaultCodeDefinitionSet;
use JBBCode\CodeDefinitionBuilder;
/**
* Class BBcode
* Sakura wrapper for JBBCode.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class BBcode
{
// Parser container
/**
* The container for JBBCode.
*
* @var Parser
*/
private static $bbcode = null;
// Constructor
/**
* Initialiser.
*/
public static function init()
{
// Create new parser class
@ -28,7 +32,9 @@ class BBcode
self::loadStandardCodes();
}
// Add basic bbcodes
/**
* Adds the standard BBcode.
*/
public static function loadStandardCodes()
{
// Add the standard definitions
@ -82,7 +88,11 @@ class BBcode
}
}
// Set text
/**
* Set the text to parse.
*
* @param string $text The text that should be parsed.
*/
public static function text($text)
{
// Check if $bbcode is still null
@ -93,7 +103,13 @@ class BBcode
self::$bbcode->parse($text);
}
// Get as HTML
/**
* Convert the parsed text to HTML.
*
* @param string $text The text that should be parsed.
*
* @return string The parsed HTML.
*/
public static function toHTML($text = null)
{
// Check if text isn't null
@ -109,7 +125,13 @@ class BBcode
return $parsed;
}
// Get as BBmarkup
/**
* Convert the parsed text to BBCode.
*
* @param string $text The text that should be parsed.
*
* @return string The converted bbcode.
*/
public static function toEditor($text = null)
{
// Check if text isn't null
@ -120,7 +142,13 @@ class BBcode
return self::$bbcode->getAsBBCode();
}
// Get as plaintext
/**
* Convert the parsed text to plain.
*
* @param string $text The text that should be parsed.
*
* @return string The converted plaintext.
*/
public static function toPlain($text = null)
{
// Check if text isn't null

View file

@ -1,16 +1,21 @@
<?php
/*
* Text align bbcode
*/
namespace Sakura\BBcodeDefinitions;
use JBBCode\Parser;
use JBBCode\CodeDefinition;
use JBBCode\ElementNode;
/**
* Text alignment bbcode for JBBCode
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Align extends CodeDefinition
{
/**
* Constructor.
*/
public function __construct()
{
parent::__construct();
@ -18,6 +23,13 @@ class Align extends CodeDefinition
$this->setUseOption(true);
}
/**
* Creates compiled HTML from the align bbcode.
*
* @param ElementNode $el The JBBCode element node.
*
* @return string Compiled HTML.
*/
public function asHtml(ElementNode $el)
{
$alignments = [

View file

@ -1,22 +1,34 @@
<?php
/*
* Code bbcode
*/
namespace Sakura\BBcodeDefinitions;
use JBBCode\Parser;
use JBBCode\CodeDefinition;
use JBBCode\ElementNode;
/**
* Code bbcode for JBBCode
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Code extends CodeDefinition
{
/**
* Constructor.
*/
public function __construct()
{
parent::__construct();
$this->setTagName("code");
}
/**
* Compiles the code bbcode to HTML.
*
* @param ElementNode $el The JBBCode element node.
*
* @return mixed The compiled HTML.
*/
public function asHtml(ElementNode $el)
{
return preg_replace("#\n*\[code\]\n*(.*?)\n*\[/code\]\n*#s", '<pre class="code"><code>\\1</code></pre>', $el->getAsBBCode());

View file

@ -1,9 +1,4 @@
<?php
/*
* List BBcode
* https://gist.github.com/jbowens/5646994
*/
namespace Sakura\BBcodeDefinitions;
use JBBCode\Parser;
@ -19,9 +14,14 @@ use JBBCode\ElementNode;
* [*] third item
* [/list]
*
* @package Sakura
* @author Jackson Owens <jackson_owens@alumni.brown.edu>
*/
class Lists extends CodeDefinition
{
/**
* Constructor
*/
public function __construct()
{
$this->parseContent = true;
@ -30,6 +30,13 @@ class Lists extends CodeDefinition
$this->nestLimit = -1;
}
/**
* Compiles the list bbcode to HTML.
*
* @param ElementNode $el The JBBCode element node.
*
* @return string The compiled HTML list.
*/
public function asHtml(ElementNode $el)
{
$bodyHtml = '';

View file

@ -1,16 +1,21 @@
<?php
/*
* Font size BBcode
*/
namespace Sakura\BBcodeDefinitions;
use JBBCode\Parser;
use JBBCode\CodeDefinition;
use JBBCode\ElementNode;
/**
* Size BBcode for JBBCode.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Size extends CodeDefinition
{
/**
* Constructor.
*/
public function __construct()
{
parent::__construct();
@ -18,6 +23,13 @@ class Size extends CodeDefinition
$this->setUseOption(true);
}
/**
* Compiles the size bbcode to HTML
*
* @param ElementNode $el The JBBCode element node.
*
* @return string The compiled HTML.
*/
public function asHtml(ElementNode $el)
{
$minSize = 0;

View file

@ -1,23 +1,34 @@
<?php
/*
* YouTube BBcode
* As displayed on this page http://jbbcode.com/docs
*/
namespace Sakura\BBcodeDefinitions;
use JBBCode\Parser;
use JBBCode\CodeDefinition;
use JBBCode\ElementNode;
/**
* YouTube video embedding bbcode for JBBCode
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class YouTube extends CodeDefinition
{
/**
* Constructor.
*/
public function __construct()
{
parent::__construct();
$this->setTagName("youtube");
}
/**
* Compiles the YouTube bbcode to HTML
*
* @param ElementNode $el The JBBCode element node.
*
* @return string The compiled HTML.
*/
public function asHtml(ElementNode $el)
{
$content = "";

View file

@ -1,17 +1,21 @@
<?php
/*
* Ban management
*/
namespace Sakura;
/**
* Class Bans
* User banishment management.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Bans
{
// Check if a user is banned
/**
* Checks if a user is banned.
*
* @param int $uid The ID of the user that is being checked.
*
* @return array|bool Either false or an array containing information about the ban.
*/
public static function checkBan($uid)
{

View file

@ -1,23 +1,33 @@
<?php
/*
* CSRF protection
*/
namespace Sakura;
use Sakura\Hashing;
/**
* Class CSRF
* Used to generate and validate CSRF tokens.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class CSRF
{
// Constants
/**
* The prefix to prevent collisions in the $_SESSION variable.
*/
const ID_PREFIX = '_sakura_csrf_';
/**
* The size of the randomly generated string.
*/
const RANDOM_SIZE = 16;
// Create a new CSRF token
/**
* Create a new CSRF token.
*
* @param mixed $id The ID for this token.
*
* @return string The token.
*/
public static function create($id)
{
// Generate a token
@ -33,13 +43,24 @@ class CSRF
return $token;
}
// Generate a CSRF token
/**
* Generate a CSRF token.
*
* @return string Cryptographically secure random string.
*/
public static function generate()
{
return bin2hex(\mcrypt_create_iv(self::RANDOM_SIZE, MCRYPT_DEV_URANDOM));
}
// Validate a CSRF token
/**
* Validate a CSRF token.
*
* @param mixed $token The token.
* @param mixed $id The ID.
*
* @return bool Indicator if it was right or not.
*/
public static function validate($token, $id)
{
// Set id

View file

@ -1,21 +1,39 @@
<?php
/*
* A flexible comment system
*/
namespace Sakura;
/**
* Class Comments
* Handles and serves comments on pages.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Comments
{
public $comments = []; // Array containing comments
public $category; // Comment category
public $count = 0; // Amount of comments
/**
* The array containing the comments.
*
* @var array
*/
public $comments = [];
// Constructor
/**
* The comment category.
*
* @var string
*/
public $category;
/**
* The amount of comments.
* @var int
*/
public $count = 0;
/**
* Constructor.
*
* @param mixed $category The category that comments should be fetched from.
*/
public function __construct($category)
{
// Set category
@ -36,7 +54,13 @@ class Comments
$this->comments = $this->sortComments($comments);
}
// Sorting
/**
* Sort the comments.
*
* @param array $comments Array containing comments.
*
* @return array Array containing the sorted comments.
*/
public function sortComments($comments)
{
// Create storage array
@ -84,7 +108,13 @@ class Comments
return $layer;
}
// Getting a single comment
/**
* Get a single comment.
*
* @param int $cid ID of the comment.
*
* @return array The comment.
*/
public function getComment($cid)
{
// Get from database
@ -93,7 +123,13 @@ class Comments
]);
}
// Getting comment votes
/**
* Get the votes for a comment.
*
* @param int $cid ID of the comment.
*
* @return array The votes.
*/
public function getVotes($cid)
{
// Get from database
@ -102,7 +138,15 @@ class Comments
]);
}
// Creating
/**
* Creating a new comment.
*
* @param int $uid ID of the user creating the comment.
* @param int $reply ID of the comment that is being replied to.
* @param string $content Contents of the comment.
*
* @return array Response identifier.
*/
public function makeComment($uid, $reply, $content)
{
// Check if the comment is long enough
@ -128,7 +172,15 @@ class Comments
return [1, 'SUCCESS'];
}
// Voting
/**
* Making a vote.
*
* @param int $uid User making this vote.
* @param int $cid ID of the comment that is being voted on.
* @param int $mode Positive or negative vote.
*
* @return bool Always returns true.
*/
public function makeVote($uid, $cid, $mode)
{
// Attempt to get previous vote
@ -170,7 +222,13 @@ class Comments
return true;
}
// Deleting
/**
* Remove a comment
*
* @param int $cid ID of the comment to remove.
*
* @return mixed No idea what this returns but it doesn't really matter anyway, the comment is dead.
*/
public function removeComment($cid)
{
// Remove from database

View file

@ -1,21 +1,33 @@
<?php
/*
* Configuration Management
*/
namespace Sakura;
/**
* Class Config
* Handles both the local and database stored configuration sides of Sakura.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Config
{
// Configuration data
/**
* Container for the parsed local configuration.
*
* @var array
*/
private static $local = [];
/**
* Container for the configuration stored in the database.
*
* @var array
*/
private static $database = [];
// Initialise configuration, does not contain database initialisation because explained below
/**
* Initialiser, parses the local configuration.
*
* @param string $local Path to the configuration file.
*/
public static function init($local)
{
@ -40,10 +52,8 @@ class Config
}
}
/*
* Initialise Database configuration values.
* Different from init as that is called before the database connection is initially
* established.
/**
* Fetch configuration values from the database.
*/
public static function initDB()
{
@ -63,7 +73,14 @@ class Config
self::$database = $_DBCN;
}
// Get values from the configuration on the file system
/**
* Get a value from the local configuration file.
*
* @param string $key Configuration section.
* @param string $subkey Configuration key.
*
* @return string Configuration value.
*/
public static function local($key, $subkey = null)
{
@ -86,7 +103,14 @@ class Config
return null;
}
// Get values from the configuration in the database
/**
* Get a configuration value from the database.
*
* @param string $key Configuration key.
* @param bool $returnNull Unused value, only exists to prevent explosions.
*
* @return string Configuration value.
*/
public static function get($key, $returnNull = false)
{

View file

@ -1,21 +1,27 @@
<?php
/*
* CLI Main
*/
namespace Sakura\Console;
/**
* Class Console
* Command line interface main.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Application extends \CLIFramework\Application
{
// Application info
/**
* CLI Application name
*/
const NAME = 'Sakura';
/**
* CLI Application version
*/
const VERSION = SAKURA_VERSION;
// Initialiser
/**
* CLI initialiser
*/
public function init()
{
parent::init();

View file

@ -1,8 +1,4 @@
<?php
/*
* Forum controllers
*/
namespace Sakura\Controllers;
use Sakura\Config;
@ -15,12 +11,18 @@ use Sakura\Users;
use Sakura\Utils;
/**
* Class Forum
* Forum page controllers.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Forum
{
// Forum index
/**
* Serves the forum index.
*
* @return mixed HTML for the forum index.
*/
public static function index()
{
// Get the global renderData
@ -54,9 +56,4 @@ class Forum
// Return the compiled page
return $template->render('forum/index');
}
// View a forum
public static function forum($id = null)
{
}
}

View file

@ -1,8 +1,4 @@
<?php
/*
* Meta controllers
*/
namespace Sakura\Controllers;
use Sakura\Config;
@ -14,12 +10,18 @@ use Sakura\Users;
use Sakura\Utils;
/**
* Class Meta
* Meta page controllers (sections that aren't big enough to warrant a dedicated controller class).
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Meta
{
// Site index
/**
* Serves the site index.
*
* @return mixed HTML for the index.
*/
public static function index()
{
// Get the global renderData
@ -55,7 +57,11 @@ class Meta
return $template->render('main/index');
}
// News
/**
* Handles the news pages.
*
* @return mixed HTML for the correct news section.
*/
public static function news()
{
// Get the global renderData
@ -89,7 +95,11 @@ class Meta
return $template->render('main/news');
}
// FAQ
/**
* Displays the FAQ.
*
* @return mixed HTML for the FAQ.
*/
public static function faq()
{
// Get the global renderData
@ -108,10 +118,16 @@ class Meta
$template->setVariables($renderData);
// Print page contents
echo $template->render('main/faq');
return $template->render('main/faq');
}
// Info pages
/**
* Handles the info pages.
*
* @param string $id The page ID from the database.
*
* @return mixed HTML for the info page.
*/
public static function infoPage($id = null)
{
// Get the global renderData
@ -145,7 +161,11 @@ class Meta
return $template->render('main/infopage');
}
// Search
/**
* Search page
*
* @return mixed HTML for the search page.
*/
public static function search()
{
// Get the global renderData
@ -163,6 +183,6 @@ class Meta
$template->setVariables($renderData);
// Print page contents
echo $template->render('main/search');
return $template->render('main/search');
}
}

View file

@ -1,24 +0,0 @@
<?php
/*
* Database wrapper (v2)
*/
namespace Sakura;
use PDO;
use PDOException;
/**
* Class DB
* @package Sakura
*/
class DB
{
// Database container
private static $pdo;
// Initialisation function
public static function init($wrapper)
{
}
}

View file

@ -1,26 +1,29 @@
<?php
/*
* Sakura MySQL Database Engine
*/
namespace Sakura\DBWrapper;
use PDO;
use PDOException;
use PDOStatement;
use \Sakura\Config;
/**
* Class MySQL
* @package Sakura\DBWrapper
* Sakura MySQL Wrapper.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class mysql
{
// Variable that will contain the SQL connection
// Please refrain from referring to this, unless it's for your personal branch/purpose, despite it being public
// it sort of defeats the "dynamic database system" I want to go for.
public $sql;
/**
* Contains the PDO object.
*
* @var PDO
*/
protected $sql;
// Constructor
/**
* Constructor.
*/
public function __construct()
{
if (!extension_loaded('PDO')) {
@ -51,7 +54,15 @@ class mysql
);
}
// Regular IP/Hostname connection method prepare function
/**
* Generates a DSN for a regular hostname:port endpoint.
*
* @param string $dbHost Database hostname.
* @param string $dbName Database name.
* @param int $dbPort Database host port.
*
* @return string The PDO DSN.
*/
private function prepareHost($dbHost, $dbName, $dbPort = 3306)
{
$dsn = 'mysql:host=' . $dbHost . ';port=' . $dbPort . ';dbname=' . $dbName;
@ -59,7 +70,14 @@ class mysql
return $dsn;
}
// Unix Socket connection method prepare function
/**
* Generates a DSN for a unix socket endpoint.
*
* @param string $dbHost Path to the Unix Socket.
* @param string $dbName Database name.
*
* @return string The PDO DSN.
*/
private function prepareSock($dbHost, $dbName)
{
$dsn = 'mysql:unix_socket=' . $dbHost . ';dbname=' . $dbName;
@ -67,7 +85,15 @@ class mysql
return $dsn;
}
// Initialise connection using default PDO stuff
/**
* Initialise a the database connection.
*
* @param string $dsn The PDO DSN.
* @param string $dbUname The database username.
* @param string $dbPword The database password.
*
* @return bool Returns true if the connection was successful.
*/
private function initConnect($dsn, $dbUname, $dbPword)
{
try {
@ -84,6 +110,20 @@ class mysql
return true;
}
/**
* Select table row(s).
*
* @param string $table The table to select data from.
* @param array $data The WHERE selectors.
* @param array $order The order in which the data is returned.
* @param array $limit The limit of what should be returned.
* @param array $group The way MySQL will group the data.
* @param bool $distinct Only return distinct values.
* @param string $column Only select from this column.
* @param string $prefix Use a different table prefix than the one from the configuration.
*
* @return PDOStatement The PDOStatement object for this action.
*/
public function select($table, $data = null, $order = null, $limit = null, $group = null, $distinct = false, $column = '*', $prefix = null)
{
@ -184,7 +224,21 @@ class mysql
return $query;
}
// Fetch array from database
/**
* Summary of fetch
*
* @param string $table The table to select data from.
* @param bool $fetchAll Whether all result will be returned or just the first one.
* @param array $data The WHERE selectors.
* @param array $order The order in which the data is returned.
* @param array $limit The limit of what should be returned.
* @param array $group The way MySQL will group the data.
* @param bool $distinct Only return distinct values.
* @param string $column Only select from this column.
* @param string $prefix Use a different table prefix than the one from the configuration.
*
* @return array The data the database returned.
*/
public function fetch($table, $fetchAll = true, $data = null, $order = null, $limit = null, $group = null, $distinct = false, $column = '*', $prefix = null)
{
@ -195,7 +249,15 @@ class mysql
return $fetchAll ? $query->fetchAll(PDO::FETCH_ASSOC) : $query->fetch(PDO::FETCH_ASSOC);
}
// Insert data to database
/**
* Insert data into the database.
*
* @param string $table The table that the data will be inserted into.
* @param array $data The data that should be stored.
* @param string $prefix Use a different table prefix than the one from the configuration.
*
* @return bool Successfulness.
*/
public function insert($table, $data, $prefix = null)
{
@ -236,7 +298,15 @@ class mysql
return $result;
}
// Update data in the database
/**
* Update existing database rows.
*
* @param string $table The table that the updated data will be inserted into.
* @param array $data The data that should be stored.
* @param string $prefix Use a different table prefix than the one from the configuration.
*
* @return bool Successfulness.
*/
public function update($table, $data, $prefix = null)
{
@ -289,7 +359,15 @@ class mysql
return $result;
}
// Delete data from the database
/**
* Deleted data from the database.
*
* @param string $table The table that the data will be removed from.
* @param array $data The pointers to what should be deleted.
* @param string $prefix Use a different table prefix than the one from the configuration.
*
* @return bool Successfulness.
*/
public function delete($table, $data, $prefix = null)
{
@ -328,7 +406,15 @@ class mysql
return $result;
}
// Count data from the database
/**
* Return the amount of rows from a table.
*
* @param string $table Table to count in.
* @param array $data Data that should be matched.
* @param string $prefix Use a different table prefix than the one from the configuration.
*
* @return array Array containing the SQL result.
*/
public function count($table, $data = null, $prefix = null)
{
@ -372,7 +458,13 @@ class mysql
return $query->fetch(PDO::FETCH_BOTH);
}
// Get the ID of the last inserted item
/**
* Get the id of the item that was last inserted into the database.
*
* @param string $name Sequence of which the last id should be returned.
*
* @return string The last inserted id.
*/
public function lastInsertID($name = null)
{
return $this->sql->lastInsertID($name);

View file

@ -1,20 +1,26 @@
<?php
/*
* Database wrapper container
*/
namespace Sakura;
/**
* Class Database
* A wrapper to make the database communication experience smoother.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Database
{
// Database container
/**
* The container for the wrapper.
*
* @var mixed
*/
public static $database;
// Initialisation function
/**
* Initialise the database wrapper.
*
* @param string $wrapper The wrapper to wrap.
*/
public static function init($wrapper)
{
@ -30,43 +36,108 @@ class Database
self::$database = new $wrapper;
}
// Select from database
/**
* Select table row(s).
*
* @param string $table The table to select data from.
* @param array $data The WHERE selectors.
* @param array $order The order in which the data is returned.
* @param array $limit The limit of what should be returned.
* @param array $group The way MySQL will group the data.
* @param bool $distinct Only return distinct values.
* @param string $column Only select from this column.
* @param string $prefix Use a different table prefix than the one from the configuration.
*
* @return \PDOStatement The PDOStatement object for this action.
*/
public static function select($table, $data = null, $order = null, $limit = null, $group = null, $distinct = false, $column = '*', $prefix = null)
{
return self::$database->select($table, $data, $order, $limit, $group, $distinct, $column, $prefix);
}
// Fetch from database
/**
* Summary of fetch
*
* @param string $table The table to select data from.
* @param bool $fetchAll Whether all result will be returned or just the first one.
* @param array $data The WHERE selectors.
* @param array $order The order in which the data is returned.
* @param array $limit The limit of what should be returned.
* @param array $group The way MySQL will group the data.
* @param bool $distinct Only return distinct values.
* @param string $column Only select from this column.
* @param string $prefix Use a different table prefix than the one from the configuration.
*
* @return array The data the database returned.
*/
public static function fetch($table, $fetchAll = true, $data = null, $order = null, $limit = null, $group = null, $distinct = false, $column = '*', $prefix = null)
{
return self::$database->fetch($table, $fetchAll, $data, $order, $limit, $group, $distinct, $column, $prefix);
}
// Insert into database
/**
* Insert data into the database.
*
* @param string $table The table that the data will be inserted into.
* @param array $data The data that should be stored.
* @param string $prefix Use a different table prefix than the one from the configuration.
*
* @return bool Successfulness.
*/
public static function insert($table, $data, $prefix = null)
{
return self::$database->insert($table, $data, $prefix);
}
// Update in database
/**
* Update existing database rows.
*
* @param string $table The table that the updated data will be inserted into.
* @param array $data The data that should be stored.
* @param string $prefix Use a different table prefix than the one from the configuration.
*
* @return bool Successfulness.
*/
public static function update($table, $data, $prefix = null)
{
return self::$database->update($table, $data, $prefix);
}
// Delete from database
/**
* Deleted data from the database.
*
* @param string $table The table that the data will be removed from.
* @param array $data The pointers to what should be deleted.
* @param string $prefix Use a different table prefix than the one from the configuration.
*
* @return bool Successfulness.
*/
public static function delete($table, $data, $prefix = null)
{
return self::$database->delete($table, $data, $prefix);
}
// Count from database
/**
* Return the amount of rows from a table.
*
* @param string $table Table to count in.
* @param array $data Data that should be matched.
* @param string $prefix Use a different table prefix than the one from the configuration.
*
* @return array Array containing the SQL result.
*/
public static function count($table, $data = null, $prefix = null)
{
return self::$database->count($table, $data, $prefix);
}
// Get the ID of the last inserted item
/**
* Get the id of the item that was last inserted into the database.
*
* @param string $name Sequence of which the last id should be returned.
*
* @return string The last inserted id.
*/
public static function lastInsertID($name = null)
{
return self::$database->lastInsertID($name);

View file

@ -1,28 +1,74 @@
<?php
/*
* File handler
*/
namespace Sakura;
use finfo;
/**
* Class File
* Used for storing files served through Sakura.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class File
{
// Variables
/**
* ID of the file.
* @var int
*/
public $id = 0;
/**
* User instance of the user that uploaded this file.
*
* @var User
*/
public $user = null;
/**
* Data of the file.
*
* @var string
*/
public $data = null;
/**
* Original filename of the file.
*
* @var string
*/
public $name = null;
/**
* Mime type of the file.
*
* @var string
*/
public $mime = null;
/**
* The UNIX timestamp of when this file was created.
*
* @var int
*/
public $time = 0;
/**
* The UNIX timestamp of when this file should automatically remove itself (currently unused).
*
* @var int
*/
public $expire = 0;
// Create a new file
/**
* Create a new file.
*
* @param string $data Contents of the file.
* @param string $name Name of the file.
* @param User $user User instance of the user creating this file.
* @param int $expire UNIX timestamp of when this file should automatically remove itself.
*
* @return File The created file instance for the file.
*/
public static function create($data, $name, User $user, $expire = 0)
{
// Get the mimetype
@ -45,7 +91,11 @@ class File
return new File($id);
}
// Constructor
/**
* Constructor.
*
* @param int $fileId ID of the file that should be constructed.
*/
public function __construct($fileId)
{
// Attempt to get the database row
@ -63,7 +113,9 @@ class File
}
}
// Delete the file
/**
* Delete this file from the database.
*/
public function delete()
{
Database::delete('uploads', [

View file

@ -1,8 +1,4 @@
<?php
/*
* Forum class
*/
namespace Sakura\Forum;
use Sakura\Database;
@ -11,27 +7,108 @@ use Sakura\User;
use Sakura\Perms;
/**
* Class Forum
* Used to serve forums.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Forum
{
// Variables
/**
* The ID of the forum.
*
* @var int
*/
public $id = 0;
/**
* The order of the forum.
*
* @var int
*/
public $order = 0;
/**
* The name of the forum.
*
* @var string
*/
public $name = "Forum";
/**
* The description of the forum.
*
* @var string
*/
public $description = "";
/**
* The link of the forum (if the type is 2).
* @var string
*/
public $link = "";
/**
* The ID of the parent forum.
*
* @var int
*/
public $category = 0;
/**
* The type of forum.
*
* @var int
*/
public $type = 0;
/**
* The icon of this forum.
*
* @var string
*/
public $icon = "";
/**
* A cached instance of the first post in this forum.
*
* @var Post
*/
private $_firstPost = null;
/**
* A cached instance of the last post in this forum.
*
* @var Post
*/
private $_lastPost = null;
/**
* Cached instances of the subforums.
*
* @var array
*/
private $_forums = [];
/**
* Cached instances of the threads in this forum.
*
* @var array
*/
private $_threads = [];
/**
* The permission container.
*
* @var Perms
*/
private $_permissions;
// Constructor
/**
* Constructor.
*
* @param int $forumId The ID of the forum that should be constructed.
*/
public function __construct($forumId = 0)
{
// Get the row from the database
@ -55,7 +132,15 @@ class Forum
}
}
// Checking a permission
/**
* Checking a permission flag.
*
* @param int $flag Forum permission flag.
* @param int $user The ID of the user that is being checked.
* @param bool $raw Whether the raw full permission flag should be returned.
*
* @return bool|int Either a bool indicating the permission or the full flag.
*/
public function permission($flag, $user, $raw = false)
{
// Set default permission value
@ -97,7 +182,11 @@ class Forum
return $forums;
}
// Threads
/**
* Gets the threads in this forum.
*
* @return array Array containing all threads.
*/
public function threads()
{
// Check if _threads is populated
@ -127,7 +216,11 @@ class Forum
return $threads;
}
// First post
/**
* Gets the first post in this forum.
*
* @return Post The object of the first post.
*/
public function firstPost()
{
// Check if _firstPost is set
@ -148,7 +241,11 @@ class Forum
}
}
// Last post
/**
* Gets the last post in this forum.
*
* @return Post The object of the last post.
*/
public function lastPost()
{
// Check if _lastPost is set
@ -169,19 +266,33 @@ class Forum
}
}
// Thread count
/**
* Counts the amount of threads in this forum.
*
* @return int Number of threads in this forum.
*/
public function threadCount()
{
return Database::count('topics', ['forum_id' => [$this->id, '=']])[0];
}
// Post count
/**
* Counts the amount of posts in this forum.
*
* @return int Number of posts in this forum.
*/
public function postCount()
{
return Database::count('posts', ['forum_id' => [$this->id, '=']])[0];
}
// Read status
/**
* Checks if a user has read every post in the specified forum.
*
* @param int $user Id of the user in question.
*
* @return bool Indicator if read or not.
*/
public function unread($user)
{
// Return false if the user id is less than 1
@ -207,7 +318,11 @@ class Forum
return false;
}
// Mark all threads as read
/**
* Update the read status of all threads in this forum at once.
*
* @param int $user The id of the user in question.
*/
public function trackUpdateAll($user)
{
// Iterate over every forum

View file

@ -1,8 +1,4 @@
<?php
/*
* Post class
*/
namespace Sakura\Forum;
use Sakura\Utils;
@ -12,29 +8,102 @@ use Sakura\BBcode;
use Sakura\Config;
/**
* Class Post
* Used to serve, create and update posts.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Post
{
// Variables
/**
* The ID of the post.
*
* @var int
*/
public $id = 0;
public $thread = 0;
public $forum = 0;
public $poster = [];
public $ip = "";
public $time = 0;
public $parse = 0;
public $signature = 0;
public $emotes = 0;
public $subject = "";
public $text = "";
public $parsed = "";
public $editTime = 0;
public $editReason = "";
public $editUser = [];
// Constructor
/**
* The id of the thread this post is a part of.
*
* @var int
*/
public $thread = 0;
/**
* The id of the forum this post is a part of.
*
* @var int
*/
public $forum = 0;
/**
* The User object of the poster.
*
* @var User
*/
public $poster = null;
/**
* The IP address from which this post was created.
*
* @var string
*/
public $ip = "";
/**
* The UNIX timestamp from when this post was created.
*
* @var int
*/
public $time = 0;
/**
* The subject of this post.
*
* @var string
*/
public $subject = "";
/**
* The raw contents of this post.
*
* @var string
*/
public $text = "";
/**
* The parsed contents of this post.
*
* @var string
*/
public $parsed = "";
/**
* The UNIX timestamp of the last time this post was edited.
*
* @var int
*/
public $editTime = 0;
/**
* The reason why this post was edited.
*
* @var string
*/
public $editReason = "";
/**
* The User object of the user that last edited this post.
*
* @var User
*/
public $editUser = null;
/**
* Constructor.
*
* @param int $postId ID of the post that should be constructed.
*/
public function __construct($postId)
{
// Attempt to get the database row
@ -59,7 +128,17 @@ class Post
$this->parsed = BBcode::toHTML(htmlentities($this->text));
}
// Create a new post
/**
* Creating a new post.
*
* @param string $subject The subject of the thread.
* @param string $text The raw contents of the post.
* @param User $poster The User object of the poster.
* @param int $thread The ID of the thread this post is a reply to.
* @param mixed $forum The forum this post is a reply in.
*
* @return null|Post Either null, indicating a failure, or the Post object.
*/
public static function create($subject, $text, User $poster, $thread = 0, $forum = 0)
{
// Check if the data meets the requirements
@ -103,7 +182,11 @@ class Post
return new Post($id);
}
// Update a post
/**
* Commit the changes to the Database.
*
* @return null|Post Either null, indicating a failure, or the Post object.
*/
public function update()
{
// Check if the data meets the requirements
@ -140,13 +223,21 @@ class Post
return new Post($this->id);
}
// Time elapsed since creation
/**
* The "elapsed" string for this post.
*
* @return string Readable time elapsed since this post was created.
*/
public function timeElapsed()
{
return Utils::timeElapsed($this->time);
}
// Time elapsed since last edit
/**
* Time "elapsed" since the last edit.
*
* @return string Readable time elapsed since this post was last edited.
*/
public function editTimeElapsed()
{
return Utils::timeElapsed($this->editTime);

View file

@ -1,36 +1,125 @@
<?php
/*
* Thread class
*/
namespace Sakura\Forum;
use Sakura\Database;
use Sakura\Utils;
/**
* Class Thread
* Used to serve, create and update threads.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Thread
{
// Variables
/**
* The ID of this thread.
*
* @var int
*/
public $id = 0;
/**
* The ID of the forum this thread is a part of.
*
* @var int
*/
public $forum = 0;
public $hidden = 0;
/**
* Is this forum hidden from the listing?
*
* @var bool
*/
public $hidden = false;
/**
* The title of the thread.
*
* @var string
*/
public $title = "";
/**
* The UNIX timestamp of when this thread was created.
*
* @var int
*/
public $time = 0;
/**
* The UNIX timestamp of when this thread should be autolocked (currently unused).
*
* @var int
*/
public $timeLimit = 0;
/**
* The amount of times this thread has been viewed.
*
* @var int
*/
public $views = 0;
/**
* The status of this thread.
* 0 - Unlocked
* 1 - Locked
*
* @var int
*/
public $status = 0;
/**
* The UNIX timestamp of when the status was last changed.
*
* @var int
*/
public $statusChange = 0;
/**
* The thread type
* 0 - Normal thread
* 1 - Sticky thread
* 2 - Announcement
*
* @var int
*/
public $type = 0;
/**
* The ID of the forum this thread was a part of before the last move.
*
* @var int
*/
public $oldForum = 0;
/**
* The post object cache.
*
* @var array
*/
private $_posts = [];
/**
* A cached instance of opening post.
*
* @var Post
*/
private $_firstPost = null;
/**
* A cached instance of the last reply.
*
* @var Post
*/
private $_lastPost = null;
// Constructor
/**
* Constructor.
*
* @param mixed $threadId ID of the thread that should be constructed.
*/
public function __construct($threadId)
{
// Attempt to get the database row
@ -40,7 +129,7 @@ class Thread
if ($threadRow) {
$this->id = $threadRow['topic_id'];
$this->forum = $threadRow['forum_id'];
$this->hidden = $threadRow['topic_hidden'];
$this->hidden = (bool) $threadRow['topic_hidden'];
$this->title = $threadRow['topic_title'];
$this->time = $threadRow['topic_time'];
$this->timeLimit = $threadRow['topic_time_limit'];
@ -52,7 +141,16 @@ class Thread
}
}
// Create a new topic
/**
* Create a new thread.
*
* @param mixed $forum ID of the forum this thread is part of.
* @param mixed $title Title of the thread.
* @param mixed $status Status of the thread.
* @param mixed $type Type of thread.
*
* @return Thread The new thread instance.
*/
public static function create($forum, $title, $status = 0, $type = 0)
{
// Create the database entry
@ -68,7 +166,9 @@ class Thread
return new Thread(Database::lastInsertID());
}
// Delete the thread
/**
* Delete the current thread.
*/
public function delete()
{
// Delete all posts
@ -82,7 +182,12 @@ class Thread
]);
}
// Move the thread
/**
* Move the thread.
*
* @param mixed $forum The new forum ID.
* @param mixed $setOld Remember the forum ID prior to the move for restoration.
*/
public function move($forum, $setOld = true)
{
// Update all posts
@ -107,7 +212,11 @@ class Thread
]);
}
// Update the thread
/**
* Update the thread data.
*
* @return Thread The updated thread.
*/
public function update()
{
// Update row
@ -130,7 +239,11 @@ class Thread
return new Thread($this->id);
}
// Posts
/**
* Get the replies to this thread.
*
* @return array Array containing Post instances.
*/
public function posts()
{
// Check if _posts is something
@ -155,7 +268,11 @@ class Thread
return $posts;
}
// Get the opening post
/**
* Get the opening post.
*
* @return Post A Post instance of the opening post.
*/
public function firstPost()
{
// Check if the cache var is set
@ -176,7 +293,11 @@ class Thread
return $post;
}
// Get the last reply
/**
* Get the latest reply.
*
* @return Post A Post instance of the latest reply.
*/
public function lastPost()
{
// Check if the cache var is set
@ -197,25 +318,43 @@ class Thread
return $post;
}
// Reply count
/**
* Get the amount of replies.
*
* @return int The number of replies to this thread.
*/
public function replyCount()
{
return Database::count('posts', ['topic_id' => [$this->id, '=']])[0];
}
// Time elapsed since creation
/**
* The "elapsed" string for this thread since it was created.
*
* @return string Readable time elapsed since this thread was created.
*/
public function timeElapsed()
{
return Utils::timeElapsed($this->time);
}
// Time elapsed since status change
/**
* The "elapsed" string for this thread since the status was last changed.
*
* @return string Readble time elapsed since the status was last changed.
*/
public function statusChangeElapsed()
{
return Utils::timeElapsed($this->statusChange);
}
// Read status
/**
* Check if a user has read this thread before.
*
* @param mixed $user The id of the user in question.
*
* @return bool A boolean indicating the read status.
*/
public function unread($user)
{
// Attempt to get track row from the database
@ -230,7 +369,11 @@ class Thread
return false;
}
// Update read status
/**
* Update the read status.
*
* @param mixed $user The id of the user in question.
*/
public function trackUpdate($user)
{
// Check if we already have a track record
@ -258,7 +401,9 @@ class Thread
}
}
// Update views
/**
* Update the view count.
*/
public function viewsUpdate()
{
Database::update('topics', [
@ -271,7 +416,9 @@ class Thread
]);
}
// Update last post timestamp
/**
* Update the timestamp of when this thread was last replied to.
*/
public function lastUpdate()
{
Database::update('topics', [

View file

@ -1,8 +1,6 @@
<?php
/*
* Sakura PBKDF2 Password Hashing
*
* Based on Password Hashing With PBKDF2 (https://defuse.ca/php-pbkdf2.htm).
* Password Hashing With PBKDF2 (https://defuse.ca/php-pbkdf2.htm).
* Copyright (c) 2013, Taylor Hornby
* All rights reserved.
*
@ -32,18 +30,49 @@
namespace Sakura;
/**
* Class Hashing
* PBKDF2 password hashing implementation.
*
* @package Sakura
* @author Taylor Hornby <havoc@defuse.ca>
* @author Julian van de Groep <me@flash.moe>
*/
class Hashing
{
// These variables can be changed without break the existing hashes
/**
* Hashing algorithm that should be used.
*
* @var string
*/
private static $hashAlgorithm = 'sha256';
/**
* Iterations.
*
* @var int
*/
private static $iterations = 1000;
/**
* The amount of bytes the salt should be.
*
* @var int
*/
private static $saltBytes = 24;
/**
* The amount of bytes the hash should be.
*
* @var int
*/
private static $hashBytes = 24;
// Returns an array formatted like: [algorithm, iterations, salt, hash]
/**
* Creates a hash.
*
* @param string $pass The password that should be hashed.
*
* @return array An array containing the algorithm, iterations, salt and hash.
*/
public static function createHash($pass)
{
$salt = base64_encode(
@ -74,7 +103,14 @@ class Hashing
return $passwordData;
}
// Validates hashed password
/**
* Validate a password.
*
* @param string $password The password that is being validated.
* @param array $params The parametres in the order of algorithm, iterations, salt and hash.
*
* @return bool Correct?
*/
public static function validatePassword($password, $params)
{
if (count($params) < 4) {
@ -98,7 +134,14 @@ class Hashing
return $validate;
}
// Compares two strings $a and $b in length-constant time.
/**
* Compares two strings $a and $b in length-constant time.
*
* @param string $a String A.
* @param string $b String B.
*
* @return bool Boolean indicating difference.
*/
public static function slowEquals($a, $b)
{
$diff = strlen($a) ^ strlen($b);
@ -110,22 +153,21 @@ class Hashing
return $diff === 0;
}
/*
/**
* PBKDF2 key derivation function as defined by RSA's PKCS #5: https://www.ietf.org/rfc/rfc2898.txt
* $algorithm - The hash algorithm to use. Recommended: SHA256
* $password - The password.
* $salt - A salt that is unique to the password.
* $count - Iteration count. Higher is better, but slower. Recommended: At least 1000.
* $key_length - The length of the derived key in bytes.
* $raw_output - If true, the key is returned in raw binary format. Hex encoded otherwise.
* Returns: A $key_length-byte key derived from the password and salt.
*
* Test vectors can be found here: https://www.ietf.org/rfc/rfc6070.txt
*
*
* This implementation of PBKDF2 was originally created by https://defuse.ca
* With improvements by http://www.variations-of-shadow.com
*
* @param mixed $algorithm The hash algorithm to use. Recommended: SHA256.
* @param mixed $password The password.
* @param mixed $salt A salt that is unique to the password.
* @param mixed $count Iteration count. Higher is better, but slower. Recommended: At least 1000.
* @param mixed $key_length The length of the derived key in bytes.
* @param mixed $raw_output A $key_length-byte key derived from the password and salt.
*
* @return string The PBKDF2 derivation.
*/
private static function pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false)
{
$algorithm = strtolower($algorithm);

View file

@ -1,14 +0,0 @@
<?php
/*
* Management Class
*/
namespace Sakura;
/**
* Class Manage
* @package Sakura
*/
class Manage
{
}

View file

@ -1,19 +1,26 @@
<?php
/*
* The news page backend
*/
namespace Sakura;
/**
* Class News
* Used to serve news posts.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class News
{
public $posts = []; // Posts array
/**
* Array containing news posts.
*
* @var array
*/
public $posts = [];
// Initialise the news object
/**
* Constructor
*
* @param mixed $category ID of the category that should be constructed.
*/
public function __construct($category)
{
@ -33,13 +40,23 @@ class News
}
}
// Get the amount of posts
/**
* Get the amount of news posts.
*
* @return int Number of posts.
*/
public function getCount()
{
return count($this->posts);
}
// Get the amount of posts
/**
* Check if a post exists in this category.
*
* @param int $pid The ID of the post.
*
* @return int If true the post it gets returns, else 0.
*/
public function postExists($pid)
{
return array_key_exists($pid, $this->posts) ? $pid : 0;

View file

@ -1,8 +1,4 @@
<?php
/*
* Payment components (only slightly convoluted)
*/
namespace Sakura;
use \PayPal\Api\Amount;
@ -16,15 +12,26 @@ use \PayPal\Api\RedirectUrls;
use \PayPal\Api\Transaction;
/**
* Class Payments
* Sakura PayPal API wrapper.
*
* @package Sakura
* @author Kamil Rakowski <admin@krakow.pw>
* @author Julian van de Groep <me@flash.moe>
*/
class Payments
{
// Container for PayPal API
/**
* Container for the PayPal API
*
* @var \PayPal\Rest\ApiContext
*/
private static $paypal;
// Initialise PayPal API
/**
* Initialise the wrapper.
*
* @return bool Always true.
*/
public static function init()
{
@ -40,6 +47,7 @@ class Payments
return false;
}
// Set the configuration
self::$paypal->setConfig([
'mode' => Config::get('paypal_mode'),
]);
@ -47,7 +55,16 @@ class Payments
return true;
}
// Create transaction
/**
* Create a new transaction.
*
* @param float $total The total amount of money.
* @param string $itemName The name of the item being purchased.
* @param string $transDescription The description of the item.
* @param string $returnUrl The URL that PayPal will redirect back to.
*
* @return bool|null|string If successful; the PayPal approval link.
*/
public static function createTransaction($total, $itemName, $transDescription, $returnUrl)
{
@ -122,7 +139,14 @@ class Payments
return $payment->getApprovalLink();
}
// Complete the PayPal transaction
/**
* Complete the PayPal transaction.
*
* @param string $paymentId ID of the payment.
* @param string $payerId ID of the payer.
*
* @return bool Success indicator.
*/
public static function completeTransaction($paymentId, $payerId)
{

View file

@ -1,32 +1,58 @@
<?php
/*
* Permission Handler
*/
namespace Sakura;
/**
* Class Perms
* Global permissions handler.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Perms
{
// Modes
/**
* SITE permission mode, used for general permissions.
*/
const SITE = 'permissions\permissions_site';
/**
* MANAGE permission mode, used for site management actions.
*/
const MANAGE = 'permissions\permissions_manage';
/**
* FORUM permission mode, used per forum.
*/
const FORUM = 'forum_permissions\forum_perms';
// Variables
/**
* The table containing the permissions.
*
* @var string
*/
protected $table = '';
/**
* The column containing the permissions.
*
* @var string
*/
protected $column = '';
// Constructor
/**
* Constructor.
*
* @param string $mode One of the modes above.
*/
public function __construct($mode)
{
$this->mode($mode);
}
// Change the mode
/**
* Set a permission mode.
*
* @param string $mode One of the modes above.
*/
public function mode($mode)
{
// Split the mode variable
@ -37,13 +63,28 @@ class Perms
$this->column = $mode[1];
}
// Checking permissions
/**
* Compare a permission flag.
*
* @param int $flag The permission flag.
* @param int $perm The permissions of the user.
*
* @return bool Success indicator.
*/
public function check($flag, $perm)
{
return ($flag & $perm) > 0;
}
// Getting a rank's permissions
/**
* Get the permissions from a rank.
*
* @param int $rid The ID of the rank in question.
* @param array $conditions Additional SQL conditions.
* @param int $perm A permission flag to append to.
*
* @return int A permission flag.
*/
public function rank($rid, $conditions = [], $perm = 0)
{
// Merge rank id and additional conditions
@ -62,7 +103,15 @@ class Perms
return $perm;
}
// Getting a user's permissions
/**
* Get the permissions from a user.
*
* @param int $uid The ID of the user in question.
* @param array $conditions Additional SQL conditions.
* @param int $perm A permission flag to append to.
*
* @return int A permission flag.
*/
public function user($uid, $conditions = [], $perm = 0)
{
// Create a user object

View file

@ -1,25 +1,66 @@
<?php
/*
* Forum permissions
*/
namespace Sakura\Perms;
/**
* Class Forum
* All forum permission flags.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Forum
{
const VIEW = 1; // Can view this forum
const REPLY = 2; // Can reply to threads in this forum
const CREATE_THREADS = 4; // Can create threads in this forum
const EDIT_OWN = 8; // Can edit their posts
const DELETE_OWN = 16; // Can delete theirs posts
const STICKY = 32; // Can sticky threads
const ANNOUNCEMENT = 64; // Can announce threads
const EDIT_ANY = 128; // Can edit any post
const DELETE_ANY = 256; // Can delete any post
const LOCK = 512; // Can (un)lock threads
const MOVE = 1024; // Can move threads
/**
* Can this user view/read this forum?
*/
const VIEW = 1;
/**
* Can this user post/reply in this forum?
*/
const REPLY = 2;
/**
* Can this user create threads in this forum?
*/
const CREATE_THREADS = 4;
/**
* Can this user edit their own posts?
*/
const EDIT_OWN = 8;
/**
* Can this user delete their own posts?
*/
const DELETE_OWN = 16;
/**
* Can this user change threads to the sticky type?
*/
const STICKY = 32;
/**
* Can this user change threads to the announcement type?
*/
const ANNOUNCEMENT = 64;
/**
* Can this user edit any post in this forum?
*/
const EDIT_ANY = 128;
/**
* Can this user delete any post in this forum?
*/
const DELETE_ANY = 256;
/**
* Can this user toggle the locked status on threads in this forum?
*/
const LOCK = 512;
/**
* Can this user move threads to other forums from/to this forum?
*/
const MOVE = 1024;
}

View file

@ -1,16 +1,21 @@
<?php
/*
* Management permissions
*/
namespace Sakura\Perms;
/**
* Class Manage
* All site management permission flags.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Manage
{
const USE_MANAGE = 1; // Can use manage
const CAN_RESTRICT_USERS = 2; // Can change the status of users to restricted
/**
* Can this user use the management panel?
*/
const USE_MANAGE = 1;
/**
* Can this user toggle the restriction status of users?
*/
const CAN_RESTRICT_USERS = 2;
}

View file

@ -1,45 +1,166 @@
<?php
/*
* Global site permissions
*/
namespace Sakura\Perms;
/**
* Class Site
* All global site permissions.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Site
{
const DEACTIVATED = 1; // Is a user deactivated
const RESTRICTED = 2; // Is a user restricted
const ALTER_PROFILE = 4; // Can alter their profile data
const CHANGE_AVATAR = 8; // Can change their avatar
const CHANGE_BACKGROUND = 16; // Can change their background
const CHANGE_HEADER = 32; // User can change their profile header
const VIEW_MEMBERLIST = 64; // Can view the memberlist
const CREATE_USERPAGE = 128; // Can create a userpage
const CHANGE_USERPAGE = 256; // Can change their userpage
const USE_MESSAGES = 512; // Can use the Private Messaging system
const SEND_MESSAGES = 1024; // Can send Private Messages to other users
const CHANGE_EMAIL = 2048; // Can change their account e-mail address
const CHANGE_USERNAME = 4096; // Can change their username
const CHANGE_USERTITLE = 8192; // Can change their usertitle
const CHANGE_PASSWORD = 16384; // Can change their password
const ALTER_RANKS = 32768; // Can change their ranks
const MANAGE_SESSIONS = 65536; // Can manage their sessions
const CHANGE_SIGNATURE = 131072; // User can change their signature
const DEACTIVATE_ACCOUNT = 262144; // Can deactivate their account
const VIEW_PROFILE_DATA = 524288; // Can view other's profile data
const MANAGE_FRIENDS = 1048576; // Can manage friends (add/remove)
const REPORT_USERS = 2097152; // Can report users to staff
const OBTAIN_PREMIUM = 4194304; // Can obtain the premium rank
const JOIN_GROUPS = 8388608; // Can join groups
const CREATE_GROUP = 16777216; // Can create a group
const MULTIPLE_GROUPS = 33554432; // Can create multiple groups (requires single group perm)
const CHANGE_NAMECOLOUR = 67108864; // Can change their username colour
const STATIC_PREMIUM = 134217728; // User has static premium status
const CREATE_COMMENTS = 268435456; // User can make comments
const DELETE_COMMENTS = 536870912; // User can delete own comments
const VOTE_COMMENTS = 1073741824; // User can vote on comments
/**
* Is this user deactivated?
*/
const DEACTIVATED = 1;
/**
* Is this user restricted?
*/
const RESTRICTED = 2;
/**
* Can this user alter their profile?
*/
const ALTER_PROFILE = 4;
/**
* Can this user change their avatar?
*/
const CHANGE_AVATAR = 8;
/**
* Can this user change their profile background?
*/
const CHANGE_BACKGROUND = 16;
/**
* Can this user change their profile header?
*/
const CHANGE_HEADER = 32;
/**
* Can this user view the memberlist?
*/
const VIEW_MEMBERLIST = 64;
/**
* Can this user create a userpage?
*/
const CREATE_USERPAGE = 128;
/**
* Can this user change their userpage?
*/
const CHANGE_USERPAGE = 256;
/**
* Can this user use the private messaging system?
*/
const USE_MESSAGES = 512;
/**
* Can this user send private messages?
*/
const SEND_MESSAGES = 1024;
/**
* Can this user change the e-mail address associated with their account?
*/
const CHANGE_EMAIL = 2048;
/**
* Can this user change their username (within the configured timeframe)?
*/
const CHANGE_USERNAME = 4096;
/**
* Can this user change the user title?
*/
const CHANGE_USERTITLE = 8192;
/**
* Can this user change the password to their account?
*/
const CHANGE_PASSWORD = 16384;
/**
* Can this user manage the ranks they're part of?
*/
const ALTER_RANKS = 32768;
/**
* Can this user manage the active sessions on their account?
*/
const MANAGE_SESSIONS = 65536;
/**
* Can this user change their forum signature?
*/
const CHANGE_SIGNATURE = 131072;
/**
* Can this user deactivate their account?
*/
const DEACTIVATE_ACCOUNT = 262144;
/**
* Can this user view the external accounts on other's profiles?
*/
const VIEW_PROFILE_DATA = 524288;
/**
* Can this user manage friends?
*/
const MANAGE_FRIENDS = 1048576;
/**
* Can this user report other users?
*/
const REPORT_USERS = 2097152;
/**
* Is this user allowed to buy premium?
*/
const OBTAIN_PREMIUM = 4194304;
/**
* Can this user join groups?
*/
const JOIN_GROUPS = 8388608;
/**
* Can this user create a group?
*/
const CREATE_GROUP = 16777216;
/**
* Can this user create more than one group (requires CREATE_GROUP permission as well)?
*/
const MULTIPLE_GROUPS = 33554432;
/**
* Can this user change the colour of their username?
*/
const CHANGE_NAMECOLOUR = 67108864;
/**
* Does this user have infinite premium?
*/
const STATIC_PREMIUM = 134217728;
/**
* Can this user create comments?
*/
const CREATE_COMMENTS = 268435456;
/**
* Can this user delete their own comments?
*/
const DELETE_COMMENTS = 536870912;
/**
* Can this user vote on comments?
*/
const VOTE_COMMENTS = 1073741824;
}

View file

@ -1,32 +1,95 @@
<?php
/*
* Rank Class
*/
namespace Sakura;
use Sakura\Perms;
use Sakura\Perms\Site;
/**
* Class Rank
* Serves Rank data.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Rank
{
// Variables
/**
* ID of the rank.
*
* @var int
*/
public $id = 0;
/**
* Name of the rank.
*
* @var string
*/
public $name = 'Rank';
/**
* Global hierarchy of the rank.
*
* @var int
*/
public $hierarchy = 0;
/**
* Text that should be append to the name to make it address multiple.
*
* @var string
*/
public $multiple = '';
/**
* The rank's username colour.
*
* @var string
*/
public $colour = 'inherit';
/**
* Description of the rank.
*
* @var string
*/
public $description = '';
/**
* User title of the rank.
*
* @var string
*/
public $title = '';
/**
* Indicates if this rank should be hidden.
*
* @var bool
*/
private $hidden = true;
/**
* Permission container.
*
* @var Perms
*/
private $permissions;
/**
* Instance cache container.
*
* @var array
*/
protected static $_rankCache = [];
// Static initialiser
/**
* Cached constructor.
*
* @param int $rid ID of the rank.
* @param bool $forceRefresh Force a cache refresh.
*
* @return Rank The requested rank object.
*/
public static function construct($rid, $forceRefresh = false)
{
// Check if a rank object isn't present in cache
@ -39,7 +102,11 @@ class Rank
return self::$_rankCache[$rid];
}
// Initialise the rank object
/**
* Constructor.
*
* @param int $rid ID of the rank that should be constructed.
*/
private function __construct($rid)
{
@ -68,19 +135,35 @@ class Rank
$this->permissions = new Perms(Perms::SITE);
}
// Get the rank name
/**
* Get the name of the rank.
*
* @param bool $multi Should the multiple sense be appended?
*
* @return string The rank's name.
*/
public function name($multi = false)
{
return $this->name . ($multi ? $this->multiple : null);
}
// Check if the rank is hidden
/**
* Indicates if the rank is hidden.
*
* @return bool Hidden status.
*/
public function hidden()
{
return $this->hidden || $this->permission(Site::DEACTIVATED) || $this->permission(Site::RESTRICTED);
}
// Check if the rank has the proper permissions
/**
* Check permissions.
*
* @param int $flag Permission flag that should be checked.
*
* @return bool Success indicator.
*/
public function permission($flag)
{
// Set default permission value

View file

@ -1,29 +1,43 @@
<?php
/*
* Router Wrapper
*/
namespace Sakura;
use Phroute\Phroute\RouteCollector;
use Phroute\Phroute\Dispatcher;
/**
* Class Router
* Sakura Wrapper for Phroute.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Router
{
// Router container
/**
* Container for RouteCollector
*
* @var RouteCollector
*/
protected static $router = null;
// Base path (unused for now)
/**
* Base path of the router.
*
* @var string
*/
protected static $basePath = null;
// Dispatcher
/**
* Container for the Dispatcher
*
* @var Dispatcher
*/
protected static $dispatcher = null;
// Request methods
/**
* Collection of handled HTTP request types.
*
* @var array
*/
protected static $methods = [
'GET',
'POST',
@ -34,7 +48,12 @@ class Router
'ANY'
];
// Add a handler
/**
* Method aliases for adding routes.
*
* @param string $name A HTTP method.
* @param array $args The arguments.
*/
public static function __callStatic($name, $args)
{
// Check if the method exists
@ -47,7 +66,11 @@ class Router
}
}
// Initialisation function
/**
* Initialisation.
*
* @param string $basePath The base path of the router.
*/
public static function init($basePath = '/')
{
// Set base path
@ -57,19 +80,36 @@ class Router
self::$router = new RouteCollector;
}
// Set base path
/**
* Set the base path.
*
* @param string $basePath The base path of the router.
*/
public static function setBasePath($basePath)
{
self::$basePath = $basePath;
}
// Parse the url
/**
* Parse a URL.
*
* @param string $url The URL that is to be parsed.
*
* @return string THe parsed URL.
*/
private static function parseUrl($url)
{
return parse_url($url, PHP_URL_PATH);
}
// Handle requests
/**
* Handle requests.
*
* @param string $method The HTTP method used to make the request.
* @param string $url The URL the request is made to.
*
* @return mixed The response.
*/
public static function handle($method, $url)
{
// Check if the dispatcher is defined

View file

@ -1,21 +1,34 @@
<?php
/*
* User session container
*/
namespace Sakura;
/**
* Class Session
* User session handler.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Session
{
// Current user data
/**
* The ID of the user this session is from.
*
* @var int
*/
public $userId = 0;
/**
* The ID of the session.
*
* @var string
*/
public $sessionId = "";
// Initialise new session
/**
* Constructor.
*
* @param int $userId The ID of the user.
* @param int $sessionId The active session ID.
*/
public function __construct($userId, $sessionId = null)
{
// Set the supposed session data
@ -28,7 +41,9 @@ class Session
}
}
// Destroy this session
/**
* Destroy the active session.
*/
public function destroy()
{
// Invalidate the session key
@ -47,7 +62,9 @@ class Session
}
}
// Destroy all sessions keys for this user
/**
* Destroy all sessions from this user.
*/
public function destroyAll()
{
// Delete all database entries with this user in it
@ -57,7 +74,13 @@ class Session
$this->destroy();
}
// Create a new session
/**
* Create a new session.
*
* @param boolean $permanent Is this a permanent session?
*
* @return string The session key.
*/
public function create($permanent)
{
// Generate session key
@ -78,7 +101,11 @@ class Session
return $session;
}
// Validate an apparently existing session
/**
* Validate the session.
*
* @return int Success indicator; 0 = false, 1 = active, 2 = permanent.
*/
public function validate()
{
// Get session from database

View file

@ -1,8 +1,4 @@
<?php
/*
* Template engine wrapper
*/
namespace Sakura;
use Twig_Environment;
@ -10,26 +6,62 @@ use Twig_Extension_StringLoader;
use Twig_Loader_Filesystem;
/**
* Class Template
* Sakura wrapper for Twig.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Template
{
// Engine container, template folder name, options and template variables
/**
* The variables passed on to the templating engine.
*
* @var array
*/
private $vars = [];
/**
* The templating engine.
*
* @var Twig_Environment
*/
private $template;
/**
* The template name.
*
* @var string
*/
private $templateName;
/**
* The template options.
*
* @var array
*/
private $templateOptions;
/**
* The file extension used by template files
*
* @var string
*/
protected $templateFileExtension = ".twig";
// Initialise templating engine and data
/**
* Constructor.
*/
public function __construct()
{
// Set template to default
$this->setTemplate(Config::get('site_style'));
}
// Set a template name
/**
* Set the template name.
*
* @param string $name The name of the template directory.
*/
public function setTemplate($name)
{
// Assign config path to a variable so we don't have to type it out twice
@ -50,7 +82,9 @@ class Template
$this->initTemplate();
}
// Initialise main template engine
/**
* Initialise the templating engine.
*/
public function initTemplate()
{
// Initialise Twig Filesystem Loader
@ -71,13 +105,23 @@ class Template
$this->template->addExtension(new Twig_Extension_StringLoader());
}
// Set variables
/**
* Merge the parse variables.
*
* @param array $vars The new variables.
*/
public function setVariables($vars)
{
$this->vars = array_merge($this->vars, $vars);
}
// Render a template
/**
* Render a template file.
*
* @param string $file The filename/path
*
* @return bool|string An error or the HTML.
*/
public function render($file)
{
try {

View file

@ -1,13 +1,11 @@
<?php
/*
* Extension manager
*/
namespace Sakura;
/**
* Class Trick
* Extension manager.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Trick
{

View file

@ -1,17 +1,21 @@
<?php
/*
* URL management
*/
namespace Sakura;
/**
* Class Urls
* Rewrite URL generator.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Urls
{
// Unformatted links [0] = no mod_rewrite, [1] = mod_rewrite
/**
* Unformatted links
* 0 - Plain
* 1 - mod_rewrite
*
* @var array
*/
protected $urls = [
// General site sections
@ -282,7 +286,15 @@ class Urls
];
// Get a formatted url
/**
* Format a URL.
*
* @param string $lid The ID of a URL.
* @param array $args Additional arguments.
* @param bool $rewrite Toggle mod_rewrite.
*
* @return null|string The formatted URL.
*/
public function format($lid, $args = [], $rewrite = null)
{

View file

@ -1,51 +1,227 @@
<?php
/*
* Everything you'd ever need from a specific user
*/
namespace Sakura;
use Sakura\Perms;
use Sakura\Perms\Site;
/**
* Class User
* Everything you'd ever need from a specific user.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class User
{
// Variables
/**
* The User's ID.
*
* @var int
*/
public $id = 0;
/**
* The user's username.
*
* @var string
*/
public $username = 'User';
/**
* A cleaned version of the username.
*
* @var string
*/
public $usernameClean = 'user';
/**
* The user's password hash.
*
* @var string
*/
public $passwordHash = '';
/**
* The user's password salt.
*
* @var string
*/
public $passwordSalt = '';
/**
* The user's password algorithm.
*
* @var string
*/
public $passwordAlgo = 'disabled';
/**
* The password iterations.
*
* @var int
*/
public $passwordIter = 0;
/**
* UNIX timestamp of last time the password was changed.
*
* @var int
*/
public $passwordChan = 0;
/**
* The user's e-mail address.
*
* @var string
*/
public $email = 'user@sakura';
/**
* The rank object of the user's main rank.
*
* @var Rank
*/
public $mainRank = null;
/**
* The ID of the main rank.
*
* @var int
*/
public $mainRankId = 1;
/**
* The index of rank objects.
*
* @var array
*/
public $ranks = [];
/**
* The user's username colour.
*
* @var string
*/
public $colour = '';
/**
* The IP the user registered from.
*
* @var string
*/
public $registerIp = '0.0.0.0';
/**
* The IP the user was last active from.
*
* @var string
*/
public $lastIp = '0.0.0.0';
/**
* A user's title.
*
* @var string
*/
public $title = '';
/**
* The UNIX timestamp of when the user registered.
*
* @var int
*/
public $registered = 0;
/**
* The UNIX timestamp of when the user was last online.
*
* @var int
*/
public $lastOnline = 0;
/**
* The 2 character country code of a user.
*
* @var string
*/
public $country = 'XX';
/**
* The File id of the user's avatar.
*
* @var int
*/
public $avatar = 0;
/**
* The File id of the user's background.
*
* @var int
*/
public $background = 0;
/**
* The FIle id of the user's header.
* @var mixed
*/
public $header = 0;
/**
* The raw userpage of the user.
*
* @var string
*/
public $page = '';
/**
* The raw signature of the user.
*
* @var string
*/
public $signature = '';
/**
* The user's birthday.
*
* @var string
*/
private $birthday = '0000-00-00';
/**
* The user's permission container.
*
* @var Perms
*/
private $permissions;
/**
* The user's option fields.
*
* @var array
*/
private $optionFields = null;
/**
* The user's profile fields.
*
* @var array
*/
private $profileFields = null;
/**
* The User instance cache array.
*
* @var array
*/
protected static $_userCache = [];
// Static initialiser
/**
* Cached constructor.
*
* @param int|string $uid The user ID or clean username.
* @param bool $forceRefresh Force a recreation.
*
* @return User Returns a user object.
*/
public static function construct($uid, $forceRefresh = false)
{
// Check if a user object isn't present in cache
@ -58,7 +234,16 @@ class User
return self::$_userCache[$uid];
}
// Creating a new user
/**
* Create a new user.
*
* @param string $username The username of the user.
* @param string $password The password of the user.
* @param string $email The e-mail, used primarily for activation.
* @param array $ranks The ranks assigned to the user on creation.
*
* @return User The newly created user's object.
*/
public static function create($username, $password, $email, $ranks = [2])
{
// Set a few variables
@ -99,7 +284,11 @@ class User
return $user;
}
// Initialise the user object
/**
* The actual constructor
*
* @param int|string $uid The user ID or clean username.
*/
private function __construct($uid)
{
// Get the user database row
@ -173,13 +362,22 @@ class User
$this->permissions = new Perms(Perms::SITE);
}
// Update
/**
* Commit changed to database, doesn't do anything yet.
*/
public function update()
{
// placeholder
}
// Get user birthday
/**
* Get the user's birthday.
*
* @param bool $age Just get the age.
*
* @return int|string Return the birthday.
*/
public function birthday($age = false)
{
// If age is requested calculate it
@ -199,13 +397,23 @@ class User
return $this->birthday;
}
// Get the user's long or short country names
/**
* Get the user's country.
*
* @param bool $long Get the full country name.
*
* @return string The country.
*/
public function country($long = false)
{
return $long ? Utils::getCountryName($this->country) : $this->country;
}
// Check if a user is online
/**
* Check if a user is online.
*
* @return bool Are they online?
*/
public function isOnline()
{
// Get all sessions
@ -220,7 +428,11 @@ class User
return $this->lastOnline > (time() - Config::get('max_online_time'));
}
// Get user's forum statistics
/**
* Get a few forum statistics.
*
* @return array Post and thread counts.
*/
public function forumStats()
{
return [
@ -239,7 +451,14 @@ class User
];
}
// Get amount of time since user events using the same format as dates()
/**
* Get the elapsed string for some of the user's dates
*
* @param string $append Append to the value.
* @param string $none Replace the 0 value with this.
*
* @return array The times.
*/
public function elapsed($append = ' ago', $none = 'Just now')
{
$times = [];
@ -255,7 +474,11 @@ class User
return $times;
}
// Add ranks to a user
/**
* Add ranks to a user.
*
* @param array $ranks Array containing the rank IDs.
*/
public function addRanks($ranks)
{
// Update the ranks array
@ -277,7 +500,11 @@ class User
}
}
// Remove ranks from a user
/**
* Remove a set of ranks from a user.
*
* @param array $ranks Array containing the IDs of ranks to remove.
*/
public function removeRanks($ranks)
{
// Current ranks
@ -289,7 +516,13 @@ class User
}
}
// Set the main rank of this user
/**
* Change the main rank of a user.
*
* @param int $rank The ID of the new main rank.
*
* @return bool Always true.
*/
public function setMainRank($rank)
{
// If it does exist update their row
@ -306,7 +539,13 @@ class User
return true;
}
// Check if this user has the specified ranks
/**
* Check if a user has a certain set of rank.
*
* @param array $ranks Ranks IDs to check.
*
* @return bool Successful?
*/
public function hasRanks($ranks)
{
// Check if the main rank is the specified rank
@ -326,7 +565,13 @@ class User
return false;
}
// Add a new friend
/**
* Add a new friend.
*
* @param int $uid The ID of the friend.
*
* @return array Status indicator.
*/
public function addFriend($uid)
{
// Create the foreign object
@ -353,7 +598,14 @@ class User
return [1, $user->isFriends($this->id) ? 'FRIENDS' : 'NOT_MUTUAL'];
}
// Remove a friend
/**
* Remove a friend.
*
* @param int $uid The friend Id
* @param bool $deleteRequest Delete the open request as well (remove you from their friends list).
*
* @return array Status indicator.
*/
public function removeFriend($uid, $deleteRequest = false)
{
// Create the foreign object
@ -382,7 +634,13 @@ class User
return [1, 'REMOVED'];
}
// Check if the user is friends with the currently authenticated
/**
* Check if this user is friends with another user.
*
* @param int $with ID of the other user.
*
* @return int 0 = no, 1 = pending request, 2 = mutual
*/
public function isFriends($with)
{
// Accepted from this user
@ -407,7 +665,14 @@ class User
return 0;
}
// Get all the friend of this user
/**
* Get all the friends from this user.
*
* @param int $level Friend level; (figure out what the levels are at some point)
* @param bool $noObj Just return IDs.
*
* @return array The array with either the objects or the ids.
*/
public function friends($level = 0, $noObj = false)
{
// User ID container
@ -467,13 +732,24 @@ class User
return $objects;
}
// Check if the user is banned
/**
* Check if the user is banned.
*
* @return array|bool Ban status.
*/
public function checkBan()
{
return Bans::checkBan($this->id);
}
// Check if the user has the proper permissions
/**
* Check if the user has a certaing permission flag.
*
* @param int $flag The permission flag.
* @param string $mode The permission mode.
*
* @return bool Success?
*/
public function permission($flag, $mode = null)
{
// Set mode
@ -488,13 +764,20 @@ class User
return $this->permissions->check($flag, $perm);
}
// Get a user's profile comments
/**
* Get the comments from the user's profile.
* @return Comments
*/
public function profileComments()
{
return new Comments('profile-' . $this->id);
}
// Get the user's profile fields
/**
* Get the user's profile fields.
*
* @return array The profile fields.
*/
public function profileFields()
{
// Check if we have cached data
@ -569,7 +852,11 @@ class User
return $profile;
}
// Get the user's option fields
/**
* Get a user's option fields.
*
* @return array The array containing the fields.
*/
public function optionFields()
{
// Check if we have cached data
@ -617,7 +904,11 @@ class User
return $options;
}
// Check if user has Premium
/**
* Does this user have premium?
*
* @return array Premium status information.
*/
public function isPremium()
{
@ -645,7 +936,11 @@ class User
return [1, $getRecord['premium_start'], $getRecord['premium_expire']];
}
// Get all warnings issued to the user
/**
* Get the open warnings on this user.
*
* @return array The warnings.
*/
public function getWarnings()
{
// Do the database query
@ -695,19 +990,31 @@ class User
return $warnings;
}
// Get a user's userpage
/**
* Parse the user's userpage.
*
* @return string The parsed page.
*/
public function userPage()
{
return BBcode::toHTML(htmlentities($this->page));
}
// Get a user's signature
/**
* Parse a user's signature
*
* @return string The parsed signature.
*/
public function signature()
{
return BBcode::toHTML(htmlentities($this->signature));
}
// Get username change history
/**
* Get a user's username history.
*
* @return array The history.
*/
public function getUsernameHistory()
{
// Do the database query
@ -719,7 +1026,13 @@ class User
return $changes;
}
// Set a new username
/**
* Alter the user's username
*
* @param string $username The new username.
*
* @return array Status indicator.
*/
public function setUsername($username)
{
// Create a cleaned version
@ -781,7 +1094,13 @@ class User
return [1, 'SUCCESS', $username];
}
// Set a new e-mail address
/**
* Alter a user's e-mail address
*
* @param string $email The new e-mail address.
*
* @return array Status indicator.
*/
public function setEMailAddress($email)
{
// Validate e-mail address
@ -813,7 +1132,15 @@ class User
return [1, 'SUCCESS', $email];
}
// Set a new password
/**
* Change the user's password
*
* @param string $old The old password.
* @param string $new The new password
* @param string $confirm The new one again.
*
* @return array Status indicator.
*/
public function setPassword($old, $new, $confirm)
{
// Validate password

View file

@ -1,19 +1,24 @@
<?php
/*
* User Management
*/
namespace Sakura;
use Sakura\Perms\Site;
/**
* Class Users
* User management
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Users
{
// Check if a user is logged in
/**
* Check if a user is logged in
*
* @param int $uid The user ID.
* @param string $sid The session ID.
*
* @return array|bool Either false or the ID and session in an array.
*/
public static function checkLogin($uid = null, $sid = null)
{
// Assign $uid and $sid
@ -40,8 +45,7 @@ class Users
Config::get('cookie_prefix') . 'id',
0,
time() - 60,
Config::get('cookie_path'),
Config::get('cookie_domain')
Config::get('cookie_path')
);
// Unset Session ID
@ -49,8 +53,7 @@ class Users
Config::get('cookie_prefix') . 'session',
'',
time() - 60,
Config::get('cookie_path'),
Config::get('cookie_domain')
Config::get('cookie_path')
);
return false;
@ -63,8 +66,7 @@ class Users
Config::get('cookie_prefix') . 'id',
$uid,
time() + 604800,
Config::get('cookie_path'),
Config::get('cookie_domain')
Config::get('cookie_path')
);
// Session ID cookie
@ -72,8 +74,7 @@ class Users
Config::get('cookie_prefix') . 'session',
$sid,
time() + 604800,
Config::get('cookie_path'),
Config::get('cookie_domain')
Config::get('cookie_path')
);
}
@ -94,7 +95,16 @@ class Users
return [$uid, $sid];
}
// Log a user in
/**
* Log in to an account.
*
* @param string $username The username.
* @param string $password The password.
* @param bool $remember Stay logged in "forever"?
* @param bool $cookies Set cookies?
*
* @return array Return the status.
*/
public static function login($username, $password, $remember = false, $cookies = true)
{
// Check if authentication is disallowed
@ -157,8 +167,7 @@ class Users
Config::get('cookie_prefix') . 'id',
$user->id,
time() + 604800,
Config::get('cookie_path'),
Config::get('cookie_domain')
Config::get('cookie_path')
);
// Session ID cookie
@ -166,8 +175,7 @@ class Users
Config::get('cookie_prefix') . 'session',
$sessionKey,
time() + 604800,
Config::get('cookie_path'),
Config::get('cookie_domain')
Config::get('cookie_path')
);
}
@ -175,7 +183,11 @@ class Users
return [1, 'LOGIN_SUCCESS', $user->id];
}
// Logout and kill the session
/**
* Logout
*
* @return bool Was the logout successful?
*/
public static function logout()
{
// Check if user is logged in
@ -191,8 +203,7 @@ class Users
Config::get('cookie_prefix') . 'id',
0,
time() - 60,
Config::get('cookie_path'),
Config::get('cookie_domain')
Config::get('cookie_path')
);
// Unset Session ID
@ -200,15 +211,26 @@ class Users
Config::get('cookie_prefix') . 'session',
'',
time() - 60,
Config::get('cookie_path'),
Config::get('cookie_domain')
Config::get('cookie_path')
);
// Return true indicating a successful logout
return true;
}
// Register user
/**
* Register a new account.
*
* @param string $username The username.
* @param string $password The password.
* @param string $confirmpass The password, again.
* @param string $email The e-mail.
* @param bool $tos Agreeing to the ToS.
* @param string $captcha Captcha.
* @param string $regkey Registration key (unused).
*
* @return array Status.
*/
public static function register($username, $password, $confirmpass, $email, $tos, $captcha = null, $regkey = null)
{
// Check if authentication is disallowed
@ -290,7 +312,14 @@ class Users
return [1, ($requireActive ? 'EMAILSENT' : 'SUCCESS')];
}
// Check if a user exists and then send the password forgot email
/**
* Send password forgot e-mail
*
* @param string $username The username.
* @param string $email The e-mail.
*
* @return array The status.
*/
public static function sendPasswordForgot($username, $email)
{
// Check if authentication is disallowed
@ -345,7 +374,16 @@ class Users
return [1, 'SUCCESS'];
}
// Reset password with key
/**
* Reset a password.
*
* @param string $verk The e-mail verification key.
* @param int $uid The user id.
* @param string $newpass New pass.
* @param string $verpass Again.
*
* @return array Status.
*/
public static function resetPassword($verk, $uid, $newpass, $verpass)
{
// Check if authentication is disallowed
@ -393,7 +431,14 @@ class Users
return [1, 'SUCCESS'];
}
// Check if a user exists and then resend the activation e-mail
/**
* Resend activation e-mail.
*
* @param string $username Username.
* @param string $email E-mail.
*
* @return array Status
*/
public static function resendActivationMail($username, $email)
{
// Check if authentication is disallowed
@ -430,7 +475,14 @@ class Users
return [1, 'SUCCESS'];
}
// Send the activation e-mail and do other required stuff
/**
* Send activation e-mail.
*
* @param mixed $uid User ID.
* @param mixed $customKey Key.
*
* @return bool Always true.
*/
public static function sendActivationMail($uid, $customKey = null)
{
@ -475,7 +527,15 @@ class Users
return true;
}
// Activating a user
/**
* Activate a user.
*
* @param int $uid The ID.
* @param bool $requireKey Require a key.
* @param string $key The key.
*
* @return array Status.
*/
public static function activateUser($uid, $requireKey = false, $key = null)
{
// Get the user data
@ -511,7 +571,14 @@ class Users
return [1, 'SUCCESS'];
}
// Check if a user exists
/**
* Check if a user exists.
*
* @param mixed $user The Username or ID.
* @param bool $id Use id instead.
*
* @return mixed Returns the ID if it exists, false otherwise.
*/
public static function userExists($user, $id = true)
{
// Clean string
@ -524,7 +591,11 @@ class Users
return count($user) ? $user[0]['user_id'] : false;
}
// Get the available profile fields
/**
* Get all available profile fields.
*
* @return array|null The fields.
*/
public static function getProfileFields()
{
// Get profile fields
@ -549,7 +620,11 @@ class Users
return $fields;
}
// Get the available option fields
/**
* Get all available option fields.
*
* @return array|null The fields.
*/
public static function getOptionFields()
{
// Get option fields
@ -578,7 +653,11 @@ class Users
return $fields;
}
// Get all online users
/**
* Get all online users.
*
* @return array Array containing User instances.
*/
public static function checkAllOnline()
{
// Assign time - 500 to a variable
@ -597,7 +676,14 @@ class Users
return $return;
}
// Add premium to a user
/**
* Add premium time to a user.
*
* @param int $id The user ID.
* @param int $seconds The amount of extra seconds.
*
* @return array|double|int The new expiry date.
*/
public static function addUserPremium($id, $seconds)
{
// Check if there's already a record of premium for this user in the database
@ -631,7 +717,11 @@ class Users
return $expire;
}
// Update the premium data
/**
* Process premium meta data.
*
* @param int $id The user ID.
*/
public static function updatePremiumMeta($id)
{
// Get the ID for the premium user rank from the database
@ -664,7 +754,13 @@ class Users
}
}
// Get user(s) by IP
/**
* Get all users that registered from a certain IP.
*
* @param string $ip The IP.
*
* @return array The users.
*/
public static function getUsersByIP($ip)
{
// Get users by registration IP
@ -680,7 +776,15 @@ class Users
return $users;
}
// Get users in rank
/**
* Get users from a rank.
*
* @param int $rankId The rank ID.
* @param mixed $users Array with users.
* @param mixed $excludeAbyss Unused.
*
* @return array Users.
*/
public static function getUsersInRank($rankId, $users = null, $excludeAbyss = true)
{
// Get all users (or use the supplied user list to keep server load down)
@ -703,7 +807,14 @@ class Users
return $rank;
}
// Get all users
/**
* Get all users.
*
* @param mixed $includeInactive include deactivated users.
* @param mixed $includeRestricted include restricted users.
*
* @return array The users.
*/
public static function getAllUsers($includeInactive = true, $includeRestricted = false)
{
// Execute query
@ -733,7 +844,11 @@ class Users
return $users;
}
// Get all ranks
/**
* Get all ranks.
*
* @return array All ranks.
*/
public static function getAllRanks()
{
// Execute query
@ -751,7 +866,16 @@ class Users
return $ranks;
}
// Get a user's notifications
/**
* Get a user's notifications.
*
* @param int $uid The user id.
* @param int $timediff The maximum difference in time.
* @param bool $excludeRead Exclude notifications that were already read.
* @param bool $markRead Automatically mark as read.
*
* @return array The notifications.
*/
public static function getNotifications($uid = null, $timediff = 0, $excludeRead = true, $markRead = false)
{
// Prepare conditions
@ -787,7 +911,12 @@ class Users
return $notifications;
}
// Marking notifications as read
/**
* Mark a notification as read
*
* @param mixed $id The notification's ID.
* @param mixed $mode Read or unread.
*/
public static function markNotificationRead($id, $mode = true)
{
// Execute an update statement
@ -801,7 +930,17 @@ class Users
]);
}
// Adding a new notification
/**
* Create a new notification.
*
* @param int $user The user id.
* @param string $title The notification title.
* @param string $text The rest of the text.
* @param int $timeout After how many seconds the notification should disappear.
* @param string $img The image.
* @param string $link The link.
* @param int $sound Whether it should play a noise.
*/
public static function createNotification($user, $title, $text, $timeout = 60000, $img = 'FONT:fa-info-circle', $link = '', $sound = 0)
{
// Get current timestamp
@ -821,7 +960,11 @@ class Users
]);
}
// Get the ID of the newest user
/**
* Get the newest member's ID.
*
* @return int The user ID.
*/
public static function getNewestUserId()
{
return Database::fetch('users', false, ['rank_main' => [Config::get('restricted_rank_id'), '!=']], ['user_id', true], ['1'])['user_id'];

View file

@ -1,25 +1,33 @@
<?php
/*
* Utils Class
*/
namespace Sakura;
use PHPMailer;
/**
* Class Utils
* Meta utility functions.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Utils
{
// Get emoticons
/**
* Get the emoticons.
*
* @return array Array containing emoticons.
*/
public static function getEmotes()
{
return Database::fetch('emoticons');
}
// Parsing emoticons
/**
* Parse the emoticons.
*
* @param string $text String to parse emoticons from.
*
* @return string Parsed text.
*/
public static function parseEmotes($text)
{
@ -39,7 +47,13 @@ class Utils
return $text;
}
// Verify ReCAPTCHA
/**
* Verify a ReCaptcha
*
* @param string $response The user response.
*
* @return array The response from the ReCaptcha API.
*/
public static function verifyCaptcha($response)
{
@ -63,7 +77,14 @@ class Utils
return $resp;
}
// Error Handler
/**
* The error handler.
*
* @param int $errno The error ID.
* @param string $errstr Quick description of the event.
* @param string $errfile File the error occurred in.
* @param int $errline Line the error occurred on.
*/
public static function errorHandler($errno, $errstr, $errfile, $errline)
{
@ -217,7 +238,14 @@ class Utils
die($errorPage);
}
// Send emails
/**
* Send an e-mail.
*
* @param string $to Destination e-mail.
* @param string $subject E-mail subject.
* @param string $body Contents of the message.
* @return bool|string Return whatever PHPMailer returns.
*/
public static function sendMail($to, $subject, $body)
{
@ -277,7 +305,16 @@ class Utils
return $send;
}
// Cleaning strings
/**
* Clean a string
*
* @param string $string Dirty string.
* @param bool $lower Make the string lowercase.
* @param bool $noSpecial String all special characters.
* @param bool $replaceSpecial Thing to replace special characters with.
*
* @return string Clean string.
*/
public static function cleanString($string, $lower = false, $noSpecial = false, $replaceSpecial = '')
{
@ -300,7 +337,13 @@ class Utils
return $string;
}
// Loading info pages
/**
* Load contents of an infopage.
*
* @param string $id ID of the info page.
*
* @return array|bool Contents of the info page.
*/
public static function loadInfoPage($id)
{
@ -311,7 +354,13 @@ class Utils
return count($infopage) ? $infopage : false;
}
// Validate MX records
/**
* Validate MX records.
*
* @param string $email E-mail address.
*
* @return bool Success.
*/
public static function checkMXRecord($email)
{
@ -325,7 +374,13 @@ class Utils
return $record;
}
// Check IP version
/**
* Detect the version of an IP.
*
* @param string $ip The IP.
*
* @return int Either 0, 4 or 6.
*/
public static function ipVersion($ip)
{
@ -346,7 +401,13 @@ class Utils
return 0;
}
// Convert inet_pton to string with bits
/**
* Unpack an IPv6
*
* @param mixed $inet IP address.
*
* @return null|string The unpacked IP.
*/
public static function inetToBits($inet)
{
@ -368,7 +429,14 @@ class Utils
return $binaryIP;
}
// Match IP subnets
/**
* Match a subnet.
*
* @param string $ip the IP.
* @param string $range The range.
*
* @return bool|int Success.
*/
public static function matchSubnet($ip, $range)
{
@ -413,7 +481,13 @@ class Utils
}
}
// Check if IP is a CloudFlare IP
/**
* Check if an IP originates from CloudFlare.
*
* @param string $ip The IP.
*
* @return bool Success.
*/
public static function checkCFIP($ip)
{
@ -445,7 +519,11 @@ class Utils
return false;
}
// Gets IP of current visitor
/**
* Get the IP of a visitor.
*
* @return string The IP.
*/
public static function getRemoteIP()
{
@ -464,12 +542,17 @@ class Utils
return $ip;
}
// Get country code from CloudFlare header (which just returns XX if not found)
/**
* Get the country code of a visitor.
*
* @return string 2 character country code.
*/
public static function getCountryCode()
{
// Attempt to get country code using PHP's built in geo thing
if (function_exists("geoip_country_code_by_name")) {
$code = geoip_country_code_by_name(self::getRemoteIP());
// Check if $code is anything
if ($code) {
return $code;
@ -485,7 +568,13 @@ class Utils
return 'XX';
}
// Calculate password entropy
/**
* Check the entropy of a password.
*
* @param string $pw Password.
*
* @return double|int Entropy.
*/
public static function pwdEntropy($pw)
{
@ -496,7 +585,13 @@ class Utils
return count(count_chars($pw, 1)) * log(256, 2);
}
// Get country name from ISO 3166 code
/**
* Get the country name from a 2 character code.
*
* @param string $code The country code.
*
* @return string The country name.
*/
public static function getCountryName($code)
{
@ -519,7 +614,11 @@ class Utils
return 'Unknown';
}
// Get FAQ data
/**
* Get the FAQ table data (why is this a function).
*
* @return array FAQ data.
*/
public static function getFaqData()
{
@ -530,7 +629,11 @@ class Utils
return $faq;
}
// Get log type string
/**
* Get the type of log in text (unused and will probably be removwed).
* @param mixed $type
* @return mixed
*/
public static function getLogStringFromType($type)
{
@ -546,7 +649,11 @@ class Utils
return $return['string'];
}
// Get formatted logs
/**
* Get a user's logs (unused, probably removed in future).
* @param mixed $uid
* @return array
*/
public static function getUserLogs($uid = 0)
{
@ -573,7 +680,15 @@ class Utils
return $logs;
}
// Time elapsed, doesn't account for leap years
/**
* Calculate the time that has elapsed since a certain data (doesn't take leap years in account).
*
* @param int $timestamp The timestamp.
* @param string $append Append to
* @param string $none Text if 0.
*
* @return string Returns the time elapsed in a readable format.
*/
public static function timeElapsed($timestamp, $append = ' ago', $none = 'Just now')
{
@ -609,7 +724,13 @@ class Utils
}
}
// Get the byte symbol from a value
/**
* Get the byte symbol for a unit from bytes.
*
* @param int $bytes The amount of bytes.
*
* @return string The converted amount with the symbol.
*/
public static function getByteSymbol($bytes)
{
@ -631,7 +752,11 @@ class Utils
return $bytes;
}
// Get Premium tracker data
/**
* Get the premium tracker data.
*
* @return array The premium tracker data.
*/
public static function getPremiumTrackerData()
{
@ -665,7 +790,13 @@ class Utils
return $data;
}
// Update donation tracker
/**
* Add a new entry to the tracker.
*
* @param int $id The user ID.
* @param float $amount The amount of money.
* @param string $comment A little information.
*/
public static function updatePremiumTracker($id, $amount, $comment)
{
Database::insert('premium_log', [
@ -678,7 +809,13 @@ class Utils
]);
}
// Cleaning up the contents of code tags
/**
* Clean up the contents of <code> tags.
*
* @param string $text Dirty
*
* @return string Clean
*/
public static function fixCodeTags($text)
{
$parts = explode('<code>', $text);

View file

@ -30,15 +30,25 @@
namespace Sakura;
/**
* Class Whois
* WHOIS client.
*
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class Whois
{
// Variables
/**
* The index of WHOIS servers.
*
* @var array
*/
public static $servers;
// Set the whois servers list
/**
* Set the list of WHOIS servers.
*
* @param string $serversFile The file containing the servers json.
*/
public static function setServers($serversFile)
{
@ -66,7 +76,13 @@ class Whois
self::$servers = $servers;
}
// Query the whois servers
/**
* Query a whois server.
*
* @param string $address Hostname/IP address
*
* @return bool|string Whois result.
*/
public static function query($address)
{
@ -84,7 +100,13 @@ class Whois
}
}
// Validates an address
/**
* Validate an address.
*
* @param string $address The address.
*
* @return int The address type.
*/
private static function validateAddress($address)
{
@ -102,7 +124,13 @@ class Whois
return 0;
}
// Look up a domain
/**
* Look up a domain.
*
* @param string $address The address.
*
* @return string The WHOIS result.
*/
private static function lookupDomain($address)
{
@ -153,7 +181,13 @@ class Whois
return $return;
}
// Look up an IP
/**
* Look up an IP.
*
* @param string $address The IP.
*
* @return string The WHOIS result.
*/
private static function lookupIP($address)
{
@ -192,7 +226,16 @@ class Whois
return $return;
}
// Query whois server
/**
* Query a whois server.
*
* @param mixed $server The WHOIS server.
* @param mixed $address The address that should WHOIS'd.
* @param mixed $port The WHOIS server port.
* @param mixed $timeout The request timeout.
*
* @return null|string The WHOIS result.
*/
private static function queryWhois($server, $address, $port = 43, $timeout = 10)
{

View file

@ -1,14 +1,14 @@
<?php
/*
* Sakura Community Management System
* (c) 2013-2016 Flashwave <http://flash.moe>
* (c) 2013-2016 Julian van de Groep <http://flash.moe>
*/
// Declare namespace
namespace Sakura;
// Define Sakura version
define('SAKURA_VERSION', '20160130');
define('SAKURA_VERSION', '20160202');
define('SAKURA_VLABEL', 'Amethyst');
define('SAKURA_COLOUR', '#9966CC');
@ -42,11 +42,9 @@ require_once ROOT . 'libraries/BBcode.php';
require_once ROOT . 'libraries/Comments.php';
require_once ROOT . 'libraries/Config.php';
require_once ROOT . 'libraries/CSRF.php';
require_once ROOT . 'libraries/DB.php';
require_once ROOT . 'libraries/Database.php';
require_once ROOT . 'libraries/File.php';
require_once ROOT . 'libraries/Hashing.php';
require_once ROOT . 'libraries/Manage.php';
require_once ROOT . 'libraries/News.php';
require_once ROOT . 'libraries/Payments.php';
require_once ROOT . 'libraries/Perms.php';

0
serve.sh Executable file → Normal file
View file