Merge branch 'develop' of https://github.com/shish/shimmie2 into develop

This commit is contained in:
Shish
2017-09-21 05:25:48 +01:00
108 changed files with 1061 additions and 2306 deletions

View File

@ -4,11 +4,11 @@
* actually do anything as far as the app is concerned
*/
global $config, $database, $user, $page;
global $config, $database, $user, $page, $_shm_ctx;
require_once "core/sys_config.inc.php";
require_once "core/util.inc.php";
require_once "lib/context.php";
require_once "vendor/shish/libcontext-php/context.php";
require_once "vendor/autoload.php";
require_once "core/imageboard.pack.php";
@ -17,34 +17,34 @@ _version_check();
_sanitise_environment();
// load base files
ctx_log_start("Opening files");
$files = array_merge(
$_shm_ctx->log_start("Opening files");
$_shm_files = array_merge(
zglob("core/*.php"),
zglob("ext/{".ENABLED_EXTS."}/main.php")
);
foreach($files as $filename) {
if(basename($filename)[0] != "_") {
require_once $filename;
foreach($_shm_files as $_shm_filename) {
if(basename($_shm_filename)[0] != "_") {
require_once $_shm_filename;
}
}
unset($files);
unset($filename);
ctx_log_endok();
unset($_shm_files);
unset($_shm_filename);
$_shm_ctx->log_endok();
// connect to the database
ctx_log_start("Connecting to DB");
$_shm_ctx->log_start("Connecting to DB");
$database = new Database();
$config = new DatabaseConfig($database);
ctx_log_endok();
$_shm_ctx->log_endok();
// load the theme parts
ctx_log_start("Loading themelets");
$_shm_ctx->log_start("Loading themelets");
foreach(_get_themelet_files(get_theme()) as $themelet) {
require_once $themelet;
}
unset($themelet);
$page = class_exists("CustomPage") ? new CustomPage() : new Page();
ctx_log_endok();
$_shm_ctx->log_endok();
// hook up event handlers
_load_event_listeners();

View File

@ -13,8 +13,9 @@ class BaseThemelet {
* @param int $code
* @param string $title
* @param string $message
* @return void
*/
public function display_error(/*int*/ $code, /*string*/ $title, /*string*/ $message) {
public function display_error(int $code, string $title, string $message) {
global $page;
$page->set_code($code);
$page->set_title($title);
@ -34,6 +35,7 @@ class BaseThemelet {
/**
* A specific, common error message
* @return void
*/
public function display_permission_denied() {
$this->display_error(403, "Permission Denied", "You do not have permission to access this page");
@ -47,7 +49,7 @@ class BaseThemelet {
* @param Image $image
* @return string
*/
public function build_thumb_html(Image $image) {
public function build_thumb_html(Image $image): string {
global $config;
$i_id = (int) $image->id;
@ -75,45 +77,18 @@ class BaseThemelet {
"</a>\n";
}
/**
* Add a generic paginator.
*
* @param Page $page
* @param string $base
* @param string $query
* @param int $page_number
* @param int $total_pages
* @param bool $show_random
*/
public function display_paginator(Page $page, $base, $query, $page_number, $total_pages, $show_random = FALSE) {
public function display_paginator(Page $page, string $base, string $query=null, int $page_number, int $total_pages, bool $show_random = FALSE) {
if($total_pages == 0) $total_pages = 1;
$body = $this->build_paginator($page_number, $total_pages, $base, $query, $show_random);
$page->add_block(new Block(null, $body, "main", 90, "paginator"));
}
/**
* Generate a single HTML link.
*
* @param string $base_url
* @param string $query
* @param string $page
* @param string $name
* @return string
*/
private function gen_page_link($base_url, $query, $page, $name) {
private function gen_page_link(string $base_url, string $query=null, string $page, string $name): string {
$link = make_link($base_url.'/'.$page, $query);
return '<a href="'.$link.'">'.$name.'</a>';
}
/**
* @param string $base_url
* @param string $query
* @param string $page
* @param int $current_page
* @param string $name
* @return string
*/
private function gen_page_link_block($base_url, $query, $page, $current_page, $name) {
private function gen_page_link_block(string $base_url, string $query=null, string $page, int $current_page, string $name): string {
$paginator = "";
if($page == $current_page) $paginator .= "<b>";
$paginator .= $this->gen_page_link($base_url, $query, $page, $name);
@ -121,17 +96,7 @@ class BaseThemelet {
return $paginator;
}
/**
* Build the paginator.
*
* @param int $current_page
* @param int $total_pages
* @param string $base_url
* @param string $query
* @param bool $show_random
* @return string
*/
private function build_paginator($current_page, $total_pages, $base_url, $query, $show_random) {
private function build_paginator(int $current_page, int $total_pages, string $base_url, string $query=null, bool $show_random): string {
$next = $current_page + 1;
$prev = $current_page - 1;
@ -163,4 +128,3 @@ class BaseThemelet {
.'<br>&lt;&lt; '.$pages_html.' &gt;&gt;';
}
}

View File

@ -52,16 +52,7 @@ class Block {
*/
public $is_content = true;
/**
* Construct a block.
*
* @param string $header
* @param string $body
* @param string $section
* @param int $position
* @param null|int $id A unique ID for the block (generated automatically if null).
*/
public function __construct($header, $body, /*string*/ $section="main", /*int*/ $position=50, $id=null) {
public function __construct(string $header=null, string $body=null, string $section="main", int $position=50, string $id=null) {
$this->header = $header;
$this->body = $body;
$this->section = $section;
@ -79,7 +70,7 @@ class Block {
* @param bool $hidable
* @return string
*/
public function get_html($hidable=false) {
public function get_html(bool $hidable=false): string {
$h = $this->header;
$b = $this->body;
$i = $this->id;

View File

@ -12,9 +12,9 @@ interface Config {
* configuration.
*
* @param null|string $name
* @return mixed|void
* @return void
*/
public function save(/*string*/ $name=null);
public function save(string $name=null);
//@{ /*--------------------------------- SET ------------------------------------------------------*/
/**
@ -23,7 +23,7 @@ interface Config {
* @param null|int $value
* @return void
*/
public function set_int(/*string*/ $name, $value);
public function set_int(string $name, $value);
/**
* Set a configuration option to a new value, regardless of what the value is at the moment.
@ -31,7 +31,7 @@ interface Config {
* @param null|string $value
* @return void
*/
public function set_string(/*string*/ $name, $value);
public function set_string(string $name, $value);
/**
* Set a configuration option to a new value, regardless of what the value is at the moment.
@ -39,7 +39,7 @@ interface Config {
* @param null|bool|string $value
* @return void
*/
public function set_bool(/*string*/ $name, $value);
public function set_bool(string $name, $value);
/**
* Set a configuration option to a new value, regardless of what the value is at the moment.
@ -47,7 +47,7 @@ interface Config {
* @param array $value
* @return void
*/
public function set_array(/*string*/ $name, $value);
public function set_array(string $name, array $value);
//@} /*--------------------------------------------------------------------------------------------*/
//@{ /*-------------------------------- SET DEFAULT -----------------------------------------------*/
@ -63,7 +63,7 @@ interface Config {
* @param int $value
* @return void
*/
public function set_default_int(/*string*/ $name, $value);
public function set_default_int(string $name, int $value);
/**
* Set a configuration option to a new value, if there is no value currently.
@ -77,7 +77,7 @@ interface Config {
* @param string|null $value
* @return void
*/
public function set_default_string(/*string*/ $name, $value);
public function set_default_string(string $name, string $value);
/**
* Set a configuration option to a new value, if there is no value currently.
@ -91,7 +91,7 @@ interface Config {
* @param bool $value
* @return void
*/
public function set_default_bool(/*string*/ $name, /*bool*/ $value);
public function set_default_bool(string $name, bool $value);
/**
* Set a configuration option to a new value, if there is no value currently.
@ -105,7 +105,7 @@ interface Config {
* @param array $value
* @return void
*/
public function set_default_array(/*string*/ $name, $value);
public function set_default_array(string $name, array $value);
//@} /*--------------------------------------------------------------------------------------------*/
//@{ /*--------------------------------- GET ------------------------------------------------------*/
@ -115,7 +115,7 @@ interface Config {
* @param null|int $default
* @return int
*/
public function get_int(/*string*/ $name, $default=null);
public function get_int(string $name, $default=null);
/**
* Pick a value out of the table by name, cast to the appropriate data type.
@ -123,7 +123,7 @@ interface Config {
* @param null|string $default
* @return string
*/
public function get_string(/*string*/ $name, $default=null);
public function get_string(string $name, $default=null);
/**
* Pick a value out of the table by name, cast to the appropriate data type.
@ -131,7 +131,7 @@ interface Config {
* @param null|bool|string $default
* @return bool
*/
public function get_bool(/*string*/ $name, $default=null);
public function get_bool(string $name, $default=null);
/**
* Pick a value out of the table by name, cast to the appropriate data type.
@ -139,7 +139,7 @@ interface Config {
* @param array|null $default
* @return array
*/
public function get_array(/*string*/ $name, $default=array());
public function get_array(string $name, array $default=array());
//@} /*--------------------------------------------------------------------------------------------*/
}
@ -153,134 +153,67 @@ interface Config {
abstract class BaseConfig implements Config {
public $values = array();
/**
* @param string $name
* @param int|null $value
* @return void
*/
public function set_int(/*string*/ $name, $value) {
public function set_int(string $name, $value) {
$this->values[$name] = parse_shorthand_int($value);
$this->save($name);
}
/**
* @param string $name
* @param null|string $value
* @return void
*/
public function set_string(/*string*/ $name, $value) {
public function set_string(string $name, $value) {
$this->values[$name] = $value;
$this->save($name);
}
/**
* @param string $name
* @param bool|null|string $value
* @return void
*/
public function set_bool(/*string*/ $name, $value) {
$this->values[$name] = (($value == 'on' || $value === true) ? 'Y' : 'N');
public function set_bool(string $name, $value) {
$this->values[$name] = bool_escape($value) ? 'Y' : 'N';
$this->save($name);
}
/**
* @param string $name
* @param array $value
* @return void
*/
public function set_array(/*string*/ $name, $value) {
assert(isset($value) && is_array($value));
public function set_array(string $name, array $value) {
$this->values[$name] = implode(",", $value);
$this->save($name);
}
/**
* @param string $name
* @param int $value
* @return void
*/
public function set_default_int(/*string*/ $name, $value) {
if(is_null($this->get($name))) {
$this->values[$name] = parse_shorthand_int($value);
}
}
/**
* @param string $name
* @param null|string $value
* @return void
*/
public function set_default_string(/*string*/ $name, $value) {
public function set_default_int(string $name, int $value) {
if(is_null($this->get($name))) {
$this->values[$name] = $value;
}
}
/**
* @param string $name
* @param bool $value
* @return void
*/
public function set_default_bool(/*string*/ $name, /*bool*/ $value) {
public function set_default_string(string $name, string $value) {
if(is_null($this->get($name))) {
$this->values[$name] = (($value == 'on' || $value === true) ? 'Y' : 'N');
$this->values[$name] = $value;
}
}
/**
* @param string $name
* @param array $value
* @return void
*/
public function set_default_array(/*string*/ $name, $value) {
assert(isset($value) && is_array($value));
public function set_default_bool(string $name, bool $value) {
if(is_null($this->get($name))) {
$this->values[$name] = $value ? 'Y' : 'N';
}
}
public function set_default_array(string $name, array $value) {
if(is_null($this->get($name))) {
$this->values[$name] = implode(",", $value);
}
}
/**
* @param string $name
* @param null|int $default
* @return int
*/
public function get_int(/*string*/ $name, $default=null) {
public function get_int(string $name, $default=null) {
return (int)($this->get($name, $default));
}
/**
* @param string $name
* @param null|string $default
* @return null|string
*/
public function get_string(/*string*/ $name, $default=null) {
public function get_string(string $name, $default=null) {
return $this->get($name, $default);
}
/**
* @param string $name
* @param null|bool|string $default
* @return bool
*/
public function get_bool(/*string*/ $name, $default=null) {
public function get_bool(string $name, $default=null) {
return bool_escape($this->get($name, $default));
}
/**
* @param string $name
* @param array $default
* @return array
*/
public function get_array(/*string*/ $name, $default=array()) {
public function get_array(string $name, array $default=array()): array {
return explode(",", $this->get($name, ""));
}
/**
* @param string $name
* @param null|mixed $default
* @return null|mixed
*/
private function get(/*string*/ $name, $default=null) {
private function get(string $name, $default=null) {
if(isset($this->values[$name])) {
return $this->values[$name];
}
@ -297,15 +230,11 @@ abstract class BaseConfig implements Config {
* For testing, mostly.
*/
class HardcodeConfig extends BaseConfig {
public function __construct($dict) {
public function __construct(array $dict) {
$this->values = $dict;
}
/**
* @param null|string $name
* @return mixed|void
*/
public function save(/*string*/ $name=null) {
public function save(string $name=null) {
// static config is static
}
}
@ -322,11 +251,7 @@ class HardcodeConfig extends BaseConfig {
* ?>
*/
class StaticConfig extends BaseConfig {
/**
* @param string $filename
* @throws Exception
*/
public function __construct($filename) {
public function __construct(string $filename) {
if(file_exists($filename)) {
$config = array();
require_once $filename;
@ -342,11 +267,7 @@ class StaticConfig extends BaseConfig {
}
}
/**
* @param null|string $name
* @return mixed|void
*/
public function save(/*string*/ $name=null) {
public function save(string $name=null) {
// static config is static
}
}
@ -369,11 +290,6 @@ class DatabaseConfig extends BaseConfig {
/** @var Database */
private $database = null;
/**
* Load the config table from a database.
*
* @param Database $database
*/
public function __construct(Database $database) {
$this->database = $database;
@ -390,17 +306,11 @@ class DatabaseConfig extends BaseConfig {
}
}
/**
* Save the current values as the new config table.
*
* @param null|string $name
* @return mixed|void
*/
public function save(/*string*/ $name=null) {
public function save(string $name=null) {
if(is_null($name)) {
reset($this->values); // rewind the array to the first element
foreach($this->values as $name => $value) {
$this->save(/*string*/ $name);
$this->save($name);
}
}
else {
@ -417,10 +327,7 @@ class DatabaseConfig extends BaseConfig {
* Class MockConfig
*/
class MockConfig extends HardcodeConfig {
/**
* @param array $config
*/
public function __construct($config=array()) {
public function __construct(array $config=array()) {
$config["db_version"] = "999";
$config["anon_id"] = "0";
parent::__construct($config);

View File

@ -7,34 +7,20 @@ class Querylet {
/** @var array */
public $variables;
/**
* @param string $sql
* @param array $variables
*/
public function __construct($sql, $variables=array()) {
public function __construct(string $sql, array $variables=array()) {
$this->sql = $sql;
$this->variables = $variables;
}
/**
* @param \Querylet $querylet
*/
public function append($querylet) {
assert('!is_null($querylet)');
public function append(Querylet $querylet) {
$this->sql .= $querylet->sql;
$this->variables = array_merge($this->variables, $querylet->variables);
}
/**
* @param string $sql
*/
public function append_sql($sql) {
public function append_sql(string $sql) {
$this->sql .= $sql;
}
/**
* @param mixed $var
*/
public function add_variable($var) {
$this->variables[] = $var;
}
@ -46,11 +32,7 @@ class TagQuerylet {
/** @var bool */
public $positive;
/**
* @param string $tag
* @param bool $positive
*/
public function __construct($tag, $positive) {
public function __construct(string $tag, bool $positive) {
$this->tag = $tag;
$this->positive = $positive;
}
@ -62,11 +44,7 @@ class ImgQuerylet {
/** @var bool */
public $positive;
/**
* @param \Querylet $qlet
* @param bool $positive
*/
public function __construct($qlet, $positive) {
public function __construct(Querylet $qlet, bool $positive) {
$this->qlet = $qlet;
$this->positive = $positive;
}
@ -77,25 +55,13 @@ class DBEngine {
/** @var null|string */
public $name = null;
/**
* @param \PDO $db
*/
public function init($db) {}
public function init(PDO $db) {}
/**
* @param string $scoreql
* @return string
*/
public function scoreql_to_sql($scoreql) {
public function scoreql_to_sql(string $scoreql): string {
return $scoreql;
}
/**
* @param string $name
* @param string $data
* @return string
*/
public function create_table_sql($name, $data) {
public function create_table_sql(string $name, string $data): string {
return 'CREATE TABLE '.$name.' ('.$data.')';
}
}
@ -103,18 +69,11 @@ class MySQL extends DBEngine {
/** @var string */
public $name = "mysql";
/**
* @param \PDO $db
*/
public function init($db) {
public function init(PDO $db) {
$db->exec("SET NAMES utf8;");
}
/**
* @param string $data
* @return string
*/
public function scoreql_to_sql($data) {
public function scoreql_to_sql(string $data): string {
$data = str_replace("SCORE_AIPK", "INTEGER PRIMARY KEY auto_increment", $data);
$data = str_replace("SCORE_INET", "VARCHAR(45)", $data);
$data = str_replace("SCORE_BOOL_Y", "'Y'", $data);
@ -127,12 +86,7 @@ class MySQL extends DBEngine {
return $data;
}
/**
* @param string $name
* @param string $data
* @return string
*/
public function create_table_sql($name, $data) {
public function create_table_sql(string $name, string $data): string {
$data = $this->scoreql_to_sql($data);
$ctes = "ENGINE=InnoDB DEFAULT CHARSET='utf8'";
return 'CREATE TABLE '.$name.' ('.$data.') '.$ctes;
@ -142,10 +96,7 @@ class PostgreSQL extends DBEngine {
/** @var string */
public $name = "pgsql";
/**
* @param \PDO $db
*/
public function init($db) {
public function init(PDO $db) {
if(array_key_exists('REMOTE_ADDR', $_SERVER)) {
$db->exec("SET application_name TO 'shimmie [{$_SERVER['REMOTE_ADDR']}]';");
}
@ -155,11 +106,7 @@ class PostgreSQL extends DBEngine {
$db->exec("SET statement_timeout TO 10000;");
}
/**
* @param string $data
* @return string
*/
public function scoreql_to_sql($data) {
public function scoreql_to_sql(string $data): string {
$data = str_replace("SCORE_AIPK", "SERIAL PRIMARY KEY", $data);
$data = str_replace("SCORE_INET", "INET", $data);
$data = str_replace("SCORE_BOOL_Y", "'t'", $data);
@ -172,12 +119,7 @@ class PostgreSQL extends DBEngine {
return $data;
}
/**
* @param string $name
* @param string $data
* @return string
*/
public function create_table_sql($name, $data) {
public function create_table_sql(string $name, string $data): string {
$data = $this->scoreql_to_sql($data);
return "CREATE TABLE $name ($data)";
}
@ -202,10 +144,7 @@ class SQLite extends DBEngine {
/** @var string */
public $name = "sqlite";
/**
* @param \PDO $db
*/
public function init($db) {
public function init(PDO $db) {
ini_set('sqlite.assoc_case', 0);
$db->exec("PRAGMA foreign_keys = ON;");
$db->sqliteCreateFunction('UNIX_TIMESTAMP', '_unix_timestamp', 1);
@ -220,11 +159,7 @@ class SQLite extends DBEngine {
$db->sqliteCreateFunction('ln', '_ln', 1);
}
/**
* @param string $data
* @return string
*/
public function scoreql_to_sql($data) {
public function scoreql_to_sql(string $data): string {
$data = str_replace("SCORE_AIPK", "INTEGER PRIMARY KEY", $data);
$data = str_replace("SCORE_INET", "VARCHAR(45)", $data);
$data = str_replace("SCORE_BOOL_Y", "'Y'", $data);
@ -236,12 +171,7 @@ class SQLite extends DBEngine {
return $data;
}
/**
* @param string $name
* @param string $data
* @return string
*/
public function create_table_sql($name, $data) {
public function create_table_sql(string $name, string $data): string {
$data = $this->scoreql_to_sql($data);
$cols = array();
$extras = "";
@ -264,42 +194,19 @@ class SQLite extends DBEngine {
// {{{ cache engines
interface CacheEngine {
/**
* @param string $key
* @return mixed
*/
public function get($key);
/**
* @param string $key
* @param mixed $val
* @param integer $time
* @return void
*/
public function set($key, $val, $time=0);
/**
* @return void
*/
public function delete($key);
/**
* @return integer
*/
public function get_hits();
/**
* @return integer
*/
public function get_misses();
public function get(string $key);
public function set(string $key, $val, int $time=0);
public function delete(string $key);
public function get_hits(): int;
public function get_misses(): int;
}
class NoCache implements CacheEngine {
public function get($key) {return false;}
public function set($key, $val, $time=0) {}
public function delete($key) {}
public function get(string $key) {return false;}
public function set(string $key, $val, int $time=0) {}
public function delete(string $key) {}
public function get_hits() {return 0;}
public function get_misses() {return 0;}
public function get_hits(): int {return 0;}
public function get_misses(): int {return 0;}
}
class MemcacheCache implements CacheEngine {
/** @var \Memcache|null */
@ -309,21 +216,13 @@ class MemcacheCache implements CacheEngine {
/** @var int */
private $misses=0;
/**
* @param string $args
*/
public function __construct($args) {
public function __construct(string $args) {
$hp = explode(":", $args);
$this->memcache = new Memcache;
@$this->memcache->pconnect($hp[0], $hp[1]);
}
/**
* @param string $key
* @return array|bool|string
*/
public function get($key) {
assert('!is_null($key)');
public function get(string $key) {
$val = $this->memcache->get($key);
if((DEBUG_CACHE === true) || (is_null(DEBUG_CACHE) && @$_GET['DEBUG_CACHE'])) {
$hit = $val === false ? "miss" : "hit";
@ -339,39 +238,22 @@ class MemcacheCache implements CacheEngine {
}
}
/**
* @param string $key
* @param mixed $val
* @param integer $time
*/
public function set($key, $val, $time=0) {
assert('!is_null($key)');
public function set(string $key, $val, int $time=0) {
$this->memcache->set($key, $val, false, $time);
if((DEBUG_CACHE === true) || (is_null(DEBUG_CACHE) && @$_GET['DEBUG_CACHE'])) {
file_put_contents("data/cache.log", "Cache set: $key ($time)\n", FILE_APPEND);
}
}
/**
* @param string $key
*/
public function delete($key) {
assert('!is_null($key)');
public function delete(string $key) {
$this->memcache->delete($key);
if((DEBUG_CACHE === true) || (is_null(DEBUG_CACHE) && @$_GET['DEBUG_CACHE'])) {
file_put_contents("data/cache.log", "Cache delete: $key\n", FILE_APPEND);
}
}
/**
* @return int
*/
public function get_hits() {return $this->hits;}
/**
* @return int
*/
public function get_misses() {return $this->misses;}
public function get_hits(): int {return $this->hits;}
public function get_misses(): int {return $this->misses;}
}
class MemcachedCache implements CacheEngine {
/** @var \Memcached|null */
@ -381,10 +263,7 @@ class MemcachedCache implements CacheEngine {
/** @var int */
private $misses=0;
/**
* @param string $args
*/
public function __construct($args) {
public function __construct(string $args) {
$hp = explode(":", $args);
$this->memcache = new Memcached;
#$this->memcache->setOption(Memcached::OPT_COMPRESSION, False);
@ -393,12 +272,7 @@ class MemcachedCache implements CacheEngine {
$this->memcache->addServer($hp[0], $hp[1]);
}
/**
* @param string $key
* @return array|bool|string
*/
public function get($key) {
assert('!is_null($key)');
public function get(string $key) {
$key = urlencode($key);
$val = $this->memcache->get($key);
@ -418,16 +292,11 @@ class MemcachedCache implements CacheEngine {
}
else {
error_log("Memcached error during get($key): $res");
return false;
}
}
/**
* @param string $key
* @param mixed $val
* @param int $time
*/
public function set($key, $val, $time=0) {
assert('!is_null($key)');
public function set(string $key, $val, int $time=0) {
$key = urlencode($key);
$this->memcache->set($key, $val, $time);
@ -440,11 +309,7 @@ class MemcachedCache implements CacheEngine {
}
}
/**
* @param string $key
*/
public function delete($key) {
assert('!is_null($key)');
public function delete(string $key) {
$key = urlencode($key);
$this->memcache->delete($key);
@ -457,26 +322,18 @@ class MemcachedCache implements CacheEngine {
}
}
/**
* @return int
*/
public function get_hits() {return $this->hits;}
/**
* @return int
*/
public function get_misses() {return $this->misses;}
public function get_hits(): int {return $this->hits;}
public function get_misses(): int {return $this->misses;}
}
class APCCache implements CacheEngine {
public $hits=0, $misses=0;
public function __construct($args) {
public function __construct(string $args) {
// $args is not used, but is passed in when APC cache is created.
}
public function get($key) {
assert('!is_null($key)');
public function get(string $key) {
$val = apc_fetch($key);
if($val) {
$this->hits++;
@ -488,18 +345,16 @@ class APCCache implements CacheEngine {
}
}
public function set($key, $val, $time=0) {
assert('!is_null($key)');
public function set(string $key, $val, int $time=0) {
apc_store($key, $val, $time);
}
public function delete($key) {
assert('!is_null($key)');
public function delete(string $key) {
apc_delete($key);
}
public function get_hits() {return $this->hits;}
public function get_misses() {return $this->misses;}
public function get_hits(): int {return $this->hits;}
public function get_misses(): int {return $this->misses;}
}
// }}}
/** @publicsection */
@ -627,11 +482,7 @@ class Database {
}
}
/**
* @return boolean|null
* @throws SCoreException
*/
public function commit() {
public function commit(): bool {
if(!is_null($this->db)) {
if ($this->transaction === true) {
$this->transaction = false;
@ -641,13 +492,12 @@ class Database {
throw new SCoreException("<p><b>Database Transaction Error:</b> Unable to call commit() as there is no transaction currently open.");
}
}
else {
throw new SCoreException("<p><b>Database Transaction Error:</b> Unable to call commit() as there is no connection currently open.");
}
}
/**
* @return boolean|null
* @throws SCoreException
*/
public function rollback() {
public function rollback(): bool {
if(!is_null($this->db)) {
if ($this->transaction === true) {
$this->transaction = false;
@ -657,39 +507,27 @@ class Database {
throw new SCoreException("<p><b>Database Transaction Error:</b> Unable to call rollback() as there is no transaction currently open.");
}
}
else {
throw new SCoreException("<p><b>Database Transaction Error:</b> Unable to call rollback() as there is no connection currently open.");
}
}
/**
* @param string $input
* @return string
*/
public function escape($input) {
public function escape(string $input): string {
if(is_null($this->db)) $this->connect_db();
return $this->db->Quote($input);
}
/**
* @param string $input
* @return string
*/
public function scoreql_to_sql($input) {
public function scoreql_to_sql(string $input): string {
if(is_null($this->engine)) $this->connect_engine();
return $this->engine->scoreql_to_sql($input);
}
/**
* @return null|string
*/
public function get_driver_name() {
public function get_driver_name(): string {
if(is_null($this->engine)) $this->connect_engine();
return $this->engine->name;
}
/**
* @param null|PDO $db
* @param string $sql
*/
private function count_execs($db, $sql, $inputarray) {
private function count_execs(string $sql, array $inputarray) {
if((DEBUG_SQL === true) || (is_null(DEBUG_SQL) && @$_GET['DEBUG_SQL'])) {
$sql = trim(preg_replace('/\s+/msi', ' ', $sql));
if(isset($inputarray) && is_array($inputarray) && !empty($inputarray)) {
@ -706,7 +544,7 @@ class Database {
else $this->query_count++;
}
private function count_time($method, $start) {
private function count_time(string $method, float $start) {
if((DEBUG_SQL === true) || (is_null(DEBUG_SQL) && @$_GET['DEBUG_SQL'])) {
$text = $method.":".(microtime(true) - $start)."\n";
file_put_contents("data/sql.log", $text, FILE_APPEND);
@ -714,18 +552,10 @@ class Database {
$this->dbtime += microtime(true) - $start;
}
/**
* Execute an SQL query and return an PDO result-set.
*
* @param string $query
* @param array $args
* @return PDOStatement
* @throws SCoreException
*/
public function execute($query, $args=array()) {
public function execute(string $query, array $args=array()): PDOStatement {
try {
if(is_null($this->db)) $this->connect_db();
$this->count_execs($this->db, $query, $args);
$this->count_execs($query, $args);
$stmt = $this->db->prepare($query);
if (!array_key_exists(0, $args)) {
foreach($args as $name=>$value) {
@ -755,7 +585,7 @@ class Database {
* @param array $args
* @return array
*/
public function get_all($query, $args=array()) {
public function get_all(string $query, array $args=array()): array {
$_start = microtime(true);
$data = $this->execute($query, $args)->fetchAll();
$this->count_time("get_all", $_start);
@ -769,7 +599,7 @@ class Database {
* @param array $args
* @return array|null
*/
public function get_row($query, $args=array()) {
public function get_row(string $query, array $args=array()) {
$_start = microtime(true);
$row = $this->execute($query, $args)->fetch();
$this->count_time("get_row", $_start);
@ -783,7 +613,7 @@ class Database {
* @param array $args
* @return array
*/
public function get_col($query, $args=array()) {
public function get_col(string $query, array $args=array()): array {
$_start = microtime(true);
$stmt = $this->execute($query, $args);
$res = array();
@ -795,13 +625,13 @@ class Database {
}
/**
* Execute an SQL query and return the the first row => the second rown.
* Execute an SQL query and return the the first row => the second row.
*
* @param string $query
* @param array $args
* @return array
*/
public function get_pairs($query, $args=array()) {
public function get_pairs(string $query, array $args=array()): array {
$_start = microtime(true);
$stmt = $this->execute($query, $args);
$res = array();
@ -817,9 +647,9 @@ class Database {
*
* @param string $query
* @param array $args
* @return mixed
* @return mixed|null
*/
public function get_one($query, $args=array()) {
public function get_one(string $query, array $args=array()) {
$_start = microtime(true);
$row = $this->execute($query, $args)->fetch();
$this->count_time("get_one", $_start);
@ -832,7 +662,7 @@ class Database {
* @param string|null $seq
* @return int
*/
public function get_last_insert_id($seq) {
public function get_last_insert_id(string $seq): int {
if($this->engine->name == "pgsql") {
return $this->db->lastInsertId($seq);
}
@ -847,7 +677,7 @@ class Database {
* @param string $name
* @param string $data
*/
public function create_table($name, $data) {
public function create_table(string $name, string $data) {
if(is_null($this->engine)) { $this->connect_engine(); }
$data = trim($data, ", \t\n\r\0\x0B"); // mysql doesn't like trailing commas
$this->execute($this->engine->create_table_sql($name, $data));
@ -856,27 +686,26 @@ class Database {
/**
* Returns the number of tables present in the current database.
*
* @return int|null
* @return int
* @throws SCoreException
*/
public function count_tables() {
public function count_tables(): int {
if(is_null($this->db) || is_null($this->engine)) $this->connect_db();
if($this->engine->name === "mysql") {
return count(
$this->get_all("SHOW TABLES")
);
$this->get_all("SHOW TABLES")
);
} else if ($this->engine->name === "pgsql") {
return count(
$this->get_all("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'")
);
$this->get_all("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'")
);
} else if ($this->engine->name === "sqlite") {
return count(
$this->get_all("SELECT name FROM sqlite_master WHERE type = 'table'")
);
$this->get_all("SELECT name FROM sqlite_master WHERE type = 'table'")
);
} else {
// Hard to find a universal way to do this...
return NULL;
throw new SCoreException("Can't count tables for database type {$this->engine->name}");
}
}
}
@ -889,20 +718,20 @@ class MockDatabase extends Database {
/** @var \NoCache|null */
public $cache = null;
/**
* @param array $responses
*/
public function __construct($responses = array()) {
public function __construct(array $responses = array()) {
$this->cache = new NoCache();
$this->responses = $responses;
}
/**
* @param string $query
* @param array $params
* @return PDOStatement
*/
public function execute($query, $params=array()) {
public function execute(string $query, array $params=array()): PDOStatement {
log_debug("mock-database",
"QUERY: " . $query .
"\nARGS: " . var_export($params, true) .
"\nRETURN: " . var_export($this->responses[$this->query_id], true)
);
return $this->responses[$this->query_id++];
}
public function _execute(string $query, array $params=array()) {
log_debug("mock-database",
"QUERY: " . $query .
"\nARGS: " . var_export($params, true) .
@ -911,53 +740,16 @@ class MockDatabase extends Database {
return $this->responses[$this->query_id++];
}
/**
* @param string $query
* @param array $args
* @return PDOStatement
*/
public function get_all($query, $args=array()) {return $this->execute($query, $args);}
public function get_all(string $query, array $args=array()): array {return $this->_execute($query, $args);}
public function get_row(string $query, array $args=array()) {return $this->_execute($query, $args);}
public function get_col(string $query, array $args=array()): array {return $this->_execute($query, $args);}
public function get_pairs(string $query, array $args=array()): array {return $this->_execute($query, $args);}
public function get_one(string $query, array $args=array()) {return $this->_execute($query, $args);}
/**
* @param string $query
* @param array $args
* @return PDOStatement
*/
public function get_row($query, $args=array()) {return $this->execute($query, $args);}
public function get_last_insert_id(string $seq): int {return $this->query_id;}
/**
* @param string $query
* @param array $args
* @return PDOStatement
*/
public function get_col($query, $args=array()) {return $this->execute($query, $args);}
/**
* @param string $query
* @param array $args
* @return PDOStatement
*/
public function get_pairs($query, $args=array()) {return $this->execute($query, $args);}
/**
* @param string $query
* @param array $args
* @return PDOStatement
*/
public function get_one($query, $args=array()) {return $this->execute($query, $args);}
/**
* @param null|string $seq
* @return int|string
*/
public function get_last_insert_id($seq) {return $this->query_id;}
/**
* @param string $sql
* @return string
*/
public function scoreql_to_sql($sql) {return $sql;}
public function create_table($name, $def) {}
public function scoreql_to_sql(string $sql): string {return $sql;}
public function create_table(string $name, string $def) {}
public function connect_engine() {}
}

View File

@ -29,13 +29,7 @@ class Email {
/** @var null|string */
public $footer;
/**
* @param string $to
* @param string $subject
* @param string $header
* @param string $body
*/
public function __construct($to, $subject, $header, $body) {
public function __construct(string $to, string $subject, string $header, string $body) {
global $config;
$this->to = $to;
@ -60,7 +54,7 @@ class Email {
$this->footer = $config->get_string("mail_fot");
}
public function send() {
public function send(): bool {
$headers = "From: ".$this->sitename." <".$this->siteemail.">\r\n";
$headers .= "Reply-To: ".$this->siteemail."\r\n";
$headers .= "X-Mailer: PHP/" . phpversion(). "\r\n";
@ -84,7 +78,7 @@ class Email {
<table width="550" cellpadding="0" cellspacing="0">
<tr>
<td style="background-color:#FFFFFF;border-top:0px solid #333333;border-bottom:10px solid #FFFFFF;"><center><a href="'.$this->sitedomain.'"><IMG SRC="'.$this->header_img.'" alt="'.$this->sitename.'" name="Header" BORDER="0" align="center" title="'.$this->sitename.'"></a>
<td style="background-color:#FFFFFF;border-top:0 solid #333333;border-bottom:10px solid #FFFFFF;"><center><a href="'.$this->sitedomain.'"><IMG SRC="'.$this->header_img.'" alt="'.$this->sitename.'" name="Header" BORDER="0" align="center" title="'.$this->sitename.'"></a>
</center></td>
</tr>

View File

@ -43,10 +43,7 @@ class PageRequestEvent extends Event {
*/
public $part_count;
/**
* @param string $path
*/
public function __construct($path) {
public function __construct(string $path) {
global $config;
// trim starting slashes
@ -82,7 +79,7 @@ class PageRequestEvent extends Event {
* @param string $name
* @return bool
*/
public function page_matches(/*string*/ $name) {
public function page_matches(string $name): bool {
$parts = explode("/", $name);
$this->part_count = count($parts);
@ -105,7 +102,7 @@ class PageRequestEvent extends Event {
* @param int $n
* @return string|null The argument (string) or NULL
*/
public function get_arg(/*int*/ $n) {
public function get_arg(int $n) {
$offset = $this->part_count + $n;
if($offset >= 0 && $offset < $this->arg_count) {
return $this->args[$offset];
@ -119,7 +116,7 @@ class PageRequestEvent extends Event {
* Returns the number of arguments the page request has.
* @return int
*/
public function count_args() {
public function count_args(): int {
return int_escape($this->arg_count - $this->part_count);
}
@ -127,10 +124,7 @@ class PageRequestEvent extends Event {
* Many things use these functions
*/
/**
* @return array
*/
public function get_search_terms() {
public function get_search_terms(): array {
$search_terms = array();
if($this->count_args() === 2) {
$search_terms = Tag::explode($this->get_arg(0));
@ -138,10 +132,7 @@ class PageRequestEvent extends Event {
return $search_terms;
}
/**
* @return int
*/
public function get_page_number() {
public function get_page_number(): int {
$page_number = 1;
if($this->count_args() === 1) {
$page_number = int_escape($this->get_arg(0));
@ -153,10 +144,7 @@ class PageRequestEvent extends Event {
return $page_number;
}
/**
* @return int
*/
public function get_page_size() {
public function get_page_size(): int {
global $config;
return $config->get_int('index_images');
}
@ -180,7 +168,7 @@ class CommandEvent extends Event {
/**
* @param string[] $args
*/
public function __construct(/*array(string)*/ $args) {
public function __construct(array $args) {
global $user;
$opts = array();
@ -257,10 +245,7 @@ class TextFormattingEvent extends Event {
*/
public $stripped;
/**
* @param string $text
*/
public function __construct(/*string*/ $text) {
public function __construct(string $text) {
$h_text = html_escape(trim($text));
$this->original = $h_text;
$this->formatted = $h_text;
@ -308,13 +293,7 @@ class LogEvent extends Event {
*/
public $args;
/**
* @param string $section
* @param int $priority
* @param string $message
* @param array $args
*/
public function __construct($section, $priority, $message, $args) {
public function __construct(string $section, int $priority, string $message, array $args) {
$this->section = $section;
$this->priority = $priority;
$this->message = $message;

View File

@ -92,10 +92,7 @@ abstract class Extension {
$this->theme = $this->get_theme_object(get_called_class());
}
/**
* @return boolean
*/
public function is_live() {
public function is_live(): bool {
global $database;
return (
empty($this->db_support) ||
@ -107,9 +104,9 @@ abstract class Extension {
* Find the theme object for a given extension.
*
* @param string $base
* @return Themelet
* @return Themelet|null
*/
private function get_theme_object($base) {
private function get_theme_object(string $base) {
$custom = 'Custom'.$base.'Theme';
$normal = $base.'Theme';
@ -126,11 +123,10 @@ abstract class Extension {
/**
* Override this to change the priority of the extension,
* lower numbered ones will recieve events first.
*
* lower numbered ones will receive events first.
* @return int
*/
public function get_priority() {
public function get_priority(): int {
return 50;
}
}
@ -141,25 +137,13 @@ abstract class Extension {
* Several extensions have this in common, make a common API.
*/
abstract class FormatterExtension extends Extension {
/**
* @param TextFormattingEvent $event
*/
public function onTextFormatting(TextFormattingEvent $event) {
$event->formatted = $this->format($event->formatted);
$event->stripped = $this->strip($event->stripped);
}
/**
* @param string $text
* @return string
*/
abstract public function format(/*string*/ $text);
/**
* @param string $text
* @return string
*/
abstract public function strip(/*string*/ $text);
abstract public function format(string $text): string;
abstract public function strip(string $text): string;
}
/**
@ -169,10 +153,6 @@ abstract class FormatterExtension extends Extension {
* so we have a base class to extend from.
*/
abstract class DataHandlerExtension extends Extension {
/**
* @param DataUploadEvent $event
* @throws UploadException
*/
public function onDataUpload(DataUploadEvent $event) {
$supported_ext = $this->supported_ext($event->type);
$check_contents = $this->check_contents($event->tmpname);
@ -236,9 +216,6 @@ abstract class DataHandlerExtension extends Extension {
}
}
/**
* @param ThumbnailGenerationEvent $event
*/
public function onThumbnailGeneration(ThumbnailGenerationEvent $event) {
if($this->supported_ext($event->type)) {
if (method_exists($this, 'create_thumb_force') && $event->force == true) {
@ -250,9 +227,6 @@ abstract class DataHandlerExtension extends Extension {
}
}
/**
* @param DisplayingImageEvent $event
*/
public function onDisplayingImage(DisplayingImageEvent $event) {
global $page;
if($this->supported_ext($event->image->ext)) {
@ -269,29 +243,9 @@ abstract class DataHandlerExtension extends Extension {
protected function setup() {}
*/
/**
* @param string $ext
* @return bool
*/
abstract protected function supported_ext($ext);
/**
* @param string $tmpname
* @return bool
*/
abstract protected function check_contents($tmpname);
/**
* @param string $filename
* @param array $metadata
* @return Image|null
*/
abstract protected function create_image_from_data($filename, $metadata);
/**
* @param string $hash
* @return bool
*/
abstract protected function create_thumb($hash);
abstract protected function supported_ext(string $ext): bool;
abstract protected function check_contents(string $tmpname): bool;
abstract protected function create_image_from_data(string $filename, array $metadata);
abstract protected function create_thumb(string $hash): bool;
}

View File

@ -72,17 +72,15 @@ class Image {
public $source;
/** @var boolean */
public $locked;
public $locked = false;
/**
* One will very rarely construct an image directly, more common
* would be to use Image::by_id, Image::by_hash, etc.
*
* @param null|mixed $row
* @param null|mixed[] $row
*/
public function __construct($row=null) {
assert('is_null($row) || is_array($row)');
public function __construct(array $row=null) {
if(!is_null($row)) {
foreach($row as $name => $value) {
// some databases use table.name rather than name
@ -97,40 +95,19 @@ class Image {
}
}
/**
* Find an image by ID.
*
* @param int $id
* @return Image
*/
public static function by_id(/*int*/ $id) {
assert('is_numeric($id)');
public static function by_id(int $id) {
global $database;
$row = $database->get_row("SELECT * FROM images WHERE images.id=:id", array("id"=>$id));
return ($row ? new Image($row) : null);
}
/**
* Find an image by hash.
*
* @param string $hash
* @return Image
*/
public static function by_hash(/*string*/ $hash) {
assert('is_string($hash)');
public static function by_hash(string $hash) {
global $database;
$row = $database->get_row("SELECT images.* FROM images WHERE hash=:hash", array("hash"=>$hash));
return ($row ? new Image($row) : null);
}
/**
* Pick a random image out of a set.
*
* @param string[] $tags
* @return Image
*/
public static function by_random($tags=array()) {
assert('is_array($tags)');
public static function by_random(array $tags=array()) {
$max = Image::count_images($tags);
if ($max < 1) return null; // From Issue #22 - opened by HungryFeline on May 30, 2011.
$rand = mt_rand(0, $max-1);
@ -148,10 +125,7 @@ class Image {
* @throws SCoreException
* @return Image[]
*/
public static function find_images(/*int*/ $start, /*int*/ $limit, $tags=array()) {
assert('is_numeric($start)');
assert('is_numeric($limit)');
assert('is_array($tags)');
public static function find_images(int $start, int $limit, array $tags=array()): array {
global $database, $user, $config;
$images = array();
@ -185,11 +159,7 @@ class Image {
return $images;
}
/**
* @param string[] $tags
* @return boolean
*/
public static function validate_accel($tags) {
public static function validate_accel(array $tags): bool {
$yays = 0;
$nays = 0;
foreach($tags as $tag) {
@ -202,14 +172,7 @@ class Image {
return ($yays > 1 || $nays > 0);
}
/**
* @param string[] $tags
* @param int $offset
* @param int $limit
* @return null|PDOStatement
* @throws SCoreException
*/
public static function get_accelerated_result($tags, $offset, $limit) {
public static function get_accelerated_result(array $tags, int $offset, int $limit) {
global $database;
if(!Image::validate_accel($tags)) {
@ -262,15 +225,14 @@ class Image {
* @param string[] $tags
* @return int
*/
public static function count_images($tags=array()) {
assert('is_array($tags)');
public static function count_images(array $tags=array()): int {
global $database;
$tag_count = count($tags);
if($tag_count === 0) {
$total = $database->cache->get("image-count");
if(!$total) {
$total = $database->get_one("SELECT COUNT(*) FROM images");
$total = $database->get_one("SELECT COUNT(*) FROM images") || 0;
$database->cache->set("image-count", $total, 600);
}
return $total;
@ -278,11 +240,11 @@ class Image {
else if($tag_count === 1 && !preg_match("/[:=><\*\?]/", $tags[0])) {
return $database->get_one(
$database->scoreql_to_sql("SELECT count FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(:tag)"),
array("tag"=>$tags[0]));
array("tag"=>$tags[0])) || 0;
}
else {
$querylet = Image::build_search_querylet($tags);
return $database->get_one("SELECT COUNT(*) AS cnt FROM ($querylet->sql) AS tbl", $querylet->variables);
return $database->get_one("SELECT COUNT(*) AS cnt FROM ($querylet->sql) AS tbl", $querylet->variables) || 0;
}
}
@ -292,8 +254,7 @@ class Image {
* @param string[] $tags
* @return float
*/
public static function count_pages($tags=array()) {
assert('is_array($tags)');
public static function count_pages(array $tags=array()): float {
global $config;
return ceil(Image::count_images($tags) / $config->get_int('index_images'));
}
@ -312,9 +273,7 @@ class Image {
* @param bool $next
* @return Image
*/
public function get_next($tags=array(), $next=true) {
assert('is_array($tags)');
assert('is_bool($next)');
public function get_next(array $tags=array(), bool $next=true) {
global $database;
if($next) {
@ -351,7 +310,7 @@ class Image {
* @param string[] $tags
* @return Image
*/
public function get_prev($tags=array()) {
public function get_prev(array $tags=array()) {
return $this->get_next($tags, false);
}
@ -543,7 +502,7 @@ class Image {
*
* @param string $new_source
*/
public function set_source(/*string*/ $new_source) {
public function set_source(string $new_source) {
global $database;
$old_source = $this->source;
if(empty($new_source)) $new_source = null;
@ -617,8 +576,8 @@ class Image {
* @param string[] $tags
* @throws Exception
*/
public function set_tags($tags) {
assert('is_array($tags) && count($tags) > 0', var_export($tags, true));
public function set_tags(array $tags) {
assert('count($tags) > 0', var_export($tags, true));
global $database;
if(count($tags) <= 0) {
@ -793,8 +752,7 @@ class Image {
* @param string[] $terms
* @return \Querylet
*/
private static function build_search_querylet($terms) {
assert('is_array($terms)');
private static function build_search_querylet(array $terms): Querylet {
global $database;
$tag_querylets = array();
@ -936,7 +894,7 @@ class Image {
* @param TagQuerylet[] $tag_querylets
* @return Querylet
*/
private static function build_accurate_search_querylet($tag_querylets) {
private static function build_accurate_search_querylet(array $tag_querylets): Querylet {
global $database;
$positive_tag_id_array = array();
@ -1081,13 +1039,7 @@ class Image {
*
*/
class Tag {
/**
* @param string[] $tags
* @return string
*/
public static function implode($tags) {
assert('is_array($tags)');
public static function implode(array $tags): string {
sort($tags);
$tags = implode(' ', $tags);
@ -1101,9 +1053,8 @@ class Tag {
* @param bool $tagme add "tagme" if the string is empty
* @return string[]
*/
public static function explode($tags, $tagme=true) {
public static function explode(string $tags, bool $tagme=true): array {
global $database;
assert('is_string($tags)');
$tags = explode(' ', trim($tags));
@ -1267,7 +1218,7 @@ function add_image($tmpname, $filename, $tags) {
* @param int $orig_height
* @return integer[]
*/
function get_thumbnail_size(/*int*/ $orig_width, /*int*/ $orig_height) {
function get_thumbnail_size(int $orig_width, int $orig_height) {
global $config;
if($orig_width === 0) $orig_width = 192;

View File

@ -47,7 +47,7 @@ class Page {
* Set what this page should do; "page", "data", or "redirect".
* @param string $mode
*/
public function set_mode($mode) {
public function set_mode(string $mode) {
$this->mode = $mode;
}
@ -55,7 +55,7 @@ class Page {
* Set the page's MIME type.
* @param string $type
*/
public function set_type($type) {
public function set_type(string $type) {
$this->type = $type;
}
@ -75,7 +75,7 @@ class Page {
* Set the raw data to be sent.
* @param string $data
*/
public function set_data($data) {
public function set_data(string $data) {
$this->data = $data;
}
@ -83,7 +83,7 @@ class Page {
* Set the recommended download filename.
* @param string $filename
*/
public function set_filename($filename) {
public function set_filename(string $filename) {
$this->filename = $filename;
}
@ -101,7 +101,7 @@ class Page {
* to a page in the same site).
* @param string $redirect
*/
public function set_redirect($redirect) {
public function set_redirect(string $redirect) {
$this->redirect = $redirect;
}
@ -142,31 +142,19 @@ class Page {
* Set the HTTP status code
* @param int $code
*/
public function set_code($code) {
public function set_code(int $code) {
$this->code = $code;
}
/**
* Set the window title.
* @param string $title
*/
public function set_title($title) {
public function set_title(string $title) {
$this->title = $title;
}
/**
* Set the main heading.
* @param string $heading
*/
public function set_heading($heading) {
public function set_heading(string $heading) {
$this->heading = $heading;
}
/**
* Set the sub heading.
* @param string $subheading
*/
public function set_subheading($subheading) {
public function set_subheading(string $subheading) {
$this->subheading = $subheading;
}
@ -175,7 +163,7 @@ class Page {
* @param string $line
* @param int $position
*/
public function add_html_header($line, $position=50) {
public function add_html_header(string $line, int $position=50) {
while(isset($this->html_headers[$position])) $position++;
$this->html_headers[$position] = $line;
}
@ -185,7 +173,7 @@ class Page {
* @param string $line
* @param int $position
*/
public function add_http_header($line, $position=50) {
public function add_http_header(string $line, int $position=50) {
while(isset($this->http_headers[$position])) $position++;
$this->http_headers[$position] = $line;
}
@ -200,7 +188,7 @@ class Page {
* @param int $time
* @param string $path
*/
public function add_cookie($name, $value, $time, $path) {
public function add_cookie(string $name, $value, $time, $path) {
$full_name = COOKIE_PREFIX."_".$name;
$this->cookies[] = array($full_name, $value, $time, $path);
}
@ -209,7 +197,7 @@ class Page {
* @param string $name
* @return string|null
*/
public function get_cookie(/*string*/ $name) {
public function get_cookie(string $name) {
$full_name = COOKIE_PREFIX."_".$name;
if(isset($_COOKIE[$full_name])) {
return $_COOKIE[$full_name];
@ -223,7 +211,7 @@ class Page {
* Get all the HTML headers that are currently set and return as a string.
* @return string
*/
public function get_all_html_headers() {
public function get_all_html_headers(): string {
$data = '';
ksort($this->html_headers);
foreach ($this->html_headers as $line) {

View File

@ -19,8 +19,7 @@
*
*/
/** @private */
function _d($name, $value) {if(!defined($name)) define($name, $value);}
function _d(string $name, $value) {if(!defined($name)) define($name, $value);}
_d("DATABASE_DSN", null); // string PDO database connection details
_d("DATABASE_KA", true); // string Keep database connection alive
_d("CACHE_DSN", null); // string cache connection details
@ -36,12 +35,12 @@ _d("COMPILE_ELS", false); // boolean pre-build the list of event listeners
_d("NICE_URLS", false); // boolean force niceurl mode
_d("SEARCH_ACCEL", false); // boolean use search accelerator
_d("WH_SPLITS", 1); // int how many levels of subfolders to put in the warehouse
_d("VERSION", '2.6.0+'); // string shimmie version
_d("VERSION", '2.7-beta'); // string shimmie version
_d("TIMEZONE", null); // string timezone
_d("CORE_EXTS", "bbcode,user,mail,upload,image,view,handle_pixel,ext_manager,setup,upgrade,handle_404,comment,tag_list,index,tag_edit,alias_editor"); // extensions to always enable
_d("EXTRA_EXTS", ""); // string optional extra extensions
_d("BASE_URL", null); // string force a specific base URL (default is auto-detect)
_d("MIN_PHP_VERSION", '5.6');// string minium supported PHP version
_d("MIN_PHP_VERSION", '7.0');// string minium supported PHP version
/*
* Calculated settings - you should never need to change these

View File

@ -48,10 +48,10 @@ class User {
* One will very rarely construct a user directly, more common
* would be to use User::by_id, User::by_session, etc.
*
* @param mixed $row
* @param mixed[] $row
* @throws SCoreException
*/
public function __construct($row) {
public function __construct(array $row) {
global $_shm_user_classes;
$this->id = int_escape($row['id']);
@ -68,14 +68,7 @@ class User {
}
}
/**
* Construct a User by session.
*
* @param string $name
* @param string $session
* @return null|User
*/
public static function by_session(/*string*/ $name, /*string*/ $session) {
public static function by_session(string $name, string $session) {
global $config, $database;
$row = $database->cache->get("user-session:$name-$session");
if(!$row) {
@ -91,13 +84,7 @@ class User {
return is_null($row) ? null : new User($row);
}
/**
* Construct a User by session.
* @param int $id
* @return null|User
*/
public static function by_id(/*int*/ $id) {
assert('is_numeric($id)', var_export($id, true));
public static function by_id(int $id) {
global $database;
if($id === 1) {
$cached = $database->cache->get('user-id:'.$id);
@ -108,27 +95,13 @@ class User {
return is_null($row) ? null : new User($row);
}
/**
* Construct a User by name.
* @param string $name
* @return null|User
*/
public static function by_name(/*string*/ $name) {
assert('is_string($name)', var_export($name, true));
public static function by_name(string $name) {
global $database;
$row = $database->get_row($database->scoreql_to_sql("SELECT * FROM users WHERE SCORE_STRNORM(name) = SCORE_STRNORM(:name)"), array("name"=>$name));
return is_null($row) ? null : new User($row);
}
/**
* Construct a User by name and password.
* @param string $name
* @param string $pass
* @return null|User
*/
public static function by_name_and_pass(/*string*/ $name, /*string*/ $pass) {
assert('is_string($name)', var_export($name, true));
assert('is_string($pass)', var_export($pass, true));
public static function by_name_and_pass(string $name, string $pass) {
$user = User::by_name($name);
if($user) {
if($user->passhash == md5(strtolower($name) . $pass)) {
@ -138,65 +111,38 @@ class User {
return $user;
}
}
return null;
}
/* useful user object functions start here */
/**
* @param string $ability
* @return bool
*/
public function can($ability) {
public function can(string $ability): bool {
return $this->class->can($ability);
}
/**
* Test if this user is anonymous (not logged in).
*
* @return bool
*/
public function is_anonymous() {
public function is_anonymous(): bool {
global $config;
return ($this->id === $config->get_int('anon_id'));
}
/**
* Test if this user is logged in.
*
* @return bool
*/
public function is_logged_in() {
public function is_logged_in(): bool {
global $config;
return ($this->id !== $config->get_int('anon_id'));
}
/**
* Test if this user is an administrator.
*
* @return bool
*/
public function is_admin() {
public function is_admin(): bool {
return ($this->class->name === "admin");
}
/**
* @param string $class
*/
public function set_class(/*string*/ $class) {
assert('is_string($class)', var_export($class, true));
public function set_class(string $class) {
global $database;
$database->Execute("UPDATE users SET class=:class WHERE id=:id", array("class"=>$class, "id"=>$this->id));
log_info("core-user", 'Set class for '.$this->name.' to '.$class);
}
/**
* @param string $name
* @throws Exception
*/
public function set_name(/*string*/ $name) {
public function set_name(string $name) {
global $database;
if(User::by_name($name)) {
throw new Exception("Desired username is already in use");
@ -207,10 +153,7 @@ class User {
log_info("core-user", "Changed username for {$old_name} to {$this->name}");
}
/**
* @param string $password
*/
public function set_password(/*string*/ $password) {
public function set_password(string $password) {
global $database;
$hash = password_hash($password, PASSWORD_BCRYPT);
if(is_string($hash)) {
@ -223,10 +166,7 @@ class User {
}
}
/**
* @param string $address
*/
public function set_email(/*string*/ $address) {
public function set_email(string $address) {
global $database;
$database->Execute("UPDATE users SET email=:email WHERE id=:id", array("email"=>$address, "id"=>$this->id));
log_info("core-user", 'Set email for '.$this->name);
@ -238,7 +178,7 @@ class User {
*
* @return String of HTML
*/
public function get_avatar_html() {
public function get_avatar_html(): string {
// FIXME: configurable
global $config;
if($config->get_string("avatar_host") === "gravatar") {
@ -267,25 +207,25 @@ class User {
*
* @return string A string containing auth token (MD5sum)
*/
public function get_auth_token() {
public function get_auth_token(): string {
global $config;
$salt = DATABASE_DSN;
$addr = get_session_ip($config);
return md5(md5($this->passhash . $addr) . "salty-csrf-" . $salt);
}
public function get_auth_html() {
public function get_auth_html(): string {
$at = $this->get_auth_token();
return '<input type="hidden" name="auth_token" value="'.$at.'">';
}
public function check_auth_token() {
public function check_auth_token(): bool {
return (isset($_POST["auth_token"]) && $_POST["auth_token"] == $this->get_auth_token());
}
}
class MockUser extends User {
public function __construct($name) {
public function __construct(string $name) {
$row = array(
"name" => $name,
"id" => 1,

View File

@ -25,12 +25,7 @@ class UserClass {
*/
public $abilities = array();
/**
* @param string $name
* @param null|string $parent
* @param array $abilities
*/
public function __construct($name, $parent=null, $abilities=array()) {
public function __construct(string $name, string $parent=null, array $abilities=array()) {
global $_shm_user_classes;
$this->name = $name;
@ -50,7 +45,7 @@ class UserClass {
* @return bool
* @throws SCoreException
*/
public function can(/*string*/ $ability) {
public function can(string $ability): bool {
if(array_key_exists($ability, $this->abilities)) {
$val = $this->abilities[$ability];
return $val;

View File

@ -1,5 +1,5 @@
<?php
require_once "lib/context.php";
require_once "vendor/shish/libcontext-php/context.php";
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\
* Input / Output Sanitising *
@ -11,7 +11,7 @@ require_once "lib/context.php";
* @param string $input
* @return string
*/
function html_escape($input) {
function html_escape($input): string {
return htmlentities($input, ENT_QUOTES, "UTF-8");
}
@ -21,7 +21,7 @@ function html_escape($input) {
* @param string $input
* @return string
*/
function html_unescape($input) {
function html_unescape($input): string {
return html_entity_decode($input, ENT_QUOTES, "UTF-8");
}
@ -31,7 +31,7 @@ function html_unescape($input) {
* @param string $input
* @return int
*/
function int_escape($input) {
function int_escape($input): int {
/*
Side note, Casting to an integer is FASTER than using intval.
http://hakre.wordpress.com/2010/05/13/php-casting-vs-intval/
@ -45,7 +45,7 @@ function int_escape($input) {
* @param string $input
* @return string
*/
function url_escape($input) {
function url_escape($input): string {
/*
Shish: I have a feeling that these three lines are important, possibly for searching for tags with slashes in them like fate/stay_night
green-ponies: indeed~
@ -80,7 +80,7 @@ function url_escape($input) {
* @param string $input
* @return string
*/
function sql_escape($input) {
function sql_escape($input): string {
global $database;
return $database->escape($input);
}
@ -92,7 +92,7 @@ function sql_escape($input) {
* @param mixed $input
* @return boolean
*/
function bool_escape($input) {
function bool_escape($input): bool {
/*
Sometimes, I don't like PHP -- this, is one of those times...
"a boolean FALSE is not considered a valid boolean value by this function."
@ -132,13 +132,7 @@ function no_escape($input) {
return $input;
}
/**
* @param int $val
* @param int|null $min
* @param int|null $max
* @return int
*/
function clamp($val, $min, $max) {
function clamp(int $val, int $min=null, int $max=null): int {
if(!is_numeric($val) || (!is_null($min) && $val < $min)) {
$val = $min;
}
@ -151,13 +145,7 @@ function clamp($val, $min, $max) {
return $val;
}
/**
* @param string $name
* @param array $attrs
* @param array $children
* @return string
*/
function xml_tag($name, $attrs=array(), $children=array()) {
function xml_tag(string $name, array $attrs=array(), array $children=array()): string {
$xml = "<$name ";
foreach($attrs as $k => $v) {
$xv = str_replace('&#039;', '&apos;', htmlspecialchars($v, ENT_QUOTES));
@ -184,6 +172,7 @@ function xml_tag($name, $attrs=array(), $children=array()) {
* @param int $limit how long the string should be
* @param string $break where to break the string
* @param string $pad what to add to the end of the string after truncating
* @return string
*/
function truncate($string, $limit, $break=" ", $pad="...") {
// return with no change if string is shorter than $limit
@ -202,14 +191,10 @@ function truncate($string, $limit, $break=" ", $pad="...") {
/**
* Turn a human readable filesize into an integer, eg 1KB -> 1024
*
* @param string|integer $limit
* @param string $limit
* @return int
*/
function parse_shorthand_int($limit) {
if(is_numeric($limit)) {
return (int)$limit;
}
function parse_shorthand_int(string $limit): int {
if(preg_match('/^([\d\.]+)([gmk])?b?$/i', (string)$limit, $m)) {
$value = $m[1];
if (isset($m[2])) {
@ -235,7 +220,7 @@ function parse_shorthand_int($limit) {
* @param integer $int
* @return string
*/
function to_shorthand_int($int) {
function to_shorthand_int(int $int): string {
if($int >= pow(1024, 3)) {
return sprintf("%.1fGB", $int / pow(1024, 3));
}
@ -258,7 +243,7 @@ function to_shorthand_int($int) {
* @param bool $html
* @return string
*/
function autodate($date, $html=true) {
function autodate(string $date, bool $html=true): string {
$cpu = date('c', strtotime($date));
$hum = date('F j, Y; H:i', strtotime($date));
return ($html ? "<time datetime='$cpu'>$hum</time>" : $hum);
@ -270,7 +255,7 @@ function autodate($date, $html=true) {
* @param string $dateTime
* @return bool
*/
function isValidDateTime($dateTime) {
function isValidDateTime(string $dateTime): bool {
if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)) {
if (checkdate($matches[2], $matches[3], $matches[1])) {
return true;
@ -286,7 +271,7 @@ function isValidDateTime($dateTime) {
* @param string $date
* @return bool
*/
function isValidDate($date) {
function isValidDate(string $date): bool {
if (preg_match("/^(\d{4})-(\d{2})-(\d{2})$/", $date, $matches)) {
// checkdate wants (month, day, year)
if (checkdate($matches[2], $matches[3], $matches[1])) {
@ -297,10 +282,7 @@ function isValidDate($date) {
return false;
}
/**
* @param string[] $inputs
*/
function validate_input($inputs) {
function validate_input(array $inputs): array {
$outputs = array();
foreach($inputs as $key => $validations) {
@ -398,7 +380,7 @@ function validate_input($inputs) {
* @param string $ban_reason
* @return string
*/
function show_ip($ip, $ban_reason) {
function show_ip(string $ip, string $ban_reason): string {
global $user;
$u_reason = url_escape($ban_reason);
$u_end = url_escape("+1 week");
@ -407,26 +389,12 @@ function show_ip($ip, $ban_reason) {
return $ip;
}
/**
* Checks if a given string contains another at the beginning.
*
* @param string $haystack String to examine.
* @param string $needle String to look for.
* @return bool
*/
function startsWith(/*string*/ $haystack, /*string*/ $needle) {
function startsWith(string $haystack, string $needle): bool {
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
/**
* Checks if a given string contains another at the end.
*
* @param string $haystack String to examine.
* @param string $needle String to look for.
* @return bool
*/
function endsWith(/*string*/ $haystack, /*string*/ $needle) {
function endsWith(string $haystack, string $needle): bool {
$length = strlen($needle);
$start = $length * -1; //negative
return (substr($haystack, $start) === $needle);
@ -446,7 +414,7 @@ function endsWith(/*string*/ $haystack, /*string*/ $needle) {
* @param null|string $query
* @return string
*/
function make_link($page=null, $query=null) {
function make_link(string $page=null, string $query=null): string {
global $config;
if(is_null($page)) $page = $config->get_string('main_page');
@ -481,14 +449,14 @@ function make_link($page=null, $query=null) {
/**
* Take the current URL and modify some parameters
*
* @param $changes
* @param array $changes
* @return string
*/
function modify_current_url($changes) {
function modify_current_url(array $changes): string {
return modify_url($_SERVER['QUERY_STRING'], $changes);
}
function modify_url($url, $changes) {
function modify_url(string $url, array $changes): string {
// SHIT: PHP is officially the worst web API ever because it does not
// have a built-in function to do this.
@ -526,7 +494,7 @@ function modify_url($url, $changes) {
* @param string $link
* @return string
*/
function make_http(/*string*/ $link) {
function make_http(string $link) {
if(strpos($link, "://") > 0) {
return $link;
}
@ -553,7 +521,7 @@ function make_http(/*string*/ $link) {
*
* @return string
*/
function make_form($target, $method="POST", $multipart=False, $form_id="", $onsubmit="") {
function make_form(string $target, string $method="POST", bool $multipart=False, string $form_id="", string $onsubmit=""): string {
global $user;
if($method == "GET") {
$link = html_escape($target);
@ -578,7 +546,7 @@ function make_form($target, $method="POST", $multipart=False, $form_id="", $onsu
* @param string $file The filename
* @return string
*/
function mtimefile($file) {
function mtimefile(string $file): string {
$data_href = get_base_href();
$mtime = filemtime($file);
return "$data_href/$file?$mtime";
@ -589,7 +557,7 @@ function mtimefile($file) {
*
* @return string
*/
function get_theme() {
function get_theme(): string {
global $config;
$theme = $config->get_string("theme", "default");
if(!file_exists("themes/$theme")) $theme = "default";
@ -602,7 +570,7 @@ function get_theme() {
* @param string $pattern
* @return array
*/
function zglob($pattern) {
function zglob(string $pattern): array {
$results = array();
if(preg_match('/(.*)\{(.*)\}(.*)/', $pattern, $matches)) {
$braced = explode(",", $matches[2]);
@ -621,11 +589,13 @@ function zglob($pattern) {
/**
* Gets contact link as mailto: or http:
* @return string
* @return string|null
*/
function contact_link() {
global $config;
$text = $config->get_string('contact_link');
if(is_null($text)) return null;
if(
startsWith($text, "http:") ||
startsWith($text, "https:") ||
@ -650,10 +620,7 @@ function contact_link() {
* CAPTCHA abstraction *
\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* @return string
*/
function captcha_get_html() {
function captcha_get_html(): string {
global $config, $user;
if(DEBUG && ip_in_range($_SERVER['REMOTE_ADDR'], "127.0.0.0/8")) return "";
@ -673,10 +640,7 @@ function captcha_get_html() {
return $captcha;
}
/**
* @return bool
*/
function captcha_check() {
function captcha_check(): bool {
global $config, $user;
if(DEBUG && ip_in_range($_SERVER['REMOTE_ADDR'], "127.0.0.0/8")) return true;
@ -715,10 +679,27 @@ function captcha_check() {
*
* @return bool True if HTTPS is enabled
*/
function is_https_enabled() {
function is_https_enabled(): bool {
return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
}
define("MIME_TYPE_MAP", [
'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png',
'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'ico' => 'image/x-icon',
'swf' => 'application/x-shockwave-flash', 'video/x-flv' => 'flv',
'svg' => 'image/svg+xml', 'pdf' => 'application/pdf',
'zip' => 'application/zip', 'gz' => 'application/x-gzip',
'tar' => 'application/x-tar', 'bz' => 'application/x-bzip',
'bz2' => 'application/x-bzip2', 'txt' => 'text/plain',
'asc' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html',
'css' => 'text/css', 'js' => 'text/javascript',
'xml' => 'text/xml', 'xsl' => 'application/xsl+xml',
'ogg' => 'application/ogg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav',
'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg',
'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php',
'mp4' => 'video/mp4', 'ogv' => 'video/ogg', 'webm' => 'video/webm'
]);
/**
* Get MIME type for file
*
@ -728,33 +709,13 @@ function is_https_enabled() {
*
* @param string $file File path
* @param string $ext
* @param bool $list
* @return string
*/
function getMimeType($file, $ext="", $list=false) {
function getMimeType(string $file, string $ext=""): string {
// Static extension lookup
$ext = strtolower($ext);
static $exts = array(
'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png',
'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'ico' => 'image/x-icon',
'swf' => 'application/x-shockwave-flash', 'video/x-flv' => 'flv',
'svg' => 'image/svg+xml', 'pdf' => 'application/pdf',
'zip' => 'application/zip', 'gz' => 'application/x-gzip',
'tar' => 'application/x-tar', 'bz' => 'application/x-bzip',
'bz2' => 'application/x-bzip2', 'txt' => 'text/plain',
'asc' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html',
'css' => 'text/css', 'js' => 'text/javascript',
'xml' => 'text/xml', 'xsl' => 'application/xsl+xml',
'ogg' => 'application/ogg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav',
'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg',
'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php',
'mp4' => 'video/mp4', 'ogv' => 'video/ogg', 'webm' => 'video/webm'
);
if ($list === true){ return $exts; }
if (isset($exts[$ext])) { return $exts[$ext]; }
if (isset($exts[$ext])) { return MIME_TYPE_MAP[$ext]; }
$type = false;
// Fileinfo documentation says fileinfo_open() will use the
@ -785,13 +746,12 @@ function getMimeType($file, $ext="", $list=false) {
* @param string $mime_type
* @return bool|string
*/
function getExtension ($mime_type){
function getExtension(string $mime_type) {
if(empty($mime_type)){
return false;
}
$extensions = getMimeType(null, null, true);
$ext = array_search($mime_type, $extensions);
$ext = array_search($mime_type, MIME_TYPE_MAP);
return ($ext ? $ext : false);
}
@ -816,7 +776,7 @@ function blockcmp(Block $a, Block $b) {
*
* @return int
*/
function get_memory_limit() {
function get_memory_limit(): int {
global $config;
// thumbnail generation requires lots of memory
@ -866,7 +826,7 @@ function get_memory_limit() {
* @param Config $config
* @return string
*/
function get_session_ip(Config $config) {
function get_session_ip(Config $config): string {
$mask = $config->get_string("session_hash_mask", "255.255.0.0");
$addr = $_SERVER['REMOTE_ADDR'];
$addr = inet_ntop(inet_pton($addr) & inet_pton($mask));
@ -886,7 +846,7 @@ function get_session_ip(Config $config) {
* @param string $text
* @param string $type
*/
function flash_message(/*string*/ $text, /*string*/ $type="info") {
function flash_message(string $text, string $type="info") {
global $page;
$current = $page->get_cookie("flash_message");
if($current) {
@ -907,7 +867,7 @@ function flash_message(/*string*/ $text, /*string*/ $type="info") {
*
* @return string
*/
function get_base_href() {
function get_base_href(): string {
if(defined("BASE_HREF")) return BASE_HREF;
$possible_vars = array('SCRIPT_NAME', 'PHP_SELF', 'PATH_INFO', 'ORIG_PATH_INFO');
$ok_var = null;
@ -931,19 +891,13 @@ function get_base_href() {
* @param string $string
* @return string
*/
function format_text(/*string*/ $string) {
function format_text(string $string): string {
$tfe = new TextFormattingEvent($string);
send_event($tfe);
return $tfe->formatted;
}
/**
* @param string $base
* @param string $hash
* @param bool $create
* @return string
*/
function warehouse_path(/*string*/ $base, /*string*/ $hash, /*bool*/ $create=true) {
function warehouse_path(string $base, string $hash, bool $create=true): string {
$ab = substr($hash, 0, 2);
$cd = substr($hash, 2, 2);
if(WH_SPLITS == 2) {
@ -956,11 +910,7 @@ function warehouse_path(/*string*/ $base, /*string*/ $hash, /*bool*/ $create=tru
return $pa;
}
/**
* @param string $filename
* @return string
*/
function data_path($filename) {
function data_path(string $filename): string {
$filename = "data/" . $filename;
if(!file_exists(dirname($filename))) mkdir(dirname($filename), 0755, true);
return $filename;
@ -982,7 +932,7 @@ if (!function_exists('mb_strlen')) {
* @param string $mfile
* @return array|bool
*/
function transload($url, $mfile) {
function transload(string $url, string $mfile) {
global $config;
if($config->get_string("transload_engine") === "curl" && function_exists("curl_init")) {
@ -1076,7 +1026,7 @@ if (!function_exists('http_parse_headers')) { #http://www.php.net/manual/en/func
* @param string $name
* @return string|bool
*/
function findHeader ($headers, $name) {
function findHeader(array $headers, string $name) {
if (!is_array($headers)) {
return false;
}
@ -1103,7 +1053,7 @@ function findHeader ($headers, $name) {
* @param string $fname
* @return string|null
*/
function manual_include($fname) {
function manual_include(string $fname) {
static $included = array();
if(!file_exists($fname)) return null;
@ -1159,7 +1109,7 @@ define("SCORE_LOG_NOTSET", 0);
* @param bool|string $flash
* @param array $args
*/
function log_msg(/*string*/ $section, /*int*/ $priority, /*string*/ $message, $flash=false, $args=array()) {
function log_msg(string $section, int $priority, string $message, $flash=false, $args=array()) {
send_event(new LogEvent($section, $priority, $message, $args));
$threshold = defined("CLI_LOG_LEVEL") ? CLI_LOG_LEVEL : 0;
@ -1181,43 +1131,43 @@ function log_msg(/*string*/ $section, /*int*/ $priority, /*string*/ $message, $f
* @param bool|string $flash
* @param array $args
*/
function log_debug( /*string*/ $section, /*string*/ $message, $flash=false, $args=array()) {log_msg($section, SCORE_LOG_DEBUG, $message, $flash, $args);}
function log_debug( string $section, string $message, $flash=false, $args=array()) {log_msg($section, SCORE_LOG_DEBUG, $message, $flash, $args);}
/**
* @param string $section
* @param string $message
* @param bool|string $flash
* @param array $args
*/
function log_info( /*string*/ $section, /*string*/ $message, $flash=false, $args=array()) {log_msg($section, SCORE_LOG_INFO, $message, $flash, $args);}
function log_info( string $section, string $message, $flash=false, $args=array()) {log_msg($section, SCORE_LOG_INFO, $message, $flash, $args);}
/**
* @param string $section
* @param string $message
* @param bool|string $flash
* @param array $args
*/
function log_warning( /*string*/ $section, /*string*/ $message, $flash=false, $args=array()) {log_msg($section, SCORE_LOG_WARNING, $message, $flash, $args);}
function log_warning( string $section, string $message, $flash=false, $args=array()) {log_msg($section, SCORE_LOG_WARNING, $message, $flash, $args);}
/**
* @param string $section
* @param string $message
* @param bool|string $flash
* @param array $args
*/
function log_error( /*string*/ $section, /*string*/ $message, $flash=false, $args=array()) {log_msg($section, SCORE_LOG_ERROR, $message, $flash, $args);}
function log_error( string $section, string $message, $flash=false, $args=array()) {log_msg($section, SCORE_LOG_ERROR, $message, $flash, $args);}
/**
* @param string $section
* @param string $message
* @param bool|string $flash
* @param array $args
*/
function log_critical(/*string*/ $section, /*string*/ $message, $flash=false, $args=array()) {log_msg($section, SCORE_LOG_CRITICAL, $message, $flash, $args);}
function log_critical(string $section, string $message, $flash=false, $args=array()) {log_msg($section, SCORE_LOG_CRITICAL, $message, $flash, $args);}
/**
* Get a unique ID for this request, useful for grouping log messages.
*
* @return null|string
* @return string
*/
function get_request_id() {
function get_request_id(): string {
static $request_id = null;
if(!$request_id) {
// not completely trustworthy, as a user can spoof this
@ -1243,7 +1193,7 @@ function get_request_id() {
* @param mixed $to_remove
* @return array
*/
function array_remove($array, $to_remove) {
function array_remove(array $array, $to_remove): array {
$array = array_unique($array);
$a2 = array();
foreach($array as $existing) {
@ -1263,7 +1213,7 @@ function array_remove($array, $to_remove) {
* @param mixed $element
* @return array
*/
function array_add($array, $element) {
function array_add(array $array, $element): array {
// Could we just use array_push() ?
// http://www.php.net/manual/en/function.array-push.php
$array[] = $element;
@ -1277,7 +1227,7 @@ function array_add($array, $element) {
* @param array $array
* @return array
*/
function array_iunique($array) {
function array_iunique(array $array): array {
$ok = array();
foreach($array as $element) {
$found = false;
@ -1302,7 +1252,7 @@ function array_iunique($array) {
* @param string $CIDR
* @return bool
*/
function ip_in_range($IP, $CIDR) {
function ip_in_range(string $IP, string $CIDR): bool {
list ($net, $mask) = explode("/", $CIDR);
$ip_net = ip2long ($net);
@ -1323,7 +1273,7 @@ function ip_in_range($IP, $CIDR) {
*
* @param string $f
*/
function deltree($f) {
function deltree(string $f) {
//Because Windows (I know, bad excuse)
if(PHP_OS === 'WINNT') {
$real = realpath($f);
@ -1369,7 +1319,7 @@ function deltree($f) {
* @param string $source
* @param string $target
*/
function full_copy($source, $target) {
function full_copy(string $source, string $target) {
if(is_dir($source)) {
@mkdir($target);
@ -1401,7 +1351,7 @@ function full_copy($source, $target) {
* @param string $_sub_dir
* @return array file list
*/
function list_files(/*string*/ $base, $_sub_dir="") {
function list_files(string $base, string $_sub_dir=""): array {
assert(is_dir($base));
$file_list = array();
@ -1438,11 +1388,7 @@ function list_files(/*string*/ $base, $_sub_dir="") {
return $file_list;
}
/**
* @param string $path
* @return string
*/
function path_to_tags($path) {
function path_to_tags(string $path): string {
$matches = array();
if(preg_match("/\d+ - (.*)\.([a-zA-Z]+)/", basename($path), $matches)) {
$tags = $matches[1];
@ -1466,9 +1412,9 @@ global $_shm_event_listeners;
$_shm_event_listeners = array();
function _load_event_listeners() {
global $_shm_event_listeners;
global $_shm_event_listeners, $_shm_ctx;
ctx_log_start("Loading extensions");
$_shm_ctx->log_start("Loading extensions");
$cache_path = data_path("cache/shm_event_listeners.php");
if(COMPILE_ELS && file_exists($cache_path)) {
@ -1482,7 +1428,7 @@ function _load_event_listeners() {
}
}
ctx_log_endok();
$_shm_ctx->log_endok();
}
function _set_event_listeners() {
@ -1548,7 +1494,7 @@ function _dump_event_listeners($event_listeners, $path) {
* @param string $ext_name Main class name (eg ImageIO as opposed to ImageIOTheme or ImageIOTest)
* @return bool
*/
function ext_is_live($ext_name) {
function ext_is_live(string $ext_name): bool {
if (class_exists($ext_name)) {
/** @var Extension $ext */
$ext = new $ext_name();
@ -1568,27 +1514,27 @@ $_shm_event_count = 0;
* @param Event $event
*/
function send_event(Event $event) {
global $_shm_event_listeners, $_shm_event_count;
global $_shm_event_listeners, $_shm_event_count, $_shm_ctx;
if(!isset($_shm_event_listeners[get_class($event)])) return;
$method_name = "on".str_replace("Event", "", get_class($event));
// send_event() is performance sensitive, and with the number
// of times context gets called the time starts to add up
$ctx = constant('CONTEXT');
$ctx_enabled = constant('CONTEXT');
if($ctx) ctx_log_start(get_class($event));
if($ctx_enabled) $_shm_ctx->log_start(get_class($event));
// SHIT: http://bugs.php.net/bug.php?id=35106
$my_event_listeners = $_shm_event_listeners[get_class($event)];
ksort($my_event_listeners);
foreach($my_event_listeners as $listener) {
if($ctx) ctx_log_start(get_class($listener));
if($ctx_enabled) $_shm_ctx->log_start(get_class($listener));
if(method_exists($listener, $method_name)) {
$listener->$method_name($event);
}
if($ctx) ctx_log_endok();
if($ctx_enabled) $_shm_ctx->log_endok();
}
$_shm_event_count++;
if($ctx) ctx_log_endok();
if($ctx_enabled) $_shm_ctx->log_endok();
}
@ -1607,7 +1553,7 @@ $_shm_load_start = microtime(true);
*
* @return string debug info to add to the page.
*/
function get_debug_info() {
function get_debug_info(): string {
global $config, $_shm_event_count, $database, $_shm_load_start;
$i_mem = sprintf("%5.2f", ((memory_get_peak_usage(true)+512)/1024)/1024);
@ -1666,6 +1612,8 @@ date and you should plan on moving elsewhere.
}
function _sanitise_environment() {
global $_shm_ctx;
if(TIMEZONE) {
date_default_timezone_set(TIMEZONE);
}
@ -1679,8 +1627,9 @@ function _sanitise_environment() {
assert_options(ASSERT_CALLBACK, 'score_assert_handler');
}
$_shm_ctx = new Context();
if(CONTEXT) {
ctx_set_log(CONTEXT);
$_shm_ctx->set_log(CONTEXT);
}
if(COVERAGE) {
@ -1702,9 +1651,9 @@ function _sanitise_environment() {
/**
* @param string $_theme
* @return array
* @return string[]
*/
function _get_themelet_files($_theme) {
function _get_themelet_files(string $_theme): array {
$base_themelets = array();
if(file_exists('themes/'.$_theme.'/custompage.class.php')) $base_themelets[] = 'themes/'.$_theme.'/custompage.class.php';
$base_themelets[] = 'themes/'.$_theme.'/layout.class.php';
@ -1755,7 +1704,7 @@ function _fatal_error(Exception $e) {
* @param string $str
* @return string
*/
function _decaret($str) {
function _decaret(string $str): string {
$out = "";
$length = strlen($str);
for($i=0; $i<$length; $i++) {
@ -1772,10 +1721,7 @@ function _decaret($str) {
return $out;
}
/**
* @return User
*/
function _get_user() {
function _get_user(): User {
global $config, $page;
$user = null;
if($page->get_cookie("user") && $page->get_cookie("session")) {
@ -1793,7 +1739,7 @@ function _get_user() {
}
/**
* @return string
* @return string|null
*/
function _get_query() {
return @$_POST["q"]?:@$_GET["q"];