Merge branch 'dev' into hash-passwords
This commit is contained in:
@@ -123,7 +123,7 @@ class AntiBot {
|
||||
$html = '';
|
||||
|
||||
if ($count === false) {
|
||||
$count = mt_rand(1, abs(count($this->inputs) / 15) + 1);
|
||||
$count = mt_rand(1, (int)abs(count($this->inputs) / 15) + 1);
|
||||
}
|
||||
|
||||
if ($count === true) {
|
||||
|
||||
19
inc/bans.php
19
inc/bans.php
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use Vichan\Functions\Format;
|
||||
use Lifo\IP\CIDR;
|
||||
|
||||
class Bans {
|
||||
@@ -369,16 +370,14 @@ class Bans {
|
||||
$query->bindValue(':post', null, PDO::PARAM_NULL);
|
||||
|
||||
$query->execute() or error(db_error($query));
|
||||
if (isset($mod['id']) && $mod['id'] == $mod_id) {
|
||||
modLog('Created a new ' .
|
||||
($length > 0 ? preg_replace('/^(\d+) (\w+?)s?$/', '$1-$2', until($length)) : 'permanent') .
|
||||
' ban on ' .
|
||||
($ban_board ? '/' . $ban_board . '/' : 'all boards') .
|
||||
' for ' .
|
||||
(filter_var($mask, FILTER_VALIDATE_IP) !== false ? "<a href=\"?/IP/$cloaked_mask\">$cloaked_mask</a>" : $cloaked_mask) .
|
||||
' (<small>#' . $pdo->lastInsertId() . '</small>)' .
|
||||
' with ' . ($reason ? 'reason: ' . utf8tohtml($reason) . '' : 'no reason'));
|
||||
}
|
||||
|
||||
$ban_len = $length > 0 ? preg_replace('/^(\d+) (\w+?)s?$/', '$1-$2', Format\until($length)) : 'permanent';
|
||||
$ban_board = $ban_board ? "/$ban_board/" : 'all boards';
|
||||
$ban_ip = filter_var($mask, FILTER_VALIDATE_IP) !== false ? "<a href=\"?/IP/$cloaked_mask\">$cloaked_mask</a>" : $cloaked_mask;
|
||||
$ban_id = $pdo->lastInsertId();
|
||||
$ban_reason = $reason ? 'reason: ' . utf8tohtml($reason) : 'no reason';
|
||||
|
||||
modLog("Created a new $ban_len ban on $ban_board for $ban_ip (<small># $ban_id </small>) with $ban_reason");
|
||||
|
||||
rebuildThemes('bans');
|
||||
|
||||
|
||||
@@ -165,31 +165,3 @@ class Cache {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class Twig_Cache_TinyboardFilesystem extends Twig\Cache\FilesystemCache
|
||||
{
|
||||
private $directory;
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __construct($directory, $options = 0)
|
||||
{
|
||||
parent::__construct($directory, $options);
|
||||
|
||||
$this->directory = $directory;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function was removed in Twig 2.x due to developer views on the Twig library. Who says we can't keep it for ourselves though?
|
||||
*/
|
||||
public function clear()
|
||||
{
|
||||
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->directory), RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
|
||||
if ($file->isFile()) {
|
||||
@unlink($file->getPathname());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -65,9 +65,22 @@
|
||||
// been generated. This keeps the script from querying the database and causing strain when not needed.
|
||||
$config['has_installed'] = '.installed';
|
||||
|
||||
// Use syslog() for logging all error messages and unauthorized login attempts.
|
||||
// Deprecated, use 'log_system'.
|
||||
$config['syslog'] = false;
|
||||
|
||||
$config['log_system'] = [];
|
||||
// Log all error messages and unauthorized login attempts.
|
||||
// Can be "syslog", "error_log" (default), "file", "stderr" or "none".
|
||||
$config['log_system']['type'] = 'error_log';
|
||||
// The application name used by the logging system. Defaults to "tinyboard" for backwards compatibility.
|
||||
$config['log_system']['name'] = 'tinyboard';
|
||||
// Only relevant if 'log_system' is set to "syslog". If true, double print the logs also in stderr.
|
||||
// Defaults to false.
|
||||
$config['log_system']['syslog_stderr'] = false;
|
||||
// Only relevant if "log_system" is set to `file`. Sets the file that vichan will log to.
|
||||
// Defaults to '/var/log/vichan.log'.
|
||||
$config['log_system']['file_path'] = '/var/log/vichan.log';
|
||||
|
||||
// Use `host` via shell_exec() to lookup hostnames, avoiding query timeouts. May not work on your system.
|
||||
// Requires safe_mode to be disabled.
|
||||
$config['dns_system'] = false;
|
||||
@@ -173,7 +186,7 @@
|
||||
|
||||
// How long should the cookies last (in seconds). Defines how long should moderators should remain logged
|
||||
// in (0 = browser session).
|
||||
$config['cookies']['expire'] = 60 * 60 * 24 * 30 * 6; // ~6 months
|
||||
$config['cookies']['expire'] = 60 * 60 * 24 * 7; // 1 week.
|
||||
|
||||
// Make this something long and random for security.
|
||||
$config['cookies']['salt'] = 'abcdefghijklmnopqrstuvwxyz09123456789!@#$%^&*()';
|
||||
@@ -181,6 +194,14 @@
|
||||
// Whether or not you can access the mod cookie in JavaScript. Most users should not need to change this.
|
||||
$config['cookies']['httponly'] = true;
|
||||
|
||||
// Do not allow logins via unsecure connections.
|
||||
// 0 = off. Allow logins on unencrypted HTTP connections. Should only be used in testing environments.
|
||||
// 1 = on, trust HTTP headers. Allow logins on (at least reportedly partial) HTTPS connections. Use this only if you
|
||||
// use a proxy, CDN or load balancer via an unencrypted connection. Be sure to filter 'HTTP_X_FORWARDED_PROTO' in
|
||||
// the remote server, since an attacker could inject the header from the client.
|
||||
// 2 = on, do not trust HTTP headers. Secure default, allow logins only on HTTPS connections.
|
||||
$config['cookies']['secure_login_only'] = 2;
|
||||
|
||||
// Used to salt secure tripcodes ("##trip") and poster IDs (if enabled).
|
||||
$config['secure_trip_salt'] = ')(*&^%$#@!98765432190zyxwvutsrqponmlkjihgfedcba';
|
||||
|
||||
@@ -614,6 +635,9 @@
|
||||
// Example: Custom secure tripcode.
|
||||
// $config['custom_tripcode']['##securetrip'] = '!!somethingelse';
|
||||
|
||||
//Disable tripcodes. This will make it so all new posts will act as if no tripcode exists.
|
||||
$config['disable_tripcodes'] = false;
|
||||
|
||||
// Allow users to mark their image as a "spoiler" when posting. The thumbnail will be replaced with a
|
||||
// static spoiler image instead (see $config['spoiler_image']).
|
||||
$config['spoiler_images'] = false;
|
||||
@@ -979,11 +1003,11 @@
|
||||
|
||||
// Timezone to use for displaying dates/times.
|
||||
$config['timezone'] = 'America/Los_Angeles';
|
||||
// The format string passed to strftime() for displaying dates.
|
||||
// http://www.php.net/manual/en/function.strftime.php
|
||||
$config['post_date'] = '%m/%d/%y (%a) %H:%M:%S';
|
||||
// The format string passed to DateTime::format() for displaying dates. ISO 8601-like by default.
|
||||
// https://www.php.net/manual/en/datetime.format.php
|
||||
$config['post_date'] = 'm/d/y (D) H:i:s';
|
||||
// Same as above, but used for "you are banned' pages.
|
||||
$config['ban_date'] = '%A %e %B, %Y';
|
||||
$config['ban_date'] = 'l j F, Y';
|
||||
|
||||
// The names on the post buttons. (On most imageboards, these are both just "Post").
|
||||
$config['button_newtopic'] = _('New Topic');
|
||||
@@ -1235,11 +1259,14 @@
|
||||
$config['error']['captcha'] = _('You seem to have mistyped the verification.');
|
||||
$config['error']['flag_undefined'] = _('The flag %s is undefined, your PHP version is too old!');
|
||||
$config['error']['flag_wrongtype'] = _('defined_flags_accumulate(): The flag %s is of the wrong type!');
|
||||
$config['error']['remote_io_error'] = _('IO error while interacting with a remote service.');
|
||||
$config['error']['local_io_error'] = _('IO error while interacting with a local resource or service.');
|
||||
|
||||
|
||||
// Moderator errors
|
||||
$config['error']['toomanyunban'] = _('You are only allowed to unban %s users at a time. You tried to unban %u users.');
|
||||
$config['error']['invalid'] = _('Invalid username and/or password.');
|
||||
$config['error']['insecure'] = _('Login on insecure connections is disabled.');
|
||||
$config['error']['notamod'] = _('You are not a mod…');
|
||||
$config['error']['invalidafter'] = _('Invalid username and/or password. Your user may have been deleted or changed.');
|
||||
$config['error']['malformed'] = _('Invalid/malformed cookies.');
|
||||
@@ -1834,6 +1861,9 @@
|
||||
// Boards for searching
|
||||
//$config['search']['boards'] = array('a', 'b', 'c', 'd', 'e');
|
||||
|
||||
// Blacklist boards for searching, basically the opposite of the one above
|
||||
//$config['search']['disallowed_boards'] = array('j', 'z');
|
||||
|
||||
// Enable public logs? 0: NO, 1: YES, 2: YES, but drop names
|
||||
$config['public_logs'] = 0;
|
||||
|
||||
|
||||
66
inc/context.php
Normal file
66
inc/context.php
Normal file
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
namespace Vichan;
|
||||
|
||||
use Vichan\Driver\{HttpDriver, HttpDrivers, Log, LogDrivers};
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
interface DependencyFactory {
|
||||
public function buildLogDriver(): Log;
|
||||
public function buildHttpDriver(): HttpDriver;
|
||||
}
|
||||
|
||||
class WebDependencyFactory implements DependencyFactory {
|
||||
private array $config;
|
||||
|
||||
|
||||
public function __construct(array $config) {
|
||||
$this->config = $config;
|
||||
}
|
||||
|
||||
public function buildLogDriver(): Log {
|
||||
$name = $this->config['log_system']['name'];
|
||||
$level = $this->config['debug'] ? Log::DEBUG : Log::NOTICE;
|
||||
$backend = $this->config['log_system']['type'];
|
||||
|
||||
// Check 'syslog' for backwards compatibility.
|
||||
if ((isset($this->config['syslog']) && $this->config['syslog']) || $backend === 'syslog') {
|
||||
return LogDrivers::syslog($name, $level, $this->config['log_system']['syslog_stderr']);
|
||||
} elseif ($backend === 'file') {
|
||||
return LogDrivers::file($name, $level, $this->config['log_system']['file_path']);
|
||||
} elseif ($backend === 'stderr') {
|
||||
return LogDrivers::stderr($name, $level);
|
||||
} elseif ($backend === 'none') {
|
||||
return LogDrivers::none();
|
||||
} else {
|
||||
return LogDrivers::error_log($name, $level);
|
||||
}
|
||||
}
|
||||
|
||||
public function buildHttpDriver(): HttpDriver {
|
||||
return HttpDrivers::getHttpDriver(
|
||||
$this->config['upload_by_url_timeout'],
|
||||
$this->config['max_filesize']
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class Context {
|
||||
private DependencyFactory $factory;
|
||||
private ?Log $log;
|
||||
private ?HttpDriver $http;
|
||||
|
||||
|
||||
public function __construct(DependencyFactory $factory) {
|
||||
$this->factory = $factory;
|
||||
}
|
||||
|
||||
public function getLog(): Log {
|
||||
return $this->log ??= $this->factory->buildLogDriver();
|
||||
}
|
||||
|
||||
public function getHttpDriver(): HttpDriver {
|
||||
return $this->http ??= $this->factory->buildHttpDriver();
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,7 @@ function createBoardlist($mod=false) {
|
||||
);
|
||||
}
|
||||
|
||||
function error($message, $priority = true, $debug_stuff = false) {
|
||||
function error($message, $priority = true, $debug_stuff = []) {
|
||||
global $board, $mod, $config, $db_error;
|
||||
|
||||
if ($config['syslog'] && $priority !== false) {
|
||||
@@ -351,13 +351,20 @@ class Post {
|
||||
if (isset($this->files) && $this->files) {
|
||||
$this->files = is_string($this->files) ? json_decode($this->files) : $this->files;
|
||||
// Compatibility for posts before individual file hashing
|
||||
foreach ($this->files as $i => &$file) {
|
||||
foreach ($this->files as $i => &$file) {
|
||||
if (empty($file)) {
|
||||
unset($this->files[$i]);
|
||||
continue;
|
||||
}
|
||||
if (!isset($file->hash))
|
||||
$file->hash = $this->filehash;
|
||||
if (is_array($file)) {
|
||||
if (!isset($file['hash'])) {
|
||||
$file['hash'] = $this->filehash;
|
||||
}
|
||||
} else if (is_object($file)) {
|
||||
if (!isset($file->hash)) {
|
||||
$file->hash = $this->filehash;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
151
inc/driver/http-driver.php
Normal file
151
inc/driver/http-driver.php
Normal file
@@ -0,0 +1,151 @@
|
||||
<?php // Honestly this is just a wrapper for cURL. Still useful to mock it and have an OOP API on PHP 7.
|
||||
namespace Vichan\Driver;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
class HttpDrivers {
|
||||
private const DEFAULT_USER_AGENT = 'Tinyboard';
|
||||
|
||||
|
||||
public static function getHttpDriver(int $timeout, int $max_file_size): HttpDriver {
|
||||
return new HttpDriver($timeout, self::DEFAULT_USER_AGENT, $max_file_size);
|
||||
}
|
||||
}
|
||||
|
||||
class HttpDriver {
|
||||
private mixed $inner;
|
||||
private int $timeout;
|
||||
private string $user_agent;
|
||||
private int $max_file_size;
|
||||
|
||||
|
||||
private function resetTowards(string $url, int $timeout): void {
|
||||
curl_reset($this->inner);
|
||||
curl_setopt_array($this->inner, array(
|
||||
CURLOPT_URL => $url,
|
||||
CURLOPT_TIMEOUT => $this->timeout,
|
||||
CURLOPT_USERAGENT => $this->user_agent,
|
||||
CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
|
||||
));
|
||||
}
|
||||
|
||||
private function setSizeLimit(): void {
|
||||
// Adapted from: https://stackoverflow.com/a/17642638
|
||||
curl_setopt($this->inner, CURLOPT_NOPROGRESS, false);
|
||||
|
||||
if (PHP_MAJOR_VERSION >= 8 && PHP_MINOR_VERSION >= 2) {
|
||||
curl_setopt($this->inner, CURLOPT_XFERINFOFUNCTION, function($res, $next_dl, $dl, $next_up, $up) {
|
||||
return (int)($dl <= $this->max_file_size);
|
||||
});
|
||||
} else {
|
||||
curl_setopt($this->inner, CURLOPT_PROGRESSFUNCTION, function($res, $next_dl, $dl, $next_up, $up) {
|
||||
return (int)($dl <= $this->max_file_size);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function __construct($timeout, $user_agent, $max_file_size) {
|
||||
$this->inner = curl_init();
|
||||
$this->timeout = $timeout;
|
||||
$this->user_agent = $user_agent;
|
||||
$this->max_file_size = $max_file_size;
|
||||
}
|
||||
|
||||
function __destruct() {
|
||||
curl_close($this->inner);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a GET request.
|
||||
*
|
||||
* @param string $endpoint Uri endpoint.
|
||||
* @param ?array $data Optional GET parameters.
|
||||
* @param int $timeout Optional request timeout in seconds. Use the default timeout if 0.
|
||||
* @return string Returns the body of the response.
|
||||
* @throws RuntimeException Throws on IO error.
|
||||
*/
|
||||
public function requestGet(string $endpoint, ?array $data, int $timeout = 0): string {
|
||||
if (!empty($data)) {
|
||||
$endpoint .= '?' . http_build_query($data);
|
||||
}
|
||||
if ($timeout == 0) {
|
||||
$timeout = $this->timeout;
|
||||
}
|
||||
|
||||
$this->resetTowards($endpoint, $timeout);
|
||||
curl_setopt($this->inner, CURLOPT_RETURNTRANSFER, true);
|
||||
$ret = curl_exec($this->inner);
|
||||
|
||||
if ($ret === false) {
|
||||
throw new \RuntimeException(curl_error($this->inner));
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a POST request.
|
||||
*
|
||||
* @param string $endpoint Uri endpoint.
|
||||
* @param ?array $data Optional POST parameters.
|
||||
* @param int $timeout Optional request timeout in seconds. Use the default timeout if 0.
|
||||
* @return string Returns the body of the response.
|
||||
* @throws RuntimeException Throws on IO error.
|
||||
*/
|
||||
public function requestPost(string $endpoint, ?array $data, int $timeout = 0): string {
|
||||
if ($timeout == 0) {
|
||||
$timeout = $this->timeout;
|
||||
}
|
||||
|
||||
$this->resetTowards($endpoint, $timeout);
|
||||
curl_setopt($this->inner, CURLOPT_POST, true);
|
||||
if (!empty($data)) {
|
||||
curl_setopt($this->inner, CURLOPT_POSTFIELDS, http_build_query($data));
|
||||
}
|
||||
curl_setopt($this->inner, CURLOPT_RETURNTRANSFER, true);
|
||||
$ret = curl_exec($this->inner);
|
||||
|
||||
if ($ret === false) {
|
||||
throw new \RuntimeException(curl_error($this->inner));
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Download the url's target with curl.
|
||||
*
|
||||
* @param string $url Url to the file to download.
|
||||
* @param ?array $data Optional GET parameters.
|
||||
* @param resource $fd File descriptor to save the content to.
|
||||
* @param int $timeout Optional request timeout in seconds. Use the default timeout if 0.
|
||||
* @return bool Returns true on success, false if the file was too large.
|
||||
* @throws RuntimeException Throws on IO error.
|
||||
*/
|
||||
public function requestGetInto(string $endpoint, ?array $data, mixed $fd, int $timeout = 0): bool {
|
||||
if (!empty($data)) {
|
||||
$endpoint .= '?' . http_build_query($data);
|
||||
}
|
||||
if ($timeout == 0) {
|
||||
$timeout = $this->timeout;
|
||||
}
|
||||
|
||||
$this->resetTowards($endpoint, $timeout);
|
||||
curl_setopt($this->inner, CURLOPT_FAILONERROR, true);
|
||||
curl_setopt($this->inner, CURLOPT_FOLLOWLOCATION, false);
|
||||
curl_setopt($this->inner, CURLOPT_FILE, $fd);
|
||||
curl_setopt($this->inner, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
|
||||
$this->setSizeLimit();
|
||||
$ret = curl_exec($this->inner);
|
||||
|
||||
if ($ret === false) {
|
||||
if (curl_errno($this->inner) === CURLE_ABORTED_BY_CALLBACK) {
|
||||
return false;
|
||||
}
|
||||
|
||||
throw new \RuntimeException(curl_error($this->inner));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
189
inc/driver/log-driver.php
Normal file
189
inc/driver/log-driver.php
Normal file
@@ -0,0 +1,189 @@
|
||||
<?php // Logging
|
||||
namespace Vichan\Driver;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
class LogDrivers {
|
||||
public static function levelToString(int $level): string {
|
||||
switch ($level) {
|
||||
case Log::EMERG:
|
||||
return 'EMERG';
|
||||
case Log::ERROR:
|
||||
return 'ERROR';
|
||||
case Log::WARNING:
|
||||
return 'WARNING';
|
||||
case Log::NOTICE:
|
||||
return 'NOTICE';
|
||||
case Log::INFO:
|
||||
return 'INFO';
|
||||
case Log::DEBUG:
|
||||
return 'DEBUG';
|
||||
default:
|
||||
throw new InvalidArgumentException('Not a logging level');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Log to syslog.
|
||||
*/
|
||||
public static function syslog(string $name, int $level, bool $print_stderr): Log {
|
||||
$flags = LOG_ODELAY;
|
||||
if ($print_stderr) {
|
||||
$flags |= LOG_PERROR;
|
||||
}
|
||||
|
||||
if (!openlog($name, $flags, LOG_USER)) {
|
||||
throw new RuntimeException('Unable to open syslog');
|
||||
}
|
||||
|
||||
return new class($level) implements Log {
|
||||
private $level;
|
||||
|
||||
public function __construct(int $level) {
|
||||
$this->level = $level;
|
||||
}
|
||||
|
||||
public function log(int $level, string $message): void {
|
||||
if ($level <= $this->level) {
|
||||
if (isset($_SERVER['REMOTE_ADDR'], $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'])) {
|
||||
// CGI
|
||||
syslog($level, "$message - client: {$_SERVER['REMOTE_ADDR']}, request: \"{$_SERVER['REQUEST_METHOD']} {$_SERVER['REQUEST_URI']}\"");
|
||||
} else {
|
||||
syslog($level, $message);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Log via the php function error_log.
|
||||
*/
|
||||
public static function error_log(string $name, int $level): Log {
|
||||
return new class($name, $level) implements Log {
|
||||
private string $name;
|
||||
private int $level;
|
||||
|
||||
public function __construct(string $name, int $level) {
|
||||
$this->name = $name;
|
||||
$this->level = $level;
|
||||
}
|
||||
|
||||
public function log(int $level, string $message): void {
|
||||
if ($level <= $this->level) {
|
||||
$lv = LogDrivers::levelToString($level);
|
||||
$line = "{$this->name} $lv: $message";
|
||||
error_log($line, 0, null, null);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Log to a file.
|
||||
*/
|
||||
public static function file(string $name, int $level, string $file_path): Log {
|
||||
/*
|
||||
* error_log is slow as hell in it's 3rd mode, so use fopen + file locking instead.
|
||||
* https://grobmeier.solutions/performance-ofnonblocking-write-to-files-via-php-21082009.html
|
||||
*
|
||||
* Whatever file appending is atomic is contentious:
|
||||
* - There are no POSIX guarantees: https://stackoverflow.com/a/7237901
|
||||
* - But linus suggested they are on linux, on some filesystems: https://web.archive.org/web/20151201111541/http://article.gmane.org/gmane.linux.kernel/43445
|
||||
* - But it doesn't seem to be always the case: https://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/
|
||||
*
|
||||
* So we just use file locking to be sure.
|
||||
*/
|
||||
|
||||
$fd = fopen($file_path, 'a');
|
||||
if ($fd === false) {
|
||||
throw new RuntimeException("Unable to open log file at $file_path");
|
||||
}
|
||||
|
||||
$logger = new class($name, $level, $fd) implements Log {
|
||||
private string $name;
|
||||
private int $level;
|
||||
private mixed $fd;
|
||||
|
||||
public function __construct(string $name, int $level, mixed $fd) {
|
||||
$this->name = $name;
|
||||
$this->level = $level;
|
||||
$this->fd = $fd;
|
||||
}
|
||||
|
||||
public function log(int $level, string $message): void {
|
||||
if ($level <= $this->level) {
|
||||
$lv = LogDrivers::levelToString($level);
|
||||
$line = "{$this->name} $lv: $message\n";
|
||||
flock($this->fd, LOCK_EX);
|
||||
fwrite($this->fd, $line);
|
||||
flock($this->fd, LOCK_UN);
|
||||
}
|
||||
}
|
||||
|
||||
public function close() {
|
||||
fclose($this->fd);
|
||||
}
|
||||
};
|
||||
|
||||
// Close the file on shutdown.
|
||||
register_shutdown_function([$logger, 'close']);
|
||||
|
||||
return $logger;
|
||||
}
|
||||
|
||||
/**
|
||||
* Log to php's standard error file stream.
|
||||
*/
|
||||
public static function stderr(string $name, int $level): Log {
|
||||
return new class($name, $level) implements Log {
|
||||
private $name;
|
||||
private $level;
|
||||
|
||||
public function __construct(string $name, int $level) {
|
||||
$this->name = $name;
|
||||
$this->level = $level;
|
||||
}
|
||||
|
||||
public function log(int $level, string $message): void {
|
||||
if ($level <= $this->level) {
|
||||
$lv = LogDrivers::levelToString($level);
|
||||
fwrite(STDERR, "{$this->name} $lv: $message\n");
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* No-op logging system.
|
||||
*/
|
||||
public static function none(): Log {
|
||||
return new class() implements Log {
|
||||
public function log($level, $message): void {
|
||||
// No-op.
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
interface Log {
|
||||
public const EMERG = LOG_EMERG;
|
||||
public const ERROR = LOG_ERR;
|
||||
public const WARNING = LOG_WARNING;
|
||||
public const NOTICE = LOG_NOTICE;
|
||||
public const INFO = LOG_INFO;
|
||||
public const DEBUG = LOG_DEBUG;
|
||||
|
||||
|
||||
/**
|
||||
* Log a message if the level of relevancy is at least the minimum.
|
||||
*
|
||||
* @param int $level Message level. Use Log interface constants.
|
||||
* @param string $message The message to log.
|
||||
*/
|
||||
public function log(int $level, string $message): void;
|
||||
}
|
||||
@@ -21,9 +21,7 @@ loadConfig();
|
||||
|
||||
function init_locale($locale, $error='error') {
|
||||
if (extension_loaded('gettext')) {
|
||||
if (setlocale(LC_ALL, $locale) === false) {
|
||||
//$error('The specified locale (' . $locale . ') does not exist on your platform!');
|
||||
}
|
||||
setlocale(LC_ALL, $locale);
|
||||
bindtextdomain('tinyboard', './inc/locale');
|
||||
bind_textdomain_codeset('tinyboard', 'UTF-8');
|
||||
textdomain('tinyboard');
|
||||
@@ -55,8 +53,9 @@ function loadConfig() {
|
||||
|
||||
|
||||
if (isset($config['cache_config']) &&
|
||||
$config['cache_config'] &&
|
||||
$config = Cache::get('config_' . $boardsuffix ) ) {
|
||||
$config['cache_config'] &&
|
||||
$config = Cache::get('config_' . $boardsuffix))
|
||||
{
|
||||
$events = Cache::get('events_' . $boardsuffix );
|
||||
|
||||
define_groups();
|
||||
@@ -66,11 +65,10 @@ function loadConfig() {
|
||||
}
|
||||
|
||||
if ($config['locale'] != $current_locale) {
|
||||
$current_locale = $config['locale'];
|
||||
init_locale($config['locale'], $error);
|
||||
}
|
||||
}
|
||||
else {
|
||||
$current_locale = $config['locale'];
|
||||
init_locale($config['locale'], $error);
|
||||
}
|
||||
} else {
|
||||
$config = array();
|
||||
|
||||
reset_events();
|
||||
@@ -180,8 +178,8 @@ function loadConfig() {
|
||||
'(' .
|
||||
str_replace('%d', '\d+', preg_quote($config['file_page'], '/')) . '|' .
|
||||
str_replace('%d', '\d+', preg_quote($config['file_page50'], '/')) . '|' .
|
||||
str_replace(array('%d', '%s'), array('\d+', '[a-z0-9-]+'), preg_quote($config['file_page_slug'], '/')) . '|' .
|
||||
str_replace(array('%d', '%s'), array('\d+', '[a-z0-9-]+'), preg_quote($config['file_page50_slug'], '/')) .
|
||||
str_replace(array('%d', '%s'), array('\d+', '[a-z0-9-]+'), preg_quote($config['file_page_slug'], '/')) . '|' .
|
||||
str_replace(array('%d', '%s'), array('\d+', '[a-z0-9-]+'), preg_quote($config['file_page50_slug'], '/')) .
|
||||
')' .
|
||||
'|' .
|
||||
preg_quote($config['file_mod'], '/') . '\?\/.+' .
|
||||
@@ -242,12 +240,13 @@ function loadConfig() {
|
||||
$__version = file_exists('.installed') ? trim(file_get_contents('.installed')) : false;
|
||||
$config['version'] = $__version;
|
||||
|
||||
if ($config['allow_roll'])
|
||||
if ($config['allow_roll']) {
|
||||
event_handler('post', 'diceRoller');
|
||||
}
|
||||
|
||||
if (in_array('webm', $config['allowed_ext_files']) ||
|
||||
in_array('mp4', $config['allowed_ext_files']))
|
||||
if (in_array('webm', $config['allowed_ext_files']) || in_array('mp4', $config['allowed_ext_files'])) {
|
||||
event_handler('post', 'postHandler');
|
||||
}
|
||||
}
|
||||
// Effectful config processing below:
|
||||
|
||||
@@ -280,8 +279,7 @@ function loadConfig() {
|
||||
if ($config['cache']['enabled'])
|
||||
require_once 'inc/cache.php';
|
||||
|
||||
if (in_array('webm', $config['allowed_ext_files']) ||
|
||||
in_array('mp4', $config['allowed_ext_files']))
|
||||
if (in_array('webm', $config['allowed_ext_files']) || in_array('mp4', $config['allowed_ext_files']))
|
||||
require_once 'inc/lib/webm/posthandler.php';
|
||||
|
||||
event('load-config');
|
||||
@@ -428,10 +426,10 @@ function rebuildThemes($action, $boardname = false) {
|
||||
$board = $_board;
|
||||
|
||||
// Reload the locale
|
||||
if ($config['locale'] != $current_locale) {
|
||||
$current_locale = $config['locale'];
|
||||
init_locale($config['locale']);
|
||||
}
|
||||
if ($config['locale'] != $current_locale) {
|
||||
$current_locale = $config['locale'];
|
||||
init_locale($config['locale']);
|
||||
}
|
||||
|
||||
if (PHP_SAPI === 'cli') {
|
||||
echo "Rebuilding theme ".$theme['theme']."... ";
|
||||
@@ -450,8 +448,8 @@ function rebuildThemes($action, $boardname = false) {
|
||||
|
||||
// Reload the locale
|
||||
if ($config['locale'] != $current_locale) {
|
||||
$current_locale = $config['locale'];
|
||||
init_locale($config['locale']);
|
||||
$current_locale = $config['locale'];
|
||||
init_locale($config['locale']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -517,12 +515,11 @@ function mb_substr_replace($string, $replacement, $start, $length) {
|
||||
function setupBoard($array) {
|
||||
global $board, $config;
|
||||
|
||||
$board = array(
|
||||
$board = [
|
||||
'uri' => $array['uri'],
|
||||
'title' => $array['title'],
|
||||
'subtitle' => $array['subtitle'],
|
||||
#'indexed' => $array['indexed'],
|
||||
);
|
||||
];
|
||||
|
||||
// older versions
|
||||
$board['name'] = &$board['title'];
|
||||
@@ -718,12 +715,18 @@ function file_unlink($path) {
|
||||
$debug['unlink'][] = $path;
|
||||
}
|
||||
|
||||
$ret = @unlink($path);
|
||||
if (file_exists($path)) {
|
||||
$ret = @unlink($path);
|
||||
} else {
|
||||
$ret = true;
|
||||
}
|
||||
|
||||
if ($config['gzip_static']) {
|
||||
$gzpath = "$path.gz";
|
||||
if ($config['gzip_static']) {
|
||||
$gzpath = "$path.gz";
|
||||
|
||||
@unlink($gzpath);
|
||||
if (file_exists($gzpath)) {
|
||||
@unlink($gzpath);
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($config['purge']) && $path[0] != '/' && isset($_SERVER['HTTP_HOST'])) {
|
||||
@@ -797,42 +800,6 @@ function listBoards($just_uri = false) {
|
||||
return $boards;
|
||||
}
|
||||
|
||||
function until($timestamp) {
|
||||
$difference = $timestamp - time();
|
||||
switch(TRUE){
|
||||
case ($difference < 60):
|
||||
return $difference . ' ' . ngettext('second', 'seconds', $difference);
|
||||
case ($difference < 3600): //60*60 = 3600
|
||||
return ($num = round($difference/(60))) . ' ' . ngettext('minute', 'minutes', $num);
|
||||
case ($difference < 86400): //60*60*24 = 86400
|
||||
return ($num = round($difference/(3600))) . ' ' . ngettext('hour', 'hours', $num);
|
||||
case ($difference < 604800): //60*60*24*7 = 604800
|
||||
return ($num = round($difference/(86400))) . ' ' . ngettext('day', 'days', $num);
|
||||
case ($difference < 31536000): //60*60*24*365 = 31536000
|
||||
return ($num = round($difference/(604800))) . ' ' . ngettext('week', 'weeks', $num);
|
||||
default:
|
||||
return ($num = round($difference/(31536000))) . ' ' . ngettext('year', 'years', $num);
|
||||
}
|
||||
}
|
||||
|
||||
function ago($timestamp) {
|
||||
$difference = time() - $timestamp;
|
||||
switch(TRUE){
|
||||
case ($difference < 60) :
|
||||
return $difference . ' ' . ngettext('second', 'seconds', $difference);
|
||||
case ($difference < 3600): //60*60 = 3600
|
||||
return ($num = round($difference/(60))) . ' ' . ngettext('minute', 'minutes', $num);
|
||||
case ($difference < 86400): //60*60*24 = 86400
|
||||
return ($num = round($difference/(3600))) . ' ' . ngettext('hour', 'hours', $num);
|
||||
case ($difference < 604800): //60*60*24*7 = 604800
|
||||
return ($num = round($difference/(86400))) . ' ' . ngettext('day', 'days', $num);
|
||||
case ($difference < 31536000): //60*60*24*365 = 31536000
|
||||
return ($num = round($difference/(604800))) . ' ' . ngettext('week', 'weeks', $num);
|
||||
default:
|
||||
return ($num = round($difference/(31536000))) . ' ' . ngettext('year', 'years', $num);
|
||||
}
|
||||
}
|
||||
|
||||
function displayBan($ban) {
|
||||
global $config, $board;
|
||||
|
||||
@@ -1267,25 +1234,25 @@ function deletePost($id, $error_if_doesnt_exist=true, $rebuild_after=true) {
|
||||
$query->bindValue(':board', $board['uri']);
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
// No need to run on OPs
|
||||
if ($config['anti_bump_flood'] && isset($thread_id)) {
|
||||
$query = prepare(sprintf("SELECT `sage` FROM ``posts_%s`` WHERE `id` = :thread", $board['uri']));
|
||||
$query->bindValue(':thread', $thread_id);
|
||||
$query->execute() or error(db_error($query));
|
||||
$bumplocked = (bool)$query->fetchColumn();
|
||||
// No need to run on OPs
|
||||
if ($config['anti_bump_flood'] && isset($thread_id)) {
|
||||
$query = prepare(sprintf("SELECT `sage` FROM ``posts_%s`` WHERE `id` = :thread", $board['uri']));
|
||||
$query->bindValue(':thread', $thread_id);
|
||||
$query->execute() or error(db_error($query));
|
||||
$bumplocked = (bool)$query->fetchColumn();
|
||||
|
||||
if (!$bumplocked) {
|
||||
$query = prepare(sprintf("SELECT `time` FROM ``posts_%s`` WHERE (`thread` = :thread AND NOT email <=> 'sage') OR `id` = :thread ORDER BY `time` DESC LIMIT 1", $board['uri']));
|
||||
$query->bindValue(':thread', $thread_id);
|
||||
$query->execute() or error(db_error($query));
|
||||
$bump = $query->fetchColumn();
|
||||
if (!$bumplocked) {
|
||||
$query = prepare(sprintf("SELECT `time` FROM ``posts_%s`` WHERE (`thread` = :thread AND NOT email <=> 'sage') OR `id` = :thread ORDER BY `time` DESC LIMIT 1", $board['uri']));
|
||||
$query->bindValue(':thread', $thread_id);
|
||||
$query->execute() or error(db_error($query));
|
||||
$bump = $query->fetchColumn();
|
||||
|
||||
$query = prepare(sprintf("UPDATE ``posts_%s`` SET `bump` = :bump WHERE `id` = :thread", $board['uri']));
|
||||
$query->bindValue(':bump', $bump);
|
||||
$query->bindValue(':thread', $thread_id);
|
||||
$query->execute() or error(db_error($query));
|
||||
}
|
||||
}
|
||||
$query = prepare(sprintf("UPDATE ``posts_%s`` SET `bump` = :bump WHERE `id` = :thread", $board['uri']));
|
||||
$query->bindValue(':bump', $bump);
|
||||
$query->bindValue(':thread', $thread_id);
|
||||
$query->execute() or error(db_error($query));
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($rebuild) && $rebuild_after) {
|
||||
buildThread($rebuild);
|
||||
@@ -2029,7 +1996,7 @@ function extract_modifiers($body) {
|
||||
}
|
||||
|
||||
function remove_modifiers($body) {
|
||||
return preg_replace('@<tinyboard ([\w\s]+)>(.+?)</tinyboard>@usm', '', $body);
|
||||
return $body ? preg_replace('@<tinyboard ([\w\s]+)>(.+?)</tinyboard>@usm', '', $body) : null;
|
||||
}
|
||||
|
||||
function markup(&$body, $track_cites = false, $op = false) {
|
||||
@@ -2298,6 +2265,7 @@ function escape_markup_modifiers($string) {
|
||||
}
|
||||
|
||||
function defined_flags_accumulate($desired_flags) {
|
||||
global $config;
|
||||
$output_flags = 0x0;
|
||||
foreach ($desired_flags as $flagname) {
|
||||
if (defined($flagname)) {
|
||||
@@ -2315,7 +2283,7 @@ function defined_flags_accumulate($desired_flags) {
|
||||
|
||||
function utf8tohtml($utf8) {
|
||||
$flags = defined_flags_accumulate(['ENT_NOQUOTES', 'ENT_SUBSTITUTE', 'ENT_DISALLOWED']);
|
||||
return htmlspecialchars($utf8, $flags, 'UTF-8');
|
||||
return $utf8 ? htmlspecialchars($utf8, $flags, 'UTF-8') : '';
|
||||
}
|
||||
|
||||
function ordutf8($string, &$offset) {
|
||||
@@ -2572,35 +2540,6 @@ function generate_tripcode($name) {
|
||||
return array($name, $trip);
|
||||
}
|
||||
|
||||
// Highest common factor
|
||||
function hcf($a, $b){
|
||||
$gcd = 1;
|
||||
if ($a>$b) {
|
||||
$a = $a+$b;
|
||||
$b = $a-$b;
|
||||
$a = $a-$b;
|
||||
}
|
||||
if ($b==(round($b/$a))*$a)
|
||||
$gcd=$a;
|
||||
else {
|
||||
for ($i=round($a/2);$i;$i--) {
|
||||
if ($a == round($a/$i)*$i && $b == round($b/$i)*$i) {
|
||||
$gcd = $i;
|
||||
$i = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $gcd;
|
||||
}
|
||||
|
||||
function fraction($numerator, $denominator, $sep) {
|
||||
$gcf = hcf($numerator, $denominator);
|
||||
$numerator = $numerator / $gcf;
|
||||
$denominator = $denominator / $gcf;
|
||||
|
||||
return "{$numerator}{$sep}{$denominator}";
|
||||
}
|
||||
|
||||
function getPostByHash($hash) {
|
||||
global $board;
|
||||
$query = prepare(sprintf("SELECT `id`,`thread` FROM ``posts_%s`` WHERE `filehash` = :hash", $board['uri']));
|
||||
@@ -2835,10 +2774,10 @@ function link_for($post, $page50 = false, $foreignlink = false, $thread = false)
|
||||
|
||||
if ($slug === false) {
|
||||
$query = prepare(sprintf("SELECT `slug` FROM ``posts_%s`` WHERE `id` = :id", $b['uri']));
|
||||
$query->bindValue(':id', $id, PDO::PARAM_INT);
|
||||
$query->execute() or error(db_error($query));
|
||||
$query->bindValue(':id', $id, PDO::PARAM_INT);
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
$thread = $query->fetch(PDO::FETCH_ASSOC);
|
||||
$thread = $query->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
$slug = $thread['slug'];
|
||||
|
||||
@@ -2854,7 +2793,7 @@ function link_for($post, $page50 = false, $foreignlink = false, $thread = false)
|
||||
}
|
||||
|
||||
|
||||
if ( $page50 && $slug) $tpl = $config['file_page50_slug'];
|
||||
if ( $page50 && $slug) $tpl = $config['file_page50_slug'];
|
||||
else if (!$page50 && $slug) $tpl = $config['file_page_slug'];
|
||||
else if ( $page50 && !$slug) $tpl = $config['file_page50'];
|
||||
else if (!$page50 && !$slug) $tpl = $config['file_page'];
|
||||
@@ -2866,24 +2805,6 @@ function prettify_textarea($s){
|
||||
return str_replace("\t", '	', str_replace("\n", ' ', htmlentities($s)));
|
||||
}
|
||||
|
||||
/*class HTMLPurifier_URIFilter_NoExternalImages extends HTMLPurifier_URIFilter {
|
||||
public $name = 'NoExternalImages';
|
||||
public function filter(&$uri, $c, $context) {
|
||||
global $config;
|
||||
$ct = $context->get('CurrentToken');
|
||||
|
||||
if (!$ct || $ct->name !== 'img') return true;
|
||||
|
||||
if (!isset($uri->host) && !isset($uri->scheme)) return true;
|
||||
|
||||
if (!in_array($uri->scheme . '://' . $uri->host . '/', $config['allowed_offsite_urls'])) {
|
||||
error('No off-site links in board announcement images.');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}*/
|
||||
|
||||
function purify_html($s) {
|
||||
global $config;
|
||||
|
||||
@@ -2899,7 +2820,6 @@ function purify_html($s) {
|
||||
function markdown($s) {
|
||||
$pd = new Parsedown();
|
||||
$pd->setMarkupEscaped(true);
|
||||
$pd->setimagesEnabled(false);
|
||||
|
||||
return $pd->text($s);
|
||||
}
|
||||
@@ -2918,7 +2838,20 @@ function generation_strategy($fun, $array=array()) { global $config;
|
||||
return 'rebuild';
|
||||
case 'defer':
|
||||
// Ok, it gets interesting here :)
|
||||
get_queue('generate')->push(serialize(array('build', $fun, $array, $action)));
|
||||
$queue = Queues::get_queue($config, 'generate');
|
||||
if ($queue === false) {
|
||||
if ($config['syslog']) {
|
||||
_syslog(LOG_ERR, "Could not initialize generate queue, falling back to immediate rebuild strategy");
|
||||
}
|
||||
return 'rebuild';
|
||||
}
|
||||
$ret = $queue->push(serialize(array('build', $fun, $array, $action)));
|
||||
if ($ret === false) {
|
||||
if ($config['syslog']) {
|
||||
_syslog(LOG_ERR, "Could not push item in the queue, falling back to immediate rebuild strategy");
|
||||
}
|
||||
return 'rebuild';
|
||||
}
|
||||
return 'ignore';
|
||||
case 'build_on_load':
|
||||
return 'delete';
|
||||
|
||||
28
inc/functions/format.php
Normal file
28
inc/functions/format.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
namespace Vichan\Functions\Format;
|
||||
|
||||
|
||||
function format_timestamp(int $delta): string {
|
||||
switch (true) {
|
||||
case $delta < 60:
|
||||
return $delta . ' ' . ngettext('second', 'seconds', $delta);
|
||||
case $delta < 3600: //60*60 = 3600
|
||||
return ($num = round($delta/ 60)) . ' ' . ngettext('minute', 'minutes', $num);
|
||||
case $delta < 86400: //60*60*24 = 86400
|
||||
return ($num = round($delta / 3600)) . ' ' . ngettext('hour', 'hours', $num);
|
||||
case $delta < 604800: //60*60*24*7 = 604800
|
||||
return ($num = round($delta / 86400)) . ' ' . ngettext('day', 'days', $num);
|
||||
case $delta < 31536000: //60*60*24*365 = 31536000
|
||||
return ($num = round($delta / 604800)) . ' ' . ngettext('week', 'weeks', $num);
|
||||
default:
|
||||
return ($num = round($delta / 31536000)) . ' ' . ngettext('year', 'years', $num);
|
||||
}
|
||||
}
|
||||
|
||||
function until(int $timestamp): string {
|
||||
return format_timestamp($timestamp - time());
|
||||
}
|
||||
|
||||
function ago(int $timestamp): string {
|
||||
return format_timestamp(time() - $timestamp);
|
||||
}
|
||||
16
inc/functions/net.php
Normal file
16
inc/functions/net.php
Normal file
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
namespace Vichan\Functions\Net;
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $trust_headers. If true, trust the `HTTP_X_FORWARDED_PROTO` header to check if the connection is HTTPS.
|
||||
* @return bool Returns if the client-server connection is an encrypted one (HTTPS).
|
||||
*/
|
||||
function is_connection_secure(bool $trust_headers): bool {
|
||||
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
|
||||
return true;
|
||||
} elseif ($trust_headers && isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
33
inc/functions/num.php
Normal file
33
inc/functions/num.php
Normal file
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
namespace Vichan\Functions\Num;
|
||||
|
||||
// Highest common factor
|
||||
function hcf($a, $b){
|
||||
$gcd = 1;
|
||||
|
||||
if ($a > $b) {
|
||||
$a = $a+$b;
|
||||
$b = $a-$b;
|
||||
$a = $a-$b;
|
||||
}
|
||||
if ($b == (round($b / $a)) * $a) {
|
||||
$gcd = $a;
|
||||
} else {
|
||||
for ($i = round($a / 2); $i; $i--) {
|
||||
if ($a == round($a / $i) * $i && $b == round($b / $i) * $i) {
|
||||
$gcd = $i;
|
||||
$i = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $gcd;
|
||||
}
|
||||
|
||||
function fraction($numerator, $denominator, $sep) {
|
||||
$gcf = hcf($numerator, $denominator);
|
||||
$numerator = $numerator / $gcf;
|
||||
$denominator = $denominator / $gcf;
|
||||
|
||||
return "{$numerator}{$sep}{$denominator}";
|
||||
}
|
||||
@@ -291,6 +291,7 @@ class ImageConvert extends ImageBase {
|
||||
} else {
|
||||
rename($this->temp, $src);
|
||||
chmod($src, 0664);
|
||||
$this->temp = false;
|
||||
}
|
||||
}
|
||||
public function width() {
|
||||
@@ -300,8 +301,10 @@ class ImageConvert extends ImageBase {
|
||||
return $this->height;
|
||||
}
|
||||
public function destroy() {
|
||||
@unlink($this->temp);
|
||||
$this->temp = false;
|
||||
if ($this->temp !== false) {
|
||||
@unlink($this->temp);
|
||||
$this->temp = false;
|
||||
}
|
||||
}
|
||||
public function resize() {
|
||||
global $config;
|
||||
|
||||
111
inc/lock.php
111
inc/lock.php
@@ -1,39 +1,84 @@
|
||||
<?php
|
||||
class Lock {
|
||||
function __construct($key) { global $config;
|
||||
if ($config['lock']['enabled'] == 'fs') {
|
||||
$key = str_replace('/', '::', $key);
|
||||
$key = str_replace("\0", '', $key);
|
||||
|
||||
$this->f = fopen("tmp/locks/$key", "w");
|
||||
}
|
||||
}
|
||||
class Locks {
|
||||
private static function filesystem(string $key): Lock|false {
|
||||
$key = str_replace('/', '::', $key);
|
||||
$key = str_replace("\0", '', $key);
|
||||
|
||||
// Get a shared lock
|
||||
function get($nonblock = false) { global $config;
|
||||
if ($config['lock']['enabled'] == 'fs') {
|
||||
$wouldblock = false;
|
||||
flock($this->f, LOCK_SH | ($nonblock ? LOCK_NB : 0), $wouldblock);
|
||||
if ($nonblock && $wouldblock) return false;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
$fd = fopen("tmp/locks/$key", "w");
|
||||
if ($fd === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get an exclusive lock
|
||||
function get_ex($nonblock = false) { global $config;
|
||||
if ($config['lock']['enabled'] == 'fs') {
|
||||
$wouldblock = false;
|
||||
flock($this->f, LOCK_EX | ($nonblock ? LOCK_NB : 0), $wouldblock);
|
||||
if ($nonblock && $wouldblock) return false;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
return new class($fd) implements Lock {
|
||||
// Resources have no type in php.
|
||||
private mixed $f;
|
||||
|
||||
// Free a lock
|
||||
function free() { global $config;
|
||||
if ($config['lock']['enabled'] == 'fs') {
|
||||
flock($this->f, LOCK_UN);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
function __construct($fd) {
|
||||
$this->f = $fd;
|
||||
}
|
||||
|
||||
public function get(bool $nonblock = false): Lock|false {
|
||||
$wouldblock = false;
|
||||
flock($this->f, LOCK_SH | ($nonblock ? LOCK_NB : 0), $wouldblock);
|
||||
if ($nonblock && $wouldblock) {
|
||||
return false;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_ex(bool $nonblock = false): Lock|false {
|
||||
$wouldblock = false;
|
||||
flock($this->f, LOCK_EX | ($nonblock ? LOCK_NB : 0), $wouldblock);
|
||||
if ($nonblock && $wouldblock) {
|
||||
return false;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function free(): Lock {
|
||||
flock($this->f, LOCK_UN);
|
||||
return $this;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* No-op. Can be used for mocking.
|
||||
*/
|
||||
public static function none(): Lock|false {
|
||||
return new class() implements Lock {
|
||||
public function get(bool $nonblock = false): Lock|false {
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_ex(bool $nonblock = false): Lock|false {
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function free(): Lock {
|
||||
return $this;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static function get_lock(array $config, string $key): Lock|false {
|
||||
if ($config['lock']['enabled'] == 'fs') {
|
||||
return self::filesystem($key);
|
||||
} else {
|
||||
return self::none();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface Lock {
|
||||
// Get a shared lock
|
||||
public function get(bool $nonblock = false): Lock|false;
|
||||
|
||||
// Get an exclusive lock
|
||||
public function get_ex(bool $nonblock = false): Lock|false;
|
||||
|
||||
// Free a lock
|
||||
public function free(): Lock;
|
||||
}
|
||||
|
||||
200
inc/mod/auth.php
200
inc/mod/auth.php
@@ -4,19 +4,21 @@
|
||||
* Copyright (c) 2010-2013 Tinyboard Development Group
|
||||
*/
|
||||
|
||||
use Vichan\Functions\Net;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
// create a hash/salt pair for validate logins
|
||||
function mkhash($username, $password, $salt = false) {
|
||||
function mkhash(string $username, string $password, mixed $salt = false): array|string {
|
||||
global $config;
|
||||
|
||||
|
||||
if (!$salt) {
|
||||
// create some sort of salt for the hash
|
||||
$salt = substr(base64_encode(sha1(rand() . time(), true) . $config['cookies']['salt']), 0, 15);
|
||||
|
||||
|
||||
$generated_salt = true;
|
||||
}
|
||||
|
||||
|
||||
// generate hash (method is not important as long as it's strong)
|
||||
$hash = substr(
|
||||
base64_encode(
|
||||
@@ -30,62 +32,59 @@ function mkhash($username, $password, $salt = false) {
|
||||
)
|
||||
), 0, 20
|
||||
);
|
||||
|
||||
if (isset($generated_salt))
|
||||
return array($hash, $salt);
|
||||
else
|
||||
|
||||
if (isset($generated_salt)) {
|
||||
return [ $hash, $salt ];
|
||||
} else {
|
||||
return $hash;
|
||||
}
|
||||
}
|
||||
|
||||
function crypt_password_old($password) {
|
||||
$salt = generate_salt();
|
||||
$password = hash('sha256', $salt . sha1($password));
|
||||
return array($salt, $password);
|
||||
}
|
||||
|
||||
function crypt_password($password) {
|
||||
function crypt_password(string $password): array {
|
||||
global $config;
|
||||
// `salt` database field is reused as a version value. We don't want it to be 0.
|
||||
$version = $config['password_crypt_version'] ? $config['password_crypt_version'] : 1;
|
||||
$new_salt = generate_salt();
|
||||
$password = crypt($password, $config['password_crypt'] . $new_salt . "$");
|
||||
return array($version, $password);
|
||||
return [ $version, $password ];
|
||||
}
|
||||
|
||||
function test_password($password, $salt, $test) {
|
||||
global $config;
|
||||
|
||||
function test_password(string $password, string $salt, string $test): array {
|
||||
// Version = 0 denotes an old password hashing schema. In the same column, the
|
||||
// password hash was kept previously
|
||||
$version = (strlen($salt) <= 8) ? (int) $salt : 0;
|
||||
$version = strlen($salt) <= 8 ? (int)$salt : 0;
|
||||
|
||||
if ($version == 0) {
|
||||
$comp = hash('sha256', $salt . sha1($test));
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
$comp = crypt($test, $password);
|
||||
}
|
||||
return array($version, hash_equals($password, $comp));
|
||||
return [ $version, hash_equals($password, $comp) ];
|
||||
}
|
||||
|
||||
function generate_salt() {
|
||||
// mcrypt_create_iv() was deprecated in PHP 7.1.0, only use it if we're below that version number.
|
||||
if (PHP_VERSION_ID < 70100) {
|
||||
// 128 bits of entropy
|
||||
return strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
|
||||
}
|
||||
|
||||
// Otherwise, use random_bytes()
|
||||
function generate_salt(): string {
|
||||
return strtr(base64_encode(random_bytes(16)), '+', '.');
|
||||
}
|
||||
|
||||
function login($username, $password) {
|
||||
function calc_cookie_name(bool $is_https, bool $is_path_jailed, string $base_name): string {
|
||||
if ($is_https) {
|
||||
if ($is_path_jailed) {
|
||||
return "__Host-$base_name";
|
||||
} else {
|
||||
return "__Secure-$base_name";
|
||||
}
|
||||
} else {
|
||||
return $base_name;
|
||||
}
|
||||
}
|
||||
|
||||
function login(string $username, string $password): array|false {
|
||||
global $mod, $config;
|
||||
|
||||
|
||||
$query = prepare("SELECT `id`, `type`, `boards`, `password`, `version` FROM ``mods`` WHERE BINARY `username` = :username");
|
||||
$query->bindValue(':username', $username);
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
|
||||
if ($user = $query->fetch(PDO::FETCH_ASSOC)) {
|
||||
list($version, $ok) = test_password($user['password'], $user['version'], $password);
|
||||
|
||||
@@ -100,40 +99,83 @@ function login($username, $password) {
|
||||
$query->execute() or error(db_error($query));
|
||||
}
|
||||
|
||||
return $mod = array(
|
||||
return $mod = [
|
||||
'id' => $user['id'],
|
||||
'type' => $user['type'],
|
||||
'username' => $username,
|
||||
'hash' => mkhash($username, $user['password']),
|
||||
'boards' => explode(',', $user['boards'])
|
||||
);
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function setCookies() {
|
||||
function setCookies(): void {
|
||||
global $mod, $config;
|
||||
if (!$mod)
|
||||
if (!$mod) {
|
||||
error('setCookies() was called for a non-moderator!');
|
||||
|
||||
setcookie($config['cookies']['mod'],
|
||||
$mod['username'] . // username
|
||||
':' .
|
||||
$mod['hash'][0] . // password
|
||||
':' .
|
||||
$mod['hash'][1], // salt
|
||||
time() + $config['cookies']['expire'], $config['cookies']['jail'] ? $config['cookies']['path'] : '/', null, !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off', $config['cookies']['httponly']);
|
||||
}
|
||||
|
||||
$is_https = Net\is_connection_secure($config['cookies']['secure_login_only'] === 1);
|
||||
$is_path_jailed = $config['cookies']['jail'];
|
||||
$name = calc_cookie_name($is_https, $is_path_jailed, $config['cookies']['mod']);
|
||||
|
||||
// <username>:<password>:<salt>
|
||||
$value = "{$mod['username']}:{$mod['hash'][0]}:{$mod['hash'][1]}";
|
||||
|
||||
$options = [
|
||||
'expires' => time() + $config['cookies']['expire'],
|
||||
'path' => $is_path_jailed ? $config['cookies']['path'] : '/',
|
||||
'secure' => $is_https,
|
||||
'httponly' => $config['cookies']['httponly'],
|
||||
'samesite' => 'Strict'
|
||||
];
|
||||
|
||||
setcookie($name, $value, $options);
|
||||
}
|
||||
|
||||
function destroyCookies() {
|
||||
function destroyCookies(): void {
|
||||
global $config;
|
||||
// Delete the cookies
|
||||
setcookie($config['cookies']['mod'], 'deleted', time() - $config['cookies']['expire'], $config['cookies']['jail']?$config['cookies']['path'] : '/', null, !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off', true);
|
||||
$base_name = $config['cookies']['mod'];
|
||||
$del_time = time() - 60 * 60 * 24 * 365; // 1 year.
|
||||
$jailed_path = $config['cookies']['jail'] ? $config['cookies']['path'] : '/';
|
||||
$http_only = $config['cookies']['httponly'];
|
||||
|
||||
$options_multi = [
|
||||
$base_name => [
|
||||
'expires' => $del_time,
|
||||
'path' => $jailed_path ,
|
||||
'secure' => false,
|
||||
'httponly' => $http_only,
|
||||
'samesite' => 'Strict'
|
||||
],
|
||||
"__Host-$base_name" => [
|
||||
'expires' => $del_time,
|
||||
'path' => $jailed_path,
|
||||
'secure' => true,
|
||||
'httponly' => $http_only,
|
||||
'samesite' => 'Strict'
|
||||
],
|
||||
"__Secure-$base_name" => [
|
||||
'expires' => $del_time,
|
||||
'path' => '/',
|
||||
'secure' => true,
|
||||
'httponly' => $http_only,
|
||||
'samesite' => 'Strict'
|
||||
]
|
||||
];
|
||||
|
||||
foreach ($options_multi as $name => $options) {
|
||||
if (isset($_COOKIE[$name])) {
|
||||
setcookie($name, 'deleted', $options);
|
||||
unset($_COOKIE[$name]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function modLog($action, $_board=null) {
|
||||
function modLog(string $action, ?string $_board = null): void {
|
||||
global $mod, $board, $config;
|
||||
$query = prepare("INSERT INTO ``modlogs`` VALUES (:id, :ip, :board, :time, :text)");
|
||||
$query->bindValue(':id', (isset($mod['id']) ? $mod['id'] : -1), PDO::PARAM_INT);
|
||||
@@ -147,62 +189,72 @@ function modLog($action, $_board=null) {
|
||||
else
|
||||
$query->bindValue(':board', null, PDO::PARAM_NULL);
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
if ($config['syslog'])
|
||||
|
||||
if ($config['syslog']) {
|
||||
_syslog(LOG_INFO, '[mod/' . $mod['username'] . ']: ' . $action);
|
||||
}
|
||||
}
|
||||
|
||||
function create_pm_header() {
|
||||
function create_pm_header(): mixed {
|
||||
global $mod, $config;
|
||||
|
||||
|
||||
if ($config['cache']['enabled'] && ($header = cache::get('pm_unread_' . $mod['id'])) != false) {
|
||||
if ($header === true)
|
||||
if ($header === true) {
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
return $header;
|
||||
}
|
||||
|
||||
|
||||
$query = prepare("SELECT `id` FROM ``pms`` WHERE `to` = :id AND `unread` = 1");
|
||||
$query->bindValue(':id', $mod['id'], PDO::PARAM_INT);
|
||||
$query->execute() or error(db_error($query));
|
||||
|
||||
if ($pm = $query->fetch(PDO::FETCH_ASSOC))
|
||||
$header = array('id' => $pm['id'], 'waiting' => $query->rowCount() - 1);
|
||||
else
|
||||
|
||||
if ($pm = $query->fetch(PDO::FETCH_ASSOC)) {
|
||||
$header = [ 'id' => $pm['id'], 'waiting' => $query->rowCount() - 1 ];
|
||||
} else {
|
||||
$header = true;
|
||||
|
||||
if ($config['cache']['enabled'])
|
||||
}
|
||||
|
||||
if ($config['cache']['enabled']) {
|
||||
cache::set('pm_unread_' . $mod['id'], $header);
|
||||
|
||||
if ($header === true)
|
||||
}
|
||||
|
||||
if ($header === true) {
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
return $header;
|
||||
}
|
||||
|
||||
function make_secure_link_token($uri) {
|
||||
function make_secure_link_token(string $uri): string {
|
||||
global $mod, $config;
|
||||
return substr(sha1($config['cookies']['salt'] . '-' . $uri . '-' . $mod['id']), 0, 8);
|
||||
}
|
||||
|
||||
function check_login($prompt = false) {
|
||||
function check_login(bool $prompt = false): void {
|
||||
global $config, $mod;
|
||||
|
||||
$is_https = Net\is_connection_secure($config['cookies']['secure_login_only'] === 1);
|
||||
$is_path_jailed = $config['cookies']['jail'];
|
||||
$expected_cookie_name = calc_cookie_name($is_https, $is_path_jailed, $config['cookies']['mod']);
|
||||
|
||||
// Validate session
|
||||
if (isset($_COOKIE[$config['cookies']['mod']])) {
|
||||
if (isset($_COOKIE[$expected_cookie_name])) {
|
||||
// Should be username:hash:salt
|
||||
$cookie = explode(':', $_COOKIE[$config['cookies']['mod']]);
|
||||
$cookie = explode(':', $_COOKIE[$expected_cookie_name]);
|
||||
if (count($cookie) != 3) {
|
||||
// Malformed cookies
|
||||
destroyCookies();
|
||||
if ($prompt) mod_login();
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
$query = prepare("SELECT `id`, `type`, `boards`, `password` FROM ``mods`` WHERE `username` = :username");
|
||||
$query->bindValue(':username', $cookie[0]);
|
||||
$query->execute() or error(db_error($query));
|
||||
$user = $query->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
|
||||
// validate password hash
|
||||
if ($cookie[1] !== mkhash($cookie[0], $user['password'], $cookie[2])) {
|
||||
// Malformed cookies
|
||||
@@ -210,7 +262,7 @@ function check_login($prompt = false) {
|
||||
if ($prompt) mod_login();
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
$mod = array(
|
||||
'id' => (int)$user['id'],
|
||||
'type' => (int)$user['type'],
|
||||
|
||||
@@ -3,9 +3,13 @@
|
||||
/*
|
||||
* Copyright (c) 2010-2013 Tinyboard Development Group
|
||||
*/
|
||||
use Vichan\Functions\Format;
|
||||
|
||||
use Vichan\Functions\Net;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
function mod_page($title, $template, $args, $subtitle = false) {
|
||||
global $config, $mod;
|
||||
|
||||
@@ -29,9 +33,12 @@ function mod_page($title, $template, $args, $subtitle = false) {
|
||||
function mod_login($redirect = false) {
|
||||
global $config;
|
||||
|
||||
$args = array();
|
||||
$args = [];
|
||||
|
||||
if (isset($_POST['login'])) {
|
||||
$secure_login_mode = $config['cookies']['secure_login_only'];
|
||||
if ($secure_login_mode !== 0 && !Net\is_connection_secure($secure_login_mode === 1)) {
|
||||
$args['error'] = $config['error']['insecure'];
|
||||
} elseif (isset($_POST['login'])) {
|
||||
// Check if inputs are set and not empty
|
||||
if (!isset($_POST['username'], $_POST['password']) || $_POST['username'] == '' || $_POST['password'] == '') {
|
||||
$args['error'] = $config['error']['invalid'];
|
||||
@@ -1335,8 +1342,8 @@ function mod_move($originBoard, $postID) {
|
||||
if ($targetBoard === $originBoard)
|
||||
error(_('Target and source board are the same.'));
|
||||
|
||||
// copy() if leaving a shadow thread behind; else, rename().
|
||||
$clone = $shadow ? 'copy' : 'rename';
|
||||
// link() if leaving a shadow thread behind; else, rename().
|
||||
$clone = $shadow ? 'link' : 'rename';
|
||||
|
||||
// indicate that the post is a thread
|
||||
$post['op'] = true;
|
||||
@@ -1553,7 +1560,7 @@ function mod_ban_post($board, $delete, $post, $token = false) {
|
||||
|
||||
if (isset($_POST['public_message'], $_POST['message'])) {
|
||||
// public ban message
|
||||
$length_english = Bans::parse_time($_POST['length']) ? 'for ' . until(Bans::parse_time($_POST['length'])) : 'permanently';
|
||||
$length_english = Bans::parse_time($_POST['length']) ? 'for ' . Format\until(Bans::parse_time($_POST['length'])) : 'permanently';
|
||||
$_POST['message'] = preg_replace('/[\r\n]/', '', $_POST['message']);
|
||||
$_POST['message'] = str_replace('%length%', $length_english, $_POST['message']);
|
||||
$_POST['message'] = str_replace('%LENGTH%', strtoupper($length_english), $_POST['message']);
|
||||
|
||||
131
inc/queue.php
131
inc/queue.php
@@ -1,49 +1,98 @@
|
||||
<?php
|
||||
|
||||
class Queue {
|
||||
function __construct($key) { global $config;
|
||||
if ($config['queue']['enabled'] == 'fs') {
|
||||
$this->lock = new Lock($key);
|
||||
$key = str_replace('/', '::', $key);
|
||||
$key = str_replace("\0", '', $key);
|
||||
$this->key = "tmp/queue/$key/";
|
||||
}
|
||||
}
|
||||
class Queues {
|
||||
private static $queues = array();
|
||||
|
||||
function push($str) { global $config;
|
||||
if ($config['queue']['enabled'] == 'fs') {
|
||||
$this->lock->get_ex();
|
||||
file_put_contents($this->key.microtime(true), $str);
|
||||
$this->lock->free();
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
function pop($n = 1) { global $config;
|
||||
if ($config['queue']['enabled'] == 'fs') {
|
||||
$this->lock->get_ex();
|
||||
$dir = opendir($this->key);
|
||||
$paths = array();
|
||||
while ($n > 0) {
|
||||
$path = readdir($dir);
|
||||
if ($path === FALSE) break;
|
||||
elseif ($path == '.' || $path == '..') continue;
|
||||
else { $paths[] = $path; $n--; }
|
||||
}
|
||||
$out = array();
|
||||
foreach ($paths as $v) {
|
||||
$out []= file_get_contents($this->key.$v);
|
||||
unlink($this->key.$v);
|
||||
}
|
||||
$this->lock->free();
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* This queue implementation isn't actually ordered, so it works more as a "bag".
|
||||
*/
|
||||
private static function filesystem(string $key, Lock $lock): Queue {
|
||||
$key = str_replace('/', '::', $key);
|
||||
$key = str_replace("\0", '', $key);
|
||||
$key = "tmp/queue/$key/";
|
||||
|
||||
return new class($key, $lock) implements Queue {
|
||||
private Lock $lock;
|
||||
private string $key;
|
||||
|
||||
|
||||
function __construct(string $key, Lock $lock) {
|
||||
$this->lock = $lock;
|
||||
$this->key = $key;
|
||||
}
|
||||
|
||||
public function push(string $str): bool {
|
||||
$this->lock->get_ex();
|
||||
$ret = file_put_contents($this->key . microtime(true), $str);
|
||||
$this->lock->free();
|
||||
return $ret !== false;
|
||||
}
|
||||
|
||||
public function pop(int $n = 1): array {
|
||||
$this->lock->get_ex();
|
||||
$dir = opendir($this->key);
|
||||
$paths = array();
|
||||
|
||||
while ($n > 0) {
|
||||
$path = readdir($dir);
|
||||
if ($path === false) {
|
||||
break;
|
||||
} elseif ($path == '.' || $path == '..') {
|
||||
continue;
|
||||
} else {
|
||||
$paths[] = $path;
|
||||
$n--;
|
||||
}
|
||||
}
|
||||
|
||||
$out = array();
|
||||
foreach ($paths as $v) {
|
||||
$out[] = file_get_contents($this->key . $v);
|
||||
unlink($this->key . $v);
|
||||
}
|
||||
|
||||
$this->lock->free();
|
||||
return $out;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* No-op. Can be used for mocking.
|
||||
*/
|
||||
public static function none(): Queue {
|
||||
return new class() implements Queue {
|
||||
public function push(string $str): bool {
|
||||
return true;
|
||||
}
|
||||
|
||||
public function pop(int $n = 1): array {
|
||||
return array();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static function get_queue(array $config, string $name): Queue|false {
|
||||
if (!isset(self::$queues[$name])) {
|
||||
if ($config['queue']['enabled'] == 'fs') {
|
||||
$lock = Locks::get_lock($config, $name);
|
||||
if ($lock === false) {
|
||||
return false;
|
||||
}
|
||||
self::$queues[$name] = self::filesystem($name, $lock);
|
||||
} else {
|
||||
self::$queues[$name] = self::none();
|
||||
}
|
||||
}
|
||||
return self::$queues[$name];
|
||||
}
|
||||
}
|
||||
|
||||
// Don't use the constructor. Use the get_queue function.
|
||||
$queues = array();
|
||||
interface Queue {
|
||||
// Push a string in the queue.
|
||||
public function push(string $str): bool;
|
||||
|
||||
function get_queue($name) { global $queues;
|
||||
return $queues[$name] = isset ($queues[$name]) ? $queues[$name] : new Queue($name);
|
||||
// Get a string from the queue.
|
||||
public function pop(int $n = 1): array;
|
||||
}
|
||||
|
||||
102
inc/service/captcha-queries.php
Normal file
102
inc/service/captcha-queries.php
Normal file
@@ -0,0 +1,102 @@
|
||||
<?php // Verify captchas server side.
|
||||
namespace Vichan\Service;
|
||||
|
||||
use Vichan\Driver\HttpDriver;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
class RemoteCaptchaQuery {
|
||||
private HttpDriver $http;
|
||||
private string $secret;
|
||||
private string $endpoint;
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new CaptchaRemoteQueries instance using the google recaptcha service.
|
||||
*
|
||||
* @param HttpDriver $http The http client.
|
||||
* @param string $secret Server side secret.
|
||||
* @return CaptchaRemoteQueries A new captcha query instance.
|
||||
*/
|
||||
public static function withRecaptcha(HttpDriver $http, string $secret): RemoteCaptchaQuery {
|
||||
return new self($http, $secret, 'https://www.google.com/recaptcha/api/siteverify');
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new CaptchaRemoteQueries instance using the hcaptcha service.
|
||||
*
|
||||
* @param HttpDriver $http The http client.
|
||||
* @param string $secret Server side secret.
|
||||
* @return CaptchaRemoteQueries A new captcha query instance.
|
||||
*/
|
||||
public static function withHCaptcha(HttpDriver $http, string $secret): RemoteCaptchaQuery {
|
||||
return new self($http, $secret, 'https://hcaptcha.com/siteverify');
|
||||
}
|
||||
|
||||
private function __construct(HttpDriver $http, string $secret, string $endpoint) {
|
||||
$this->http = $http;
|
||||
$this->secret = $secret;
|
||||
$this->endpoint = $endpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the user at the remote ip passed the captcha.
|
||||
*
|
||||
* @param string $response User provided response.
|
||||
* @param string $remote_ip User ip.
|
||||
* @return bool Returns true if the user passed the captcha.
|
||||
* @throws RuntimeException|JsonException Throws on IO errors or if it fails to decode the answer.
|
||||
*/
|
||||
public function verify(string $response, string $remote_ip): bool {
|
||||
$data = array(
|
||||
'secret' => $this->secret,
|
||||
'response' => $response,
|
||||
'remoteip' => $remote_ip
|
||||
);
|
||||
|
||||
$ret = $this->http->requestGet($this->endpoint, $data);
|
||||
$resp = json_decode($ret, true, 16, JSON_THROW_ON_ERROR);
|
||||
|
||||
return isset($resp['success']) && $resp['success'];
|
||||
}
|
||||
}
|
||||
|
||||
class NativeCaptchaQuery {
|
||||
private HttpDriver $http;
|
||||
private string $domain;
|
||||
private string $provider_check;
|
||||
|
||||
|
||||
/**
|
||||
* @param HttpDriver $http The http client.
|
||||
* @param string $domain The server's domain.
|
||||
* @param string $provider_check Path to the endpoint.
|
||||
*/
|
||||
function __construct(HttpDriver $http, string $domain, string $provider_check) {
|
||||
$this->http = $http;
|
||||
$this->domain = $domain;
|
||||
$this->provider_check = $provider_check;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the user at the remote ip passed the native vichan captcha.
|
||||
*
|
||||
* @param string $extra Extra http parameters.
|
||||
* @param string $user_text Remote user's text input.
|
||||
* @param string $user_cookie Remote user cookie.
|
||||
* @return bool Returns true if the user passed the check.
|
||||
* @throws RuntimeException Throws on IO errors.
|
||||
*/
|
||||
public function verify(string $extra, string $user_text, string $user_cookie): bool {
|
||||
$data = array(
|
||||
'mode' => 'check',
|
||||
'text' => $user_text,
|
||||
'extra' => $extra,
|
||||
'cookie' => $user_cookie
|
||||
);
|
||||
|
||||
$ret = $this->http->requestGet($this->domain . '/' . $this->provider_check, $data);
|
||||
return $ret === '1';
|
||||
}
|
||||
}
|
||||
@@ -11,12 +11,14 @@ $twig = false;
|
||||
function load_twig() {
|
||||
global $twig, $config;
|
||||
|
||||
$cache_dir = "{$config['dir']['template']}/cache/";
|
||||
|
||||
$loader = new Twig\Loader\FilesystemLoader($config['dir']['template']);
|
||||
$loader->setPaths($config['dir']['template']);
|
||||
$twig = new Twig\Environment($loader, array(
|
||||
'autoescape' => false,
|
||||
'cache' => is_writable('templates') || (is_dir('templates/cache') && is_writable('templates/cache')) ?
|
||||
new Twig_Cache_TinyboardFilesystem("{$config['dir']['template']}/cache") : false,
|
||||
'cache' => is_writable('templates/') || (is_dir($cache_dir) && is_writable($cache_dir)) ?
|
||||
new TinyboardTwigCache($cache_dir) : false,
|
||||
'debug' => $config['debug'],
|
||||
'auto_reload' => $config['twig_auto_reload']
|
||||
));
|
||||
@@ -28,17 +30,17 @@ function load_twig() {
|
||||
|
||||
function Element($templateFile, array $options) {
|
||||
global $config, $debug, $twig, $build_pages;
|
||||
|
||||
|
||||
if (!$twig)
|
||||
load_twig();
|
||||
|
||||
|
||||
if (function_exists('create_pm_header') && ((isset($options['mod']) && $options['mod']) || isset($options['__mod'])) && !preg_match('!^mod/!', $templateFile)) {
|
||||
$options['pm'] = create_pm_header();
|
||||
}
|
||||
|
||||
|
||||
if (isset($options['body']) && $config['debug']) {
|
||||
$_debug = $debug;
|
||||
|
||||
|
||||
if (isset($debug['start'])) {
|
||||
$_debug['time']['total'] = '~' . round((microtime(true) - $_debug['start']) * 1000, 2) . 'ms';
|
||||
$_debug['time']['init'] = '~' . round(($_debug['start_debug'] - $_debug['start']) * 1000, 2) . 'ms';
|
||||
@@ -56,18 +58,44 @@ function Element($templateFile, array $options) {
|
||||
str_replace("\n", '<br/>', utf8tohtml(print_r($_debug, true))) .
|
||||
'</pre>';
|
||||
}
|
||||
|
||||
|
||||
// Read the template file
|
||||
if (@file_get_contents("{$config['dir']['template']}/${templateFile}")) {
|
||||
if (@file_get_contents("{$config['dir']['template']}/{$templateFile}")) {
|
||||
$body = $twig->render($templateFile, $options);
|
||||
|
||||
|
||||
if ($config['minify_html'] && preg_match('/\.html$/', $templateFile)) {
|
||||
$body = trim(preg_replace("/[\t\r\n]/", '', $body));
|
||||
}
|
||||
|
||||
|
||||
return $body;
|
||||
} else {
|
||||
throw new Exception("Template file '${templateFile}' does not exist or is empty in '{$config['dir']['template']}'!");
|
||||
throw new Exception("Template file '{$templateFile}' does not exist or is empty in '{$config['dir']['template']}'!");
|
||||
}
|
||||
}
|
||||
|
||||
class TinyboardTwigCache extends Twig\Cache\FilesystemCache {
|
||||
private string $directory;
|
||||
|
||||
public function __construct(string $directory) {
|
||||
parent::__construct($directory);
|
||||
$this->directory = $directory;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function was removed in Twig 2.x due to developer views on the Twig library.
|
||||
* Who says we can't keep it for ourselves though?
|
||||
*/
|
||||
public function clear() {
|
||||
$iter = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($this->directory),
|
||||
RecursiveIteratorIterator::LEAVES_ONLY
|
||||
);
|
||||
|
||||
foreach ($iter as $file) {
|
||||
if ($file->isFile()) {
|
||||
@unlink($file->getPathname());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,8 +121,8 @@ class Tinyboard extends Twig\Extension\AbstractExtension
|
||||
new Twig\TwigFilter('date', 'twig_date_filter'),
|
||||
new Twig\TwigFilter('poster_id', 'poster_id'),
|
||||
new Twig\TwigFilter('count', 'count'),
|
||||
new Twig\TwigFilter('ago', 'ago'),
|
||||
new Twig\TwigFilter('until', 'until'),
|
||||
new Twig\TwigFilter('ago', 'Vichan\Functions\Format\ago'),
|
||||
new Twig\TwigFilter('until', 'Vichan\Functions\Format\until'),
|
||||
new Twig\TwigFilter('push', 'twig_push_filter'),
|
||||
new Twig\TwigFilter('bidi_cleanup', 'bidi_cleanup'),
|
||||
new Twig\TwigFilter('addslashes', 'addslashes'),
|
||||
@@ -102,7 +130,7 @@ class Tinyboard extends Twig\Extension\AbstractExtension
|
||||
new Twig\TwigFilter('cloak_mask', 'cloak_mask'),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a list of functions to add to the existing list.
|
||||
*
|
||||
@@ -113,7 +141,6 @@ class Tinyboard extends Twig\Extension\AbstractExtension
|
||||
return array(
|
||||
new Twig\TwigFunction('time', 'time'),
|
||||
new Twig\TwigFunction('floor', 'floor'),
|
||||
new Twig\TwigFunction('timezone', 'twig_timezone_function'),
|
||||
new Twig\TwigFunction('hiddenInputs', 'hiddenInputs'),
|
||||
new Twig\TwigFunction('hiddenInputsHash', 'hiddenInputsHash'),
|
||||
new Twig\TwigFunction('ratio', 'twig_ratio_function'),
|
||||
@@ -122,7 +149,7 @@ class Tinyboard extends Twig\Extension\AbstractExtension
|
||||
new Twig\TwigFunction('link_for', 'link_for')
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the name of the extension.
|
||||
*
|
||||
@@ -134,17 +161,18 @@ class Tinyboard extends Twig\Extension\AbstractExtension
|
||||
}
|
||||
}
|
||||
|
||||
function twig_timezone_function() {
|
||||
return 'Z';
|
||||
}
|
||||
|
||||
function twig_push_filter($array, $value) {
|
||||
array_push($array, $value);
|
||||
return $array;
|
||||
}
|
||||
|
||||
function twig_date_filter($date, $format) {
|
||||
return gmstrftime($format, $date);
|
||||
if (is_numeric($date)) {
|
||||
$date = new DateTime("@$date", new DateTimeZone('UTC'));
|
||||
} else {
|
||||
$date = new DateTime($date, new DateTimeZone('UTC'));
|
||||
}
|
||||
return $date->format($format);
|
||||
}
|
||||
|
||||
function twig_hasPermission_filter($mod, $permission, $board = null) {
|
||||
@@ -154,7 +182,7 @@ function twig_hasPermission_filter($mod, $permission, $board = null) {
|
||||
function twig_extension_filter($value, $case_insensitive = true) {
|
||||
$ext = mb_substr($value, mb_strrpos($value, '.') + 1);
|
||||
if($case_insensitive)
|
||||
$ext = mb_strtolower($ext);
|
||||
$ext = mb_strtolower($ext);
|
||||
return $ext;
|
||||
}
|
||||
|
||||
@@ -179,7 +207,7 @@ function twig_filename_truncate_filter($value, $length = 30, $separator = '…')
|
||||
$value = strrev($value);
|
||||
$array = array_reverse(explode(".", $value, 2));
|
||||
$array = array_map("strrev", $array);
|
||||
|
||||
|
||||
$filename = &$array[0];
|
||||
$extension = isset($array[1]) ? $array[1] : false;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user