This commit is contained in:
czaks 2016-01-26 01:13:20 +01:00
commit d918fddea1
5 changed files with 206 additions and 112 deletions

21
404.php Normal file
View File

@ -0,0 +1,21 @@
<?php
require_once 'inc/functions.php';
$base=substr(dirname(str_replace($_SERVER['DOCUMENT_ROOT'], '', $_SERVER['SCRIPT_FILENAME'])), 1);
//echo "base[$base]<br>\n";
$path=trim($_SERVER['REQUEST_URI'], '/');
$path=str_replace($base.'/', '', $path);
if (file_exists($path) && !is_dir($path)) {
if (strpos($path, 'css')!==false) {
header('Content-type: text/css');
}
readfile($path);
exit();
}
if (is_dir($path)) {
$path.='/index.html';
}
$key='vichan_filecache_'.$path;
echo Cache::get($key);
?>

26
README.md Normal file → Executable file
View File

@ -1,7 +1,23 @@
vichan - A lightweight and full featured PHP imageboard. modified vichan
======================================================== ========================================================
About OdiliTime Modifications
-----------------------
This is a reduced disk-IO version that does not write the HTML or JSON files to disk.
It writes them to a redis-backed memory store which then can be quickly retrieved by a webserver
without hitting the disk at all. See nginx's HttpRedis2Module module for more of what I mean.
If you don't have HttpRedis2Module, i've included a 404.php that you can use with an htaccess like:
```
RewriteEngine On
RewriteRule ^[^/]+/$ %{REQUEST_URI}/../../404.php [NC,L]
RewriteRule ^[^/]+/[^/]+$ %{REQUEST_URI}/../../404.php [NC,L]
RewriteRule ^[^/]+/res/[^/]+$ %{REQUEST_URI}/../../404.php [NC,L]
```
This example assumes your URL includes one directory level, i.e. http://localhost/vichan/
About vichan
------------ ------------
vichan is a free light-weight, fast, highly configurable and user-friendly vichan is a free light-weight, fast, highly configurable and user-friendly
imageboard software package. It is written in PHP and has few dependencies. imageboard software package. It is written in PHP and has few dependencies.
@ -17,7 +33,7 @@ Requirements
1. PHP >= 5.4 (we still try to keep compatibility with php 5.3 as much as possible) 1. PHP >= 5.4 (we still try to keep compatibility with php 5.3 as much as possible)
PHP 7.0 is explicitly supported. PHP 7.0 is explicitly supported.
2. MySQL/MariaDB server 2. MySQL/MariaDB server
3. [mbstring](http://www.php.net/manual/en/mbstring.installation.php) 3. [mbstring](http://www.php.net/manual/en/mbstring.installation.php)
4. [PHP GD](http://www.php.net/manual/en/intro.image.php) 4. [PHP GD](http://www.php.net/manual/en/intro.image.php)
5. [PHP PDO](http://www.php.net/manual/en/intro.pdo.php) 5. [PHP PDO](http://www.php.net/manual/en/intro.pdo.php)
@ -47,7 +63,7 @@ Installation
development version with: development version with:
git clone git://github.com/vichan-devel/vichan.git git clone git://github.com/vichan-devel/vichan.git
2. Navigate to ```install.php``` in your web browser and follow the 2. Navigate to ```install.php``` in your web browser and follow the
prompts. prompts.
3. vichan should now be installed. Log in to ```mod.php``` with the 3. vichan should now be installed. Log in to ```mod.php``` with the
@ -84,7 +100,7 @@ find support from a variety of sources:
### Tinyboard support ### Tinyboard support
vichan is based on a Tinyboard, so both engines have very much in common. These vichan is based on a Tinyboard, so both engines have very much in common. These
links may be helpful for you as well: links may be helpful for you as well:
* Tinyboard documentation can be found [here](https://web.archive.org/web/20121016074303/http://tinyboard.org/docs/?p=Main_Page). * Tinyboard documentation can be found [here](https://web.archive.org/web/20121016074303/http://tinyboard.org/docs/?p=Main_Page).

63
inc/cache.php Normal file → Executable file
View File

@ -10,7 +10,7 @@ class Cache {
private static $cache; private static $cache;
public static function init() { public static function init() {
global $config; global $config;
switch ($config['cache']['enabled']) { switch ($config['cache']['enabled']) {
case 'memcached': case 'memcached':
self::$cache = new Memcached(); self::$cache = new Memcached();
@ -31,9 +31,9 @@ class Cache {
} }
public static function get($key) { public static function get($key) {
global $config, $debug; global $config, $debug;
$key = $config['cache']['prefix'] . $key; $key = $config['cache']['prefix'] . $key;
$data = false; $data = false;
switch ($config['cache']['enabled']) { switch ($config['cache']['enabled']) {
case 'memcached': case 'memcached':
@ -67,20 +67,20 @@ class Cache {
$data = json_decode(self::$cache->get($key), true); $data = json_decode(self::$cache->get($key), true);
break; break;
} }
if ($config['debug']) if ($config['debug'])
$debug['cached'][] = $key . ($data === false ? ' (miss)' : ' (hit)'); $debug['cached'][] = $key . ($data === false ? ' (miss)' : ' (hit)');
return $data; return $data;
} }
public static function set($key, $value, $expires = false) { public static function set($key, $value, $expires = false) {
global $config, $debug; global $config, $debug;
$key = $config['cache']['prefix'] . $key; $key = $config['cache']['prefix'] . $key;
if (!$expires) if (!$expires)
$expires = $config['cache']['timeout']; $expires = $config['cache']['timeout'];
switch ($config['cache']['enabled']) { switch ($config['cache']['enabled']) {
case 'memcached': case 'memcached':
if (!self::$cache) if (!self::$cache)
@ -107,15 +107,50 @@ class Cache {
self::$cache[$key] = $value; self::$cache[$key] = $value;
break; break;
} }
if ($config['debug'])
$debug['cached'][] = $key . ' (set)';
}
public static function store($key, $value) {
global $config, $debug;
$key = $config['cache']['prefix'] . $key;
switch ($config['cache']['enabled']) {
case 'memcached':
if (!self::$cache)
self::init();
self::$cache->set($key, $value);
break;
case 'redis':
if (!self::$cache)
self::init();
self::$cache->set($key, json_encode($value));
break;
case 'apc':
apc_store($key, $value);
break;
case 'xcache':
xcache_set($key, $value);
break;
case 'fs':
$key = str_replace('/', '::', $key);
$key = str_replace("\0", '', $key);
file_put_contents('tmp/cache/'.$key, json_encode($value));
break;
case 'php':
self::$cache[$key] = $value;
break;
}
if ($config['debug']) if ($config['debug'])
$debug['cached'][] = $key . ' (set)'; $debug['cached'][] = $key . ' (set)';
} }
public static function delete($key) { public static function delete($key) {
global $config, $debug; global $config, $debug;
$key = $config['cache']['prefix'] . $key; $key = $config['cache']['prefix'] . $key;
switch ($config['cache']['enabled']) { switch ($config['cache']['enabled']) {
case 'memcached': case 'memcached':
case 'redis': case 'redis':
@ -138,13 +173,13 @@ class Cache {
unset(self::$cache[$key]); unset(self::$cache[$key]);
break; break;
} }
if ($config['debug']) if ($config['debug'])
$debug['cached'][] = $key . ' (deleted)'; $debug['cached'][] = $key . ' (deleted)';
} }
public static function flush() { public static function flush() {
global $config; global $config;
switch ($config['cache']['enabled']) { switch ($config['cache']['enabled']) {
case 'memcached': case 'memcached':
if (!self::$cache) if (!self::$cache)
@ -166,7 +201,7 @@ class Cache {
self::init(); self::init();
return self::$cache->flushDB(); return self::$cache->flushDB();
} }
return false; return false;
} }
} }

50
inc/database.php Normal file → Executable file
View File

@ -8,30 +8,31 @@ defined('TINYBOARD') or exit;
class PreparedQueryDebug { class PreparedQueryDebug {
protected $query, $explain_query = false; protected $query, $explain_query = false;
public function __construct($query) { public function __construct($query) {
global $pdo, $config; global $pdo, $config;
$query = preg_replace("/[\n\t]+/", ' ', $query); $query = preg_replace("/[\n\t]+/", ' ', $query);
$this->query = $pdo->prepare($query); $this->query = $pdo->prepare($query);
if ($config['debug'] && $config['debug_explain'] && preg_match('/^(SELECT|INSERT|UPDATE|DELETE) /i', $query)) //|INSERT|UPDATE|DELETE
if ($config['debug'] && $config['debug_explain'] && preg_match('/^(SELECT) /i', $query))
$this->explain_query = $pdo->prepare("EXPLAIN $query"); $this->explain_query = $pdo->prepare("EXPLAIN $query");
} }
public function __call($function, $args) { public function __call($function, $args) {
global $config, $debug; global $config, $debug;
if ($config['debug'] && $function == 'execute') { if ($config['debug'] && $function == 'execute') {
if ($this->explain_query) { if ($this->explain_query) {
$this->explain_query->execute() or error(db_error($this->explain_query)); $this->explain_query->execute() or error(db_error($this->explain_query));
} }
$start = microtime(true); $start = microtime(true);
} }
if ($this->explain_query && $function == 'bindValue') if ($this->explain_query && $function == 'bindValue')
call_user_func_array(array($this->explain_query, $function), $args); call_user_func_array(array($this->explain_query, $function), $args);
$return = call_user_func_array(array($this->query, $function), $args); $return = call_user_func_array(array($this->query, $function), $args);
if ($config['debug'] && $function == 'execute') { if ($config['debug'] && $function == 'execute') {
$time = microtime(true) - $start; $time = microtime(true) - $start;
$debug['sql'][] = array( $debug['sql'][] = array(
@ -42,7 +43,7 @@ class PreparedQueryDebug {
); );
$debug['time']['db_queries'] += $time; $debug['time']['db_queries'] += $time;
} }
return $return; return $return;
} }
} }
@ -51,16 +52,16 @@ function sql_open() {
global $pdo, $config, $debug; global $pdo, $config, $debug;
if ($pdo) if ($pdo)
return true; return true;
if ($config['debug']) if ($config['debug'])
$start = microtime(true); $start = microtime(true);
if (isset($config['db']['server'][0]) && $config['db']['server'][0] == ':') if (isset($config['db']['server'][0]) && $config['db']['server'][0] == ':')
$unix_socket = substr($config['db']['server'], 1); $unix_socket = substr($config['db']['server'], 1);
else else
$unix_socket = false; $unix_socket = false;
$dsn = $config['db']['type'] . ':' . $dsn = $config['db']['type'] . ':' .
($unix_socket ? 'unix_socket=' . $unix_socket : 'host=' . $config['db']['server']) . ($unix_socket ? 'unix_socket=' . $unix_socket : 'host=' . $config['db']['server']) .
';dbname=' . $config['db']['database']; ';dbname=' . $config['db']['database'];
@ -74,10 +75,10 @@ function sql_open() {
if ($config['db']['persistent']) if ($config['db']['persistent'])
$options[PDO::ATTR_PERSISTENT] = true; $options[PDO::ATTR_PERSISTENT] = true;
$pdo = new PDO($dsn, $config['db']['user'], $config['db']['password'], $options); $pdo = new PDO($dsn, $config['db']['user'], $config['db']['password'], $options);
if ($config['debug']) if ($config['debug'])
$debug['time']['db_connect'] = '~' . round((microtime(true) - $start) * 1000, 2) . 'ms'; $debug['time']['db_connect'] = '~' . round((microtime(true) - $start) * 1000, 2) . 'ms';
if (mysql_version() >= 50503) if (mysql_version() >= 50503)
query('SET NAMES utf8mb4') or error(db_error()); query('SET NAMES utf8mb4') or error(db_error());
else else
@ -85,11 +86,11 @@ function sql_open() {
return $pdo; return $pdo;
} catch(PDOException $e) { } catch(PDOException $e) {
$message = $e->getMessage(); $message = $e->getMessage();
// Remove any sensitive information // Remove any sensitive information
$message = str_replace($config['db']['user'], '<em>hidden</em>', $message); $message = str_replace($config['db']['user'], '<em>hidden</em>', $message);
$message = str_replace($config['db']['password'], '<em>hidden</em>', $message); $message = str_replace($config['db']['password'], '<em>hidden</em>', $message);
// Print error // Print error
error(_('Database error: ') . $message); error(_('Database error: ') . $message);
} }
@ -98,7 +99,7 @@ function sql_open() {
// 5.6.10 becomes 50610 // 5.6.10 becomes 50610
function mysql_version() { function mysql_version() {
global $pdo; global $pdo;
$version = $pdo->getAttribute(PDO::ATTR_SERVER_VERSION); $version = $pdo->getAttribute(PDO::ATTR_SERVER_VERSION);
$v = explode('.', $version); $v = explode('.', $version);
if (count($v) != 3) if (count($v) != 3)
@ -108,11 +109,11 @@ function mysql_version() {
function prepare($query) { function prepare($query) {
global $pdo, $debug, $config; global $pdo, $debug, $config;
$query = preg_replace('/``('.$config['board_regex'].')``/u', '`' . $config['db']['prefix'] . '$1`', $query); $query = preg_replace('/``('.$config['board_regex'].')``/u', '`' . $config['db']['prefix'] . '$1`', $query);
sql_open(); sql_open();
if ($config['debug']) if ($config['debug'])
return new PreparedQueryDebug($query); return new PreparedQueryDebug($query);
@ -121,13 +122,14 @@ function prepare($query) {
function query($query) { function query($query) {
global $pdo, $debug, $config; global $pdo, $debug, $config;
$query = preg_replace('/``('.$config['board_regex'].')``/u', '`' . $config['db']['prefix'] . '$1`', $query); $query = preg_replace('/``('.$config['board_regex'].')``/u', '`' . $config['db']['prefix'] . '$1`', $query);
sql_open(); sql_open();
if ($config['debug']) { if ($config['debug']) {
if ($config['debug_explain'] && preg_match('/^(SELECT|INSERT|UPDATE|DELETE) /i', $query)) { //|INSERT|UPDATE|DELETE
if ($config['debug_explain'] && preg_match('/^(SELECT) /i', $query)) {
$explain = $pdo->query("EXPLAIN $query") or error(db_error()); $explain = $pdo->query("EXPLAIN $query") or error(db_error());
} }
$start = microtime(true); $start = microtime(true);

View File

@ -64,7 +64,7 @@ function loadConfig() {
} }
if (isset($config['cache_config']) && if (isset($config['cache_config']) &&
$config['cache_config'] && $config['cache_config'] &&
$config = Cache::get('config_' . $boardsuffix ) ) { $config = Cache::get('config_' . $boardsuffix ) ) {
$events = Cache::get('events_' . $boardsuffix ); $events = Cache::get('events_' . $boardsuffix );
@ -83,7 +83,7 @@ function loadConfig() {
else { else {
$config = array(); $config = array();
reset_events(); reset_events();
$arrays = array( $arrays = array(
'db', 'db',
@ -283,7 +283,7 @@ function loadConfig() {
if ($config['recaptcha']) if ($config['recaptcha'])
require_once 'inc/lib/recaptcha/recaptchalib.php'; require_once 'inc/lib/recaptcha/recaptchalib.php';
if ($config['cache']['enabled']) if ($config['cache']['enabled'])
require_once 'inc/cache.php'; require_once 'inc/cache.php';
@ -310,7 +310,7 @@ function loadConfig() {
if (is_array($config['anonymous'])) if (is_array($config['anonymous']))
$config['anonymous'] = $config['anonymous'][array_rand($config['anonymous'])]; $config['anonymous'] = $config['anonymous'][array_rand($config['anonymous'])];
if ($config['debug']) { if ($config['debug']) {
if (!isset($debug)) { if (!isset($debug)) {
$debug = array( $debug = array(
@ -350,7 +350,7 @@ function basic_error_function_because_the_other_isnt_loaded_yet($message, $prior
'<p class="c">This alternative error page is being displayed because the other couldn\'t be found or hasn\'t loaded yet.</p></body></html>'); '<p class="c">This alternative error page is being displayed because the other couldn\'t be found or hasn\'t loaded yet.</p></body></html>');
} }
function fatal_error_handler() { function fatal_error_handler() {
if ($error = error_get_last()) { if ($error = error_get_last()) {
if ($error['type'] == E_ERROR) { if ($error['type'] == E_ERROR) {
if (function_exists('error')) { if (function_exists('error')) {
@ -391,7 +391,7 @@ function define_groups() {
define($group_name, $group_value, true); define($group_name, $group_value, true);
} }
} }
ksort($config['mod']['groups']); ksort($config['mod']['groups']);
} }
@ -429,7 +429,7 @@ function rebuildThemes($action, $boardname = false) {
$config = $_config; $config = $_config;
$board = $_board; $board = $_board;
// Reload the locale // Reload the locale
if ($config['locale'] != $current_locale) { if ($config['locale'] != $current_locale) {
$current_locale = $config['locale']; $current_locale = $config['locale'];
init_locale($config['locale']); init_locale($config['locale']);
@ -450,7 +450,7 @@ function rebuildThemes($action, $boardname = false) {
$config = $_config; $config = $_config;
$board = $_board; $board = $_board;
// Reload the locale // Reload the locale
if ($config['locale'] != $current_locale) { if ($config['locale'] != $current_locale) {
$current_locale = $config['locale']; $current_locale = $config['locale'];
init_locale($config['locale']); init_locale($config['locale']);
@ -596,7 +596,7 @@ function purge($uri) {
global $config, $debug; global $config, $debug;
// Fix for Unicode // Fix for Unicode
$uri = rawurlencode($uri); $uri = rawurlencode($uri);
$noescape = "/!~*()+:"; $noescape = "/!~*()+:";
$noescape = preg_split('//', $noescape); $noescape = preg_split('//', $noescape);
@ -630,6 +630,16 @@ function purge($uri) {
function file_write($path, $data, $simple = false, $skip_purge = false) { function file_write($path, $data, $simple = false, $skip_purge = false) {
global $config, $debug; global $config, $debug;
//echo "file_write($path, ", strlen($data), ", $simple, $skip_purge)<br>\n";
Cache::store('vichan_filecache_'.$path, $data, -1);
if ($config['gzip_static']) {
$bytes=strlen($data);
if ($bytes & ~0x3ff) {
Cache::store('vichan_filecache_'.$path.'.gz', gzencode($data), -1);
} else {
Cache::delete('vichan_filecache_'.$path.'.gz');
}
}
if (preg_match('/^remote:\/\/(.+)\:(.+)$/', $path, $m)) { if (preg_match('/^remote:\/\/(.+)\:(.+)$/', $path, $m)) {
if (isset($config['remote'][$m[1]])) { if (isset($config['remote'][$m[1]])) {
@ -643,6 +653,7 @@ function file_write($path, $data, $simple = false, $skip_purge = false) {
} }
} }
/*
if (!$fp = fopen($path, $simple ? 'w' : 'c')) if (!$fp = fopen($path, $simple ? 'w' : 'c'))
error('Unable to open file for writing: ' . $path); error('Unable to open file for writing: ' . $path);
@ -666,7 +677,7 @@ function file_write($path, $data, $simple = false, $skip_purge = false) {
// Close // Close
if (!fclose($fp)) if (!fclose($fp))
error('Unable to close file: ' . $path); error('Unable to close file: ' . $path);
*/
/** /**
* Create gzipped file. * Create gzipped file.
* *
@ -675,6 +686,7 @@ function file_write($path, $data, $simple = false, $skip_purge = false) {
* *
* This is useful with nginx with gzip_static on. * This is useful with nginx with gzip_static on.
*/ */
/*
if ($config['gzip_static']) { if ($config['gzip_static']) {
$gzpath = "$path.gz"; $gzpath = "$path.gz";
@ -688,6 +700,7 @@ function file_write($path, $data, $simple = false, $skip_purge = false) {
@unlink($gzpath); @unlink($gzpath);
} }
} }
*/
if (!$skip_purge && isset($config['purge'])) { if (!$skip_purge && isset($config['purge'])) {
// Purge cache // Purge cache
@ -705,6 +718,7 @@ function file_write($path, $data, $simple = false, $skip_purge = false) {
} }
if ($config['debug']) { if ($config['debug']) {
$bytes=strlen($data);
$debug['write'][] = $path . ': ' . $bytes . ' bytes'; $debug['write'][] = $path . ': ' . $bytes . ' bytes';
} }
@ -713,6 +727,12 @@ function file_write($path, $data, $simple = false, $skip_purge = false) {
function file_unlink($path) { function file_unlink($path) {
global $config, $debug; global $config, $debug;
//echo "file_unlink($path)<br>\n";
if ($config['gzip_static']) {
Cache::delete('vichan_filecache_'.$path);
} else {
Cache::delete('vichan_filecache_'.$path.'.gz');
}
if ($config['debug']) { if ($config['debug']) {
if (!isset($debug['unlink'])) if (!isset($debug['unlink']))
@ -720,14 +740,14 @@ function file_unlink($path) {
$debug['unlink'][] = $path; $debug['unlink'][] = $path;
} }
$ret=true;
/*
$ret = @unlink($path); $ret = @unlink($path);
if ($config['gzip_static']) {
if ($config['gzip_static']) { $gzpath = "$path.gz";
$gzpath = "$path.gz";
@unlink($gzpath); @unlink($gzpath);
} }
*/
if (isset($config['purge']) && $path[0] != '/' && isset($_SERVER['HTTP_HOST'])) { if (isset($config['purge']) && $path[0] != '/' && isset($_SERVER['HTTP_HOST'])) {
// Purge cache // Purge cache
if (basename($path) == $config['file_index']) { if (basename($path) == $config['file_index']) {
@ -792,7 +812,7 @@ function listBoards($just_uri = false) {
$boards[] = $board; $boards[] = $board;
} }
} }
if ($config['cache']['enabled']) if ($config['cache']['enabled'])
cache::set($cache_name, $boards); cache::set($cache_name, $boards);
@ -858,10 +878,10 @@ function displayBan($ban) {
$post = new Thread($ban['post'], null, false, false); $post = new Thread($ban['post'], null, false, false);
} }
} }
$denied_appeals = array(); $denied_appeals = array();
$pending_appeal = false; $pending_appeal = false;
if ($config['ban_appeals']) { if ($config['ban_appeals']) {
$query = query("SELECT `time`, `denied` FROM ``ban_appeals`` WHERE `ban_id` = " . (int)$ban['id']) or error(db_error()); $query = query("SELECT `time`, `denied` FROM ``ban_appeals`` WHERE `ban_id` = " . (int)$ban['id']) or error(db_error());
while ($ban_appeal = $query->fetch(PDO::FETCH_ASSOC)) { while ($ban_appeal = $query->fetch(PDO::FETCH_ASSOC)) {
@ -872,7 +892,7 @@ function displayBan($ban) {
} }
} }
} }
// Show banned page and exit // Show banned page and exit
die( die(
Element('page.html', array( Element('page.html', array(
@ -897,7 +917,7 @@ function checkBan($board = false) {
if (!isset($_SERVER['REMOTE_ADDR'])) { if (!isset($_SERVER['REMOTE_ADDR'])) {
// Server misconfiguration // Server misconfiguration
return; return;
} }
if (event('check-ban', $board)) if (event('check-ban', $board))
return true; return true;
@ -912,7 +932,7 @@ function checkBan($board = false) {
foreach ($ips as $ip) { foreach ($ips as $ip) {
$bans = Bans::find($_SERVER['REMOTE_ADDR'], $board, $config['show_modname']); $bans = Bans::find($_SERVER['REMOTE_ADDR'], $board, $config['show_modname']);
foreach ($bans as &$ban) { foreach ($bans as &$ban) {
if ($ban['expires'] && $ban['expires'] < time()) { if ($ban['expires'] && $ban['expires'] < time()) {
Bans::delete($ban['id']); Bans::delete($ban['id']);
@ -941,9 +961,9 @@ function checkBan($board = false) {
if (time() - $last_time_purged < $config['purge_bans'] ) if (time() - $last_time_purged < $config['purge_bans'] )
return; return;
} }
Bans::purge(); Bans::purge();
if ($config['cache']['enabled']) if ($config['cache']['enabled'])
cache::set('purged_bans_last', time()); cache::set('purged_bans_last', time());
} }
@ -1000,7 +1020,7 @@ function threadExists($id) {
function insertFloodPost(array $post) { function insertFloodPost(array $post) {
global $board; global $board;
$query = prepare("INSERT INTO ``flood`` VALUES (NULL, :ip, :board, :time, :posthash, :filehash, :isreply)"); $query = prepare("INSERT INTO ``flood`` VALUES (NULL, :ip, :board, :time, :posthash, :filehash, :isreply)");
$query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
$query->bindValue(':board', $board['uri']); $query->bindValue(':board', $board['uri']);
@ -1041,7 +1061,7 @@ function post(array $post) {
$query->bindValue(':body', $post['body']); $query->bindValue(':body', $post['body']);
$query->bindValue(':body_nomarkup', $post['body_nomarkup']); $query->bindValue(':body_nomarkup', $post['body_nomarkup']);
$query->bindValue(':time', isset($post['time']) ? $post['time'] : time(), PDO::PARAM_INT); $query->bindValue(':time', isset($post['time']) ? $post['time'] : time(), PDO::PARAM_INT);
$query->bindValue(':password', $post['password']); $query->bindValue(':password', $post['password']);
$query->bindValue(':ip', isset($post['ip']) ? $post['ip'] : $_SERVER['REMOTE_ADDR']); $query->bindValue(':ip', isset($post['ip']) ? $post['ip'] : $_SERVER['REMOTE_ADDR']);
if ($post['op'] && $post['mod'] && isset($post['sticky']) && $post['sticky']) { if ($post['op'] && $post['mod'] && isset($post['sticky']) && $post['sticky']) {
@ -1203,7 +1223,7 @@ function deletePost($id, $error_if_doesnt_exist=true, $rebuild_after=true) {
// Delete posts and maybe replies // Delete posts and maybe replies
while ($post = $query->fetch(PDO::FETCH_ASSOC)) { while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
event('delete', $post); event('delete', $post);
if (!$post['thread']) { if (!$post['thread']) {
// Delete thread HTML page // Delete thread HTML page
file_unlink($board['dir'] . $config['dir']['res'] . link_for($post) ); file_unlink($board['dir'] . $config['dir']['res'] . link_for($post) );
@ -1254,7 +1274,7 @@ function deletePost($id, $error_if_doesnt_exist=true, $rebuild_after=true) {
$query = prepare("DELETE FROM ``cites`` WHERE (`target_board` = :board AND (`target` = " . implode(' OR `target` = ', $ids) . ")) OR (`board` = :board AND (`post` = " . implode(' OR `post` = ', $ids) . "))"); $query = prepare("DELETE FROM ``cites`` WHERE (`target_board` = :board AND (`target` = " . implode(' OR `target` = ', $ids) . ")) OR (`board` = :board AND (`post` = " . implode(' OR `post` = ', $ids) . "))");
$query->bindValue(':board', $board['uri']); $query->bindValue(':board', $board['uri']);
$query->execute() or error(db_error($query)); $query->execute() or error(db_error($query));
if (isset($rebuild) && $rebuild_after) { if (isset($rebuild) && $rebuild_after) {
buildThread($rebuild); buildThread($rebuild);
buildIndex(); buildIndex();
@ -1305,7 +1325,7 @@ function index($page, $mod=false) {
return false; return false;
$threads = array(); $threads = array();
while ($th = $query->fetch(PDO::FETCH_ASSOC)) { while ($th = $query->fetch(PDO::FETCH_ASSOC)) {
$thread = new Thread($th, $mod ? '?/' : $config['root'], $mod); $thread = new Thread($th, $mod ? '?/' : $config['root'], $mod);
@ -1355,7 +1375,7 @@ function index($page, $mod=false) {
$thread->omitted = $omitted['post_count'] - ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview']); $thread->omitted = $omitted['post_count'] - ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview']);
$thread->omitted_images = $omitted['image_count'] - $num_images; $thread->omitted_images = $omitted['image_count'] - $num_images;
} }
$threads[] = $thread; $threads[] = $thread;
$body .= $thread->build(true); $body .= $thread->build(true);
} }
@ -1569,7 +1589,7 @@ function checkMute() {
// Not expired yet // Not expired yet
error(sprintf($config['error']['youaremuted'], $mute['time'] + $mutetime - time())); error(sprintf($config['error']['youaremuted'], $mute['time'] + $mutetime - time()));
} else { } else {
// Already expired // Already expired
return; return;
} }
} }
@ -1696,7 +1716,7 @@ function buildJavascript() {
} }
if ($config['minify_js']) { if ($config['minify_js']) {
require_once 'inc/lib/minify/JSMin.php'; require_once 'inc/lib/minify/JSMin.php';
$script = JSMin::minify($script); $script = JSMin::minify($script);
} }
@ -1802,7 +1822,7 @@ function markup_url($matches) {
'rel' => 'nofollow', 'rel' => 'nofollow',
'target' => '_blank', 'target' => '_blank',
); );
event('markup-url', $link); event('markup-url', $link);
$link = (array)$link; $link = (array)$link;
@ -1833,7 +1853,7 @@ function unicodify($body) {
function extract_modifiers($body) { function extract_modifiers($body) {
$modifiers = array(); $modifiers = array();
if (preg_match_all('@<tinyboard ([\w\s]+)>(.*?)</tinyboard>@us', $body, $matches, PREG_SET_ORDER)) { if (preg_match_all('@<tinyboard ([\w\s]+)>(.*?)</tinyboard>@us', $body, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) { foreach ($matches as $match) {
if (preg_match('/^escape /', $match[1])) if (preg_match('/^escape /', $match[1]))
@ -1841,18 +1861,18 @@ function extract_modifiers($body) {
$modifiers[$match[1]] = html_entity_decode($match[2]); $modifiers[$match[1]] = html_entity_decode($match[2]);
} }
} }
return $modifiers; return $modifiers;
} }
function markup(&$body, $track_cites = false) { function markup(&$body, $track_cites = false) {
global $board, $config, $markup_urls; global $board, $config, $markup_urls;
$modifiers = extract_modifiers($body); $modifiers = extract_modifiers($body);
$body = preg_replace('@<tinyboard (?!escape )([\w\s]+)>(.+?)</tinyboard>@us', '', $body); $body = preg_replace('@<tinyboard (?!escape )([\w\s]+)>(.+?)</tinyboard>@us', '', $body);
$body = preg_replace('@<(tinyboard) escape ([\w\s]+)>@i', '<$1 $2>', $body); $body = preg_replace('@<(tinyboard) escape ([\w\s]+)>@i', '<$1 $2>', $body);
if (isset($modifiers['raw html']) && $modifiers['raw html'] == '1') { if (isset($modifiers['raw html']) && $modifiers['raw html'] == '1') {
return array(); return array();
} }
@ -1893,7 +1913,7 @@ function markup(&$body, $track_cites = false) {
if ($num_links > $config['max_links']) if ($num_links > $config['max_links'])
error($config['error']['toomanylinks']); error($config['error']['toomanylinks']);
} }
if ($config['markup_repair_tidy']) if ($config['markup_repair_tidy'])
$body = str_replace(' ', ' &nbsp;', $body); $body = str_replace(' ', ' &nbsp;', $body);
@ -1917,21 +1937,21 @@ function markup(&$body, $track_cites = false) {
$skip_chars = 0; $skip_chars = 0;
$body_tmp = $body; $body_tmp = $body;
$search_cites = array(); $search_cites = array();
foreach ($cites as $matches) { foreach ($cites as $matches) {
$search_cites[] = '`id` = ' . $matches[2][0]; $search_cites[] = '`id` = ' . $matches[2][0];
} }
$search_cites = array_unique($search_cites); $search_cites = array_unique($search_cites);
$query = query(sprintf('SELECT `thread`, `id` FROM ``posts_%s`` WHERE ' . $query = query(sprintf('SELECT `thread`, `id` FROM ``posts_%s`` WHERE ' .
implode(' OR ', $search_cites), $board['uri'])) or error(db_error()); implode(' OR ', $search_cites), $board['uri'])) or error(db_error());
$cited_posts = array(); $cited_posts = array();
while ($cited = $query->fetch(PDO::FETCH_ASSOC)) { while ($cited = $query->fetch(PDO::FETCH_ASSOC)) {
$cited_posts[$cited['id']] = $cited['thread'] ? $cited['thread'] : false; $cited_posts[$cited['id']] = $cited['thread'] ? $cited['thread'] : false;
} }
foreach ($cites as $matches) { foreach ($cites as $matches) {
$cite = $matches[2][0]; $cite = $matches[2][0];
@ -1964,34 +1984,34 @@ function markup(&$body, $track_cites = false) {
$skip_chars = 0; $skip_chars = 0;
$body_tmp = $body; $body_tmp = $body;
if (isset($cited_posts)) { if (isset($cited_posts)) {
// Carry found posts from local board >>X links // Carry found posts from local board >>X links
foreach ($cited_posts as $cite => $thread) { foreach ($cited_posts as $cite => $thread) {
$cited_posts[$cite] = $config['root'] . $board['dir'] . $config['dir']['res'] . $cited_posts[$cite] = $config['root'] . $board['dir'] . $config['dir']['res'] .
($thread ? $thread : $cite) . '.html#' . $cite; ($thread ? $thread : $cite) . '.html#' . $cite;
} }
$cited_posts = array( $cited_posts = array(
$board['uri'] => $cited_posts $board['uri'] => $cited_posts
); );
} else } else
$cited_posts = array(); $cited_posts = array();
$crossboard_indexes = array(); $crossboard_indexes = array();
$search_cites_boards = array(); $search_cites_boards = array();
foreach ($cites as $matches) { foreach ($cites as $matches) {
$_board = $matches[2][0]; $_board = $matches[2][0];
$cite = @$matches[3][0]; $cite = @$matches[3][0];
if (!isset($search_cites_boards[$_board])) if (!isset($search_cites_boards[$_board]))
$search_cites_boards[$_board] = array(); $search_cites_boards[$_board] = array();
$search_cites_boards[$_board][] = $cite; $search_cites_boards[$_board][] = $cite;
} }
$tmp_board = $board['uri']; $tmp_board = $board['uri'];
foreach ($search_cites_boards as $_board => $search_cites) { foreach ($search_cites_boards as $_board => $search_cites) {
$clauses = array(); $clauses = array();
foreach ($search_cites as $cite) { foreach ($search_cites as $cite) {
@ -2000,27 +2020,27 @@ function markup(&$body, $track_cites = false) {
$clauses[] = '`id` = ' . $cite; $clauses[] = '`id` = ' . $cite;
} }
$clauses = array_unique($clauses); $clauses = array_unique($clauses);
if ($board['uri'] != $_board) { if ($board['uri'] != $_board) {
if (!openBoard($_board)) if (!openBoard($_board))
continue; // Unknown board continue; // Unknown board
} }
if (!empty($clauses)) { if (!empty($clauses)) {
$cited_posts[$_board] = array(); $cited_posts[$_board] = array();
$query = query(sprintf('SELECT `thread`, `id`, `slug` FROM ``posts_%s`` WHERE ' . $query = query(sprintf('SELECT `thread`, `id`, `slug` FROM ``posts_%s`` WHERE ' .
implode(' OR ', $clauses), $board['uri'])) or error(db_error()); implode(' OR ', $clauses), $board['uri'])) or error(db_error());
while ($cite = $query->fetch(PDO::FETCH_ASSOC)) { while ($cite = $query->fetch(PDO::FETCH_ASSOC)) {
$cited_posts[$_board][$cite['id']] = $config['root'] . $board['dir'] . $config['dir']['res'] . $cited_posts[$_board][$cite['id']] = $config['root'] . $board['dir'] . $config['dir']['res'] .
link_for($cite) . '#' . $cite['id']; link_for($cite) . '#' . $cite['id'];
} }
} }
$crossboard_indexes[$_board] = $config['root'] . $board['dir'] . $config['file_index']; $crossboard_indexes[$_board] = $config['root'] . $board['dir'] . $config['file_index'];
} }
// Restore old board // Restore old board
if ($board['uri'] != $tmp_board) if ($board['uri'] != $tmp_board)
openBoard($tmp_board); openBoard($tmp_board);
@ -2037,7 +2057,7 @@ function markup(&$body, $track_cites = false) {
if ($cite) { if ($cite) {
if (isset($cited_posts[$_board][$cite])) { if (isset($cited_posts[$_board][$cite])) {
$link = $cited_posts[$_board][$cite]; $link = $cited_posts[$_board][$cite];
$replacement = '<a ' . $replacement = '<a ' .
($_board == $board['uri'] ? ($_board == $board['uri'] ?
'onclick="highlightReply(\''.$cite.'\');" ' 'onclick="highlightReply(\''.$cite.'\');" '
@ -2060,7 +2080,7 @@ function markup(&$body, $track_cites = false) {
} }
} }
} }
$tracked_cites = array_unique($tracked_cites, SORT_REGULAR); $tracked_cites = array_unique($tracked_cites, SORT_REGULAR);
$body = preg_replace("/^\s*&gt;.*$/m", '<span class="quote">$0</span>', $body); $body = preg_replace("/^\s*&gt;.*$/m", '<span class="quote">$0</span>', $body);
@ -2115,7 +2135,7 @@ function utf8tohtml($utf8) {
} }
function ordutf8($string, &$offset) { function ordutf8($string, &$offset) {
$code = ord(substr($string, $offset,1)); $code = ord(substr($string, $offset,1));
if ($code >= 128) { // otherwise 0xxxxxxx if ($code >= 128) { // otherwise 0xxxxxxx
if ($code < 224) if ($code < 224)
$bytesnumber = 2; // 110xxxxx $bytesnumber = 2; // 110xxxxx
@ -2193,7 +2213,7 @@ function buildThread($id, $return = false, $mod = false) {
// Check if any posts were found // Check if any posts were found
if (!isset($thread)) if (!isset($thread))
error($config['error']['nonexistant']); error($config['error']['nonexistant']);
$hasnoko50 = $thread->postCount() >= $config['noko50_min']; $hasnoko50 = $thread->postCount() >= $config['noko50_min'];
$antibot = $mod || $return ? false : create_antibot($board['uri'], $id); $antibot = $mod || $return ? false : create_antibot($board['uri'], $id);
@ -2244,16 +2264,16 @@ function buildThread($id, $return = false, $mod = false) {
function buildThread50($id, $return = false, $mod = false, $thread = null, $antibot = false) { function buildThread50($id, $return = false, $mod = false, $thread = null, $antibot = false) {
global $board, $config, $build_pages; global $board, $config, $build_pages;
$id = round($id); $id = round($id);
if ($antibot) if ($antibot)
$antibot->reset(); $antibot->reset();
if (!$thread) { if (!$thread) {
$query = prepare(sprintf("SELECT * FROM ``posts_%s`` WHERE (`thread` IS NULL AND `id` = :id) OR `thread` = :id ORDER BY `thread`,`id` DESC LIMIT :limit", $board['uri'])); $query = prepare(sprintf("SELECT * FROM ``posts_%s`` WHERE (`thread` IS NULL AND `id` = :id) OR `thread` = :id ORDER BY `thread`,`id` DESC LIMIT :limit", $board['uri']));
$query->bindValue(':id', $id, PDO::PARAM_INT); $query->bindValue(':id', $id, PDO::PARAM_INT);
$query->bindValue(':limit', $config['noko50_count']+1, PDO::PARAM_INT); $query->bindValue(':limit', $config['noko50_count']+1, PDO::PARAM_INT);
$query->execute() or error(db_error($query)); $query->execute() or error(db_error($query));
$num_images = 0; $num_images = 0;
while ($post = $query->fetch(PDO::FETCH_ASSOC)) { while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
if (!isset($thread)) { if (!isset($thread)) {
@ -2261,7 +2281,7 @@ function buildThread50($id, $return = false, $mod = false, $thread = null, $anti
} else { } else {
if ($post['files']) if ($post['files'])
$num_images += $post['num_files']; $num_images += $post['num_files'];
$thread->add(new Post($post, $mod ? '?/' : $config['root'], $mod)); $thread->add(new Post($post, $mod ? '?/' : $config['root'], $mod));
} }
} }
@ -2276,10 +2296,10 @@ function buildThread50($id, $return = false, $mod = false, $thread = null, $anti
SELECT SUM(`num_files`) FROM ``posts_%s`` WHERE `files` IS NOT NULL AND `thread` = :thread", $board['uri'], $board['uri'])); SELECT SUM(`num_files`) FROM ``posts_%s`` WHERE `files` IS NOT NULL AND `thread` = :thread", $board['uri'], $board['uri']));
$count->bindValue(':thread', $id, PDO::PARAM_INT); $count->bindValue(':thread', $id, PDO::PARAM_INT);
$count->execute() or error(db_error($count)); $count->execute() or error(db_error($count));
$c = $count->fetch(); $c = $count->fetch();
$thread->omitted = $c['num'] - $config['noko50_count']; $thread->omitted = $c['num'] - $config['noko50_count'];
$c = $count->fetch(); $c = $count->fetch();
$thread->omitted_images = $c['num'] - $num_images; $thread->omitted_images = $c['num'] - $num_images;
} }
@ -2292,13 +2312,13 @@ function buildThread50($id, $return = false, $mod = false, $thread = null, $anti
$thread->omitted += count($allPosts) - count($thread->posts); $thread->omitted += count($allPosts) - count($thread->posts);
foreach ($allPosts as $index => $post) { foreach ($allPosts as $index => $post) {
if ($index == count($allPosts)-count($thread->posts)) if ($index == count($allPosts)-count($thread->posts))
break; break;
if ($post->files) if ($post->files)
$thread->omitted_images += $post->num_files; $thread->omitted_images += $post->num_files;
} }
} }
$hasnoko50 = $thread->postCount() >= $config['noko50_min']; $hasnoko50 = $thread->postCount() >= $config['noko50_min'];
$body = Element('thread.html', array( $body = Element('thread.html', array(
'board' => $board, 'board' => $board,
@ -2312,7 +2332,7 @@ function buildThread50($id, $return = false, $mod = false, $thread = null, $anti
'antibot' => $mod ? false : ($antibot ? $antibot : create_antibot($board['uri'], $id)), 'antibot' => $mod ? false : ($antibot ? $antibot : create_antibot($board['uri'], $id)),
'boardlist' => createBoardlist($mod), 'boardlist' => createBoardlist($mod),
'return' => ($mod ? '?' . $board['url'] . $config['file_index'] : $config['root'] . $board['dir'] . $config['file_index']) 'return' => ($mod ? '?' . $board['url'] . $config['file_index'] : $config['root'] . $board['dir'] . $config['file_index'])
)); ));
if ($return) { if ($return) {
return $body; return $body;
@ -2391,7 +2411,7 @@ function hcf($a, $b){
$b = $a-$b; $b = $a-$b;
$a = $a-$b; $a = $a-$b;
} }
if ($b==(round($b/$a))*$a) if ($b==(round($b/$a))*$a)
$gcd=$a; $gcd=$a;
else { else {
for ($i=round($a/2);$i;$i--) { for ($i=round($a/2);$i;$i--) {