diff options
| author | Michael Save <savetheinternet@tinyboard.org> | 2012-04-12 02:49:22 +1000 |
|---|---|---|
| committer | Michael Save <savetheinternet@tinyboard.org> | 2012-04-12 02:49:22 +1000 |
| commit | c9423a2c34a5b93bf9cf2c506acca713781e60b6 (patch) | |
| tree | 16f4a569d34fc67365b453bafe561524fce87b22 /inc | |
| parent | 88092e4f9e50e94f094e55c54a6150df104043b1 (diff) | |
large cleanup
Diffstat (limited to 'inc')
| -rw-r--r-- | inc/cache.php | 9 | ||||
| -rw-r--r-- | inc/config.php | 103 | ||||
| -rw-r--r-- | inc/database.php | 186 | ||||
| -rw-r--r-- | inc/display.php | 788 | ||||
| -rw-r--r-- | inc/events.php | 9 | ||||
| -rw-r--r-- | inc/filters.php | 9 | ||||
| -rw-r--r-- | inc/functions.php | 3159 | ||||
| -rw-r--r-- | inc/image.php | 869 | ||||
| -rw-r--r-- | inc/mod.php | 520 | ||||
| -rw-r--r-- | inc/remote.php | 116 | ||||
| -rw-r--r-- | inc/template.php | 97 | ||||
| -rw-r--r-- | inc/user.php | 10 |
12 files changed, 2980 insertions, 2895 deletions
diff --git a/inc/cache.php b/inc/cache.php index 3881672e..e29b282d 100644 --- a/inc/cache.php +++ b/inc/cache.php @@ -1,5 +1,14 @@ <?php +/* + * Copyright (c) 2010-2012 Tinyboard Development Group + */ + +if(realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { + // You cannot request this file directly. + exit; +} + class Cache { private static $cache; public static function init() { diff --git a/inc/config.php b/inc/config.php index d57d3263..94b7bdd7 100644 --- a/inc/config.php +++ b/inc/config.php @@ -19,6 +19,8 @@ * * More information: http://tinyboard.org/docs/?p=Config * + * Tinyboard documentation: http://tinyboard.org/docs/ + * */ @@ -100,8 +102,8 @@ $config['cache']['prefix'] = ''; // Memcached servers to use - http://www.php.net/manual/en/memcached.addservers.php - $config['cache']['memcached'] = Array( - Array('localhost', 11211) + $config['cache']['memcached'] = array( + array('localhost', 11211) ); /* @@ -144,13 +146,13 @@ // DNS blacklists (DNSBL) http://tinyboard.org/docs/?p=Config/DNSBL // http://www.sectoor.de/tor.php - $config['dnsbl'][] = Array('tor.dnsbl.sectoor.de', 1); // Tor exit servers + $config['dnsbl'][] = array('tor.dnsbl.sectoor.de', 1); // Tor exit servers // http://www.sorbs.net/using.shtml - // $config['dnsbl'][] = Array('dnsbl.sorbs.net', Array(2, 3, 4, 5, 6, 7, 8, 9)); + // $config['dnsbl'][] = array('dnsbl.sorbs.net', array(2, 3, 4, 5, 6, 7, 8, 9)); // http://www.projecthoneypot.org/httpbl.php - // $config['dnsbl'][] = Array('<your access key>.%.dnsbl.httpbl.org', function($ip) { + // $config['dnsbl'][] = array('<your access key>.%.dnsbl.httpbl.org', function($ip) { // $octets = explode('.', $ip); // // // days since last activity @@ -172,7 +174,7 @@ $config['spam']['hidden_inputs_min'] = 4; $config['spam']['hidden_inputs_max'] = 12; // These are fields used to confuse the bots. Make sure they aren't actually used by Tinyboard, or it won't work. - $config['spam']['hidden_input_names'] = Array( + $config['spam']['hidden_input_names'] = array( 'user', 'username', 'login', @@ -185,7 +187,7 @@ 'message' ); // Always update this when adding new valid fields to the post form, or EVERYTHING WILL BE DETECTED AS SPAM! - $config['spam']['valid_inputs'] = Array( + $config['spam']['valid_inputs'] = array( 'hash', 'board', 'thread', @@ -208,10 +210,10 @@ // Custom flood filters. Detect flood attacks and reject new posts if there's a positive match. // See http://tinyboard.org/wiki/index.php?title=Flood_filters for more information. - //$config['flood_filters'][] = Array( - // 'condition' => Array( + //$config['flood_filters'][] = array( + // 'condition' => array( // // 100 posts in the past 5 minutes (~20 p/m) - // 'posts_in_past_x_minutes' => Array(100, 5) + // 'posts_in_past_x_minutes' => array(100, 5) // ), // // Don't allow the user to post // 'action' => 'reject', @@ -220,10 +222,10 @@ //); // Another filter - //$config['flood_filters'][] = Array( - // 'condition' => Array( + //$config['flood_filters'][] = array( + // 'condition' => array( // // 10 new empty threads in the past 2 minutes - // 'threads_with_no_replies_in_past_x_minutes' => Array(10, 2), + // 'threads_with_no_replies_in_past_x_minutes' => array(10, 2), // // Allow replies, but not new threads (ie. reject topics only). // 'OP' => true // ), @@ -300,10 +302,10 @@ // Wordfilters are used to automatically replace certain words/phrases with something else. // For a normal string replacement: - // $config['wordfilters'][] = Array('cat', 'dog'); + // $config['wordfilters'][] = array('cat', 'dog'); // Advanced raplcement (regular expressions): - // $config['wordfilters'][] = Array('/cat/', 'dog', true); // 'true' means it's a regular expression + // $config['wordfilters'][] = array('/cat/', 'dog', true); // 'true' means it's a regular expression // Always act as if they had typed "noko" in the email field no mattter what $config['always_noko'] = false; @@ -333,13 +335,13 @@ */ // "Wiki" markup syntax ($config['wiki_markup'] in pervious versions): - $config['markup'][] = Array("/'''(.+?)'''/", "<strong>\$1</strong>"); - $config['markup'][] = Array("/''(.+?)''/", "<em>\$1</em>"); - $config['markup'][] = Array("/\*\*(.+?)\*\*/", "<span class=\"spoiler\">\$1</span>"); - $config['markup'][] = Array("/^\s*==(.+?)==\s*$/m", "<span class=\"heading\">\$1</span>"); + $config['markup'][] = array("/'''(.+?)'''/", "<strong>\$1</strong>"); + $config['markup'][] = array("/''(.+?)''/", "<em>\$1</em>"); + $config['markup'][] = array("/\*\*(.+?)\*\*/", "<span class=\"spoiler\">\$1</span>"); + $config['markup'][] = array("/^\s*==(.+?)==\s*$/m", "<span class=\"heading\">\$1</span>"); // Highlight PHP code wrapped in <code> tags (PHP 5.3.0+) - // $config['markup'][] = Array( + // $config['markup'][] = array( // '/^<code>(.+)<\/code>/ms', // function($matches) { // return highlight_string(html_entity_decode($matches[1]), true); @@ -507,29 +509,29 @@ // $config['uri_stylesheets'] = 'http://static.example.org/stylesheets/'; // The default stylesheet to use - $config['default_stylesheet'] = Array('Yotsuba B', $config['stylesheets']['Yotsuba B']); + $config['default_stylesheet'] = array('Yotsuba B', $config['stylesheets']['Yotsuba B']); // Boardlinks // You can group, order and place the boardlist at the top of every page, using the following template. - //$config['boards'] = Array( - // Array('a', 'b'), - // Array('c', 'd', 'e', 'f', 'g'), - // Array('h', 'i', 'j'), - // Array('k', Array('l', 'm')), - // Array('status' => 'http://status.example.org/') + //$config['boards'] = array( + // array('a', 'b'), + // array('c', 'd', 'e', 'f', 'g'), + // array('h', 'i', 'j'), + // array('k', array('l', 'm')), + // array('status' => 'http://status.example.org/') //); // Categories // Required for the Categories theme. - //$config['categories'] = Array( - // 'Group Name' => Array('a', 'b', 'c'), - // 'Another Group' => Array('d') + //$config['categories'] = array( + // 'Group Name' => array('a', 'b', 'c'), + // 'Another Group' => array('d') //); // Custom_categories - // Optional for the Categories theme. Array of name => (title, url) groups for categories with non-board links. - //$config['custom_categories'] = Array( - // 'Links' => Array( + // Optional for the Categories theme. array of name => (title, url) groups for categories with non-board links. + //$config['custom_categories'] = array( + // 'Links' => array( // 'Tinyboard' => 'http://tinyboard.org', // 'Donate' => 'donate.html' // ) @@ -576,24 +578,24 @@ // Custom embedding (YouTube, vimeo, etc.) // It's very important that you match the full string (with ^ and $) or things will not work correctly. - $config['embedding'] = Array( - Array( + $config['embedding'] = array( + array( '/^https?:\/\/(\w+\.)?youtube\.com\/watch\?v=([a-zA-Z0-9\-_]{10,11})(&.+)?$/i', '<object style="float: left;margin: 10px 20px;" width="%%tb_width%%" height="%%tb_height%%"><param name="movie" value="http://www.youtube.com/v/$2?fs=1&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/$2?fs=1&hl=en_US" type="application/x-shockwave-flash" width="%%tb_width%%" height="%%tb_height%%" allowscriptaccess="always" allowfullscreen="true"></embed></object>' ), - Array( + array( '/^https?:\/\/(\w+\.)?vimeo\.com\/(\d{2,10})(\?.+)?$/i', '<object style="float: left;margin: 10px 20px;" width="%%tb_width%%" height="%%tb_height%%"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=$2&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=$2&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="%%tb_width%%" height="%%tb_height%%"></embed></object>' ), - Array( + array( '/^https?:\/\/(\w+\.)?dailymotion\.com\/video\/([a-zA-Z0-9]{2,10})(_.+)?$/i', '<object style="float: left;margin: 10px 20px;" width="%%tb_width%%" height="%%tb_height%%"><param name="movie" value="http://www.dailymotion.com/swf/video/$2"></param><param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param><param name="wmode" value="transparent"></param><embed type="application/x-shockwave-flash" src="http://www.dailymotion.com/swf/video/$2" width="%%tb_width%%" height="%%tb_height%%" wmode="transparent" allowfullscreen="true" allowscriptaccess="always"></embed></object>' ), - Array( + array( '/^https?:\/\/(\w+\.)?metacafe\.com\/watch\/(\d+)\/([a-zA-Z0-9_\-.]+)\/(\?.+)?$/i', '<div style="float:left;margin:10px 20px;width:%%tb_width%%px;height:%%tb_height%%px"><embed flashVars="playerVars=showStats=no|autoPlay=no" src="http://www.metacafe.com/fplayer/$2/$3.swf" width="%%tb_width%%" height="%%tb_height%%" wmode="transparent" allowFullScreen="true" allowScriptAccess="always" name="Metacafe_$2" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed></div>' ), - Array( + array( '/^https?:\/\/video\.google\.com\/videoplay\?docid=(\d+)([&#](.+)?)?$/i', '<embed src="http://video.google.com/googleplayer.swf?docid=$1&hl=en&fs=true" style="width:%%tb_width%%px;height:%%tb_height%%px;float:left;margin:10px 20px" allowFullScreen="true" allowScriptAccess="always" type="application/x-shockwave-flash"></embed>' ) @@ -767,14 +769,14 @@ //$config['custom_capcode']['Custom'] ='<a class="capcode" style="color:lightgreen;font-style:italic;font-weight:bold"> ## %s</a>'; // "## Mod" makes everything purple, including the name and tripcode - //$config['custom_capcode']['Mod'] = Array( + //$config['custom_capcode']['Mod'] = array( // '<a class="capcode" style="color:purple"> ## %s</a>', // 'color:purple', // Change name style; optional // 'color:purple' // Change tripcode style; optional //); // "## Admin" makes everything red and bold, including the name and tripcode - //$config['custom_capcode']['Admin'] = Array( + //$config['custom_capcode']['Admin'] = array( // '<a class="capcode" style="color:red;font-weight:bold"> ## %s</a>', // 'color:red;font-weight:bold', // Change name style; optional // 'color:red;font-weight:bold' // Change tripcode style; optional @@ -996,18 +998,18 @@ // If you use Varnish, Squid, or any similar caching reverse-proxy in front of Tinyboard, // you can configure Tinyboard to PURGE files when they're written to - //$config['purge'] = Array( - // Array('127.0.0.1', 80) - // Array('127.0.0.1', 80, 'example.org') + //$config['purge'] = array( + // array('127.0.0.1', 80) + // array('127.0.0.1', 80, 'example.org') //); // Connection timeout, in seconds $config['purge_timeout'] = 3; // Remote servers // http://tinyboard.org/wiki/index.php?title=Multiple_Servers - //$config['remote']['static'] = Array( + //$config['remote']['static'] = array( // 'host' => 'static.example.org', - // 'auth' => Array( + // 'auth' => array( // 'method' => 'plain', // 'username' => 'username', // 'password' => 'password!123' @@ -1019,11 +1021,4 @@ $config['url_regex'] = '/' . '(https?|ftp):\/\/' . '(([\w\-]+\.)+[a-zA-Z]{2,6}|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' . '(:\d+)?' . '(\/([\w\-~.#\/?=&;:+%!*\[\]@$\'()+,|\^]+)?)?' . '/'; // INSANE regular expression for IPv6 addresses $config['ipv6_regex'] = '((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?'; - - - if($_SERVER['SCRIPT_FILENAME'] == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - header('Location: ../', true, 302); - exit; - } -?> + diff --git a/inc/database.php b/inc/database.php index b9338530..5e085b83 100644 --- a/inc/database.php +++ b/inc/database.php @@ -1,107 +1,111 @@ <?php - if($_SERVER['SCRIPT_FILENAME'] == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - header('Location: ../', true, 302); - exit; - } + +/* + * Copyright (c) 2010-2012 Tinyboard Development Group + */ + +if(realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { + // You cannot request this file directly. + exit; +} + +class PreparedQueryDebug { + protected $query; - class PreparedQueryDebug { - protected $query; + public function __construct($query) { + global $pdo; + $query = preg_replace("/[\n\t]+/", ' ', $query); - public function __construct($query) { - global $pdo; - $query = preg_replace("/[\n\t]+/", ' ', $query); - - $this->query = $pdo->prepare($query); - } - public function __call($function, $args) { - global $config, $debug; - - if($config['debug'] && $function == 'execute') { - $start = microtime(true); - } - - $return = call_user_func_array(Array($this->query, $function), $args); - - if($config['debug'] && $function == 'execute') { - $time = round((microtime(true) - $start) * 1000, 2) . 'ms'; - - $debug['sql'][] = Array( - 'query' => $this->query->queryString, - 'rows' => $this->query->rowCount(), - 'time' => '~' . $time - ); - } - - return $return; - } + $this->query = $pdo->prepare($query); } - - function sql_open() { - global $pdo, $config; - if($pdo) return true; + public function __call($function, $args) { + global $config, $debug; - $dsn = $config['db']['type'] . ':host=' . $config['db']['server'] . ';dbname=' . $config['db']['database']; - if(!empty($config['db']['dsn'])) - $dsn .= ';' . $config['db']['dsn']; - try { - $options = Array(PDO::ATTR_TIMEOUT => $config['db']['timeout']); - $options = Array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); - if($config['db']['persistent']) - $options[PDO::ATTR_PERSISTENT] = true; - return $pdo = new PDO($dsn, $config['db']['user'], $config['db']['password'], $options); - } catch(PDOException $e) { - $message = $e->getMessage(); - - // Remove any sensitive information - $message = str_replace($config['db']['user'], '<em>hidden</em>', $message); - $message = str_replace($config['db']['password'], '<em>hidden</em>', $message); - - // Print error - error('Database error: ' . $message); + if($config['debug'] && $function == 'execute') { + $start = microtime(true); } - } - - function prepare($query) { - global $pdo, $debug, $config; - - sql_open(); - if($config['debug']) - return new PreparedQueryDebug($query); - return $pdo->prepare($query); - } - - function query($query) { - global $pdo, $debug, $config; + $return = call_user_func_array(array($this->query, $function), $args); - sql_open(); - - if($config['debug']) { - $start = microtime(true); - $query = $pdo->query($query); - if(!$query) - return false; + if($config['debug'] && $function == 'execute') { $time = round((microtime(true) - $start) * 1000, 2) . 'ms'; + $debug['sql'][] = Array( - 'query' => $query->queryString, - 'rows' => $query->rowCount(), + 'query' => $this->query->queryString, + 'rows' => $this->query->rowCount(), 'time' => '~' . $time ); - return $query; - } else { - return $pdo->query($query); } + + return $return; } +} + +function sql_open() { + global $pdo, $config; + if($pdo) return true; - function db_error($PDOStatement=null) { - global $pdo; - if(isset($PDOStatement)) { - $err = $PDOStatement->errorInfo(); - return $err[2]; - } else { - $err = $pdo->errorInfo(); - return $err[2]; - } + $dsn = $config['db']['type'] . ':host=' . $config['db']['server'] . ';dbname=' . $config['db']['database']; + if(!empty($config['db']['dsn'])) + $dsn .= ';' . $config['db']['dsn']; + try { + $options = Array(PDO::ATTR_TIMEOUT => $config['db']['timeout']); + $options = Array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); + if($config['db']['persistent']) + $options[PDO::ATTR_PERSISTENT] = true; + return $pdo = new PDO($dsn, $config['db']['user'], $config['db']['password'], $options); + } catch(PDOException $e) { + $message = $e->getMessage(); + + // Remove any sensitive information + $message = str_replace($config['db']['user'], '<em>hidden</em>', $message); + $message = str_replace($config['db']['password'], '<em>hidden</em>', $message); + + // Print error + error('Database error: ' . $message); + } +} + +function prepare($query) { + global $pdo, $debug, $config; + + sql_open(); + + if($config['debug']) + return new PreparedQueryDebug($query); + return $pdo->prepare($query); +} + +function query($query) { + global $pdo, $debug, $config; + + sql_open(); + + if($config['debug']) { + $start = microtime(true); + $query = $pdo->query($query); + if(!$query) + return false; + $time = round((microtime(true) - $start) * 1000, 2) . 'ms'; + $debug['sql'][] = Array( + 'query' => $query->queryString, + 'rows' => $query->rowCount(), + 'time' => '~' . $time + ); + return $query; + } else { + return $pdo->query($query); + } +} + +function db_error($PDOStatement=null) { + global $pdo; + if(isset($PDOStatement)) { + $err = $PDOStatement->errorInfo(); + return $err[2]; + } else { + $err = $pdo->errorInfo(); + return $err[2]; } -?> +} + diff --git a/inc/display.php b/inc/display.php index ef6d1efc..9b118a00 100644 --- a/inc/display.php +++ b/inc/display.php @@ -1,445 +1,441 @@ <?php - if($_SERVER['SCRIPT_FILENAME'] == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - header('Location: ../', true, 302); - exit; + +/* + * Copyright (c) 2010-2012 Tinyboard Development Group + */ + +if(realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { + // You cannot request this file directly. + exit; +} + +/* + joaoptm78@gmail.com + http://www.php.net/manual/en/function.filesize.php#100097 +*/ +function format_bytes($size) { + $units = array(' B', ' KB', ' MB', ' GB', ' TB'); + for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024; + return round($size, 2).$units[$i]; +} + +function doBoardListPart($list, $root) { + global $config; + + $body = ''; + foreach($list as $board) { + if(is_array($board)) + $body .= ' [' . doBoardListPart($board, $root) . '] '; + else { + if(($key = array_search($board, $list)) && gettype($key) == 'string') { + $body .= ' <a href="' . $board . '">' . $key . '</a> /'; + } else { + $body .= ' <a href="' . $root . $board . '/' . $config['file_index'] . '">' . $board . '</a> /'; + } + } } + $body = preg_replace('/\/$/', '', $body); - /* - Stuff to help with the display. - */ + return $body; +} + +function createBoardlist($mod=false) { + global $config; + if(!isset($config['boards'])) return Array('top'=>'','bottom'=>''); - /* - joaoptm78@gmail.com - http://www.php.net/manual/en/function.filesize.php#100097 - */ - function format_bytes($size) { - $units = array(' B', ' KB', ' MB', ' GB', ' TB'); - for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024; - return round($size, 2).$units[$i]; - } + $body = doBoardListPart($config['boards'], $mod?'?/':$config['root']); + if(!preg_match('/\] $/', $body)) + $body = '[' . $body . ']'; - function commaize($n) { - $n = strval($n); - return (intval($n) < 1000) ? $n : commaize(substr($n, 0, -3)) . ',' . substr($n, -3); - } + $body = trim($body); - function doBoardListPart($list, $root) { - global $config; - - $body = ''; - foreach($list as $board) { - if(is_array($board)) - $body .= ' [' . doBoardListPart($board, $root) . '] '; - else { - if(($key = array_search($board, $list)) && gettype($key) == 'string') { - $body .= ' <a href="' . $board . '">' . $key . '</a> /'; - } else { - $body .= ' <a href="' . $root . $board . '/' . $config['file_index'] . '">' . $board . '</a> /'; - } - } - } - $body = preg_replace('/\/$/', '', $body); - - return $body; - } + return Array( + 'top' => '<div class="boardlist">' . $body . '</div>', + 'bottom' => '<div class="boardlist bottom">' . $body . '</div>' + ); +} + +function error($message, $priority = true) { + global $board, $mod, $config; - function createBoardlist($mod=false) { - global $config; - - if(!isset($config['boards'])) return Array('top'=>'','bottom'=>''); - - $body = doBoardListPart($config['boards'], $mod?'?/':$config['root']); - if(!preg_match('/\] $/', $body)) - $body = '[' . $body . ']'; - - $body = trim($body); - - return Array( - 'top' => '<div class="boardlist">' . $body . '</div>', - 'bottom' => '<div class="boardlist bottom">' . $body . '</div>' - ); + if($config['syslog'] && $priority !== false) { + // Use LOG_NOTICE instead of LOG_ERR or LOG_WARNING because most error message are not significant. + _syslog($priority !== true ? $priority : LOG_NOTICE, $message); } - function error($message, $priority = true) { - global $board, $mod, $config; - - if($config['syslog'] && $priority !== false) { - // Use LOG_NOTICE instead of LOG_ERR or LOG_WARNING because most error message are not significant. - _syslog($priority !== true ? $priority : LOG_NOTICE, $message); - } - - if(defined('STDIN')) { - // Running from CLI - die('Error: ' . $message . "\n"); - } - - die(Element('page.html', Array( - 'config'=>$config, - 'title'=>'Error', - 'subtitle'=>'An error has occured.', - 'body'=>'<center>' . - '<h2>' . _($message) . '</h2>' . - (isset($board) ? - "<p><a href=\"" . $config['root'] . - ($mod ? $config['file_mod'] . '?/' : '') . - $board['dir'] . $config['file_index'] . "\">Go back</a>.</p>" : '') . - '</center>' - ))); + if(defined('STDIN')) { + // Running from CLI + die('Error: ' . $message . "\n"); } - function loginForm($error=false, $username=false, $redirect=false) { - global $config; - - die(Element('page.html', Array( - 'index'=>$config['root'], - 'title'=>_('Login'), + die(Element('page.html', Array( + 'config'=>$config, + 'title'=>'Error', + 'subtitle'=>'An error has occured.', + 'body'=>'<center>' . + '<h2>' . _($message) . '</h2>' . + (isset($board) ? + "<p><a href=\"" . $config['root'] . + ($mod ? $config['file_mod'] . '?/' : '') . + $board['dir'] . $config['file_index'] . "\">Go back</a>.</p>" : '') . + '</center>' + ))); +} + +function loginForm($error=false, $username=false, $redirect=false) { + global $config; + + die(Element('page.html', Array( + 'index'=>$config['root'], + 'title'=>_('Login'), + 'config'=>$config, + 'body'=>Element('login.html', Array( 'config'=>$config, - 'body'=>Element('login.html', Array( - 'config'=>$config, - 'error'=>$error, - 'username'=>utf8tohtml($username), - 'redirect'=>$redirect - ) + 'error'=>$error, + 'username'=>utf8tohtml($username), + 'redirect'=>$redirect ) - ))); + ) + ))); +} + +function pm_snippet($body, $len=null) { + global $config; + + if(!isset($len)) + $len = &$config['mod']['snippet_length']; + + // Replace line breaks with some whitespace + $body = str_replace('<br/>', ' ', $body); + + // Strip tags + $body = strip_tags($body); + + // Unescape HTML characters, to avoid splitting them in half + $body = html_entity_decode($body, ENT_COMPAT, 'UTF-8'); + + // calculate strlen() so we can add "..." after if needed + $strlen = mb_strlen($body); + + $body = substr($body, 0, $len); + + // Re-escape the characters. + return '<em>' . utf8tohtml($body) . ($strlen > $len ? '…' : '') . '</em>'; +} + +function capcode($cap) { + global $config; + + if(!$cap) + return false; + + $capcode = Array(); + if(isset($config['custom_capcode'][$cap])) { + if(is_array($config['custom_capcode'][$cap])) { + $capcode['cap'] = sprintf($config['custom_capcode'][$cap][0], $cap); + if(isset($config['custom_capcode'][$cap][1])) + $capcode['name'] = $config['custom_capcode'][$cap][1]; + if(isset($config['custom_capcode'][$cap][2])) + $capcode['trip'] = $config['custom_capcode'][$cap][2]; + } else { + $capcode['cap'] = sprintf($config['custom_capcode'][$cap], $cap); + } + } else { + $capcode['cap'] = sprintf($config['capcode'], $cap); } - function pm_snippet($body, $len=null) { - global $config; - - if(!isset($len)) - $len = &$config['mod']['snippet_length']; - - // Replace line breaks with some whitespace - $body = str_replace('<br/>', ' ', $body); - - // Strip tags - $body = strip_tags($body); - - // Unescape HTML characters, to avoid splitting them in half - $body = html_entity_decode($body, ENT_COMPAT, 'UTF-8'); - - // calculate strlen() so we can add "..." after if needed - $strlen = mb_strlen($body); - - $body = substr($body, 0, $len); - - // Re-escape the characters. - return '<em>' . utf8tohtml($body) . ($strlen > $len ? '…' : '') . '</em>'; + return $capcode; +} + +function truncate($body, $url, $max_lines = false, $max_chars = false) { + global $config; + + if($max_lines === false) + $max_lines = $config['body_truncate']; + if($max_chars === false) + $max_chars = $config['body_truncate_char']; + $original_body = $body; + + $lines = substr_count($body, '<br/>'); + + // Limit line count + if($lines > $max_lines) { + if(preg_match('/(((.*?)<br\/>){' . $max_lines . '})/', $body, $m)) + $body = $m[0]; } - function capcode($cap) { - global $config; - - if(!$cap) - return false; + $body = substr($body, 0, $max_chars); + + if($body != $original_body) { + // Remove any corrupt tags at the end + $body = preg_replace('/<([\w]+)?([^>]*)?$/', '', $body); - $capcode = Array(); - if(isset($config['custom_capcode'][$cap])) { - if(is_array($config['custom_capcode'][$cap])) { - $capcode['cap'] = sprintf($config['custom_capcode'][$cap][0], $cap); - if(isset($config['custom_capcode'][$cap][1])) - $capcode['name'] = $config['custom_capcode'][$cap][1]; - if(isset($config['custom_capcode'][$cap][2])) - $capcode['trip'] = $config['custom_capcode'][$cap][2]; - } else { - $capcode['cap'] = sprintf($config['custom_capcode'][$cap], $cap); + // Open tags + if(preg_match_all('/<([\w]+)[^>]*>/', $body, $open_tags)) { + + $tags = Array(); + for($x=0;$x<count($open_tags[0]);$x++) { + if(!preg_match('/\/(\s+)?>$/', $open_tags[0][$x])) + $tags[] = $open_tags[1][$x]; + } + + // List successfully closed tags + if(preg_match_all('/(<\/([\w]+))>/', $body, $closed_tags)) { + for($x=0;$x<count($closed_tags[0]);$x++) { + unset($tags[array_search($closed_tags[2][$x], $tags)]); + } + } + + // remove broken HTML entity at the end (if existent) + $body = preg_replace('/&[^;]+$/', '', $body); + + // Close any open tags + foreach($tags as &$tag) { + $body .= "</{$tag}>"; } } else { - $capcode['cap'] = sprintf($config['capcode'], $cap); + // remove broken HTML entity at the end (if existent) + $body = preg_replace('/&[^;]+$/', '', $body); } - return $capcode; + $body .= '<span class="toolong">Post too long. Click <a href="' . $url . '">here</a> to view the full text.</span>'; } - function truncate($body, $url, $max_lines = false, $max_chars = false) { + return $body; +} + +function confirmLink($text, $title, $confirm, $href) { + global $config, $mod; + if($config['mod']['server-side_confirm']) + return '<a onclick="if(confirm(\'' . htmlentities(addslashes($confirm)) . '\')) document.location=\'?/' . htmlentities(addslashes($href)) . '\';return false;" title="' . htmlentities($title) . '" href="?/confirm/' . $href . '">' . $text . '</a>'; + else + return '<a onclick="return confirm(\'' . htmlentities(addslashes($confirm)) . '\')" title="' . htmlentities($title) . '" href="?/' . $href . '">' . $text . '</a>'; +} + +class Post { + public function __construct($id, $thread, $subject, $email, $name, $trip, $capcode, $body, $time, $thumb, $thumbx, $thumby, $file, $filex, $filey, $filesize, $filename, $ip, $embed, $root=null, $mod=false) { global $config; + if(!isset($root)) + $root = &$config['root']; - if($max_lines === false) - $max_lines = $config['body_truncate']; - if($max_chars === false) - $max_chars = $config['body_truncate_char']; - $original_body = $body; + $this->id = $id; + $this->thread = $thread; + $this->subject = utf8tohtml($subject); + $this->email = $email; + $this->name = utf8tohtml($name); + $this->trip = $trip; + $this->capcode = $capcode; + $this->body = $body; + $this->time = $time; + $this->thumb = $thumb; + $this->thumbx = $thumbx; + $this->thumby = $thumby; + $this->file = $file; + $this->filex = $filex; + $this->filey = $filey; + $this->filesize = $filesize; + $this->filename = $filename; + $this->ip = $ip; + $this->embed = $embed; + $this->root = $root; + $this->mod = $mod; - $lines = substr_count($body, '<br/>'); - - // Limit line count - if($lines > $max_lines) { - if(preg_match('/(((.*?)<br\/>){' . $max_lines . '})/', $body, $m)) - $body = $m[0]; - } + if($this->mod) + // Fix internal links + // Very complicated regex + $this->body = preg_replace( + '/<a((([a-zA-Z]+="[^"]+")|[a-zA-Z]+=[a-zA-Z]+|\s)*)href="' . preg_quote($config['root'], '/') . '(' . sprintf(preg_quote($config['board_path'], '/'), '\w+') . ')/', + '<a $1href="?/$4', + $this->body + ); + } + public function link($pre = '') { + global $config, $board; - $body = substr($body, 0, $max_chars); + return $this->root . $board['dir'] . $config['dir']['res'] . sprintf($config['file_page'], $this->thread) . '#' . $pre . $this->id; + } + public function postControls() { + global $board, $config; - if($body != $original_body) { - // Remove any corrupt tags at the end - $body = preg_replace('/<([\w]+)?([^>]*)?$/', '', $body); + $built = ''; + if($this->mod) { + // Mod controls (on posts) - // Open tags - if(preg_match_all('/<([\w]+)[^>]*>/', $body, $open_tags)) { - - $tags = Array(); - for($x=0;$x<count($open_tags[0]);$x++) { - if(!preg_match('/\/(\s+)?>$/', $open_tags[0][$x])) - $tags[] = $open_tags[1][$x]; - } - - // List successfully closed tags - if(preg_match_all('/(<\/([\w]+))>/', $body, $closed_tags)) { - for($x=0;$x<count($closed_tags[0]);$x++) { - unset($tags[array_search($closed_tags[2][$x], $tags)]); - } - } - - // remove broken HTML entity at the end (if existent) - $body = preg_replace('/&[^;]+$/', '', $body); - - // Close any open tags - foreach($tags as &$tag) { - $body .= "</{$tag}>"; - } - } else { - // remove broken HTML entity at the end (if existent) - $body = preg_replace('/&[^;]+$/', '', $body); - } + // Delete + if(hasPermission($config['mod']['delete'], $board['uri'], $this->mod)) + $built .= ' ' . confirmLink($config['mod']['link_delete'], 'Delete', 'Are you sure you want to delete this?', $board['uri'] . '/delete/' . $this->id); + + // Delete all posts by IP + if(hasPermission($config['mod']['deletebyip'], $board['uri'], $this->mod)) + $built .= ' ' . confirmLink($config['mod']['link_deletebyip'], 'Delete all posts by IP', 'Are you sure you want to delete all posts by this IP address?', $board['uri'] . '/deletebyip/' . $this->id); + + // Delete all posts by IP (global) + if(hasPermission($config['mod']['deletebyip_global'], $board['uri'], $this->mod)) + $built .= ' ' . confirmLink($config['mod']['link_deletebyip_global'], 'Delete all posts by IP across all boards', 'Are you sure you want to delete all posts by this IP address, across all boards?', $board['uri'] . '/deletebyip/' . $this->id . '/global'); + + // Ban + if(hasPermission($config['mod']['ban'], $board['uri'], $this->mod)) + $built .= ' <a title="Ban" href="?/' . $board['uri'] . '/ban/' . $this->id . '">' . $config['mod']['link_ban'] . '</a>'; + + // Ban & Delete + if(hasPermission($config['mod']['bandelete'], $board['uri'], $this->mod)) + $built .= ' <a title="Ban & Delete" href="?/' . $board['uri'] . '/ban&delete/' . $this->id . '">' . $config['mod']['link_bandelete'] . '</a>'; - $body .= '<span class="toolong">Post too long. Click <a href="' . $url . '">here</a> to view the full text.</span>'; + // Delete file (keep post) + if(!empty($this->file) && hasPermission($config['mod']['deletefile'], $board['uri'], $this->mod)) + $built .= ' <a title="Remove file" href="?/' . $board['uri'] . '/deletefile/' . $this->id . '">' . $config['mod']['link_deletefile'] . '</a>'; + + // Edit post + if(hasPermission($config['mod']['editpost'], $board['uri'], $this->mod)) + $built .= ' <a title="Edit post" href="?/' . $board['uri'] . '/edit/' . $this->id . '">' . $config['mod']['link_editpost'] . '</a>'; + + if(!empty($built)) + $built = '<span class="controls">' . $built . '</span>'; } - - return $body; + return $built; } - function confirmLink($text, $title, $confirm, $href) { - global $config, $mod; - if($config['mod']['server-side_confirm']) - return '<a onclick="if(confirm(\'' . htmlentities(addslashes($confirm)) . '\')) document.location=\'?/' . htmlentities(addslashes($href)) . '\';return false;" title="' . htmlentities($title) . '" href="?/confirm/' . $href . '">' . $text . '</a>'; - else - return '<a onclick="return confirm(\'' . htmlentities(addslashes($confirm)) . '\')" title="' . htmlentities($title) . '" href="?/' . $href . '">' . $text . '</a>'; + public function build($index=false) { + global $board, $config; + + return Element('post_reply.html', Array('config' => $config, 'board' => $board, 'post' => &$this, 'index' => $index)); } - - class Post { - public function __construct($id, $thread, $subject, $email, $name, $trip, $capcode, $body, $time, $thumb, $thumbx, $thumby, $file, $filex, $filey, $filesize, $filename, $ip, $embed, $root=null, $mod=false) { - global $config; - if(!isset($root)) $root = &$config['root']; +}; + +class Thread { + public function __construct($id, $subject, $email, $name, $trip, $capcode, $body, $time, $thumb, $thumbx, $thumby, $file, $filex, $filey, $filesize, $filename, $ip, $sticky, $locked, $bumplocked, $embed, $root=null, $mod=false, $hr=true) { + global $config; + if(!isset($root)) + $root = &$config['root']; + + $this->id = $id; + $this->subject = utf8tohtml($subject); + $this->email = $email; + $this->name = utf8tohtml($name); + $this->trip = $trip; + $this->capcode = $capcode; + $this->body = $body; + $this->time = $time; + $this->thumb = $thumb; + $this->thumbx = $thumbx; + $this->thumby = $thumby; + $this->file = $file; + $this->filex = $filex; + $this->filey = $filey; + $this->filesize = $filesize; + $this->filename = $filename; + $this->omitted = 0; + $this->omitted_images = 0; + $this->posts = Array(); + $this->ip = $ip; + $this->sticky = $sticky; + $this->locked = $locked; + $this->bumplocked = $bumplocked; + $this->embed = $embed; + $this->root = $root; + $this->mod = $mod; + $this->hr = $hr; + + if($this->mod) + // Fix internal links + // Very complicated regex + $this->body = preg_replace( + '/<a(([a-zA-Z]+="[^"]+")|[a-zA-Z]+=[a-zA-Z]+|\s)*href="' . preg_quote($config['root'], '/') . '(' . sprintf(preg_quote($config['board_path'], '/'), '\w+') . ')/', + '<a href="?/$3', + $this->body + ); + } + public function link($pre = '') { + global $config, $board; + + return $this->root . $board['dir'] . $config['dir']['res'] . sprintf($config['file_page'], $this->id) . '#' . $pre . $this->id; + } + public function add(Post $post) { + $this->posts[] = $post; + } + public function postControls() { + global $board, $config; + + $built = ''; + if($this->mod) { + // Mod controls (on posts) + // Delete + if(hasPermission($config['mod']['delete'], $board['uri'], $this->mod)) + $built .= ' ' . confirmLink($config['mod']['link_delete'], 'Delete', 'Are you sure you want to delete this?', $board['uri'] . '/delete/' . $this->id); - $this->id = $id; - $this->thread = $thread; - $this->subject = utf8tohtml($subject); - $this->email = $email; - $this->name = utf8tohtml($name); - $this->trip = $trip; - $this->capcode = $capcode; - $this->body = $body; - $this->time = $time; - $this->thumb = $thumb; - $this->thumbx = $thumbx; - $this->thumby = $thumby; - $this->file = $file; - $this->filex = $filex; - $this->filey = $filey; - $this->filesize = $filesize; - $this->filename = $filename; - $this->ip = $ip; - $this->embed = $embed; - $this->root = $root; - $this->mod = $mod; + // Delete all posts by IP + if(hasPermission($config['mod']['deletebyip'], $board['uri'], $this->mod)) + $built .= ' ' . confirmLink($config['mod']['link_deletebyip'], 'Delete all posts by IP', 'Are you sure you want to delete all posts by this IP address?', $board['uri'] . '/deletebyip/' . $this->id); - if($this->mod) - // Fix internal links - // Very complicated regex - $this->body = preg_replace( - '/<a((([a-zA-Z]+="[^"]+")|[a-zA-Z]+=[a-zA-Z]+|\s)*)href="' . preg_quote($config['root'], '/') . '(' . sprintf(preg_quote($config['board_path'], '/'), '\w+') . ')/', - '<a $1href="?/$4', - $this->body - ); - } - public function link($pre = '') { - global $config, $board; + // Delete all posts by IP (global) + if(hasPermission($config['mod']['deletebyip_global'], $board['uri'], $this->mod)) + $built .= ' ' . confirmLink($config['mod']['link_deletebyip_global'], 'Delete all posts by IP across all boards', 'Are you sure you want to delete all posts by this IP address, across all boards?', $board['uri'] . '/deletebyip/' . $this->id . '/global'); - return $this->root . $board['dir'] . $config['dir']['res'] . sprintf($config['file_page'], $this->thread) . '#' . $pre . $this->id; - } - public function postControls() { - global $board, $config; + // Ban + if(hasPermission($config['mod']['ban'], $board['uri'], $this->mod)) + $built .= ' <a title="Ban" href="?/' . $board['uri'] . '/ban/' . $this->id . '">' . $config['mod']['link_ban'] . '</a>'; - $built = ''; - if($this->mod) { - // Mod controls (on posts) - - // Delete - if(hasPermission($config['mod']['delete'], $board['uri'], $this->mod)) - $built .= ' ' . confirmLink($config['mod']['link_delete'], 'Delete', 'Are you sure you want to delete this?', $board['uri'] . '/delete/' . $this->id); - - // Delete all posts by IP - if(hasPermission($config['mod']['deletebyip'], $board['uri'], $this->mod)) - $built .= ' ' . confirmLink($config['mod']['link_deletebyip'], 'Delete all posts by IP', 'Are you sure you want to delete all posts by this IP address?', $board['uri'] . '/deletebyip/' . $this->id); - - // Delete all posts by IP (global) - if(hasPermission($config['mod']['deletebyip_global'], $board['uri'], $this->mod)) - $built .= ' ' . confirmLink($config['mod']['link_deletebyip_global'], 'Delete all posts by IP across all boards', 'Are you sure you want to delete all posts by this IP address, across all boards?', $board['uri'] . '/deletebyip/' . $this->id . '/global'); - - // Ban - if(hasPermission($config['mod']['ban'], $board['uri'], $this->mod)) - $built .= ' <a title="Ban" href="?/' . $board['uri'] . '/ban/' . $this->id . '">' . $config['mod']['link_ban'] . '</a>'; - - // Ban & Delete - if(hasPermission($config['mod']['bandelete'], $board['uri'], $this->mod)) - $built .= ' <a title="Ban & Delete" href="?/' . $board['uri'] . '/ban&delete/' . $this->id . '">' . $config['mod']['link_bandelete'] . '</a>'; - - // Delete file (keep post) - if(!empty($this->file) && hasPermission($config['mod']['deletefile'], $board['uri'], $this->mod)) - $built .= ' <a title="Remove file" href="?/' . $board['uri'] . '/deletefile/' . $this->id . '">' . $config['mod']['link_deletefile'] . '</a>'; - - // Edit post - if(hasPermission($config['mod']['editpost'], $board['uri'], $this->mod)) - $built .= ' <a title="Edit post" href="?/' . $board['uri'] . '/edit/' . $this->id . '">' . $config['mod']['link_editpost'] . '</a>'; - - if(!empty($built)) - $built = '<span class="controls">' . $built . '</span>'; - } - return $built; - } - - public function build($index=false) { - global $board, $config; + // Ban & Delete + if(hasPermission($config['mod']['bandelete'], $board['uri'], $this->mod)) + $built .= ' <a title="Ban & Delete" href="?/' . $board['uri'] . '/ban&delete/' . $this->id . '">' . $config['mod']['link_bandelete'] . '</a>'; - return Element('post_reply.html', Array('config' => $config, 'board' => $board, 'post' => &$this, 'index' => $index)); - } - }; - - class Thread { - public function __construct($id, $subject, $email, $name, $trip, $capcode, $body, $time, $thumb, $thumbx, $thumby, $file, $filex, $filey, $filesize, $filename, $ip, $sticky, $locked, $bumplocked, $embed, $root=null, $mod=false, $hr=true) { - global $config; - if(!isset($root)) $root = &$config['root']; + // Delete file (keep post) + if(!empty($this->file) && $this->file != 'deleted' && hasPermission($config['mod']['deletefile'], $board['uri'], $this->mod)) + $built .= ' <a title="Remove file" href="?/' . $board['uri'] . '/deletefile/' . $this->id . '">' . $config['mod']['link_deletefile'] . '</a>'; - $this->id = $id; - $this->subject = utf8tohtml($subject); - $this->email = $email; - $this->name = utf8tohtml($name); - $this->trip = $trip; - $this->capcode = $capcode; - $this->body = $body; - $this->time = $time; - $this->thumb = $thumb; - $this->thumbx = $thumbx; - $this->thumby = $thumby; - $this->file = $file; - $this->filex = $filex; - $this->filey = $filey; - $this->filesize = $filesize; - $this->filename = $filename; - $this->omitted = 0; - $this->omitted_images = 0; - $this->posts = Array(); - $this->ip = $ip; - $this->sticky = $sticky; - $this->locked = $locked; - $this->bumplocked = $bumplocked; - $this->embed = $embed; - $this->root = $root; - $this->mod = $mod; - $this->hr = $hr; + // Sticky + if(hasPermission($config['mod']['sticky'], $board['uri'], $this->mod)) + if($this->sticky) + $built .= ' <a title="Make thread not sticky" href="?/' . $board['uri'] . '/unsticky/' . $this->id . '">' . $config['mod']['link_desticky'] . '</a>'; + else + $built .= ' <a title="Make thread sticky" href="?/' . $board['uri'] . '/sticky/' . $this->id . '">' . $config['mod']['link_sticky'] . '</a>'; - if($this->mod) - // Fix internal links - // Very complicated regex - $this->body = preg_replace( - '/<a(([a-zA-Z]+="[^"]+")|[a-zA-Z]+=[a-zA-Z]+|\s)*href="' . preg_quote($config['root'], '/') . '(' . sprintf(preg_quote($config['board_path'], '/'), '\w+') . ')/', - '<a href="?/$3', - $this->body - ); - } - public function link($pre = '') { - global $config, $board; + if(hasPermission($config['mod']['bumplock'], $board['uri'], $this->mod)) + if($this->bumplocked) + $built .= ' <a title="Allow thread to be bumped" href="?/' . $board['uri'] . '/bumpunlock/' . $this->id . '">' . $config['mod']['link_bumpunlock'] . '</a>'; + else + $built .= ' <a title="Prevent thread from being bumped" href="?/' . $board['uri'] . '/bumplock/' . $this->id . '">' . $config['mod']['link_bumplock'] . '</a>'; - return $this->root . $board['dir'] . $config['dir']['res'] . sprintf($config['file_page'], $this->id) . '#' . $pre . $this->id; - } - public function add(Post $post) { - $this->posts[] = $post; - } - public function postControls() { - global $board, $config; + // Lock + if(hasPermission($config['mod']['lock'], $board['uri'], $this->mod)) + if($this->locked) + $built .= ' <a title="Unlock thread" href="?/' . $board['uri'] . '/unlock/' . $this->id . '">' . $config['mod']['link_unlock'] . '</a>'; + else + $built .= ' <a title="Lock thread" href="?/' . $board['uri'] . '/lock/' . $this->id . '">' . $config['mod']['link_lock'] . '</a>'; - $built = ''; - if($this->mod) { - // Mod controls (on posts) - // Delete - if(hasPermission($config['mod']['delete'], $board['uri'], $this->mod)) - $built .= ' ' . confirmLink($config['mod']['link_delete'], 'Delete', 'Are you sure you want to delete this?', $board['uri'] . '/delete/' . $this->id); - - // Delete all posts by IP - if(hasPermission($config['mod']['deletebyip'], $board['uri'], $this->mod)) - $built .= ' ' . confirmLink($config['mod']['link_deletebyip'], 'Delete all posts by IP', 'Are you sure you want to delete all posts by this IP address?', $board['uri'] . '/deletebyip/' . $this->id); - - // Delete all posts by IP (global) - if(hasPermission($config['mod']['deletebyip_global'], $board['uri'], $this->mod)) - $built .= ' ' . confirmLink($config['mod']['link_deletebyip_global'], 'Delete all posts by IP across all boards', 'Are you sure you want to delete all posts by this IP address, across all boards?', $board['uri'] . '/deletebyip/' . $this->id . '/global'); - - // Ban - if(hasPermission($config['mod']['ban'], $board['uri'], $this->mod)) - $built .= ' <a title="Ban" href="?/' . $board['uri'] . '/ban/' . $this->id . '">' . $config['mod']['link_ban'] . '</a>'; - - // Ban & Delete - if(hasPermission($config['mod']['bandelete'], $board['uri'], $this->mod)) - $built .= ' <a title="Ban & Delete" href="?/' . $board['uri'] . '/ban&delete/' . $this->id . '">' . $config['mod']['link_bandelete'] . '</a>'; - - // Delete file (keep post) - if(!empty($this->file) && $this->file != 'deleted' && hasPermission($config['mod']['deletefile'], $board['uri'], $this->mod)) - $built .= ' <a title="Remove file" href="?/' . $board['uri'] . '/deletefile/' . $this->id . '">' . $config['mod']['link_deletefile'] . '</a>'; - - // Sticky - if(hasPermission($config['mod']['sticky'], $board['uri'], $this->mod)) - if($this->sticky) - $built .= ' <a title="Make thread not sticky" href="?/' . $board['uri'] . '/unsticky/' . $this->id . '">' . $config['mod']['link_desticky'] . '</a>'; - else - $built .= ' <a title="Make thread sticky" href="?/' . $board['uri'] . '/sticky/' . $this->id . '">' . $config['mod']['link_sticky'] . '</a>'; - - if(hasPermission($config['mod']['bumplock'], $board['uri'], $this->mod)) - if($this->bumplocked) - $built .= ' <a title="Allow thread to be bumped" href="?/' . $board['uri'] . '/bumpunlock/' . $this->id . '">' . $config['mod']['link_bumpunlock'] . '</a>'; - else - $built .= ' <a title="Prevent thread from being bumped" href="?/' . $board['uri'] . '/bumplock/' . $this->id . '">' . $config['mod']['link_bumplock'] . '</a>'; - - // Lock - if(hasPermission($config['mod']['lock'], $board['uri'], $this->mod)) - if($this->locked) - $built .= ' <a title="Unlock thread" href="?/' . $board['uri'] . '/unlock/' . $this->id . '">' . $config['mod']['link_unlock'] . '</a>'; - else - $built .= ' <a title="Lock thread" href="?/' . $board['uri'] . '/lock/' . $this->id . '">' . $config['mod']['link_lock'] . '</a>'; - - if(hasPermission($config['mod']['move'], $board['uri'], $this->mod)) - $built .= ' <a title="Move thread to another board" href="?/' . $board['uri'] . '/move/' . $this->id . '">' . $config['mod']['link_move'] . '</a>'; - - // Edit post - if(hasPermission($config['mod']['editpost'], $board['uri'], $this->mod)) - $built .= ' <a title="Edit post" href="?/' . $board['uri'] . '/edit/' . $this->id . '">' . $config['mod']['link_editpost'] . '</a>'; - - if(!empty($built)) - $built = '<span class="controls op">' . $built . '</span>'; - } - return $built; - } - - public function ratio() { - return fraction($this->filex, $this->filey, ':'); - } - - public function build($index=false) { - global $board, $config, $debug; + if(hasPermission($config['mod']['move'], $board['uri'], $this->mod)) + $built .= ' <a title="Move thread to another board" href="?/' . $board['uri'] . '/move/' . $this->id . '">' . $config['mod']['link_move'] . '</a>'; - $built = Element('post_thread.html', Array('config' => $config, 'board' => $board, 'post' => &$this, 'index' => $index)); + // Edit post + if(hasPermission($config['mod']['editpost'], $board['uri'], $this->mod)) + $built .= ' <a title="Edit post" href="?/' . $board['uri'] . '/edit/' . $this->id . '">' . $config['mod']['link_editpost'] . '</a>'; - if(!$this->mod && $index && $config['cache']['enabled']) { - cache::set($this->cache_key($index), $built); - } - - return $built; + if(!empty($built)) + $built = '<span class="controls op">' . $built . '</span>'; } - function cache_key($index) { - global $board; - - return 'thread_' . ($index ? 'index_' : '') . $board['uri'] . '_' . $this->id; + return $built; + } + + public function ratio() { + return fraction($this->filex, $this->filey, ':'); + } + + public function build($index=false) { + global $board, $config, $debug; + + $built = Element('post_thread.html', Array('config' => $config, 'board' => $board, 'post' => &$this, 'index' => $index)); + + if(!$this->mod && $index && $config['cache']['enabled']) { + cache::set($this->cache_key($index), $built); } - }; -?> + + return $built; + } + function cache_key($index) { + global $board; + + return 'thread_' . ($index ? 'index_' : '') . $board['uri'] . '_' . $this->id; + } +}; + diff --git a/inc/events.php b/inc/events.php index 1c45b91b..33fa5a61 100644 --- a/inc/events.php +++ b/inc/events.php @@ -1,5 +1,14 @@ <?php +/* + * Copyright (c) 2010-2012 Tinyboard Development Group + */ + +if(realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { + // You cannot request this file directly. + exit; +} + function event() { global $events; diff --git a/inc/filters.php b/inc/filters.php index 3698f4e0..b3a0ca43 100644 --- a/inc/filters.php +++ b/inc/filters.php @@ -1,5 +1,14 @@ <?php +/* + * Copyright (c) 2010-2012 Tinyboard Development Group + */ + +if(realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { + // You cannot request this file directly. + exit; +} + class Filter { private $condition; diff --git a/inc/functions.php b/inc/functions.php index 3592512e..d7fcc3dd 100644 --- a/inc/functions.php +++ b/inc/functions.php @@ -1,1786 +1,1827 @@ <?php - if($_SERVER['SCRIPT_FILENAME'] == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - header('Location: ../', true, 302); - exit; + +/* + * Copyright (c) 2010-2012 Tinyboard Development Group + */ + +if(realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { + // You cannot request this file directly. + exit; +} + +require_once 'inc/display.php'; +require_once 'inc/template.php'; +require_once 'inc/database.php'; +require_once 'inc/events.php'; +require_once 'inc/lib/gettext/gettext.inc'; + +// the user is not currently logged in as a moderator +$mod = false; + +register_shutdown_function('fatal_error_handler'); +mb_internal_encoding('UTF-8'); +loadConfig(); + +function loadConfig() { + global $board, $config, $__ip, $debug, $__version; + + $error = function_exists('error') ? 'error' : 'basic_error_function_because_the_other_isnt_loaded_yet'; + + reset_events(); + + if(!isset($_SERVER['REMOTE_ADDR'])) + $_SERVER['REMOTE_ADDR'] = '0.0.0.0'; + + $arrays = array('db', 'cache', 'cookies', 'error', 'dir', 'mod', 'spam', 'flood_filters', 'wordfilters', 'custom_capcode', 'custom_tripcode', 'dnsbl', 'dnsbl_exceptions', 'remote', 'allowed_ext', 'allowed_ext_files', 'file_icons', 'footer', 'stylesheets', 'additional_javascript', 'markup'); + + $config = array(); + foreach($arrays as $key) { + $config[$key] = array(); } - require 'inc/events.php'; - require 'lib/gettext/gettext.inc'; + require 'inc/config.php'; + if(!file_exists('inc/instance-config.php')) + $error('Tinyboard is not configured! Create inc/instance-config.php.'); - register_shutdown_function('fatal_error_handler'); - mb_internal_encoding('UTF-8'); - loadConfig(); + require 'inc/instance-config.php'; - function loadConfig() { - global $board, $config, $__ip, $debug, $__version; - - $error = function_exists('error') ? 'error' : 'basic_error_function_because_the_other_isnt_loaded_yet'; - - reset_events(); - - if(!isset($_SERVER['REMOTE_ADDR'])) - $_SERVER['REMOTE_ADDR'] = '0.0.0.0'; - - $arrays = Array('db', 'cache', 'cookies', 'error', 'dir', 'mod', 'spam', 'flood_filters', 'wordfilters', 'custom_capcode', 'custom_tripcode', 'dnsbl', 'dnsbl_exceptions', 'remote', 'allowed_ext', 'allowed_ext_files', 'file_icons', 'footer', 'stylesheets', 'additional_javascript', 'markup'); - - $config = Array(); - foreach($arrays as $key) { - $config[$key] = Array(); - } - - require 'inc/config.php'; - if(!file_exists('inc/instance-config.php')) - $error('Tinyboard is not configured! Create inc/instance-config.php.'); - - require 'inc/instance-config.php'; - - if(isset($board['dir']) && file_exists($board['dir'] . '/config.php')) { - require $board['dir'] . '/config.php'; - } - - if(!isset($__version)) - $__version = file_exists('.installed') ? trim(file_get_contents('.installed')) : false; - $config['version'] = $__version; - - if($config['debug']) { - if(!isset($debug)) { - $debug = Array('sql' => Array(), 'purge' => Array(), 'cached' => Array()); - $debug['start'] = microtime(true); - } - } - - date_default_timezone_set($config['timezone']); - - if(!isset($config['blotter'])) - $config['blotter'] = false; - - if(!isset($config['post_url'])) - $config['post_url'] = $config['root'] . $config['file_post']; - - if(!isset($config['referer_match'])) - if(isset($_SERVER['HTTP_HOST'])) { - $config['referer_match'] = '/^' . - (preg_match($config['url_regex'], $config['root']) ? '' : - 'https?:\/\/' . $_SERVER['HTTP_HOST']) . - preg_quote($config['root'], '/') . - '(' . - str_replace('%s', '\w+', preg_quote($config['board_path'], '/')) . - '(' . - preg_quote($config['file_index'], '/') . '|' . - str_replace('%d', '\d+', preg_quote($config['file_page'])) . - ')?' . - '|' . - str_replace('%s', '\w+', preg_quote($config['board_path'], '/')) . - preg_quote($config['dir']['res'], '/') . - str_replace('%d', '\d+', preg_quote($config['file_page'], '/')) . - '|' . - preg_quote($config['file_mod'], '/') . '\?\/.+' . - ')([#?](.+)?)?$/i'; - } else { - // CLI mode - $config['referer_match'] = '//'; - } - if(!isset($config['cookies']['path'])) - $config['cookies']['path'] = &$config['root']; - - if(!isset($config['dir']['static'])) - $config['dir']['static'] = $config['root'] . 'static/'; - - if(!isset($config['image_sticky'])) - $config['image_sticky'] = $config['dir']['static'] . 'sticky.gif'; - if(!isset($config['image_locked'])) - $config['image_locked'] = $config['dir']['static'] . 'locked.gif'; - if(!isset($config['image_bumplocked'])) - $config['image_bumplocked'] = $config['dir']['static'] . 'sage.gif'; - if(!isset($config['image_deleted'])) - $config['image_deleted'] = $config['dir']['static'] . 'deleted.png'; - if(!isset($config['image_zip'])) - $config['image_zip'] = $config['dir']['static'] . 'zip.png'; - - if(!isset($config['uri_thumb'])) - $config['uri_thumb'] = $config['root'] . $board['dir'] . $config['dir']['thumb']; - elseif(isset($board['dir'])) - $config['uri_thumb'] = sprintf($config['uri_thumb'], $board['dir']); - - if(!isset($config['uri_img'])) - $config['uri_img'] = $config['root'] . $board['dir'] . $config['dir']['img']; - elseif(isset($board['dir'])) - $config['uri_img'] = sprintf($config['uri_img'], $board['dir']); - - if(!isset($config['uri_stylesheets'])) - $config['uri_stylesheets'] = $config['root'] . 'stylesheets/'; - - if(!isset($config['url_stylesheet'])) - $config['url_stylesheet'] = $config['uri_stylesheets'] . 'style.css'; - if(!isset($config['url_javascript'])) - $config['url_javascript'] = $config['root'] . $config['file_script']; - if(!isset($config['additional_javascript_url'])) - $config['additional_javascript_url'] = $config['root']; - - if($config['root_file']) { - chdir($config['root_file']); - } - - if($config['verbose_errors']) { - error_reporting(E_ALL); - ini_set('display_errors', 1); - } - - // Keep the original address to properly comply with other board configurations - if(!isset($__ip)) - $__ip = $_SERVER['REMOTE_ADDR']; - - // ::ffff:0.0.0.0 - if(preg_match('/^\:\:(ffff\:)?(\d+\.\d+\.\d+\.\d+)$/', $__ip, $m)) - $_SERVER['REMOTE_ADDR'] = $m[2]; - - if(_setlocale(LC_ALL, $config['locale']) === false) { - $error('The specified locale (' . $config['locale'] . ') does not exist on your platform!'); + if(isset($board['dir']) && file_exists($board['dir'] . '/config.php')) { + require $board['dir'] . '/config.php'; + } + + if(!isset($__version)) + $__version = file_exists('.installed') ? trim(file_get_contents('.installed')) : false; + $config['version'] = $__version; + + if($config['debug']) { + if(!isset($debug)) { + $debug = array('sql' => array(), 'purge' => array(), 'cached' => array()); + $debug['start'] = microtime(true); } - - if(extension_loaded('gettext')) { - bindtextdomain('tinyboard', './inc/locale'); - bind_textdomain_codeset('tinyboard', 'UTF-8'); - textdomain('tinyboard'); + } + + date_default_timezone_set($config['timezone']); + + if(!isset($config['blotter'])) + $config['blotter'] = false; + + if(!isset($config['post_url'])) + $config['post_url'] = $config['root'] . $config['file_post']; + + if(!isset($config['referer_match'])) + if(isset($_SERVER['HTTP_HOST'])) { + $config['referer_match'] = '/^' . + (preg_match($config['url_regex'], $config['root']) ? '' : + 'https?:\/\/' . $_SERVER['HTTP_HOST']) . + preg_quote($config['root'], '/') . + '(' . + str_replace('%s', '\w+', preg_quote($config['board_path'], '/')) . + '(' . + preg_quote($config['file_index'], '/') . '|' . + str_replace('%d', '\d+', preg_quote($config['file_page'])) . + ')?' . + '|' . + str_replace('%s', '\w+', preg_quote($config['board_path'], '/')) . + preg_quote($config['dir']['res'], '/') . + str_replace('%d', '\d+', preg_quote($config['file_page'], '/')) . + '|' . + preg_quote($config['file_mod'], '/') . '\?\/.+' . + ')([#?](.+)?)?$/i'; } else { - _bindtextdomain('tinyboard', './inc/locale'); - _bind_textdomain_codeset('tinyboard', 'UTF-8'); - _textdomain('tinyboard'); + // CLI mode + $config['referer_match'] = '//'; } + if(!isset($config['cookies']['path'])) + $config['cookies']['path'] = &$config['root']; - - if($config['syslog']) - openlog('tinyboard', LOG_ODELAY, LOG_SYSLOG); // open a connection to sysem logger - - if($config['recaptcha']) - require_once 'inc/lib/recaptcha/recaptchalib.php'; - if($config['cache']['enabled']) - require_once 'inc/cache.php'; + if(!isset($config['dir']['static'])) + $config['dir']['static'] = $config['root'] . 'static/'; + + if(!isset($config['image_sticky'])) + $config['image_sticky'] = $config['dir']['static'] . 'sticky.gif'; + if(!isset($config['image_locked'])) + $config['image_locked'] = $config['dir']['static'] . 'locked.gif'; + if(!isset($config['image_bumplocked'])) + $config['image_bumplocked'] = $config['dir']['static'] . 'sage.gif'; + if(!isset($config['image_deleted'])) + $config['image_deleted'] = $config['dir']['static'] . 'deleted.png'; + if(!isset($config['image_zip'])) + $config['image_zip'] = $config['dir']['static'] . 'zip.png'; + + if(!isset($config['uri_thumb'])) + $config['uri_thumb'] = $config['root'] . $board['dir'] . $config['dir']['thumb']; + elseif(isset($board['dir'])) + $config['uri_thumb'] = sprintf($config['uri_thumb'], $board['dir']); + + if(!isset($config['uri_img'])) + $config['uri_img'] = $config['root'] . $board['dir'] . $config['dir']['img']; + elseif(isset($board['dir'])) + $config['uri_img'] = sprintf($config['uri_img'], $board['dir']); + + if(!isset($config['uri_stylesheets'])) + $config['uri_stylesheets'] = $config['root'] . 'stylesheets/'; + + if(!isset($config['url_stylesheet'])) + $config['url_stylesheet'] = $config['uri_stylesheets'] . 'style.css'; + if(!isset($config['url_javascript'])) + $config['url_javascript'] = $config['root'] . $config['file_script']; + if(!isset($config['additional_javascript_url'])) + $config['additional_javascript_url'] = $config['root']; + + if($config['root_file']) { + chdir($config['root_file']); + } + + if($config['verbose_errors']) { + error_reporting(E_ALL); + ini_set('display_errors', 1); } - function basic_error_function_because_the_other_isnt_loaded_yet($message, $priority = true) { - global $config; - - if($config['syslog'] && $priority !== false) { - // Use LOG_NOTICE instead of LOG_ERR or LOG_WARNING because most error message are not significant. - _syslog($priority !== true ? $priority : LOG_NOTICE, $message); - } - - // Yes, this is horrible. - die('<!DOCTYPE html><html><head><title>Error</title>' . - '<style type="text/css">' . - 'body{text-align:center;font-family:arial, helvetica, sans-serif;font-size:10pt;}' . - 'p{padding:0;margin:20px 0;}' . - 'p.c{font-size:11px;}' . - '</style></head>' . - '<body><h2>Error</h2>' . $message . '<hr/>' . - '<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>'); + // Keep the original address to properly comply with other board configurations + if(!isset($__ip)) + $__ip = $_SERVER['REMOTE_ADDR']; + + // ::ffff:0.0.0.0 + if(preg_match('/^\:\:(ffff\:)?(\d+\.\d+\.\d+\.\d+)$/', $__ip, $m)) + $_SERVER['REMOTE_ADDR'] = $m[2]; + + if(_setlocale(LC_ALL, $config['locale']) === false) { + $error('The specified locale (' . $config['locale'] . ') does not exist on your platform!'); } - function fatal_error_handler() { - if($error = error_get_last()) { - if($error['type'] == E_ERROR) { - if(function_exists('error')) { - error('Caught fatal error: ' . $error['message'] . ' in <strong>' . $error['file'] . '</strong> on line ' . $error['line'], LOG_ERR); - } else { - basic_error_function_because_the_other_isnt_loaded_yet('Caught fatal error: ' . $error['message'] . ' in ' . $error['file'] . ' on line ' . $error['line'], LOG_ERR); - } - } - } + if(extension_loaded('gettext')) { + bindtextdomain('tinyboard', './inc/locale'); + bind_textdomain_codeset('tinyboard', 'UTF-8'); + textdomain('tinyboard'); + } else { + _bindtextdomain('tinyboard', './inc/locale'); + _bind_textdomain_codeset('tinyboard', 'UTF-8'); + _textdomain('tinyboard'); } - function _syslog($priority, $message) { - if(isset($_SERVER['REMOTE_ADDR'], $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'])) { - // CGI - syslog($priority, $message . ' - client: ' . $_SERVER['REMOTE_ADDR'] . ', request: "' . $_SERVER['REQUEST_METHOD'] . ' ' . $_SERVER['REQUEST_URI'] . '"'); - } else { - syslog($priority, $message); - } + + if($config['syslog']) + openlog('tinyboard', LOG_ODELAY, LOG_SYSLOG); // open a connection to sysem logger + + if($config['recaptcha']) + require_once 'inc/lib/recaptcha/recaptchalib.php'; + if($config['cache']['enabled']) + require_once 'inc/cache.php'; +} + +function basic_error_function_because_the_other_isnt_loaded_yet($message, $priority = true) { + global $config; + + if($config['syslog'] && $priority !== false) { + // Use LOG_NOTICE instead of LOG_ERR or LOG_WARNING because most error message are not significant. + _syslog($priority !== true ? $priority : LOG_NOTICE, $message); } + // Yes, this is horrible. + die('<!DOCTYPE html><html><head><title>Error</title>' . + '<style type="text/css">' . + 'body{text-align:center;font-family:arial, helvetica, sans-serif;font-size:10pt;}' . + 'p{padding:0;margin:20px 0;}' . + 'p.c{font-size:11px;}' . + '</style></head>' . + '<body><h2>Error</h2>' . $message . '<hr/>' . + '<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 rebuildThemes($action) { - // List themes - $query = query("SELECT `theme` FROM `theme_settings` WHERE `name` IS NULL AND `value` IS NULL") or error(db_error()); - while($theme = $query->fetch()) { - rebuildTheme($theme['theme'], $action); +function fatal_error_handler() { + if($error = error_get_last()) { + if($error['type'] == E_ERROR) { + if(function_exists('error')) { + error('Caught fatal error: ' . $error['message'] . ' in <strong>' . $error['file'] . '</strong> on line ' . $error['line'], LOG_ERR); + } else { + basic_error_function_because_the_other_isnt_loaded_yet('Caught fatal error: ' . $error['message'] . ' in ' . $error['file'] . ' on line ' . $error['line'], LOG_ERR); + } } } +} + +function _syslog($priority, $message) { + if(isset($_SERVER['REMOTE_ADDR'], $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'])) { + // CGI + syslog($priority, $message . ' - client: ' . $_SERVER['REMOTE_ADDR'] . ', request: "' . $_SERVER['REQUEST_METHOD'] . ' ' . $_SERVER['REQUEST_URI'] . '"'); + } else { + syslog($priority, $message); + } +} + + +function rebuildThemes($action) { + // List themes + $query = query("SELECT `theme` FROM `theme_settings` WHERE `name` IS NULL AND `value` IS NULL") or error(db_error()); + while($theme = $query->fetch()) { + rebuildTheme($theme['theme'], $action); + } +} + + +function loadThemeConfig($_theme) { + global $config; + + if(!file_exists($config['dir']['themes'] . '/' . $_theme . '/info.php')) + return false; + // Load theme information into $theme + include $config['dir']['themes'] . '/' . $_theme . '/info.php'; - function loadThemeConfig($_theme) { - global $config; + return $theme; +} + +function rebuildTheme($theme, $action) { + global $config, $_theme; + $_theme = $theme; + + $theme = loadThemeConfig($_theme); + + if(file_exists($config['dir']['themes'] . '/' . $_theme . '/theme.php')) { + require_once $config['dir']['themes'] . '/' . $_theme . '/theme.php'; - if(!file_exists($config['dir']['themes'] . '/' . $_theme . '/info.php')) - return false; + $theme['build_function']($action, themeSettings($_theme)); + } +} + + +function themeSettings($theme) { + $query = prepare("SELECT `name`, `value` FROM `theme_settings` WHERE `theme` = :theme AND `name` IS NOT NULL"); + $query->bindValue(':theme', $theme); + $query->execute() or error(db_error($query)); + + $settings = array(); + while($s = $query->fetch()) { + $settings[$s['name']] = $s['value']; + } + + return $settings; +} + +function sprintf3($str, $vars, $delim = '%') { + $replaces = array(); + foreach($vars as $k => $v) { + $replaces[$delim . $k . $delim] = $v; + } + return str_replace(array_keys($replaces), + array_values($replaces), $str); +} + +function setupBoard($array) { + global $board, $config; - // Load theme information into $theme - include $config['dir']['themes'] . '/' . $_theme . '/info.php'; + $board = array( + 'id' => $array['id'], + 'uri' => $array['uri'], + 'name' => $array['title'], + 'title' => $array['subtitle']); - return $theme; + $board['dir'] = sprintf($config['board_path'], $board['uri']); + $board['url'] = sprintf($config['board_abbreviation'], $board['uri']); + + loadConfig(); + + if(!file_exists($board['dir'])) + mkdir($board['dir'], 0777) or error("Couldn't create " . $board['dir'] . ". Check permissions.", true); + if(!file_exists($board['dir'] . $config['dir']['img'])) + @mkdir($board['dir'] . $config['dir']['img'], 0777) or error("Couldn't create " . $board['dir'] . $config['dir']['img'] . ". Check permissions.", true); + if(!file_exists($board['dir'] . $config['dir']['thumb'])) + @mkdir($board['dir'] . $config['dir']['thumb'], 0777) or error("Couldn't create " . $board['dir'] . $config['dir']['img'] . ". Check permissions.", true); + if(!file_exists($board['dir'] . $config['dir']['res'])) + @mkdir($board['dir'] . $config['dir']['res'], 0777) or error("Couldn't create " . $board['dir'] . $config['dir']['img'] . ". Check permissions.", true); +} + +function openBoard($uri) { + global $config; + if($config['cache']['enabled'] && ($board = cache::get('board_' . $uri))) { + setupBoard($board); + return true; } + + $query = prepare("SELECT * FROM `boards` WHERE `uri` = :uri LIMIT 1"); + $query->bindValue(':uri', $uri); + $query->execute() or error(db_error($query)); + + if($board = $query->fetch()) { + if($config['cache']['enabled']) + cache::set('board_' . $uri, $board); + setupBoard($board); + return true; + } else return false; +} - function rebuildTheme($theme, $action) { - global $config, $_theme; - $_theme = $theme; +function boardTitle($uri) { + global $config; + if($config['cache']['enabled'] && ($board = cache::get('board_' . $uri))) { + return $board['title']; + } - $theme = loadThemeConfig($_theme); + $query = prepare("SELECT `title` FROM `boards` WHERE `uri` = :uri LIMIT 1"); + $query->bindValue(':uri', $uri); + $query->execute() or error(db_error($query)); - if(file_exists($config['dir']['themes'] . '/' . $_theme . '/theme.php')) { - require_once $config['dir']['themes'] . '/' . $_theme . '/theme.php'; - - $theme['build_function']($action, themeSettings($_theme)); + if($title = $query->fetch()) { + return $title['title']; + } else return false; +} + +function purge($uri) { + global $config, $debug; + if(preg_match($config['referer_match'], $config['root'])) { + $uri = (str_replace('\\', '/', dirname($_SERVER['REQUEST_URI'])) == '/' ? '/' : str_replace('\\', '/', dirname($_SERVER['REQUEST_URI'])) . '/') . $uri; + } else { + $uri = $config['root'] . $uri; + } + + if($config['debug']) { + $debug['purge'][] = $uri; + } + + foreach($config['purge'] as &$purge) { + $host = &$purge[0]; + $port = &$purge[1]; + $http_host = isset($purge[2]) ? $purge[2] : $_SERVER['HTTP_HOST']; + $request = "PURGE {$uri} HTTP/1.1\r\nHost: {$http_host}\r\nUser-Agent: Tinyboard\r\nConnection: Close\r\n\r\n"; + if($fp = fsockopen($host, $port, $errno, $errstr, $config['purge_timeout'])) { + fwrite($fp, $request); + fclose($fp); + } else { + // Cannot connect? + error('Could not PURGE for ' . $host); } } +} - - function themeSettings($theme) { - $query = prepare("SELECT `name`, `value` FROM `theme_settings` WHERE `theme` = :theme AND `name` IS NOT NULL"); - $query->bindValue(':theme', $theme); - $query->execute() or error(db_error($query)); +function file_write($path, $data, $simple = false, $skip_purge = false) { + global $config; - $settings = Array(); - while($s = $query->fetch()) { - $settings[$s['name']] = $s['value']; + if(preg_match('/^remote:\/\/(.+)\:(.+)$/', $path, $m)) { + if(isset($config['remote'][$m[1]])) { + require_once 'inc/remote.php'; + + $remote = new Remote($config['remote'][$m[1]]); + $remote->write($data, $m[2]); + return; + } else { + error('Invalid remote server: ' . $m[1]); } + } - return $settings; + if(!$fp = fopen($path, $simple ? 'w' : 'c')) + error('Unable to open file for writing: ' . $path); + + // File locking + if(!$simple && !flock($fp, LOCK_EX)) { + error('Unable to lock file: ' . $path); } - - function sprintf3($str, $vars, $delim = '%') { - $replaces = array(); - foreach($vars as $k => $v) { - $replaces[$delim . $k . $delim] = $v; + + // Truncate file + if(!$simple && !ftruncate($fp, 0)) + error('Unable to truncate file: ' . $path); + + // Write data + if(fwrite($fp, $data) === false) + error('Unable to write to file: ' . $path); + + // Unlock + if(!$simple) + flock($fp, LOCK_UN); + + // Close + if(!fclose($fp)) + error('Unable to close file: ' . $path); + + if(!$skip_purge && isset($config['purge']) && isset($_SERVER['HTTP_HOST'])) { + // Purge cache + if(basename($path) == $config['file_index']) { + // Index file (/index.html); purge "/" as well + $uri = dirname($path); + // root + if($uri == '.') + $uri = ''; + else + $uri .= '/'; + purge($uri); } - return str_replace(array_keys($replaces), - array_values($replaces), $str); + purge($path); } - function setupBoard($array) { - global $board, $config; - - $board = Array( - 'id' => $array['id'], - 'uri' => $array['uri'], - 'name' => $array['title'], - 'title' => $array['subtitle']); - - $board['dir'] = sprintf($config['board_path'], $board['uri']); - $board['url'] = sprintf($config['board_abbreviation'], $board['uri']); - - loadConfig(); - - if(!file_exists($board['dir'])) - mkdir($board['dir'], 0777) or error("Couldn't create " . $board['dir'] . ". Check permissions.", true); - if(!file_exists($board['dir'] . $config['dir']['img'])) - @mkdir($board['dir'] . $config['dir']['img'], 0777) or error("Couldn't create " . $board['dir'] . $config['dir']['img'] . ". Check permissions.", true); - if(!file_exists($board['dir'] . $config['dir']['thumb'])) - @mkdir($board['dir'] . $config['dir']['thumb'], 0777) or error("Couldn't create " . $board['dir'] . $config['dir']['img'] . ". Check permissions.", true); - if(!file_exists($board['dir'] . $config['dir']['res'])) - @mkdir($board['dir'] . $config['dir']['res'], 0777) or error("Couldn't create " . $board['dir'] . $config['dir']['img'] . ". Check permissions.", true); + event('write', $path); +} + +function file_unlink($path) { + global $config, $debug; + + if($config['debug']) { + if(!isset($debug['unlink'])) + $debug['unlink'] = array(); + $debug['unlink'][] = $path; } - function openBoard($uri) { - global $config; - if($config['cache']['enabled'] && ($board = cache::get('board_' . $uri))) { - setupBoard($board); - return true; + $ret = @unlink($path); + if(isset($config['purge']) && $path[0] != '/' && isset($_SERVER['HTTP_HOST'])) { + // Purge cache + if(basename($path) == $config['file_index']) { + // Index file (/index.html); purge "/" as well + $uri = dirname($path); + // root + if($uri == '.') + $uri = ''; + else + $uri .= '/'; + purge($uri); } - - $query = prepare("SELECT * FROM `boards` WHERE `uri` = :uri LIMIT 1"); - $query->bindValue(':uri', $uri); - $query->execute() or error(db_error($query)); - - if($board = $query->fetch()) { - if($config['cache']['enabled']) - cache::set('board_' . $uri, $board); - setupBoard($board); - return true; - } else return false; + purge($path); } - function boardTitle($uri) { - global $config; - if($config['cache']['enabled'] && ($board = cache::get('board_' . $uri))) { - return $board['title']; - } + event('unlink', $path); + + return $ret; +} + +function hasPermission($action = null, $board = null, $_mod = null) { + global $config; - $query = prepare("SELECT `title` FROM `boards` WHERE `uri` = :uri LIMIT 1"); - $query->bindValue(':uri', $uri); + if(isset($_mod)) + $mod = &$_mod; + else + global $mod; + + if(!is_array($mod)) + return false; + + if(isset($action) && $mod['type'] < $action) + return false; + + if(!isset($board) || $config['mod']['skip_per_board']) + return true; + + if(!isset($mod['boards'])) + return false; + + if(!in_array('*', $mod['boards']) && !in_array($board, $mod['boards'])) + return false; + + return true; +} + +function listBoards() { + global $config; + + if($config['cache']['enabled'] && ($boards = cache::get('all_boards'))) + return $boards; + + $query = query("SELECT * FROM `boards` ORDER BY `uri`") or error(db_error()); + $boards = $query->fetchAll(); + + if($config['cache']['enabled']) + cache::set('all_boards', $boards); + + return $boards; +} + +function checkFlood($post) { + global $board, $config; + + $query = prepare(sprintf("SELECT * FROM `posts_%s` WHERE (`ip` = :ip AND `time` >= :floodtime) OR (`ip` = :ip AND `body` != '' AND `body` = :body AND `time` >= :floodsameiptime) OR (`body` != '' AND `body` = :body AND `time` >= :floodsametime) LIMIT 1", $board['uri'])); + $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); + $query->bindValue(':body', $post['body'], PDO::PARAM_INT); + $query->bindValue(':floodtime', time()-$config['flood_time'], PDO::PARAM_INT); + $query->bindValue(':floodsameiptime', time()-$config['flood_time_ip'], PDO::PARAM_INT); + $query->bindValue(':floodsametime', time()-$config['flood_time_same'], PDO::PARAM_INT); + $query->execute() or error(db_error($query)); + + $flood = (bool)$query->fetch(); + + if(event('check-flood', $post)) + return true; + + return $flood; +} + +function until($timestamp) { + $difference = $timestamp - time(); + if($difference < 60) { + return $difference . ' second' . ($difference != 1 ? 's' : ''); + } elseif($difference < 60*60) { + return ($num = round($difference/(60))) . ' minute' . ($num != 1 ? 's' : ''); + } elseif($difference < 60*60*24) { + return ($num = round($difference/(60*60))) . ' hour' . ($num != 1 ? 's' : ''); + } elseif($difference < 60*60*24*7) { + return ($num = round($difference/(60*60*24))) . ' day' . ($num != 1 ? 's' : ''); + } elseif($difference < 60*60*24*365) { + return ($num = round($difference/(60*60*24*7))) . ' week' . ($num != 1 ? 's' : ''); + } else { + return ($num = round($difference/(60*60*24*365))) . ' year' . ($num != 1 ? 's' : ''); + } +} + +function ago($timestamp) { + $difference = time() - $timestamp; + if($difference < 60) { + return $difference . ' second' . ($difference != 1 ? 's' : ''); + } elseif($difference < 60*60) { + return ($num = round($difference/(60))) . ' minute' . ($num != 1 ? 's' : ''); + } elseif($difference < 60*60*24) { + return ($num = round($difference/(60*60))) . ' hour' . ($num != 1 ? 's' : ''); + } elseif($difference < 60*60*24*7) { + return ($num = round($difference/(60*60*24))) . ' day' . ($num != 1 ? 's' : ''); + } elseif($difference < 60*60*24*365) { + return ($num = round($difference/(60*60*24*7))) . ' week' . ($num != 1 ? 's' : ''); + } else { + return ($num = round($difference/(60*60*24*365))) . ' year' . ($num != 1 ? 's' : ''); + } +} + +function displayBan($ban) { + global $config; + + $ban['ip'] = $_SERVER['REMOTE_ADDR']; + + // Show banned page and exit + die( + Element('page.html', array( + 'title' => 'Banned!', + 'config' => $config, + 'body' => Element('banned.html', array( + 'config' => $config, + 'ban' => $ban + ) + )) + )); +} + +function checkBan($board = 0) { + global $config; + + if(!isset($_SERVER['REMOTE_ADDR'])) { + // Server misconfiguration + return; + } + + if(event('check-ban', $board)) + return true; + + $query = prepare("SELECT `set`, `expires`, `reason`, `board`, `uri`, `bans`.`id` FROM `bans` LEFT JOIN `boards` ON `boards`.`id` = `board` WHERE (`board` IS NULL OR `uri` = :board) AND `ip` = :ip ORDER BY `expires` IS NULL DESC, `expires` DESC, `expires` DESC LIMIT 1"); + $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); + $query->bindValue(':board', $board); + $query->execute() or error(db_error($query)); + if($query->rowCount() < 1 && $config['ban_range']) { + $query = prepare("SELECT `set`, `expires`, `reason`, `board`, `uri`, `bans`.`id` FROM `bans` LEFT JOIN `boards` ON `boards`.`id` = `board` WHERE (`board` IS NULL OR `uri` = :board) AND :ip LIKE REPLACE(REPLACE(`ip`, '%', '!%'), '*', '%') ESCAPE '!' ORDER BY `expires` IS NULL DESC, `expires` DESC LIMIT 1"); + $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); + $query->bindValue(':board', $board); $query->execute() or error(db_error($query)); - - if($title = $query->fetch()) { - return $title['title']; - } else return false; } - function purge($uri) { - global $config, $debug; - if(preg_match($config['referer_match'], $config['root'])) { - $uri = (str_replace('\\', '/', dirname($_SERVER['REQUEST_URI'])) == '/' ? '/' : str_replace('\\', '/', dirname($_SERVER['REQUEST_URI'])) . '/') . $uri; - } else { - $uri = $config['root'] . $uri; - } - - if($config['debug']) { - $debug['purge'][] = $uri; - } - - foreach($config['purge'] as &$purge) { - $host = &$purge[0]; - $port = &$purge[1]; - $http_host = isset($purge[2]) ? $purge[2] : $_SERVER['HTTP_HOST']; - $request = "PURGE {$uri} HTTP/1.1\r\nHost: {$http_host}\r\nUser-Agent: Tinyboard\r\nConnection: Close\r\n\r\n"; - if($fp = fsockopen($host, $port, $errno, $errstr, $config['purge_timeout'])) { - fwrite($fp, $request); - fclose($fp); - } else { - // Cannot connect? - error('Could not PURGE for ' . $host); - } - } + if($query->rowCount() < 1 && $config['ban_cidr'] && !isIPv6()) { + // my most insane SQL query yet + $query = prepare("SELECT `set`, `expires`, `reason`, `board`, `uri`, `bans`.`id` FROM `bans` LEFT JOIN `boards` ON `boards`.`id` = `board` WHERE (`board` IS NULL OR `uri` = :board) + AND ( + `ip` REGEXP '^(\[0-9]+\.\[0-9]+\.\[0-9]+\.\[0-9]+\)\/(\[0-9]+)$' + AND + :ip >= INET_ATON(SUBSTRING_INDEX(`ip`, '/', 1)) + AND + :ip < INET_ATON(SUBSTRING_INDEX(`ip`, '/', 1)) + POW(2, 32 - SUBSTRING_INDEX(`ip`, '/', -1)) + ) + ORDER BY `expires` IS NULL DESC, `expires` DESC LIMIT 1"); + $query->bindValue(':ip', ip2long($_SERVER['REMOTE_ADDR'])); + $query->bindValue(':board', $board); + $query->execute() or error(db_error($query)); } - function file_write($path, $data, $simple = false, $skip_purge = false) { - global $config; - - if(preg_match('/^remote:\/\/(.+)\:(.+)$/', $path, $m)) { - if(isset($config['remote'][$m[1]])) { - require_once 'inc/remote.php'; - - $remote = new Remote($config['remote'][$m[1]]); - $remote->write($data, $m[2]); - return; - } else { - error('Invalid remote server: ' . $m[1]); - } - } - - if(!$fp = fopen($path, $simple ? 'w' : 'c')) - error('Unable to open file for writing: ' . $path); - - // File locking - if(!$simple && !flock($fp, LOCK_EX)) { - error('Unable to lock file: ' . $path); - } - - // Truncate file - if(!$simple && !ftruncate($fp, 0)) - error('Unable to truncate file: ' . $path); + if($ban = $query->fetch()) { + if($ban['expires'] && $ban['expires'] < time()) { + // Ban expired + $query = prepare("DELETE FROM `bans` WHERE `id` = :id LIMIT 1"); + $query->bindValue(':id', $ban['id'], PDO::PARAM_INT); + $query->execute() or error(db_error($query)); - // Write data - if(fwrite($fp, $data) === false) - error('Unable to write to file: ' . $path); - - // Unlock - if(!$simple) - flock($fp, LOCK_UN); - - // Close - if(!fclose($fp)) - error('Unable to close file: ' . $path); - - if(!$skip_purge && isset($config['purge']) && isset($_SERVER['HTTP_HOST'])) { - // Purge cache - if(basename($path) == $config['file_index']) { - // Index file (/index.html); purge "/" as well - $uri = dirname($path); - // root - if($uri == '.') - $uri = ''; - else - $uri .= '/'; - purge($uri); - } - purge($path); + return; } - event('write', $path); + displayBan($ban); } +} + +function threadLocked($id) { + global $board; - function file_unlink($path) { - global $config, $debug; - - if($config['debug']) { - if(!isset($debug['unlink'])) - $debug['unlink'] = Array(); - $debug['unlink'][] = $path; - } - - $ret = @unlink($path); - if(isset($config['purge']) && $path[0] != '/' && isset($_SERVER['HTTP_HOST'])) { - // Purge cache - if(basename($path) == $config['file_index']) { - // Index file (/index.html); purge "/" as well - $uri = dirname($path); - // root - if($uri == '.') - $uri = ''; - else - $uri .= '/'; - purge($uri); - } - purge($path); - } - - event('unlink', $path); - - return $ret; + if(event('check-locked', $id)) + return true; + + $query = prepare(sprintf("SELECT `locked` FROM `posts_%s` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri'])); + $query->bindValue(':id', $id, PDO::PARAM_INT); + $query->execute() or error(db_error()); + + if(!$post = $query->fetch()) { + // Non-existant, so it can't be locked... + return false; } - function hasPermission($action = null, $board = null, $_mod = null) { - global $config; - - if(isset($_mod)) - $mod = &$_mod; - else - global $mod; - - if(!is_array($mod)) - return false; - - if(isset($action) && $mod['type'] < $action) - return false; - - if(!isset($board) || $config['mod']['skip_per_board']) - return true; - - if(!isset($mod['boards'])) - return false; - - if(!in_array('*', $mod['boards']) && !in_array($board, $mod['boards'])) - return false; - + return (bool)$post['locked']; +} + +function threadSageLocked($id) { + global $board; + + if(event('check-sage-locked', $id)) return true; - } - function listBoards() { - global $config; - - if($config['cache']['enabled'] && ($boards = cache::get('all_boards'))) - return $boards; - - $query = query("SELECT * FROM `boards` ORDER BY `uri`") or error(db_error()); - $boards = $query->fetchAll(); - - if($config['cache']['enabled']) - cache::set('all_boards', $boards); - - return $boards; + $query = prepare(sprintf("SELECT `sage` FROM `posts_%s` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri'])); + $query->bindValue(':id', $id, PDO::PARAM_INT); + $query->execute() or error(db_error()); + + if(!$post = $query->fetch()) { + // Non-existant, so it can't be locked... + return false; } - function checkFlood($post) { - global $board, $config; - - $query = prepare(sprintf("SELECT * FROM `posts_%s` WHERE (`ip` = :ip AND `time` >= :floodtime) OR (`ip` = :ip AND `body` != '' AND `body` = :body AND `time` >= :floodsameiptime) OR (`body` != '' AND `body` = :body AND `time` >= :floodsametime) LIMIT 1", $board['uri'])); - $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); - $query->bindValue(':body', $post['body'], PDO::PARAM_INT); - $query->bindValue(':floodtime', time()-$config['flood_time'], PDO::PARAM_INT); - $query->bindValue(':floodsameiptime', time()-$config['flood_time_ip'], PDO::PARAM_INT); - $query->bindValue(':floodsametime', time()-$config['flood_time_same'], PDO::PARAM_INT); - $query->execute() or error(db_error($query)); - - $flood = (bool)$query->fetch(); - - if(event('check-flood', $post)) - return true; - - return $flood; + return (bool) $post['sage']; +} + +function threadExists($id) { + global $board; + + $query = prepare(sprintf("SELECT 1 FROM `posts_%s` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri'])); + $query->bindValue(':id', $id, PDO::PARAM_INT); + $query->execute() or error(db_error()); + + if($query->rowCount()) { + return true; + } else return false; +} + +function post(array $post) { + global $pdo, $board; + $query = prepare(sprintf("INSERT INTO `posts_%s` VALUES ( NULL, :thread, :subject, :email, :name, :trip, :capcode, :body, :body_nomarkup, :time, :time, :thumb, :thumbwidth, :thumbheight, :file, :width, :height, :filesize, :filename, :filehash, :password, :ip, :sticky, :locked, 0, :embed)", $board['uri'])); + + // Basic stuff + if(!empty($post['subject'])) { + $query->bindValue(':subject', $post['subject']); + } else { + $query->bindValue(':subject', NULL, PDO::PARAM_NULL); } - function until($timestamp) { - $difference = $timestamp - time(); - if($difference < 60) { - return $difference . ' second' . ($difference != 1 ? 's' : ''); - } elseif($difference < 60*60) { - return ($num = round($difference/(60))) . ' minute' . ($num != 1 ? 's' : ''); - } elseif($difference < 60*60*24) { - return ($num = round($difference/(60*60))) . ' hour' . ($num != 1 ? 's' : ''); - } elseif($difference < 60*60*24*7) { - return ($num = round($difference/(60*60*24))) . ' day' . ($num != 1 ? 's' : ''); - } elseif($difference < 60*60*24*365) { - return ($num = round($difference/(60*60*24*7))) . ' week' . ($num != 1 ? 's' : ''); - } else { - return ($num = round($difference/(60*60*24*365))) . ' year' . ($num != 1 ? 's' : ''); - } + if(!empty($post['email'])) { + $query->bindValue(':email', $post['email']); + } else { + $query->bindValue(':email', NULL, PDO::PARAM_NULL); } - function ago($timestamp) { - $difference = time() - $timestamp; - if($difference < 60) { - return $difference . ' second' . ($difference != 1 ? 's' : ''); - } elseif($difference < 60*60) { - return ($num = round($difference/(60))) . ' minute' . ($num != 1 ? 's' : ''); - } elseif($difference < 60*60*24) { - return ($num = round($difference/(60*60))) . ' hour' . ($num != 1 ? 's' : ''); - } elseif($difference < 60*60*24*7) { - return ($num = round($difference/(60*60*24))) . ' day' . ($num != 1 ? 's' : ''); - } elseif($difference < 60*60*24*365) { - return ($num = round($difference/(60*60*24*7))) . ' week' . ($num != 1 ? 's' : ''); - } else { - return ($num = round($difference/(60*60*24*365))) . ' year' . ($num != 1 ? 's' : ''); - } + if(!empty($post['trip'])) { + $query->bindValue(':trip', $post['trip']); + } else { + $query->bindValue(':trip', NULL, PDO::PARAM_NULL); } - function displayBan($ban) { - global $config; - - $ban['ip'] = $_SERVER['REMOTE_ADDR']; - - // Show banned page and exit - die( - Element('page.html', Array( - 'title' => 'Banned!', - 'config' => $config, - 'body' => Element('banned.html', Array( - 'config' => $config, - 'ban' => $ban - ) - )) - )); + $query->bindValue(':name', $post['name']); + $query->bindValue(':body', $post['body']); + $query->bindValue(':body_nomarkup', $post['body_nomarkup']); + $query->bindValue(':time', isset($post['time']) ? $post['time'] : time(), PDO::PARAM_INT); + $query->bindValue(':password', $post['password']); + $query->bindValue(':ip', isset($post['ip']) ? $post['ip'] : $_SERVER['REMOTE_ADDR']); + + if($post['mod'] && $post['sticky']) { + $query->bindValue(':sticky', 1, PDO::PARAM_INT); + } else { + $query->bindValue(':sticky', 0, PDO::PARAM_INT); } - function checkBan($board = 0) { - global $config; - - if(!isset($_SERVER['REMOTE_ADDR'])) { - // Server misconfiguration - return; - } - - if(event('check-ban', $board)) - return true; - - $query = prepare("SELECT `set`, `expires`, `reason`, `board`, `uri`, `bans`.`id` FROM `bans` LEFT JOIN `boards` ON `boards`.`id` = `board` WHERE (`board` IS NULL OR `uri` = :board) AND `ip` = :ip ORDER BY `expires` IS NULL DESC, `expires` DESC, `expires` DESC LIMIT 1"); - $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); - $query->bindValue(':board', $board); - $query->execute() or error(db_error($query)); - if($query->rowCount() < 1 && $config['ban_range']) { - $query = prepare("SELECT `set`, `expires`, `reason`, `board`, `uri`, `bans`.`id` FROM `bans` LEFT JOIN `boards` ON `boards`.`id` = `board` WHERE (`board` IS NULL OR `uri` = :board) AND :ip LIKE REPLACE(REPLACE(`ip`, '%', '!%'), '*', '%') ESCAPE '!' ORDER BY `expires` IS NULL DESC, `expires` DESC LIMIT 1"); - $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); - $query->bindValue(':board', $board); - $query->execute() or error(db_error($query)); - } - - if($query->rowCount() < 1 && $config['ban_cidr'] && !isIPv6()) { - // my most insane SQL query yet - $query = prepare("SELECT `set`, `expires`, `reason`, `board`, `uri`, `bans`.`id` FROM `bans` LEFT JOIN `boards` ON `boards`.`id` = `board` WHERE (`board` IS NULL OR `uri` = :board) - AND ( - `ip` REGEXP '^(\[0-9]+\.\[0-9]+\.\[0-9]+\.\[0-9]+\)\/(\[0-9]+)$' - AND - :ip >= INET_ATON(SUBSTRING_INDEX(`ip`, '/', 1)) - AND - :ip < INET_ATON(SUBSTRING_INDEX(`ip`, '/', 1)) + POW(2, 32 - SUBSTRING_INDEX(`ip`, '/', -1)) - ) - ORDER BY `expires` IS NULL DESC, `expires` DESC LIMIT 1"); - $query->bindValue(':ip', ip2long($_SERVER['REMOTE_ADDR'])); - $query->bindValue(':board', $board); - $query->execute() or error(db_error($query)); - } - - if($ban = $query->fetch()) { - if($ban['expires'] && $ban['expires'] < time()) { - // Ban expired - $query = prepare("DELETE FROM `bans` WHERE `id` = :id LIMIT 1"); - $query->bindValue(':id', $ban['id'], PDO::PARAM_INT); - $query->execute() or error(db_error($query)); - - return; - } - - displayBan($ban); - } + if($post['mod'] && $post['locked']) { + $query->bindValue(':locked', 1, PDO::PARAM_INT); + } else { + $query->bindValue(':locked', 0, PDO::PARAM_INT); } - function threadLocked($id) { - global $board; - - if(event('check-locked', $id)) - return true; - - $query = prepare(sprintf("SELECT `locked` FROM `posts_%s` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri'])); - $query->bindValue(':id', $id, PDO::PARAM_INT); - $query->execute() or error(db_error()); - - if(!$post = $query->fetch()) { - // Non-existant, so it can't be locked... - return false; - } - - return (bool)$post['locked']; + if($post['mod'] && isset($post['capcode']) && $post['capcode']) { + $query->bindValue(':capcode', $post['capcode'], PDO::PARAM_INT); + } else { + $query->bindValue(':capcode', NULL, PDO::PARAM_NULL); } - function threadSageLocked($id) { - global $board; - - if(event('check-sage-locked', $id)) - return true; - - $query = prepare(sprintf("SELECT `sage` FROM `posts_%s` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri'])); - $query->bindValue(':id', $id, PDO::PARAM_INT); - $query->execute() or error(db_error()); - - if(!$post = $query->fetch()) { - // Non-existant, so it can't be locked... - return false; - } - - return (bool) $post['sage']; + if(!empty($post['embed'])) { + $query->bindValue(':embed', $post['embed']); + } else { + $query->bindValue(':embed', NULL, PDO::PARAM_NULL); } - function threadExists($id) { - global $board; - - $query = prepare(sprintf("SELECT 1 FROM `posts_%s` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri'])); - $query->bindValue(':id', $id, PDO::PARAM_INT); - $query->execute() or error(db_error()); - - if($query->rowCount()) { - return true; - } else return false; + if($post['op']) { + // No parent thread, image + $query->bindValue(':thread', null, PDO::PARAM_NULL); + } else { + $query->bindValue(':thread', $post['thread'], PDO::PARAM_INT); } - function post($post) { - global $pdo, $board; - $query = prepare(sprintf("INSERT INTO `posts_%s` VALUES ( NULL, :thread, :subject, :email, :name, :trip, :capcode, :body, :body_nomarkup, :time, :time, :thumb, :thumbwidth, :thumbheight, :file, :width, :height, :filesize, :filename, :filehash, :password, :ip, :sticky, :locked, 0, :embed)", $board['uri'])); + if($post['has_file']) { + $query->bindValue(':thumb', $post['thumb']); + $query->bindValue(':thumbwidth', $post['thumbwidth'], PDO::PARAM_INT); + $query->bindValue(':thumbheight', $post['thumbheight'], PDO::PARAM_INT); + $query->bindValue(':file', $post['file']); - // Basic stuff - if(!empty($post['subject'])) { - $query->bindValue(':subject', $post['subject']); + if(isset($post['width'], $post['height'])) { + $query->bindValue(':width', $post['width'], PDO::PARAM_INT); + $query->bindValue(':height', $post['height'], PDO::PARAM_INT); } else { - $query->bindValue(':subject', NULL, PDO::PARAM_NULL); - } - - if(!empty($post['email'])) { - $query->bindValue(':email', $post['email']); - } else { - $query->bindValue(':email', NULL, PDO::PARAM_NULL); - } - - if(!empty($post['trip'])) { - $query->bindValue(':trip', $post['trip']); - } else { - $query->bindValue(':trip', NULL, PDO::PARAM_NULL); - } - - $query->bindValue(':name', $post['name']); - $query->bindValue(':body', $post['body']); - $query->bindValue(':body_nomarkup', $post['body_nomarkup']); - $query->bindValue(':time', isset($post['time']) ? $post['time'] : time(), PDO::PARAM_INT); - $query->bindValue(':password', $post['password']); - $query->bindValue(':ip', isset($post['ip']) ? $post['ip'] : $_SERVER['REMOTE_ADDR']); - - if($post['mod'] && $post['sticky']) { - $query->bindValue(':sticky', 1, PDO::PARAM_INT); - } else { - $query->bindValue(':sticky', 0, PDO::PARAM_INT); - } - - if($post['mod'] && $post['locked']) { - $query->bindValue(':locked', 1, PDO::PARAM_INT); - } else { - $query->bindValue(':locked', 0, PDO::PARAM_INT); - } - - if($post['mod'] && isset($post['capcode']) && $post['capcode']) { - $query->bindValue(':capcode', $post['capcode'], PDO::PARAM_INT); - } else { - $query->bindValue(':capcode', NULL, PDO::PARAM_NULL); - } - - if(!empty($post['embed'])) { - $query->bindValue(':embed', $post['embed']); - } else { - $query->bindValue(':embed', NULL, PDO::PARAM_NULL); - } - - if($post['op']) { - // No parent thread, image - $query->bindValue(':thread', null, PDO::PARAM_NULL); - } else { - $query->bindValue(':thread', $post['thread'], PDO::PARAM_INT); - } - - if($post['has_file']) { - $query->bindValue(':thumb', $post['thumb']); - $query->bindValue(':thumbwidth', $post['thumbwidth'], PDO::PARAM_INT); - $query->bindValue(':thumbheight', $post['thumbheight'], PDO::PARAM_INT); - $query->bindValue(':file', $post['file']); - - if(isset($post['width'], $post['height'])) { - $query->bindValue(':width', $post['width'], PDO::PARAM_INT); - $query->bindValue(':height', $post['height'], PDO::PARAM_INT); - } else { - $query->bindValue(':width', null, PDO::PARAM_NULL); - $query->bindValue(':height', null, PDO::PARAM_NULL); - } - - $query->bindValue(':filesize', $post['filesize'], PDO::PARAM_INT); - $query->bindValue(':filename', $post['filename']); - $query->bindValue(':filehash', $post['filehash']); - } else { - $query->bindValue(':thumb', null, PDO::PARAM_NULL); - $query->bindValue(':thumbwidth', null, PDO::PARAM_NULL); - $query->bindValue(':thumbheight', null, PDO::PARAM_NULL); - $query->bindValue(':file', null, PDO::PARAM_NULL); $query->bindValue(':width', null, PDO::PARAM_NULL); $query->bindValue(':height', null, PDO::PARAM_NULL); - $query->bindValue(':filesize', null, PDO::PARAM_NULL); - $query->bindValue(':filename', null, PDO::PARAM_NULL); - $query->bindValue(':filehash', null, PDO::PARAM_NULL); } - $query->execute() or error(db_error($query)); - - return $pdo->lastInsertId(); + $query->bindValue(':filesize', $post['filesize'], PDO::PARAM_INT); + $query->bindValue(':filename', $post['filename']); + $query->bindValue(':filehash', $post['filehash']); + } else { + $query->bindValue(':thumb', null, PDO::PARAM_NULL); + $query->bindValue(':thumbwidth', null, PDO::PARAM_NULL); + $query->bindValue(':thumbheight', null, PDO::PARAM_NULL); + $query->bindValue(':file', null, PDO::PARAM_NULL); + $query->bindValue(':width', null, PDO::PARAM_NULL); + $query->bindValue(':height', null, PDO::PARAM_NULL); + $query->bindValue(':filesize', null, PDO::PARAM_NULL); + $query->bindValue(':filename', null, PDO::PARAM_NULL); + $query->bindValue(':filehash', null, PDO::PARAM_NULL); } - function bumpThread($id) { - global $board; - - if(event('bump', $id)) - return true; - - $query = prepare(sprintf("UPDATE `posts_%s` SET `bump` = :time WHERE `id` = :id AND `thread` IS NULL", $board['uri'])); - $query->bindValue(':time', time(), PDO::PARAM_INT); - $query->bindValue(':id', $id, PDO::PARAM_INT); - $query->execute() or error(db_error($query)); + if(!$query->execute()) { + undoImage($post); + error(db_error($query)); } - // Remove file from post - function deleteFile($id, $remove_entirely_if_already=true) { - global $board, $config; + return $pdo->lastInsertId(); +} + +function bumpThread($id) { + global $board; + + if(event('bump', $id)) + return true; + + $query = prepare(sprintf("UPDATE `posts_%s` SET `bump` = :time WHERE `id` = :id AND `thread` IS NULL", $board['uri'])); + $query->bindValue(':time', time(), PDO::PARAM_INT); + $query->bindValue(':id', $id, PDO::PARAM_INT); + $query->execute() or error(db_error($query)); +} + +// Remove file from post +function deleteFile($id, $remove_entirely_if_already=true) { + global $board, $config; + + $query = prepare(sprintf("SELECT `thread`,`thumb`,`file` FROM `posts_%s` WHERE `id` = :id LIMIT 1", $board['uri'])); + $query->bindValue(':id', $id, PDO::PARAM_INT); + $query->execute() or error(db_error($query)); + + if($query->rowCount() < 1) { + error($config['error']['invalidpost']); + } + + $post = $query->fetch(); + + if($post['file'] == 'deleted' && !$post['thread']) + return; // Can't delete OP's image completely. + + $query = prepare(sprintf("UPDATE `posts_%s` SET `thumb` = NULL, `thumbwidth` = NULL, `thumbheight` = NULL, `filewidth` = NULL, `fileheight` = NULL, `filesize` = NULL, `filename` = NULL, `filehash` = NULL, `file` = :file WHERE `id` = :id", $board['uri'])); + if($post['file'] == 'deleted' && $remove_entirely_if_already) { + // Already deleted; remove file fully + $query->bindValue(':file', null, PDO::PARAM_NULL); + } else { + // Delete thumbnail + file_unlink($board['dir'] . $config['dir']['thumb'] . $post['thumb']); - $query = prepare(sprintf("SELECT `thread`,`thumb`,`file` FROM `posts_%s` WHERE `id` = :id LIMIT 1", $board['uri'])); - $query->bindValue(':id', $id, PDO::PARAM_INT); - $query->execute() or error(db_error($query)); + // Delete file + file_unlink($board['dir'] . $config['dir']['img'] . $post['file']); - if($query->rowCount() < 1) { + // Set file to 'deleted' + $query->bindValue(':file', 'deleted', PDO::PARAM_INT); + } + // Update database + + $query->bindValue(':id', $id, PDO::PARAM_INT); + $query->execute() or error(db_error($query)); + + if($post['thread']) + buildThread($post['thread']); +} + +// rebuild post (markup) +function rebuildPost($id) { + global $board; + + $query = prepare(sprintf("SELECT `body_nomarkup`, `thread` FROM `posts_%s` WHERE `id` = :id", $board['uri'])); + $query->bindValue(':id', $id, PDO::PARAM_INT); + $query->execute() or error(db_error($query)); + + if(!$post = $query->fetch()) + return false; + + if(!$post['body_nomarkup']) + return false; + + markup($body = &$post['body_nomarkup']); + + $query = prepare(sprintf("UPDATE `posts_%s` SET `body` = :body WHERE `id` = :id", $board['uri'])); + $query->bindValue(':body', $body); + $query->bindValue(':id', $id, PDO::PARAM_INT); + $query->execute() or error(db_error($query)); + + buildThread($post['thread'] ? $post['thread'] : $id); + + return true; +} + +// Delete a post (reply or thread) +function deletePost($id, $error_if_doesnt_exist=true, $rebuild_after=true) { + global $board, $config; + + // Select post and replies (if thread) in one query + $query = prepare(sprintf("SELECT `id`,`thread`,`thumb`,`file` FROM `posts_%s` WHERE `id` = :id OR `thread` = :id", $board['uri'])); + $query->bindValue(':id', $id, PDO::PARAM_INT); + $query->execute() or error(db_error($query)); + + if($query->rowCount() < 1) { + if($error_if_doesnt_exist) error($config['error']['invalidpost']); + else return false; + } + + $ids = array(); + + // Delete posts and maybe replies + while($post = $query->fetch()) { + if(!$post['thread']) { + // Delete thread HTML page + file_unlink($board['dir'] . $config['dir']['res'] . sprintf($config['file_page'], $post['id'])); + } elseif($query->rowCount() == 1) { + // Rebuild thread + $rebuild = &$post['thread']; } - - $post = $query->fetch(); - - if($post['file'] == 'deleted' && !$post['thread']) - return; // Can't delete OP's image completely. - - $query = prepare(sprintf("UPDATE `posts_%s` SET `thumb` = NULL, `thumbwidth` = NULL, `thumbheight` = NULL, `filewidth` = NULL, `fileheight` = NULL, `filesize` = NULL, `filename` = NULL, `filehash` = NULL, `file` = :file WHERE `id` = :id", $board['uri'])); - if($post['file'] == 'deleted' && $remove_entirely_if_already) { - // Already deleted; remove file fully - $query->bindValue(':file', null, PDO::PARAM_NULL); - } else { + if($post['thumb']) { // Delete thumbnail file_unlink($board['dir'] . $config['dir']['thumb'] . $post['thumb']); - + } + if($post['file']) { // Delete file file_unlink($board['dir'] . $config['dir']['img'] . $post['file']); - - // Set file to 'deleted' - $query->bindValue(':file', 'deleted', PDO::PARAM_INT); } - // Update database - $query->bindValue(':id', $id, PDO::PARAM_INT); - $query->execute() or error(db_error($query)); + $ids[] = (int)$post['id']; - if($post['thread']) - buildThread($post['thread']); } - // rebuild post (markup) - function rebuildPost($id) { - global $board; - - $query = prepare(sprintf("SELECT `body_nomarkup`, `thread` FROM `posts_%s` WHERE `id` = :id", $board['uri'])); - $query->bindValue(':id', $id, PDO::PARAM_INT); - $query->execute() or error(db_error($query)); - - if(!$post = $query->fetch()) - return false; - - if(!$post['body_nomarkup']) - return false; - - markup($body = &$post['body_nomarkup']); - - $query = prepare(sprintf("UPDATE `posts_%s` SET `body` = :body WHERE `id` = :id", $board['uri'])); - $query->bindValue(':body', $body); - $query->bindValue(':id', $id, PDO::PARAM_INT); - $query->execute() or error(db_error($query)); - - buildThread($post['thread'] ? $post['thread'] : $id); - - return true; - } + $query = prepare(sprintf("DELETE FROM `posts_%s` WHERE `id` = :id OR `thread` = :id", $board['uri'])); + $query->bindValue(':id', $id, PDO::PARAM_INT); + $query->execute() or error(db_error($query)); - // Delete a post (reply or thread) - function deletePost($id, $error_if_doesnt_exist=true, $rebuild_after=true) { - global $board, $config; - - // Select post and replies (if thread) in one query - $query = prepare(sprintf("SELECT `id`,`thread`,`thumb`,`file` FROM `posts_%s` WHERE `id` = :id OR `thread` = :id", $board['uri'])); - $query->bindValue(':id', $id, PDO::PARAM_INT); - $query->execute() or error(db_error($query)); - - if($query->rowCount() < 1) { - if($error_if_doesnt_exist) - error($config['error']['invalidpost']); - else return false; + $query = prepare("SELECT `board`, `post` FROM `cites` WHERE `target_board` = :board AND (`target` = " . implode(' OR `target` = ', $ids) . ")"); + $query->bindValue(':board', $board['uri']); + $query->execute() or error(db_error($query)); + while($cite = $query->fetch()) { + if($board['uri'] != $cite['board']) { + if(!isset($tmp_board)) + $tmp_board = $board['uri']; + openBoard($cite['board']); } - - $ids = array(); - - // Delete posts and maybe replies - while($post = $query->fetch()) { - if(!$post['thread']) { - // Delete thread HTML page - file_unlink($board['dir'] . $config['dir']['res'] . sprintf($config['file_page'], $post['id'])); - } elseif($query->rowCount() == 1) { - // Rebuild thread - $rebuild = &$post['thread']; - } - if($post['thumb']) { - // Delete thumbnail - file_unlink($board['dir'] . $config['dir']['thumb'] . $post['thumb']); - } - if($post['file']) { - // Delete file - file_unlink($board['dir'] . $config['dir']['img'] . $post['file']); + rebuildPost($cite['post']); + } + + if(isset($tmp_board)) + openBoard($tmp_board); + + $query = prepare("DELETE FROM `cites` WHERE (`target_board` = :board AND `target` = :id) OR (`board` = :board AND `post` = :id)"); + $query->bindValue(':board', $board['uri']); + $query->bindValue(':id', $id, PDO::PARAM_INT); + $query->execute() or error(db_error($query)); + + if(isset($rebuild) && $rebuild_after) { + buildThread($rebuild); + } + + return true; +} + +function clean() { + global $board, $config; + $offset = round($config['max_pages']*$config['threads_per_page']); + + // I too wish there was an easier way of doing this... + $query = prepare(sprintf("SELECT `id` FROM `posts_%s` WHERE `thread` IS NULL ORDER BY `sticky` DESC, `bump` DESC LIMIT :offset, 9001", $board['uri'])); + $query->bindValue(':offset', $offset, PDO::PARAM_INT); + + $query->execute() or error(db_error($query)); + while($post = $query->fetch()) { + deletePost($post['id']); + } +} + +function index($page, $mod=false) { + global $board, $config, $debug; + + $body = ''; + $offset = round($page*$config['threads_per_page']-$config['threads_per_page']); + + $query = prepare(sprintf("SELECT * FROM `posts_%s` WHERE `thread` IS NULL ORDER BY `sticky` DESC, `bump` DESC LIMIT :offset,:threads_per_page", $board['uri'])); + $query->bindValue(':offset', $offset, PDO::PARAM_INT); + $query->bindValue(':threads_per_page', $config['threads_per_page'], PDO::PARAM_INT); + $query->execute() or error(db_error($query)); + + if($query->rowcount() < 1 && $page > 1) + return false; + while($th = $query->fetch()) { + if(!$mod && $config['cache']['enabled']) { + if($built = cache::get("thread_index_{$board['uri']}_{$th['id']}")) { + $body .= $built; + continue; } - - $ids[] = (int)$post['id']; - } - $query = prepare(sprintf("DELETE FROM `posts_%s` WHERE `id` = :id OR `thread` = :id", $board['uri'])); - $query->bindValue(':id', $id, PDO::PARAM_INT); - $query->execute() or error(db_error($query)); + $thread = new Thread( + $th['id'], $th['subject'], $th['email'], $th['name'], $th['trip'], $th['capcode'], $th['body'], $th['time'], $th['thumb'], + $th['thumbwidth'], $th['thumbheight'], $th['file'], $th['filewidth'], $th['fileheight'], $th['filesize'], $th['filename'], $th['ip'], + $th['sticky'], $th['locked'], $th['sage'], $th['embed'], $mod ? '?/' : $config['root'], $mod + ); - $query = prepare("SELECT `board`, `post` FROM `cites` WHERE `target_board` = :board AND (`target` = " . implode(' OR `target` = ', $ids) . ")"); - $query->bindValue(':board', $board['uri']); - $query->execute() or error(db_error($query)); - while($cite = $query->fetch()) { - if($board['uri'] != $cite['board']) { - if(!isset($tmp_board)) - $tmp_board = $board['uri']; - openBoard($cite['board']); - } - rebuildPost($cite['post']); - } + $posts = prepare(sprintf("SELECT * FROM `posts_%s` WHERE `thread` = :id ORDER BY `id` DESC LIMIT :limit", $board['uri'])); + $posts->bindValue(':id', $th['id']); + $posts->bindValue(':limit', ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview']), PDO::PARAM_INT); + $posts->execute() or error(db_error($posts)); - if(isset($tmp_board)) - openBoard($tmp_board); - - $query = prepare("DELETE FROM `cites` WHERE (`target_board` = :board AND `target` = :id) OR (`board` = :board AND `post` = :id)"); - $query->bindValue(':board', $board['uri']); - $query->bindValue(':id', $id, PDO::PARAM_INT); - $query->execute() or error(db_error($query)); - - if(isset($rebuild) && $rebuild_after) { - buildThread($rebuild); + $num_images = 0; + while($po = $posts->fetch()) { + if($po['file']) + $num_images++; + + $thread->add(new Post( + $po['id'], $th['id'], $po['subject'], $po['email'], $po['name'], $po['trip'], $po['capcode'], $po['body'], $po['time'], + $po['thumb'], $po['thumbwidth'], $po['thumbheight'], $po['file'], $po['filewidth'], $po['fileheight'], $po['filesize'], + $po['filename'], $po['ip'], $po['embed'], $mod ? '?/' : $config['root'], $mod) + ); } - return true; - } - - function clean() { - global $board, $config; - $offset = round($config['max_pages']*$config['threads_per_page']); + if($posts->rowCount() == ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview'])) { + $count = prepare(sprintf("SELECT COUNT(`id`) as `num` FROM `posts_%s` WHERE `thread` = :thread UNION ALL SELECT COUNT(`id`) FROM `posts_%s` WHERE `file` IS NOT NULL AND `thread` = :thread", $board['uri'], $board['uri'])); + $count->bindValue(':thread', $th['id'], PDO::PARAM_INT); + $count->execute() or error(db_error($count)); + + $c = $count->fetch(); + $thread->omitted = $c['num'] - ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview']); + + $c = $count->fetch(); + $thread->omitted_images = $c['num'] - $num_images; + } - // I too wish there was an easier way of doing this... - $query = prepare(sprintf("SELECT `id` FROM `posts_%s` WHERE `thread` IS NULL ORDER BY `sticky` DESC, `bump` DESC LIMIT :offset, 9001", $board['uri'])); - $query->bindValue(':offset', $offset, PDO::PARAM_INT); + $thread->posts = array_reverse($thread->posts); - $query->execute() or error(db_error($query)); - while($post = $query->fetch()) { - deletePost($post['id']); - } + $body .= $thread->build(true); } - function index($page, $mod=false) { - global $board, $config, $debug; + return array( + 'board'=>$board, + 'body'=>$body, + 'post_url' => $config['post_url'], + 'config' => $config, + 'boardlist' => createBoardlist($mod) + ); +} - $body = ''; - $offset = round($page*$config['threads_per_page']-$config['threads_per_page']); - - $query = prepare(sprintf("SELECT * FROM `posts_%s` WHERE `thread` IS NULL ORDER BY `sticky` DESC, `bump` DESC LIMIT :offset,:threads_per_page", $board['uri'])); - $query->bindValue(':offset', $offset, PDO::PARAM_INT); - $query->bindValue(':threads_per_page', $config['threads_per_page'], PDO::PARAM_INT); - $query->execute() or error(db_error($query)); - - if($query->rowcount() < 1 && $page > 1) return false; - while($th = $query->fetch()) { - if(!$mod && $config['cache']['enabled']) { - if($built = cache::get("thread_index_{$board['uri']}_{$th['id']}")) { - $body .= $built; - continue; - } - } - - $thread = new Thread($th['id'], $th['subject'], $th['email'], $th['name'], $th['trip'], $th['capcode'], $th['body'], $th['time'], $th['thumb'], $th['thumbwidth'], $th['thumbheight'], $th['file'], $th['filewidth'], $th['fileheight'], $th['filesize'], $th['filename'], $th['ip'], $th['sticky'], $th['locked'], $th['sage'], $th['embed'], $mod ? '?/' : $config['root'], $mod); - - $posts = prepare(sprintf("SELECT * FROM `posts_%s` WHERE `thread` = :id ORDER BY `id` DESC LIMIT :limit", $board['uri'])); - $posts->bindValue(':id', $th['id']); - $posts->bindValue(':limit', ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview']), PDO::PARAM_INT); - $posts->execute() or error(db_error($posts)); - - $num_images = 0; - while($po = $posts->fetch()) { - if($po['file']) - $num_images++; +function getPageButtons($pages, $mod=false) { + global $config, $board; + + $btn = array(); + $root = ($mod ? '?/' : $config['root']) . $board['dir']; + + foreach($pages as $num => $page) { + if(isset($page['selected'])) { + // Previous button + if($num == 0) { + // There is no previous page. + $btn['prev'] = _('Previous'); + } else { + $loc = ($mod ? '?/' . $board['uri'] . '/' : '') . + ($num == 1 ? + $config['file_index'] + : + sprintf($config['file_page'], $num) + ); - $thread->add(new Post($po['id'], $th['id'], $po['subject'], $po['email'], $po['name'], $po['trip'], $po['capcode'], $po['body'], $po['time'], $po['thumb'], $po['thumbwidth'], $po['thumbheight'], $po['file'], $po['filewidth'], $po['fileheight'], $po['filesize'], $po['filename'], $po['ip'], $po['embed'], $mod ? '?/' : $config['root'], $mod)); + $btn['prev'] = '<form action="' . ($mod ? '' : $root . $loc) . '" method="get">' . + ($mod ? + '<input type="hidden" name="status" value="301" />' . + '<input type="hidden" name="r" value="' . htmlentities($loc) . '" />' + :'') . + '<input type="submit" value="' . _('Previous') . '" /></form>'; } - if($posts->rowCount() == ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview'])) { - $count = prepare(sprintf("SELECT COUNT(`id`) as `num` FROM `posts_%s` WHERE `thread` = :thread UNION ALL SELECT COUNT(`id`) FROM `posts_%s` WHERE `file` IS NOT NULL AND `thread` = :thread", $board['uri'], $board['uri'])); - $count->bindValue(':thread', $th['id'], PDO::PARAM_INT); - $count->execute() or error(db_error($count)); - - $c = $count->fetch(); - $thread->omitted = $c['num'] - ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview']); + if($num == count($pages) - 1) { + // There is no next page. + $btn['next'] = _('Next'); + } else { + $loc = ($mod ? '?/' . $board['uri'] . '/' : '') . sprintf($config['file_page'], $num + 2); - $c = $count->fetch(); - $thread->omitted_images = $c['num'] - $num_images; + $btn['next'] = '<form action="' . ($mod ? '' : $root . $loc) . '" method="get">' . + ($mod ? + '<input type="hidden" name="status" value="301" />' . + '<input type="hidden" name="r" value="' . htmlentities($loc) . '" />' + :'') . + '<input type="submit" value="' . _('Next') . '" /></form>'; } - - $thread->posts = array_reverse($thread->posts); - - $body .= $thread->build(true); } - - return Array( - 'board'=>$board, - 'body'=>$body, - 'post_url' => $config['post_url'], - 'config' => $config, - 'boardlist' => createBoardlist($mod) - ); } - function getPageButtons($pages, $mod=false) { - global $config, $board; - - $btn = Array(); - $root = ($mod ? '?/' : $config['root']) . $board['dir']; - - foreach($pages as $num => $page) { - if(isset($page['selected'])) { - // Previous button - if($num == 0) { - // There is no previous page. - $btn['prev'] = _('Previous'); - } else { - $loc = ($mod ? '?/' . $board['uri'] . '/' : '') . - ($num == 1 ? - $config['file_index'] - : - sprintf($config['file_page'], $num) - ); - - $btn['prev'] = '<form action="' . ($mod ? '' : $root . $loc) . '" method="get">' . - ($mod ? - '<input type="hidden" name="status" value="301" />' . - '<input type="hidden" name="r" value="' . htmlentities($loc) . '" />' - :'') . - '<input type="submit" value="' . _('Previous') . '" /></form>'; - } - - if($num == count($pages) - 1) { - // There is no next page. - $btn['next'] = _('Next'); - } else { - $loc = ($mod ? '?/' . $board['uri'] . '/' : '') . sprintf($config['file_page'], $num + 2); - - $btn['next'] = '<form action="' . ($mod ? '' : $root . $loc) . '" method="get">' . - ($mod ? - '<input type="hidden" name="status" value="301" />' . - '<input type="hidden" name="r" value="' . htmlentities($loc) . '" />' - :'') . - '<input type="submit" value="' . _('Next') . '" /></form>'; - } - } - } - - return $btn; - } + return $btn; +} + +function getPages($mod=false) { + global $board, $config; - function getPages($mod=false) { - global $board, $config; - - // Count threads - $query = query(sprintf("SELECT COUNT(`id`) as `num` FROM `posts_%s` WHERE `thread` IS NULL", $board['uri'])) or error(db_error()); - - $count = current($query->fetch()); - $count = floor(($config['threads_per_page'] + $count - 1) / $config['threads_per_page']); - - if($count < 1) $count = 1; - - $pages = Array(); - for($x=0;$x<$count && $x<$config['max_pages'];$x++) { - $pages[] = Array( - 'num' => $x+1, - 'link' => $x==0 ? ($mod ? '?/' : $config['root']) . $board['dir'] . $config['file_index'] : ($mod ? '?/' : $config['root']) . $board['dir'] . sprintf($config['file_page'], $x+1) - ); - } - - return $pages; - } + // Count threads + $query = query(sprintf("SELECT COUNT(`id`) as `num` FROM `posts_%s` WHERE `thread` IS NULL", $board['uri'])) or error(db_error()); - function makerobot($body) { - global $config; - $body = strtolower($body); - - // Leave only letters - $body = preg_replace('/[^a-z]/i', '', $body); - // Remove repeating characters - if($config['robot_strip_repeating']) - $body = preg_replace('/(.)\\1+/', '$1', $body); - - return sha1($body); + $count = current($query->fetch()); + $count = floor(($config['threads_per_page'] + $count - 1) / $config['threads_per_page']); + + if($count < 1) $count = 1; + + $pages = array(); + for($x=0;$x<$count && $x<$config['max_pages'];$x++) { + $pages[] = array( + 'num' => $x+1, + 'link' => $x==0 ? ($mod ? '?/' : $config['root']) . $board['dir'] . $config['file_index'] : ($mod ? '?/' : $config['root']) . $board['dir'] . sprintf($config['file_page'], $x+1) + ); } - function checkRobot($body) { - if(empty($body)) - return true; - - if(event('check-robot', $body)) - return true; + return $pages; +} + +function makerobot($body) { + global $config; + $body = strtolower($body); + + // Leave only letters + $body = preg_replace('/[^a-z]/i', '', $body); + // Remove repeating characters + if($config['robot_strip_repeating']) + $body = preg_replace('/(.)\\1+/', '$1', $body); + + return sha1($body); +} + +function checkRobot($body) { + if(empty($body)) + return true; + + if(event('check-robot', $body)) + return true; + + $body = makerobot($body); + $query = prepare("SELECT 1 FROM `robot` WHERE `hash` = :hash LIMIT 1"); + $query->bindValue(':hash', $body); + $query->execute() or error(db_error($query)); + + if($query->fetch()) { + return true; + } else { + // Insert new hash - $body = makerobot($body); - $query = prepare("SELECT 1 FROM `robot` WHERE `hash` = :hash LIMIT 1"); + $query = prepare("INSERT INTO `robot` VALUES (:hash)"); $query->bindValue(':hash', $body); $query->execute() or error(db_error($query)); - - if($query->fetch()) { - return true; - } else { - // Insert new hash - - $query = prepare("INSERT INTO `robot` VALUES (:hash)"); - $query->bindValue(':hash', $body); - $query->execute() or error(db_error($query)); - return false; - } + return false; } +} + +function numPosts($id) { + global $board; + $query = prepare(sprintf("SELECT COUNT(*) as `count` FROM `posts_%s` WHERE `thread` = :thread", $board['uri'])); + $query->bindValue(':thread', $id, PDO::PARAM_INT); + $query->execute() or error(db_error($query)); - function numPosts($id) { - global $board; - $query = prepare(sprintf("SELECT COUNT(*) as `count` FROM `posts_%s` WHERE `thread` = :thread", $board['uri'])); - $query->bindValue(':thread', $id, PDO::PARAM_INT); - $query->execute() or error(db_error($query)); - - $result = $query->fetch(); - return $result['count']; - } + $result = $query->fetch(); + return $result['count']; +} + +function muteTime() { + global $config; - function muteTime() { - global $config; - - if($time = event('mute-time')) - return $time; - - // Find number of mutes in the past X hours - $query = prepare("SELECT COUNT(*) as `count` FROM `mutes` WHERE `time` >= :time AND `ip` = :ip"); - $query->bindValue(':time', time()-($config['robot_mute_hour']*3600), PDO::PARAM_INT); - $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); - $query->execute() or error(db_error($query)); - - $result = $query->fetch(); - if($result['count'] == 0) return 0; - return pow($config['robot_mute_multiplier'], $result['count']); + if($time = event('mute-time')) + return $time; + + // Find number of mutes in the past X hours + $query = prepare("SELECT COUNT(*) as `count` FROM `mutes` WHERE `time` >= :time AND `ip` = :ip"); + $query->bindValue(':time', time()-($config['robot_mute_hour']*3600), PDO::PARAM_INT); + $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); + $query->execute() or error(db_error($query)); + + $result = $query->fetch(); + if($result['count'] == 0) return 0; + return pow($config['robot_mute_multiplier'], $result['count']); +} + +function mute() { + // Insert mute + $query = prepare("INSERT INTO `mutes` VALUES (:ip, :time)"); + $query->bindValue(':time', time(), PDO::PARAM_INT); + $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); + $query->execute() or error(db_error($query)); + + return muteTime(); +} + +function checkMute() { + global $config, $debug; + + if($config['cache']['enabled']) { + // Cached mute? + if(($mute = cache::get("mute_${_SERVER['REMOTE_ADDR']}")) && ($mutetime = cache::get("mutetime_${_SERVER['REMOTE_ADDR']}"))) { + error(sprintf($config['error']['youaremuted'], $mute['time'] + $mutetime - time())); + } } - function mute() { - // Insert mute - $query = prepare("INSERT INTO `mutes` VALUES (:ip, :time)"); - $query->bindValue(':time', time(), PDO::PARAM_INT); + $mutetime = muteTime(); + if($mutetime > 0) { + // Find last mute time + $query = prepare("SELECT `time` FROM `mutes` WHERE `ip` = :ip ORDER BY `time` DESC LIMIT 1"); $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); $query->execute() or error(db_error($query)); - return muteTime(); - } - - function checkMute() { - global $config, $debug; - - if($config['cache']['enabled']) { - // Cached mute? - if(($mute = cache::get("mute_${_SERVER['REMOTE_ADDR']}")) && ($mutetime = cache::get("mutetime_${_SERVER['REMOTE_ADDR']}"))) { - error(sprintf($config['error']['youaremuted'], $mute['time'] + $mutetime - time())); - } + if(!$mute = $query->fetch()) { + // What!? He's muted but he's not muted... + return; } - $mutetime = muteTime(); - if($mutetime > 0) { - // Find last mute time - $query = prepare("SELECT `time` FROM `mutes` WHERE `ip` = :ip ORDER BY `time` DESC LIMIT 1"); - $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); - $query->execute() or error(db_error($query)); - - if(!$mute = $query->fetch()) { - // What!? He's muted but he's not muted... - return; - } - - if($mute['time'] + $mutetime > time()) { - if($config['cache']['enabled']) { - cache::set("mute_${_SERVER['REMOTE_ADDR']}", $mute, $mute['time'] + $mutetime - time()); - cache::set("mutetime_${_SERVER['REMOTE_ADDR']}", $mutetime, $mute['time'] + $mutetime - time()); - } - // Not expired yet - error(sprintf($config['error']['youaremuted'], $mute['time'] + $mutetime - time())); - } else { - // Already expired - return; + if($mute['time'] + $mutetime > time()) { + if($config['cache']['enabled']) { + cache::set("mute_${_SERVER['REMOTE_ADDR']}", $mute, $mute['time'] + $mutetime - time()); + cache::set("mutetime_${_SERVER['REMOTE_ADDR']}", $mutetime, $mute['time'] + $mutetime - time()); } + // Not expired yet + error(sprintf($config['error']['youaremuted'], $mute['time'] + $mutetime - time())); + } else { + // Already expired + return; } } +} + +function createHiddenInputs($extra_salt = array()) { + global $config; - function createHiddenInputs($extra_salt = Array()) { - global $config; - - if(!empty($extra_salt)) { - // create a salted hash of the "extra salt" - $extra_salt = implode(':', $extra_salt); - } else { - $extra_salt = ''; - } - - $inputs = Array(); - - shuffle($config['spam']['hidden_input_names']); - $hidden_input_names_x = 0; - - $input_count = rand($config['spam']['hidden_inputs_min'], $config['spam']['hidden_inputs_max']); - for($x=0;$x<$input_count;$x++) { - if(rand(0, 2) == 0 || $hidden_input_names_x < 0) { - // Use an obscure name - $name = strtolower(substr(base64_encode(sha1(rand(), true)), 0, rand(2, 20))); - - } else { - // Use a pre-defined confusing name - $name = $config['spam']['hidden_input_names'][$hidden_input_names_x++]; - if($hidden_input_names_x >= count($config['spam']['hidden_input_names'])) - $hidden_input_names_x = -1; - } - - if(rand(0, 2) == 0) { - // Value must be null - $inputs[$name] = ''; - } elseif(rand(0, 4) == 0) { - // Numeric value - $inputs[$name] = rand(0, 100); - } else { - // Obscure value - $inputs[$name] = substr(base64_encode(sha1(rand(), true) . sha1(rand(), true)), 0, rand(2, 54)); - } - } - - $content = ''; - foreach($inputs as $name => $value) { - $display_type = rand(0, 8); + if(!empty($extra_salt)) { + // create a salted hash of the "extra salt" + $extra_salt = implode(':', $extra_salt); + } else { + $extra_salt = ''; + } + + $inputs = array(); + + shuffle($config['spam']['hidden_input_names']); + $hidden_input_names_x = 0; + + $input_count = rand($config['spam']['hidden_inputs_min'], $config['spam']['hidden_inputs_max']); + for($x=0;$x<$input_count;$x++) { + if(rand(0, 2) == 0 || $hidden_input_names_x < 0) { + // Use an obscure name + $name = strtolower(substr(base64_encode(sha1(rand(), true)), 0, rand(2, 20))); - switch($display_type) { - case 0: - $content .= '<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />'; - break; - case 1: - $content .= '<input style="display:none" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />'; - break; - case 2: - $content .= '<input type="hidden" value="' . htmlspecialchars($value) . '" name="' . htmlspecialchars($name) . '" />'; - break; - case 3: - $content .= '<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />'; - break; - case 4: - $content .= '<span style="display:none"><input type="text" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" /></span>'; - break; - case 5: - $content .= '<div style="display:none"><input type="text" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" /></div>'; - break; - case 6: - if(!empty($value)) - $content .= '<textarea style="display:none" name="' . htmlspecialchars($name) . '">' . htmlspecialchars($value) . '</textarea>'; - else - $content .= '<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />'; - break; - case 7: - if(!empty($value)) - $content .= '<textarea name="' . htmlspecialchars($name) . '" style="display:none">' . htmlspecialchars($value) . '</textarea>'; - else - $content .= '<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />'; - break; - case 8: - $content .= '<div style="display:none"><textarea name="' . htmlspecialchars($name) . '" style="display:none">' . htmlspecialchars($value) . '</textarea></div>'; - break; - } + } else { + // Use a pre-defined confusing name + $name = $config['spam']['hidden_input_names'][$hidden_input_names_x++]; + if($hidden_input_names_x >= count($config['spam']['hidden_input_names'])) + $hidden_input_names_x = -1; } - // Create a hash to validate it after - // This is the tricky part. - - // First, sort the keys in alphabetical order (A-Z) - ksort($inputs); - - $hash = ''; - - // Iterate through each input - foreach($inputs as $name => $value) { - $hash .= $name . '=' . $value; + if(rand(0, 2) == 0) { + // Value must be null + $inputs[$name] = ''; + } elseif(rand(0, 4) == 0) { + // Numeric value + $inputs[$name] = rand(0, 100); + } else { + // Obscure value + $inputs[$name] = substr(base64_encode(sha1(rand(), true) . sha1(rand(), true)), 0, rand(2, 54)); } - - // Add a salt to the hash - $hash .= $config['cookies']['salt']; - - // Use SHA1 for the hash - $hash = sha1($hash . $extra_salt); - - // Append it to the HTML - $content .= '<input type="hidden" name="hash" value="' . $hash . '" />'; - - return $content; } - function checkSpam($extra_salt = Array()) { - global $config; + $content = ''; + foreach($inputs as $name => $value) { + $display_type = rand(0, 8); - if(!isset($_POST['hash'])) - return true; - - $hash = $_POST['hash']; - - if(!empty($extra_salt)) { - // create a salted hash of the "extra salt" - $extra_salt = implode(':', $extra_salt); - } else { - $extra_salt = ''; - } - - // Reconsturct the $inputs array - $inputs = Array(); - - foreach($_POST as $name => $value) { - if(in_array($name, $config['spam']['valid_inputs'])) - continue; - - $inputs[$name] = $value; + switch($display_type) { + case 0: + $content .= '<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . + htmlspecialchars($value) . '" />'; + break; + case 1: + $content .= '<input style="display:none" name="' . htmlspecialchars($name) . '" value="' . + htmlspecialchars($value) . '" />'; + break; + case 2: + $content .= '<input type="hidden" value="' . htmlspecialchars($value) . '" name="' . + htmlspecialchars($name) . '" />'; + break; + case 3: + $content .= '<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . + htmlspecialchars($value) . '" />'; + break; + case 4: + $content .= '<span style="display:none"><input type="text" name="' . htmlspecialchars($name) . '" value="' . + htmlspecialchars($value) .'" /></span>'; + break; + case 5: + $content .= '<div style="display:none"><input type="text" name="' . htmlspecialchars($name) . '" value="' . + htmlspecialchars($value) . '" /></div>'; + break; + case 6: + if(!empty($value)) + $content .= '<textarea style="display:none" name="' . htmlspecialchars($name) . '">' . + htmlspecialchars($value) . '</textarea>'; + else + $content .= '<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . + htmlspecialchars($value) . '" />'; + break; + case 7: + if(!empty($value)) + $content .= '<textarea name="' . htmlspecialchars($name) . '" style="display:none">' . + htmlspecialchars($value) . '</textarea>'; + else + $content .= '<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . + htmlspecialchars($value) . '" />'; + break; + case 8: + $content .= '<div style="display:none"><textarea name="' . htmlspecialchars($name) . '" style="display:none">' . + htmlspecialchars($value) . '</textarea></div>'; + break; } + } + + // Create a hash to validate it after + // This is the tricky part. + + // First, sort the keys in alphabetical order (A-Z) + ksort($inputs); + + $hash = ''; + + // Iterate through each input + foreach($inputs as $name => $value) { + $hash .= $name . '=' . $value; + } + + // Add a salt to the hash + $hash .= $config['cookies']['salt']; + + // Use SHA1 for the hash + $hash = sha1($hash . $extra_salt); + + // Append it to the HTML + $content .= '<input type="hidden" name="hash" value="' . $hash . '" />'; + + return $content; +} + +function checkSpam($extra_salt = array()) { + global $config; + + if(!isset($_POST['hash'])) + return true; + + $hash = $_POST['hash']; + + if(!empty($extra_salt)) { + // create a salted hash of the "extra salt" + $extra_salt = implode(':', $extra_salt); + } else { + $extra_salt = ''; + } + + // Reconsturct the $inputs array + $inputs = array(); + + foreach($_POST as $name => $value) { + if(in_array($name, $config['spam']['valid_inputs'])) + continue; - // Sort the inputs in alphabetical order (A-Z) - ksort($inputs); + $inputs[$name] = $value; + } + + // Sort the inputs in alphabetical order (A-Z) + ksort($inputs); + + $_hash = ''; + + // Iterate through each input + foreach($inputs as $name => $value) { + $_hash .= $name . '=' . $value; + } + + // Add a salt to the hash + $_hash .= $config['cookies']['salt']; + + // Use SHA1 for the hash + $_hash = sha1($_hash . $extra_salt); + + return $hash != $_hash; +} + +function buildIndex() { + global $board, $config; + + $pages = getPages(); + + $page = 1; + while($page <= $config['max_pages'] && $content = index($page)) { + $filename = $board['dir'] . ($page==1 ? $config['file_index'] : sprintf($config['file_page'], $page)); + if(file_exists($filename)) $md5 = md5_file($filename); - $_hash = ''; + $content['pages'] = $pages; + $content['pages'][$page-1]['selected'] = true; + $content['btn'] = getPageButtons($content['pages']); + file_write($filename, Element('index.html', $content)); - // Iterate through each input - foreach($inputs as $name => $value) { - $_hash .= $name . '=' . $value; + if(isset($md5) && $md5 == md5_file($filename)) { + break; } - - // Add a salt to the hash - $_hash .= $config['cookies']['salt']; - - // Use SHA1 for the hash - $_hash = sha1($_hash . $extra_salt); - - return $hash != $_hash; + $page++; } - - function buildIndex() { - global $board, $config; - - $pages = getPages(); - - $page = 1; - while($page <= $config['max_pages'] && $content = index($page)) { + if($page < $config['max_pages']) { + for(;$page<=$config['max_pages'];$page++) { $filename = $board['dir'] . ($page==1 ? $config['file_index'] : sprintf($config['file_page'], $page)); - if(file_exists($filename)) $md5 = md5_file($filename); - - $content['pages'] = $pages; - $content['pages'][$page-1]['selected'] = true; - $content['btn'] = getPageButtons($content['pages']); - file_write($filename, Element('index.html', $content)); - - if(isset($md5) && $md5 == md5_file($filename)) { - break; - } - $page++; - } - if($page < $config['max_pages']) { - for(;$page<=$config['max_pages'];$page++) { - $filename = $board['dir'] . ($page==1 ? $config['file_index'] : sprintf($config['file_page'], $page)); - file_unlink($filename); - } + file_unlink($filename); } } +} + +function buildJavascript() { + global $config; - function buildJavascript() { - global $config; - - $stylesheets = Array(); - foreach($config['stylesheets'] as $name => $uri) { - $stylesheets[] = Array( - 'name' => addslashes($name), - 'uri' => addslashes((!empty($uri) ? $config['uri_stylesheets'] : '') . $uri)); - } - - $script = Element('main.js', Array( - 'config' => $config, - 'stylesheets' => $stylesheets - )); - if($config['additional_javascript_compile']) { - foreach($config['additional_javascript'] as $file) { - $script .= file_get_contents($file); - } - } - - if($config['minify_js']) { - require_once 'inc/lib/minify/JSMin.php'; - $script = JSMin::minify($script); + $stylesheets = array(); + foreach($config['stylesheets'] as $name => $uri) { + $stylesheets[] = array( + 'name' => addslashes($name), + 'uri' => addslashes((!empty($uri) ? $config['uri_stylesheets'] : '') . $uri)); + } + + $script = Element('main.js', array( + 'config' => $config, + 'stylesheets' => $stylesheets + )); + if($config['additional_javascript_compile']) { + foreach($config['additional_javascript'] as $file) { + $script .= file_get_contents($file); } - - file_write($config['file_script'], $script); } - function checkDNSBL() { - global $config; - - - if(isIPv6()) - return; // No IPv6 support yet. + if($config['minify_js']) { + require_once 'inc/lib/minify/JSMin.php'; + $script = JSMin::minify($script); + } + + file_write($config['file_script'], $script); +} + +function checkDNSBL() { + global $config; + + + if(isIPv6()) + return; // No IPv6 support yet. + + if(!isset($_SERVER['REMOTE_ADDR'])) + return; // Fix your web server configuration + + if(in_array($_SERVER['REMOTE_ADDR'], $config['dnsbl_exceptions'])) + return; + + $ip = ReverseIPOctets($_SERVER['REMOTE_ADDR']); + + foreach($config['dnsbl'] as $blacklist) { + if(!is_array($blacklist) == 1) + $blacklist = array($blacklist); - if(!isset($_SERVER['REMOTE_ADDR'])) - return; // Fix your web server configuration + if(($lookup = str_replace('%', $ip, $blacklist[0])) == $blacklist[0]) + $lookup = $ip . '.' . $blacklist[0]; - if(in_array($_SERVER['REMOTE_ADDR'], $config['dnsbl_exceptions'])) - return; + if(!$ip = DNS($lookup)) + continue; // not in list - $ip = ReverseIPOctets($_SERVER['REMOTE_ADDR']); + $blacklist_name = isset($blacklist[2]) ? $blacklist[2] : $blacklist[0]; - foreach($config['dnsbl'] as $blacklist) { - if(!is_array($blacklist) == 1) - $blacklist = Array($blacklist); - - if(($lookup = str_replace('%', $ip, $blacklist[0])) == $blacklist[0]) - $lookup = $ip . '.' . $blacklist[0]; - - if(!$ip = DNS($lookup)) - continue; // not in list - - $blacklist_name = isset($blacklist[2]) ? $blacklist[2] : $blacklist[0]; - - if(!isset($blacklist[1])) { - // If you're listed at all, you're blocked. - error(sprintf($config['error']['dnsbl'], $blacklist_name)); - } elseif(is_array($blacklist[1])) { - foreach($blacklist[1] as $octet) { - if($ip == $octet || $ip == '127.0.0.' . $octet) - error(sprintf($config['error']['dnsbl'], $blacklist_name)); - } - } elseif(is_callable($blacklist[1])) { - if($blacklist[1]($ip)) - error(sprintf($config['error']['dnsbl'], $blacklist_name)); - } else { - if($ip == $blacklist[1] || $ip == '127.0.0.' . $blacklist[1]) + if(!isset($blacklist[1])) { + // If you're listed at all, you're blocked. + error(sprintf($config['error']['dnsbl'], $blacklist_name)); + } elseif(is_array($blacklist[1])) { + foreach($blacklist[1] as $octet) { + if($ip == $octet || $ip == '127.0.0.' . $octet) error(sprintf($config['error']['dnsbl'], $blacklist_name)); } + } elseif(is_callable($blacklist[1])) { + if($blacklist[1]($ip)) + error(sprintf($config['error']['dnsbl'], $blacklist_name)); + } else { + if($ip == $blacklist[1] || $ip == '127.0.0.' . $blacklist[1]) + error(sprintf($config['error']['dnsbl'], $blacklist_name)); } } +} + +function isIPv6() { + return strstr($_SERVER['REMOTE_ADDR'], ':') !== false; +} + +function ReverseIPOctets($ip) { + return implode('.', array_reverse(explode('.', $ip))); +} + +function wordfilters(&$body) { + global $config; - function isIPv6() { - return strstr($_SERVER['REMOTE_ADDR'], ':') !== false; + foreach($config['wordfilters'] as $filter) { + if(isset($filter[2]) && $filter[2]) { + $body = preg_replace($filter[0], $filter[1], $body); + } else { + $body = str_ireplace($filter[0], $filter[1], $body); + } } +} + +function quote($body, $quote=true) { + global $config; - function ReverseIPOctets($ip) { - $ipoc = explode('.', $ip); - return $ipoc[3] . '.' . $ipoc[2] . '.' . $ipoc[1] . '.' . $ipoc[0]; - } + $body = str_replace('<br/>', "\n", $body); - function wordfilters(&$body) { - global $config; - - foreach($config['wordfilters'] as $filter) { - if(isset($filter[2]) && $filter[2]) { - $body = preg_replace($filter[0], $filter[1], $body); - } else { - $body = str_ireplace($filter[0], $filter[1], $body); - } + $body = strip_tags($body); + + $body = preg_replace("/(^|\n)/", '$1>', $body); + + $body .= "\n"; + + if($config['minify_html']) + $body = str_replace("\n", '
', $body); + + return $body; +} + +function markup_url($matches) { + global $markup_urls; + + $url = $matches[1]; + $after = $matches[2]; + + $markup_urls[] = $url; + + return '<a target="_blank" rel="nofollow" href="' . $url . '">' . $url . '</a>' . $after; +} + +function unicodify($body) { + $body = str_replace('...', '…', $body); + $body = str_replace('<--', '←', $body); + $body = str_replace('-->', '→', $body); + + // En and em- dashes are rendered exactly the same in + // most monospace fonts (they look the same in code + // editors). + $body = str_replace('---', '–', $body); // em dash + $body = str_replace('--', '—', $body); // en dash + + return $body; +} + +function markup(&$body, $track_cites = false) { + global $board, $config, $markup_urls; + + $body = str_replace("\r", '', $body); + $body = utf8tohtml($body); + + foreach($config['markup'] as $markup) { + if(is_string($markup[1])) { + $body = preg_replace($markup[0], $markup[1], $body); + } elseif(is_callable($markup[1])) { + $body = preg_replace_callback($markup[0], $markup[1], $body); } } - function quote($body, $quote=true) { - global $config; + if($config['markup_urls']) { + $markup_urls = array(); - $body = str_replace('<br/>', "\n", $body); + $body = preg_replace_callback( + '/((?:https?:\/\/|ftp:\/\/|irc:\/\/)[^\s<>()"]+?(?:\([^\s<>()"]*?\)[^\s<>()"]*?)*)((?:\s|<|>|"|\.||\]|!|\?|,|,|")*(?:[\s<>()"]|$))/', + 'markup_url', + $body, + -1, + $num_links); - $body = strip_tags($body); - - $body = preg_replace("/(^|\n)/", '$1>', $body); - - $body .= "\n"; - - if($config['minify_html']) - $body = str_replace("\n", '
', $body); - - return $body; + if($num_links > $config['max_links']) + error($config['error']['toomanylinks']); } - function markup_url($matches) { - global $markup_urls; - - $url = $matches[1]; - $after = $matches[2]; - - $markup_urls[] = $url; - - return '<a target="_blank" rel="nofollow" href="' . $url . '">' . $url . '</a>' . $after; - } + if($config['auto_unicode']) { + $body = unicodify($body); - function unicodify($body) { - $body = str_replace('...', '…', $body); - $body = str_replace('<--', '←', $body); - $body = str_replace('-->', '→', $body); - - // En and em- dashes are rendered exactly the same in - // most monospace fonts (they look the same in code - // editors). - $body = str_replace('---', '–', $body); // em dash - $body = str_replace('--', '—', $body); // en dash - - return $body; + foreach($markup_urls as &$url) { + $body = str_replace(unicodify($url), $url, $body); + } } - function markup(&$body, $track_cites = false) { - global $board, $config, $markup_urls; - - $body = str_replace("\r", '', $body); - $body = utf8tohtml($body); - - foreach($config['markup'] as $markup) { - if(is_string($markup[1])) { - $body = preg_replace($markup[0], $markup[1], $body); - } elseif(is_callable($markup[1])) { - $body = preg_replace_callback($markup[0], $markup[1], $body); - } - } - - if($config['markup_urls']) { - $markup_urls = Array(); - - $body = preg_replace_callback( - '/((?:https?:\/\/|ftp:\/\/|irc:\/\/)[^\s<>()"]+?(?:\([^\s<>()"]*?\)[^\s<>()"]*?)*)((?:\s|<|>|"|\.||\]|!|\?|,|,|")*(?:[\s<>()"]|$))/', - 'markup_url', - $body, - -1, - $num_links); - - if($num_links > $config['max_links']) - error($config['error']['toomanylinks']); - } - - if($config['auto_unicode']) { - $body = unicodify($body); - - foreach($markup_urls as &$url) { - $body = str_replace(unicodify($url), $url, $body); - } + // replace tabs with 8 spaces + $body = str_replace("\t", ' ', $body); + + $tracked_cites = array(); + + // Cites + if(isset($board) && preg_match_all('/(^|\s)>>(\d+?)([\s,.)?]|$)/m', $body, $cites)) { + if(count($cites[0]) > $config['max_cites']) { + error($config['error']['toomanycites']); } - // replace tabs with 8 spaces - $body = str_replace("\t", ' ', $body); - - $tracked_cites = Array(); - - // Cites - if(isset($board) && preg_match_all('/(^|\s)>>(\d+?)([\s,.)?]|$)/m', $body, $cites)) { - if(count($cites[0]) > $config['max_cites']) { - error($config['error']['toomanycites']); - } + for($index=0;$index<count($cites[0]);$index++) { + $cite = $cites[2][$index]; + $query = prepare(sprintf("SELECT `thread`,`id` FROM `posts_%s` WHERE `id` = :id LIMIT 1", $board['uri'])); + $query->bindValue(':id', $cite); + $query->execute() or error(db_error($query)); - for($index=0;$index<count($cites[0]);$index++) { - $cite = $cites[2][$index]; - $query = prepare(sprintf("SELECT `thread`,`id` FROM `posts_%s` WHERE `id` = :id LIMIT 1", $board['uri'])); - $query->bindValue(':id', $cite); - $query->execute() or error(db_error($query)); + if($post = $query->fetch()) { + $replacement = '<a onclick="highlightReply(\''.$cite.'\');" href="' . + $config['root'] . $board['dir'] . $config['dir']['res'] . ($post['thread']?$post['thread']:$post['id']) . '.html#' . $cite . '">' . + '>>' . $cite . + '</a>'; + $body = str_replace($cites[0][$index], $cites[1][$index] . $replacement . $cites[3][$index], $body); - if($post = $query->fetch()) { - $replacement = '<a onclick="highlightReply(\''.$cite.'\');" href="' . - $config['root'] . $board['dir'] . $config['dir']['res'] . ($post['thread']?$post['thread']:$post['id']) . '.html#' . $cite . '">' . - '>>' . $cite . - '</a>'; - $body = str_replace($cites[0][$index], $cites[1][$index] . $replacement . $cites[3][$index], $body); - - if($track_cites && $config['track_cites']) - $tracked_cites[] = Array($board['uri'], $post['id']); - } + if($track_cites && $config['track_cites']) + $tracked_cites[] = array($board['uri'], $post['id']); } } + } + + // Cross-board linking + if(preg_match_all('/(^|\s)>>>\/(\w+?)\/(\d+)?([\s,.)?]|$)/m', $body, $cites)) { + if(count($cites[0]) > $config['max_cites']) { + error($config['error']['toomanycross']); + } - // Cross-board linking - if(preg_match_all('/(^|\s)>>>\/(\w+?)\/(\d+)?([\s,.)?]|$)/m', $body, $cites)) { - if(count($cites[0]) > $config['max_cites']) { - error($config['error']['toomanycross']); - } + for($index=0;$index<count($cites[0]);$index++) { + $_board = $cites[2][$index]; + $cite = @$cites[3][$index]; - for($index=0;$index<count($cites[0]);$index++) { - $_board = $cites[2][$index]; - $cite = @$cites[3][$index]; - - // Temporarily store board information because it will be overwritten - $tmp_board = $board['uri']; - - // Check if the board exists, and load settings - if(openBoard($_board)) { - if($cite) { - $query = prepare(sprintf("SELECT `thread`,`id` FROM `posts_%s` WHERE `id` = :id LIMIT 1", $board['uri'])); - $query->bindValue(':id', $cite); - $query->execute() or error(db_error($query)); - - if($post = $query->fetch()) { - $replacement = '<a onclick="highlightReply(\''.$cite.'\');" href="' . - $config['root'] . $board['dir'] . $config['dir']['res'] . ($post['thread']?$post['thread']:$post['id']) . '.html#' . $cite . '">' . - '>>>/' . $_board . '/' . $cite . - '</a>'; - $body = str_replace($cites[0][$index], $cites[1][$index] . $replacement . $cites[4][$index], $body); - - if($track_cites && $config['track_cites']) - $tracked_cites[] = Array($board['uri'], $post['id']); - } - } else { - $replacement = '<a href="' . - $config['root'] . $board['dir'] . $config['file_index'] . '">' . - '>>>/' . $_board . '/' . + // Temporarily store board information because it will be overwritten + $tmp_board = $board['uri']; + + // Check if the board exists, and load settings + if(openBoard($_board)) { + if($cite) { + $query = prepare(sprintf("SELECT `thread`,`id` FROM `posts_%s` WHERE `id` = :id LIMIT 1", $board['uri'])); + $query->bindValue(':id', $cite); + $query->execute() or error(db_error($query)); + + if($post = $query->fetch()) { + $replacement = '<a onclick="highlightReply(\''.$cite.'\');" href="' . + $config['root'] . $board['dir'] . $config['dir']['res'] . ($post['thread']?$post['thread']:$post['id']) . '.html#' . $cite . '">' . + '>>>/' . $_board . '/' . $cite . '</a>'; $body = str_replace($cites[0][$index], $cites[1][$index] . $replacement . $cites[4][$index], $body); + + if($track_cites && $config['track_cites']) + $tracked_cites[] = array($board['uri'], $post['id']); } + } else { + $replacement = '<a href="' . + $config['root'] . $board['dir'] . $config['file_index'] . '">' . + '>>>/' . $_board . '/' . + '</a>'; + $body = str_replace($cites[0][$index], $cites[1][$index] . $replacement . $cites[4][$index], $body); } - - // Restore main board settings - openBoard($tmp_board); } + + // Restore main board settings + openBoard($tmp_board); } - - $body = preg_replace("/^\s*>.*$/m", '<span class="quote">$0</span>', $body); - - if($config['strip_superfluous_returns']) - $body = preg_replace('/\s+$/', '', $body); - - $body = preg_replace("/\n/", '<br/>', $body); - - return $tracked_cites; } + + $body = preg_replace("/^\s*>.*$/m", '<span class="quote">$0</span>', $body); + + if($config['strip_superfluous_returns']) + $body = preg_replace('/\s+$/', '', $body); + + $body = preg_replace("/\n/", '<br/>', $body); + + return $tracked_cites; +} - function utf8tohtml($utf8) { - return mb_encode_numericentity(htmlspecialchars($utf8, ENT_NOQUOTES, 'UTF-8'), Array(0x80, 0xffff, 0, 0xffff), 'UTF-8'); - } +function utf8tohtml($utf8) { + return mb_encode_numericentity(htmlspecialchars($utf8, ENT_NOQUOTES, 'UTF-8'), array(0x80, 0xffff, 0, 0xffff), 'UTF-8'); +} - function buildThread($id, $return=false, $mod=false) { - global $board, $config; - $id = round($id); - - if(event('build-thread', $id)) - return; - - if($config['cache']['enabled'] && !$mod) { - // Clear cache - cache::delete("thread_index_{$board['uri']}_{$id}"); - cache::delete("thread_{$board['uri']}_{$id}"); - } - - $query = prepare(sprintf("SELECT * FROM `posts_%s` WHERE (`thread` IS NULL AND `id` = :id) OR `thread` = :id ORDER BY `thread`,`id`", $board['uri'])); - $query->bindValue(':id', $id, PDO::PARAM_INT); - $query->execute() or error(db_error($query)); - - while($post = $query->fetch()) { - if(!isset($thread)) { - $thread = new Thread($post['id'], $post['subject'], $post['email'], $post['name'], $post['trip'], $post['capcode'], $post['body'], $post['time'], $post['thumb'], $post['thumbwidth'], $post['thumbheight'], $post['file'], $post['filewidth'], $post['fileheight'], $post['filesize'], $post['filename'], $post['ip'], $post['sticky'], $post['locked'], $post['sage'], $post['embed'], $mod ? '?/' : $config['root'], $mod); - } else { - $thread->add(new Post($post['id'], $thread->id, $post['subject'], $post['email'], $post['name'], $post['trip'], $post['capcode'], $post['body'], $post['time'], $post['thumb'], $post['thumbwidth'], $post['thumbheight'], $post['file'], $post['filewidth'], $post['fileheight'], $post['filesize'], $post['filename'], $post['ip'], $post['embed'], $mod ? '?/' : $config['root'], $mod)); - } +function buildThread($id, $return=false, $mod=false) { + global $board, $config; + $id = round($id); + + if(event('build-thread', $id)) + return; + + if($config['cache']['enabled'] && !$mod) { + // Clear cache + cache::delete("thread_index_{$board['uri']}_{$id}"); + cache::delete("thread_{$board['uri']}_{$id}"); + } + + $query = prepare(sprintf("SELECT * FROM `posts_%s` WHERE (`thread` IS NULL AND `id` = :id) OR `thread` = :id ORDER BY `thread`,`id`", $board['uri'])); + $query->bindValue(':id', $id, PDO::PARAM_INT); + $query->execute() or error(db_error($query)); + + while($post = $query->fetch()) { + if(!isset($thread)) { + $thread = new Thread( + $post['id'], $post['subject'], $post['email'], $post['name'], $post['trip'], $post['capcode'], $post['body'], $post['time'], + $post['thumb'], $post['thumbwidth'], $post['thumbheight'], $post['file'], $post['filewidth'], $post['fileheight'], $post['filesize'], + $post['filename'], $post['ip'], $post['sticky'], $post['locked'], $post['sage'], $post['embed'], $mod ? '?/' : $config['root'], $mod + ); + } else { + $thread->add(new Post( + $post['id'], $thread->id, $post['subject'], $post['email'], $post['name'], $post['trip'], $post['capcode'], $post['body'], + $post['time'], $post['thumb'], $post['thumbwidth'], $post['thumbheight'], $post['file'], $post['filewidth'], $post['fileheight'], + $post['filesize'], $post['filename'], $post['ip'], $post['embed'], $mod ? '?/' : $config['root'], $mod) + ); } - - // Check if any posts were found - if(!isset($thread)) error($config['error']['nonexistant']); - - $body = Element('thread.html', Array( - 'board'=>$board, - 'body'=>$thread->build(), - 'config' => $config, - 'id' => $id, - 'mod' => $mod, - 'boardlist' => createBoardlist($mod), - 'return' => ($mod ? '?' . $board['url'] . $config['file_index'] : $config['root'] . $board['uri'] . '/' . $config['file_index']) - )); - - if($return) - return $body; - else - file_write($board['dir'] . $config['dir']['res'] . sprintf($config['file_page'], $id), $body); } - function rrmdir($dir) { - if (is_dir($dir)) { - $objects = scandir($dir); - foreach ($objects as $object) { - if ($object != "." && $object != "..") { - if (filetype($dir."/".$object) == "dir") - rrmdir($dir."/".$object); - else - file_unlink($dir."/".$object); - } + // Check if any posts were found + if(!isset($thread)) + error($config['error']['nonexistant']); + + $body = Element('thread.html', array( + 'board'=>$board, + 'body'=>$thread->build(), + 'config' => $config, + 'id' => $id, + 'mod' => $mod, + 'boardlist' => createBoardlist($mod), + 'return' => ($mod ? '?' . $board['url'] . $config['file_index'] : $config['root'] . $board['uri'] . '/' . $config['file_index']) + )); + + if($return) + return $body; + else + file_write($board['dir'] . $config['dir']['res'] . sprintf($config['file_page'], $id), $body); +} + + function rrmdir($dir) { + if (is_dir($dir)) { + $objects = scandir($dir); + foreach ($objects as $object) { + if ($object != "." && $object != "..") { + if (filetype($dir."/".$object) == "dir") + rrmdir($dir."/".$object); + else + file_unlink($dir."/".$object); } - reset($objects); - rmdir($dir); } + reset($objects); + rmdir($dir); } +} + +function poster_id($ip, $thread) { + global $config; - function poster_id($ip, $thread) { - global $config; - - if($id = event('poster-id', $ip, $thread)) - return $id; - - // Confusing, hard to brute-force, but simple algorithm - return substr(sha1(sha1($ip . $config['secure_trip_salt'] . $thread) . $config['secure_trip_salt']), 0, $config['poster_id_length']); + if($id = event('poster-id', $ip, $thread)) + return $id; + + // Confusing, hard to brute-force, but simple algorithm + return substr(sha1(sha1($ip . $config['secure_trip_salt'] . $thread) . $config['secure_trip_salt']), 0, $config['poster_id_length']); +} + +function generate_tripcode($name) { + global $config; + + if($trip = event('tripcode', $name)) + return $trip; + + if(!preg_match('/^([^#]+)?(##|#)(.+)$/', $name, $match)) + return array($name); + + $name = $match[1]; + $secure = $match[2] == '##'; + $trip = $match[3]; + + // convert to SHIT_JIS encoding + $trip = mb_convert_encoding($trip, 'Shift_JIS', 'UTF-8'); + + // generate salt + $salt = substr($trip . 'H..', 1, 2); + $salt = preg_replace('/[^\.-z]/', '.', $salt); + $salt = strtr($salt, ':;<=>?@[\]^_`', 'ABCDEFGabcdef'); + + if($secure) { + if(isset($config['custom_tripcode']["##{$trip}"])) + $trip = $config['custom_tripcode']["##{$trip}"]; + else + $trip = '!!' . substr(crypt($trip, $config['secure_trip_salt']), -10); + } else { + if(isset($config['custom_tripcode']["#{$trip}"])) + $trip = $config['custom_tripcode']["#{$trip}"]; + else + $trip = '!' . substr(crypt($trip, $salt), -10); } - - function generate_tripcode($name) { - global $config; - - if($trip = event('tripcode', $name)) - return $trip; - - if(!preg_match('/^([^#]+)?(##|#)(.+)$/', $name, $match)) - return Array($name); - - $name = $match[1]; - $secure = $match[2] == '##'; - $trip = $match[3]; - - // convert to SHIT_JIS encoding - $trip = mb_convert_encoding($trip, 'Shift_JIS', 'UTF-8'); - - // generate salt - $salt = substr($trip . 'H..', 1, 2); - $salt = preg_replace('/[^\.-z]/', '.', $salt); - $salt = strtr($salt, ':;<=>?@[\]^_`', 'ABCDEFGabcdef'); - - if($secure) { - if(isset($config['custom_tripcode']["##{$trip}"])) - $trip = $config['custom_tripcode']["##{$trip}"]; - else - $trip = '!!' . substr(crypt($trip, $config['secure_trip_salt']), -10); - } else { - if(isset($config['custom_tripcode']["#{$trip}"])) - $trip = $config['custom_tripcode']["#{$trip}"]; - else - $trip = '!' . substr(crypt($trip, $salt), -10); - } - - return Array($name, $trip); + + 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; } - - // 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; - } + 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; } + return $gcd; +} - function fraction($numerator, $denominator, $sep) { - $gcf = hcf($numerator, $denominator); - $numerator = $numerator / $gcf; - $denominator = $denominator / $gcf; - - return "{$numerator}{$sep}{$denominator}"; +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'])); + $query->bindValue(':hash', $hash, PDO::PARAM_STR); + $query->execute() or error(db_error($query)); + + if($post = $query->fetch()) { + return $post; } + + return false; +} +function undoImage(array $post) { + if(!$post['has_file']) + return; + if(isset($post['file'])) + file_unlink($post['file']); + if(isset($post['thumb'])) + file_unlink($post['thumb']); +} + +function rDNS($ip_addr) { + global $config; - function getPostByHash($hash) { - global $board; - $query = prepare(sprintf("SELECT `id`,`thread` FROM `posts_%s` WHERE `filehash` = :hash", $board['uri'])); - $query->bindValue(':hash', $hash, PDO::PARAM_STR); - $query->execute() or error(db_error($query)); - - if($post = $query->fetch()) { - return $post; - } - - return false; + if($config['cache']['enabled'] && ($host = cache::get('rdns_' . $ip_addr))) { + return $host; } - function undoImage($post) { - if($post['has_file']) { - if(isset($post['thumb'])) - file_unlink($post['file']); - if(isset($post['thumb'])) - file_unlink($post['thumb']); - } + if(!$config['dns_system']) { + $host = gethostbyaddr($ip_addr); + } else { + $resp = shell_exec('host -W 1 ' . $ip_addr); + if(preg_match('/domain name pointer ([^\s]+)$/', $resp, $m)) + $host = $m[1]; + else + $host = $ip_addr; } - function rDNS($ip_addr) { - global $config; - - if($config['cache']['enabled'] && ($host = cache::get('rdns_' . $ip_addr))) { - return $host; - } - - if(!$config['dns_system']) { - $host = gethostbyaddr($ip_addr); - } else { - $resp = shell_exec('host -W 1 ' . $ip_addr); - if(preg_match('/domain name pointer ([^\s]+)$/', $resp, $m)) - $host = $m[1]; - else - $host = $ip_addr; - } - - if($config['cache']['enabled']) - cache::set('rdns_' . $ip_addr, $host, 3600); - - return $host; - } + if($config['cache']['enabled']) + cache::set('rdns_' . $ip_addr, $host, 3600); - function DNS($host) { - global $config; - - if($config['cache']['enabled'] && ($ip_addr = cache::get('dns_' . $host))) { - return $ip_addr; - } - - if(!$config['dns_system']) { - $ip_addr = gethostbyname($host); - if($ip_addr == $host) - $ip_addr = false; - } else { - $resp = shell_exec('host -W 1 ' . $host); - if(preg_match('/has address ([^\s]+)$/', $resp, $m)) - $ip_addr = $m[1]; - else - $ip_addr = false; - } - - if($config['cache']['enabled']) - cache::set('dns_' . $host, $ip_addr, 3600); - + return $host; +} + +function DNS($host) { + global $config; + + if($config['cache']['enabled'] && ($ip_addr = cache::get('dns_' . $host))) { return $ip_addr; } - + + if(!$config['dns_system']) { + $ip_addr = gethostbyname($host); + if($ip_addr == $host) + $ip_addr = false; + } else { + $resp = shell_exec('host -W 1 ' . $host); + if(preg_match('/has address ([^\s]+)$/', $resp, $m)) + $ip_addr = $m[1]; + else + $ip_addr = false; + } + + if($config['cache']['enabled']) + cache::set('dns_' . $host, $ip_addr, 3600); + + return $ip_addr; +} diff --git a/inc/image.php b/inc/image.php index 9275bd9c..f6bc3e7c 100644 --- a/inc/image.php +++ b/inc/image.php @@ -1,488 +1,491 @@ <?php - if($_SERVER['SCRIPT_FILENAME'] == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - header('Location: ../', true, 302); - exit; - } - class Image { - public $src, $format, $image, $size; - public function __construct($src, $format = false) { - global $config; - - $this->src = $src; - $this->format = $format; - - if($config['thumb_method'] == 'imagick') { - $classname = 'ImageImagick'; - } elseif($config['thumb_method'] == 'convert') { - $classname = 'ImageConvert'; - } else { - $classname = 'Image' . strtoupper($this->format); - if(!class_exists($classname)) { - error('Unsupported file format: ' . $this->format); - } - } - - $this->image = new $classname($this); - if(!$this->image->valid()) { - $this->delete(); - error($config['error']['invalidimg']); - } - - $this->size = (object)Array('width' => $this->image->_width(), 'height' => $this->image->_height()); - if($this->size->width < 1 || $this->size->height < 1) { - $this->delete(); - error($config['error']['invalidimg']); - } - } +/* + * Copyright (c) 2010-2012 Tinyboard Development Group + */ + +if(realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { + // You cannot request this file directly. + exit; +} + +class Image { + public $src, $format, $image, $size; + public function __construct($src, $format = false) { + global $config; - public function resize($extension, $max_width, $max_height) { - global $config; - - if($config['thumb_method'] == 'imagick') { - $classname = 'ImageImagick'; - } elseif($config['thumb_method'] == 'convert') { - $classname = 'ImageConvert'; - } else { - $classname = 'Image' . strtoupper($extension); - if(!class_exists($classname)) { - error('Unsupported file format: ' . $extension); - } - } - - $thumb = new $classname(false); - $thumb->src = $this->src; - $thumb->original_width = $this->size->width; - $thumb->original_height = $this->size->height; - - $x_ratio = $max_width / $this->size->width; - $y_ratio = $max_height / $this->size->height; - - if(($this->size->width <= $max_width) && ($this->size->height <= $max_height)) { - $width = $this->size->width; - $height = $this->size->height; - } elseif (($x_ratio * $this->size->height) < $max_height) { - $height = ceil($x_ratio * $this->size->height); - $width = $max_width; - } else { - $width = ceil($y_ratio * $this->size->width); - $height = $max_height; + $this->src = $src; + $this->format = $format; + + if($config['thumb_method'] == 'imagick') { + $classname = 'ImageImagick'; + } elseif($config['thumb_method'] == 'convert') { + $classname = 'ImageConvert'; + } else { + $classname = 'Image' . strtoupper($this->format); + if(!class_exists($classname)) { + error('Unsupported file format: ' . $this->format); } - - $thumb->_resize($this->image->image, $width, $height); - return $thumb; } - public function to($dst) { - $this->image->to($dst); + $this->image = new $classname($this); + if(!$this->image->valid()) { + $this->delete(); + error($config['error']['invalidimg']); } - public function delete() { - file_unlink($this->src); - } - public function destroy() { - $this->image->_destroy(); + $this->size = (object)Array('width' => $this->image->_width(), 'height' => $this->image->_height()); + if($this->size->width < 1 || $this->size->height < 1) { + $this->delete(); + error($config['error']['invalidimg']); } } - class ImageGD { - public function GD_create() { - $this->image = imagecreatetruecolor($this->width, $this->height); - } - public function GD_copyresampled() { - imagecopyresampled($this->image, $this->original, 0, 0, 0, 0, $this->width, $this->height, $this->original_width, $this->original_height); + public function resize($extension, $max_width, $max_height) { + global $config; + + if($config['thumb_method'] == 'imagick') { + $classname = 'ImageImagick'; + } elseif($config['thumb_method'] == 'convert') { + $classname = 'ImageConvert'; + } else { + $classname = 'Image' . strtoupper($extension); + if(!class_exists($classname)) { + error('Unsupported file format: ' . $extension); + } } - public function GD_resize() { - $this->GD_create(); - $this->GD_copyresampled(); + + $thumb = new $classname(false); + $thumb->src = $this->src; + $thumb->original_width = $this->size->width; + $thumb->original_height = $this->size->height; + + $x_ratio = $max_width / $this->size->width; + $y_ratio = $max_height / $this->size->height; + + if(($this->size->width <= $max_width) && ($this->size->height <= $max_height)) { + $width = $this->size->width; + $height = $this->size->height; + } elseif (($x_ratio * $this->size->height) < $max_height) { + $height = ceil($x_ratio * $this->size->height); + $width = $max_width; + } else { + $width = ceil($y_ratio * $this->size->width); + $height = $max_height; } + + $thumb->_resize($this->image->image, $width, $height); + return $thumb; } - class ImageBase extends ImageGD { - public $image, $src, $original, $original_width, $original_height, $width, $height; - public function valid() { - return (bool)$this->image; - } + public function to($dst) { + $this->image->to($dst); + } + + public function delete() { + file_unlink($this->src); + } + public function destroy() { + $this->image->_destroy(); + } +} + +class ImageGD { + public function GD_create() { + $this->image = imagecreatetruecolor($this->width, $this->height); + } + public function GD_copyresampled() { + imagecopyresampled($this->image, $this->original, 0, 0, 0, 0, $this->width, $this->height, $this->original_width, $this->original_height); + } + public function GD_resize() { + $this->GD_create(); + $this->GD_copyresampled(); + } +} + +class ImageBase extends ImageGD { + public $image, $src, $original, $original_width, $original_height, $width, $height; + public function valid() { + return (bool)$this->image; + } + + public function __construct($img) { + if(method_exists($this, 'init')) + $this->init(); - public function __construct($img) { - if(method_exists($this, 'init')) - $this->init(); - - if($img !== false) { - $this->src = $img->src; - $this->from(); - } + if($img !== false) { + $this->src = $img->src; + $this->from(); } + } + + public function _width() { + if(method_exists($this, 'width')) + return $this->width(); + // use default GD functions + return imagesx($this->image); + } + public function _height() { + if(method_exists($this, 'height')) + return $this->height(); + // use default GD functions + return imagesy($this->image); + } + public function _destroy() { + if(method_exists($this, 'destroy')) + return $this->destroy(); + // use default GD functions + return imagedestroy($this->image); + } + public function _resize($original, $width, $height) { + $this->original = &$original; + $this->width = $width; + $this->height = $height; - public function _width() { - if(method_exists($this, 'width')) - return $this->width(); - // use default GD functions - return imagesx($this->image); - } - public function _height() { - if(method_exists($this, 'height')) - return $this->height(); - // use default GD functions - return imagesy($this->image); - } - public function _destroy() { - if(method_exists($this, 'destroy')) - return $this->destroy(); + if(method_exists($this, 'resize')) + $this->resize(); + else // use default GD functions - return imagedestroy($this->image); - } - public function _resize($original, $width, $height) { - $this->original = &$original; - $this->width = $width; - $this->height = $height; - - if(method_exists($this, 'resize')) - $this->resize(); - else - // use default GD functions - $this->GD_resize(); + $this->GD_resize(); + } +} + +class ImageImagick extends ImageBase { + public function init() { + $this->image = new Imagick(); + $this->image->setBackgroundColor(new ImagickPixel('transparent')); + } + public function from() { + try { + $this->image->readImage($this->src); + } catch(ImagickException $e) { + // invalid image + $this->image = false; } } - - class ImageImagick extends ImageBase { - public function init() { + public function to($src) { + if(preg_match('/\.gif$/i', $src)) + $this->image->writeImages($src, true); + else + $this->image->writeImage($src); + } + public function width() { + return $this->image->getImageWidth(); + } + public function height() { + return $this->image->getImageHeight(); + } + public function destroy() { + return $this->image->destroy(); + } + public function resize() { + global $config; + + if(preg_match('/\.gif$/i', $this->src) && $config['thumb_ext'] == 'gif') { $this->image = new Imagick(); - $this->image->setBackgroundColor(new ImagickPixel('transparent')); - } - public function from() { - try { - $this->image->readImage($this->src); - } catch(ImagickException $e) { - // invalid image - $this->image = false; - } - } - public function to($src) { - if(preg_match('/\.gif$/i', $src)) - $this->image->writeImages($src, true); - else - $this->image->writeImage($src); - } - public function width() { - return $this->image->getImageWidth(); - } - public function height() { - return $this->image->getImageHeight(); - } - public function destroy() { - return $this->image->destroy(); - } - public function resize() { - global $config; + $this->image->setFormat('gif'); - if(preg_match('/\.gif$/i', $this->src) && $config['thumb_ext'] == 'gif') { - $this->image = new Imagick(); - $this->image->setFormat('gif'); - - $keep_frames = Array(); - for($i = 0; $i < $this->original->getNumberImages(); $i += floor($this->original->getNumberImages() / $config['thumb_keep_animation_frames'])) - $keep_frames[] = $i; + $keep_frames = Array(); + for($i = 0; $i < $this->original->getNumberImages(); $i += floor($this->original->getNumberImages() / $config['thumb_keep_animation_frames'])) + $keep_frames[] = $i; + + $i = 0; + $delay = 0; + foreach($this->original as $frame) { + $delay += $frame->getImageDelay(); - $i = 0; - $delay = 0; - foreach($this->original as $frame) { - $delay += $frame->getImageDelay(); + //if($i < $config['thumb_keep_animation_frames']) { + if(in_array($i, $keep_frames)) { + // $frame->scaleImage($this->width, $this->height, false); + $frame->sampleImage($this->width, $this->height); + $frame->setImagePage($this->width, $this->height, 0, 0); + $frame->setImageDelay($delay); + $delay = 0; - //if($i < $config['thumb_keep_animation_frames']) { - if(in_array($i, $keep_frames)) { - // $frame->scaleImage($this->width, $this->height, false); - $frame->sampleImage($this->width, $this->height); - $frame->setImagePage($this->width, $this->height, 0, 0); - $frame->setImageDelay($delay); - $delay = 0; - - $this->image->addImage($frame->getImage()); - } - $i++; - } - } else { - $this->image = clone $this->original; - $this->image->scaleImage($this->width, $this->height, false); - } + $this->image->addImage($frame->getImage()); + } + $i++; + } + } else { + $this->image = clone $this->original; + $this->image->scaleImage($this->width, $this->height, false); } } +} + + +class ImageConvert extends ImageBase { + public $width, $height, $temp; - - class ImageConvert extends ImageBase { - public $width, $height, $temp; + public function init() { + global $config; - public function init() { - global $config; - - $this->temp = false; - } - public function from() { - $size = trim(shell_exec('identify -format "%w %h" ' . escapeshellarg($this->src . '[0]'))); - if(preg_match('/^(\d+) (\d+)$/', $size, $m)) { - $this->width = $m[1]; - $this->height = $m[2]; - - $this->image = true; - } else { - // mark as invalid - $this->image = false; - } - } - public function to($src) { - if(!$this->temp) { - // $config['redraw_image'] - shell_exec('convert ' . escapeshellarg($this->src) . ' ' . escapeshellarg($src)); - } else { - rename($this->temp, $src); - chmod($src, 0664); - } - } - public function width() { - return $this->width; - } - public function height() { - return $this->height; - } - public function destroy() { - @unlink($this->temp); - $this->temp = false; - } - public function resize() { - global $config; - - if($this->temp) { - // remove old - $this->destroy(); - } - - $this->temp = tempnam($config['tmp'], 'imagick'); - - $quality = $config['thumb_quality'] * 10; + $this->temp = false; + } + public function from() { + $size = trim(shell_exec('identify -format "%w %h" ' . escapeshellarg($this->src . '[0]'))); + if(preg_match('/^(\d+) (\d+)$/', $size, $m)) { + $this->width = $m[1]; + $this->height = $m[2]; - if(shell_exec("convert -flatten -filter Point -scale {$this->width}x{$this->height} +antialias -quality {$quality} " . escapeshellarg($this->src . '[0]') . " " . escapeshellarg($this->temp)) || !file_exists($this->temp)) - error('Failed to resize image!'); + $this->image = true; + } else { + // mark as invalid + $this->image = false; } } - - class ImagePNG extends ImageBase { - public function from() { - $this->image = @imagecreatefrompng($this->src); - } - public function to($src) { - global $config; - imagepng($this->image, $src, $config['thumb_quality']); - } - public function resize() { - $this->GD_create(); - imagecolortransparent($this->image, imagecolorallocatealpha($this->image, 0, 0, 0, 0)); - imagesavealpha($this->image, true); - imagealphablending($this->image, false); - $this->GD_copyresampled(); + public function to($src) { + if(!$this->temp) { + // $config['redraw_image'] + shell_exec('convert ' . escapeshellarg($this->src) . ' ' . escapeshellarg($src)); + } else { + rename($this->temp, $src); + chmod($src, 0664); } } - - class ImageGIF extends ImageBase { - public function from() { - $this->image = @imagecreatefromgif($this->src); - } - public function to($src) { - imagegif($this->image, $src); - } - public function resize() { - $this->GD_create(); - imagecolortransparent($this->image, imagecolorallocatealpha($this->image, 0, 0, 0, 0)); - imagesavealpha($this->image, true); - $this->GD_copyresampled(); - } + public function width() { + return $this->width; } - - class ImageJPG extends ImageBase { - public function from() { - $this->image = @imagecreatefromjpeg($this->src); - } - public function to($src) { - imagejpeg($this->image, $src); - } + public function height() { + return $this->height; } - class ImageJPEG extends ImageJPG { + public function destroy() { + @unlink($this->temp); + $this->temp = false; } - - class ImageBMP extends ImageBase { - public function from() { - $this->image = @imagecreatefrombmp($this->src); - } - public function to($src) { - imagebmp($this->image, $src); + public function resize() { + global $config; + + if($this->temp) { + // remove old + $this->destroy(); } + + $this->temp = tempnam($config['tmp'], 'imagick'); + + $quality = $config['thumb_quality'] * 10; + + if(shell_exec("convert -flatten -filter Point -scale {$this->width}x{$this->height} +antialias -quality {$quality} " . escapeshellarg($this->src . '[0]') . " " . escapeshellarg($this->temp)) || !file_exists($this->temp)) + error('Failed to resize image!'); } - - - /*********************************************/ - /* Fonction: imagecreatefrombmp */ - /* Author: DHKold */ - /* Contact: admin@dhkold.com */ - /* Date: The 15th of June 2005 */ - /* Version: 2.0B */ - /*********************************************/ +} - function imagecreatefrombmp($filename) { - if (! $f1 = fopen($filename,"rb")) return FALSE; - $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14)); - if ($FILE['file_type'] != 19778) return FALSE; - $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'. - '/Vcompression/Vsize_bitmap/Vhoriz_resolution'. - '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40)); - $BMP['colors'] = pow(2,$BMP['bits_per_pixel']); - if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset']; - $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8; - $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']); - $BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4); - $BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4); - $BMP['decal'] = 4-(4*$BMP['decal']); - if ($BMP['decal'] == 4) $BMP['decal'] = 0; +class ImagePNG extends ImageBase { + public function from() { + $this->image = @imagecreatefrompng($this->src); + } + public function to($src) { + global $config; + imagepng($this->image, $src, $config['thumb_quality']); + } + public function resize() { + $this->GD_create(); + imagecolortransparent($this->image, imagecolorallocatealpha($this->image, 0, 0, 0, 0)); + imagesavealpha($this->image, true); + imagealphablending($this->image, false); + $this->GD_copyresampled(); + } +} - $PALETTE = array(); - if ($BMP['colors'] < 16777216) - { - $PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4)); - } +class ImageGIF extends ImageBase { + public function from() { + $this->image = @imagecreatefromgif($this->src); + } + public function to($src) { + imagegif($this->image, $src); + } + public function resize() { + $this->GD_create(); + imagecolortransparent($this->image, imagecolorallocatealpha($this->image, 0, 0, 0, 0)); + imagesavealpha($this->image, true); + $this->GD_copyresampled(); + } +} - $IMG = fread($f1,$BMP['size_bitmap']); - $VIDE = chr(0); +class ImageJPG extends ImageBase { + public function from() { + $this->image = @imagecreatefromjpeg($this->src); + } + public function to($src) { + imagejpeg($this->image, $src); + } +} +class ImageJPEG extends ImageJPG { +} - $res = imagecreatetruecolor($BMP['width'],$BMP['height']); - $P = 0; - $Y = $BMP['height']-1; - while ($Y >= 0) - { - $X=0; - while ($X < $BMP['width']) - { - if ($BMP['bits_per_pixel'] == 24) - $COLOR = unpack("V",substr($IMG,$P,3).$VIDE); - elseif ($BMP['bits_per_pixel'] == 16) - { - $COLOR = unpack("n",substr($IMG,$P,2)); - $COLOR[1] = $PALETTE[$COLOR[1]+1]; - } - elseif ($BMP['bits_per_pixel'] == 8) - { - $COLOR = unpack("n",$VIDE.substr($IMG,$P,1)); - $COLOR[1] = $PALETTE[$COLOR[1]+1]; - } - elseif ($BMP['bits_per_pixel'] == 4) - { - $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1)); - if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F); - $COLOR[1] = $PALETTE[$COLOR[1]+1]; - } - elseif ($BMP['bits_per_pixel'] == 1) - { - $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1)); - if (($P*8)%8 == 0) $COLOR[1] = $COLOR[1] >>7; - elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6; - elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5; - elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4; - elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3; - elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2; - elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1; - elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1); - $COLOR[1] = $PALETTE[$COLOR[1]+1]; - } - else - return FALSE; - imagesetpixel($res,$X,$Y,$COLOR[1]); - $X++; - $P += $BMP['bytes_per_pixel']; - } - $Y--; - $P+=$BMP['decal']; - } - fclose($f1); +class ImageBMP extends ImageBase { + public function from() { + $this->image = @imagecreatefrombmp($this->src); + } + public function to($src) { + imagebmp($this->image, $src); + } +} + + +/*********************************************/ +/* Fonction: imagecreatefrombmp */ +/* Author: DHKold */ +/* Contact: admin@dhkold.com */ +/* Date: The 15th of June 2005 */ +/* Version: 2.0B */ +/*********************************************/ + +function imagecreatefrombmp($filename) { + if (! $f1 = fopen($filename,"rb")) return FALSE; + $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14)); + if ($FILE['file_type'] != 19778) return FALSE; + $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'. + '/Vcompression/Vsize_bitmap/Vhoriz_resolution'. + '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40)); + $BMP['colors'] = pow(2,$BMP['bits_per_pixel']); + if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset']; + $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8; + $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']); + $BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4); + $BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4); + $BMP['decal'] = 4-(4*$BMP['decal']); + if ($BMP['decal'] == 4) $BMP['decal'] = 0; + + $PALETTE = array(); + if ($BMP['colors'] < 16777216) + { + $PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4)); + } - return $res; + $IMG = fread($f1,$BMP['size_bitmap']); + $VIDE = chr(0); + + $res = imagecreatetruecolor($BMP['width'],$BMP['height']); + $P = 0; + $Y = $BMP['height']-1; + while ($Y >= 0) + { + $X=0; + while ($X < $BMP['width']) + { + if ($BMP['bits_per_pixel'] == 24) + $COLOR = unpack("V",substr($IMG,$P,3).$VIDE); + elseif ($BMP['bits_per_pixel'] == 16) + { + $COLOR = unpack("n",substr($IMG,$P,2)); + $COLOR[1] = $PALETTE[$COLOR[1]+1]; + } + elseif ($BMP['bits_per_pixel'] == 8) + { + $COLOR = unpack("n",$VIDE.substr($IMG,$P,1)); + $COLOR[1] = $PALETTE[$COLOR[1]+1]; + } + elseif ($BMP['bits_per_pixel'] == 4) + { + $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1)); + if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F); + $COLOR[1] = $PALETTE[$COLOR[1]+1]; + } + elseif ($BMP['bits_per_pixel'] == 1) + { + $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1)); + if (($P*8)%8 == 0) $COLOR[1] = $COLOR[1] >>7; + elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6; + elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5; + elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4; + elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3; + elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2; + elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1; + elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1); + $COLOR[1] = $PALETTE[$COLOR[1]+1]; + } + else + return FALSE; + imagesetpixel($res,$X,$Y,$COLOR[1]); + $X++; + $P += $BMP['bytes_per_pixel']; } - - function imagebmp(&$img, $filename='') { - $widthOrig = imagesx($img); - $widthFloor = ((floor($widthOrig/16))*16); - $widthCeil = ((ceil($widthOrig/16))*16); - $height = imagesy($img); + $Y--; + $P+=$BMP['decal']; + } + fclose($f1); - $size = ($widthCeil*$height*3)+54; + return $res; +} - // Bitmap File Header - $result = 'BM'; // header (2b) - $result .= int_to_dword($size); // size of file (4b) - $result .= int_to_dword(0); // reserved (4b) - $result .= int_to_dword(54); // byte location in the file which is first byte of IMAGE (4b) - // Bitmap Info Header - $result .= int_to_dword(40); // Size of BITMAPINFOHEADER (4b) - $result .= int_to_dword($widthCeil); // width of bitmap (4b) - $result .= int_to_dword($height); // height of bitmap (4b) - $result .= int_to_word(1); // biPlanes = 1 (2b) - $result .= int_to_word(24); // biBitCount = {1 (mono) or 4 (16 clr ) or 8 (256 clr) or 24 (16 Mil)} (2b - $result .= int_to_dword(0); // RLE COMPRESSION (4b) - $result .= int_to_dword(0); // width x height (4b) - $result .= int_to_dword(0); // biXPelsPerMeter (4b) - $result .= int_to_dword(0); // biYPelsPerMeter (4b) - $result .= int_to_dword(0); // Number of palettes used (4b) - $result .= int_to_dword(0); // Number of important colour (4b) +function imagebmp(&$img, $filename='') { + $widthOrig = imagesx($img); + $widthFloor = ((floor($widthOrig/16))*16); + $widthCeil = ((ceil($widthOrig/16))*16); + $height = imagesy($img); - // is faster than chr() - $arrChr = array(); - for($i=0; $i<256; $i++){ - $arrChr[$i] = chr($i); - } + $size = ($widthCeil*$height*3)+54; - // creates image data - $bgfillcolor = array('red'=>0, 'green'=>0, 'blue'=>0); + // Bitmap File Header + $result = 'BM'; // header (2b) + $result .= int_to_dword($size); // size of file (4b) + $result .= int_to_dword(0); // reserved (4b) + $result .= int_to_dword(54); // byte location in the file which is first byte of IMAGE (4b) + // Bitmap Info Header + $result .= int_to_dword(40); // Size of BITMAPINFOHEADER (4b) + $result .= int_to_dword($widthCeil); // width of bitmap (4b) + $result .= int_to_dword($height); // height of bitmap (4b) + $result .= int_to_word(1); // biPlanes = 1 (2b) + $result .= int_to_word(24); // biBitCount = {1 (mono) or 4 (16 clr ) or 8 (256 clr) or 24 (16 Mil)} (2b + $result .= int_to_dword(0); // RLE COMPRESSION (4b) + $result .= int_to_dword(0); // width x height (4b) + $result .= int_to_dword(0); // biXPelsPerMeter (4b) + $result .= int_to_dword(0); // biYPelsPerMeter (4b) + $result .= int_to_dword(0); // Number of palettes used (4b) + $result .= int_to_dword(0); // Number of important colour (4b) - // bottom to top - left to right - attention blue green red !!! - $y=$height-1; - for ($y2=0; $y2<$height; $y2++) { - for ($x=0; $x<$widthFloor; ) { - $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); - $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; - $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); - $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; - $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); - $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; - $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); - $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; - $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); - $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; - $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); - $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; - $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); - $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; - $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); - $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; - } - for ($x=$widthFloor; $x<$widthCeil; $x++) { - $rgb = ($x<$widthOrig) ? imagecolorsforindex($img, imagecolorat($img, $x, $y)) : $bgfillcolor; - $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; - } - $y--; - } + // is faster than chr() + $arrChr = array(); + for($i=0; $i<256; $i++){ + $arrChr[$i] = chr($i); + } - // see imagegif - if($filename == '') { - echo $result; - } else { - $file = fopen($filename, 'wb'); - fwrite($file, $result); - fclose($file); + // creates image data + $bgfillcolor = array('red'=>0, 'green'=>0, 'blue'=>0); + + // bottom to top - left to right - attention blue green red !!! + $y=$height-1; + for ($y2=0; $y2<$height; $y2++) { + for ($x=0; $x<$widthFloor; ) { + $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); + $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; + $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); + $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; + $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); + $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; + $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); + $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; + $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); + $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; + $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); + $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; + $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); + $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; + $rgb = imagecolorsforindex($img, imagecolorat($img, $x++, $y)); + $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; } + for ($x=$widthFloor; $x<$widthCeil; $x++) { + $rgb = ($x<$widthOrig) ? imagecolorsforindex($img, imagecolorat($img, $x, $y)) : $bgfillcolor; + $result .= $arrChr[$rgb['blue']].$arrChr[$rgb['green']].$arrChr[$rgb['red']]; + } + $y--; } - // imagebmp helpers - function int_to_dword($n) { - return chr($n & 255).chr(($n >> 8) & 255).chr(($n >> 16) & 255).chr(($n >> 24) & 255); - } - function int_to_word($n) { - return chr($n & 255).chr(($n >> 8) & 255); + + // see imagegif + if($filename == '') { + echo $result; + } else { + $file = fopen($filename, 'wb'); + fwrite($file, $result); + fclose($file); } +} +// imagebmp helpers +function int_to_dword($n) { + return chr($n & 255).chr(($n >> 8) & 255).chr(($n >> 16) & 255).chr(($n >> 24) & 255); +} +function int_to_word($n) { + return chr($n & 255).chr(($n >> 8) & 255); +} -?> diff --git a/inc/mod.php b/inc/mod.php index 43ed760d..de6e2e9a 100644 --- a/inc/mod.php +++ b/inc/mod.php @@ -1,283 +1,287 @@ <?php - if($_SERVER['SCRIPT_FILENAME'] == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - header('Location: ../', true, 302); - exit; - } + +/* + * Copyright (c) 2010-2012 Tinyboard Development Group + */ + +if(realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { + // You cannot request this file directly. + exit; +} + +// create a hash/salt pair for validate logins +function mkhash($username, $password, $salt = false) { + global $config; - // create a hash/salt pair for validate logins - function mkhash($username, $password, $salt = false) { - 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; - } + if(!$salt) { + // create some sort of salt for the hash + $salt = substr(base64_encode(sha1(rand() . time(), true) . $config['cookies']['salt']), 0, 15); - // generate hash (method is not important as long as it's strong) - $hash = substr(base64_encode(md5($username . sha1($username . $password . $salt . ($config['mod']['lock_ip'] ? $_SERVER['REMOTE_ADDR'] : ''), true), true)), 0, 20); - - if(isset($generated_salt)) - return Array($hash, $salt); - else - return $hash; + $generated_salt = true; } - function login($username, $password, $makehash=true) { - global $mod; - - // SHA1 password - if($makehash) { - $password = sha1($password); - } - - $query = prepare("SELECT `id`,`type`,`boards` FROM `mods` WHERE `username` = :username AND `password` = :password LIMIT 1"); - $query->bindValue(':username', $username); - $query->bindValue(':password', $password); - $query->execute() or error(db_error($query)); - - if($user = $query->fetch()) { - return $mod = Array( - 'id' => $user['id'], - 'type' => $user['type'], - 'username' => $username, - 'hash' => mkhash($username, $password), - 'boards' => explode(',', $user['boards']) - ); - } else return false; - } + // generate hash (method is not important as long as it's strong) + $hash = substr(base64_encode(md5($username . sha1($username . $password . $salt . ($config['mod']['lock_ip'] ? $_SERVER['REMOTE_ADDR'] : ''), true), true)), 0, 20); - function setCookies() { - global $mod, $config; - 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, false, true); - } + if(isset($generated_salt)) + return Array($hash, $salt); + else + return $hash; +} + +function login($username, $password, $makehash=true) { + global $mod; - function destroyCookies() { - global $config; - // Delete the cookies - setcookie($config['cookies']['mod'], 'deleted', time() - $config['cookies']['expire'], $config['cookies']['jail']?$config['cookies']['path'] : '/', null, false, true); + // SHA1 password + if($makehash) { + $password = sha1($password); } - function create_pm_header() { - global $mod; - $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()) { - return Array('id' => $pm['id'], 'waiting' => $query->rowCount() - 1); - } - - return false; + $query = prepare("SELECT `id`,`type`,`boards` FROM `mods` WHERE `username` = :username AND `password` = :password LIMIT 1"); + $query->bindValue(':username', $username); + $query->bindValue(':password', $password); + $query->execute() or error(db_error($query)); + + if($user = $query->fetch()) { + return $mod = Array( + 'id' => $user['id'], + 'type' => $user['type'], + 'username' => $username, + 'hash' => mkhash($username, $password), + 'boards' => explode(',', $user['boards']) + ); + } else return false; +} + +function setCookies() { + global $mod, $config; + 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, false, true); +} + +function destroyCookies() { + global $config; + // Delete the cookies + setcookie($config['cookies']['mod'], 'deleted', time() - $config['cookies']['expire'], $config['cookies']['jail']?$config['cookies']['path'] : '/', null, false, true); +} + +function create_pm_header() { + global $mod; + $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()) { + return Array('id' => $pm['id'], 'waiting' => $query->rowCount() - 1); } - function modLog($action, $_board=null) { - global $mod, $board, $config; - $query = prepare("INSERT INTO `modlogs` VALUES (:id, :ip, :board, :time, :text)"); - $query->bindValue(':id', $mod['id'], PDO::PARAM_INT); - $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); - $query->bindValue(':time', time(), PDO::PARAM_INT); - $query->bindValue(':text', $action); - if(isset($_board)) - $query->bindValue(':board', $_board); - elseif(isset($board)) - $query->bindValue(':board', $board['id']); - else - $query->bindValue(':board', null, PDO::PARAM_NULL); - $query->execute() or error(db_error($query)); - - if($config['syslog']) - _syslog(LOG_INFO, '[mod/' . $mod['username'] . ']: ' . $action); + return false; +} + +function modLog($action, $_board=null) { + global $mod, $board, $config; + $query = prepare("INSERT INTO `modlogs` VALUES (:id, :ip, :board, :time, :text)"); + $query->bindValue(':id', $mod['id'], PDO::PARAM_INT); + $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); + $query->bindValue(':time', time(), PDO::PARAM_INT); + $query->bindValue(':text', $action); + if(isset($_board)) + $query->bindValue(':board', $_board); + elseif(isset($board)) + $query->bindValue(':board', $board['id']); + else + $query->bindValue(':board', null, PDO::PARAM_NULL); + $query->execute() or error(db_error($query)); + + if($config['syslog']) + _syslog(LOG_INFO, '[mod/' . $mod['username'] . ']: ' . $action); +} + +// Generates a <ul> element with a list of linked +// boards and their subtitles. (without the <ul> opening and ending tags) +function ulBoards() { + global $mod, $config; + + $body = ''; + + // List of boards + $boards = listBoards(); + + foreach($boards as &$b) { + $body .= '<li>' . + '<a href="?/' . + sprintf($config['board_path'], $b['uri']) . $config['file_index'] . + '">' . + sprintf($config['board_abbreviation'], $b['uri']) . + '</a> - ' . + $b['title'] . + (isset($b['subtitle']) ? '<span class="unimportant"> — ' . $b['subtitle'] . '</span>' : '') . + ($mod['type'] >= $config['mod']['manageboards'] ? + ' <a href="?/board/' . $b['uri'] . '" class="unimportant">[manage]</a>' : '') . + '</li>'; } - // Generates a <ul> element with a list of linked - // boards and their subtitles. (without the <ul> opening and ending tags) - function ulBoards() { - global $mod, $config; - - $body = ''; - - // List of boards - $boards = listBoards(); - - foreach($boards as &$b) { - $body .= '<li>' . - '<a href="?/' . - sprintf($config['board_path'], $b['uri']) . $config['file_index'] . - '">' . - sprintf($config['board_abbreviation'], $b['uri']) . - '</a> - ' . - $b['title'] . - (isset($b['subtitle']) ? '<span class="unimportant"> — ' . $b['subtitle'] . '</span>' : '') . - ($mod['type'] >= $config['mod']['manageboards'] ? - ' <a href="?/board/' . $b['uri'] . '" class="unimportant">[manage]</a>' : '') . - '</li>'; - } - - if($mod['type'] >= $config['mod']['newboard']) { - $body .= '<li style="margin-top:15px;"><a href="?/new"><strong>' . _('Create new board') . '</strong></a></li>'; - } - return $body; + if($mod['type'] >= $config['mod']['newboard']) { + $body .= '<li style="margin-top:15px;"><a href="?/new"><strong>' . _('Create new board') . '</strong></a></li>'; } + return $body; +} + +function form_newBan($ip=null, $reason='', $continue=false, $delete=false, $board=false, $allow_public = false) { + global $config, $mod; - function form_newBan($ip=null, $reason='', $continue=false, $delete=false, $board=false, $allow_public = false) { - global $config, $mod; - - $boards = listBoards(); - $__boards = '<li><input type="radio" checked="checked" name="board_id" id="board_*" value="-1"/> <label style="display:inline" for="board_*"><em>' . _('all boards') . '</em></label></li>'; - foreach($boards as &$_board) { - $__boards .= '<li>' . - '<input type="radio" name="board_id" id="board_' . $_board['uri'] . '" value="' . $_board['id'] . '">' . - '<label style="display:inline" for="board_' . $_board['uri'] . '"> ' . - ($_board['uri'] == '*' ? - '<em>"*"</em>' - : - sprintf($config['board_abbreviation'], $_board['uri']) - ) . - ' - ' . $_board['title'] . - '</label>' . - '</li>'; - } - - return '<fieldset><legend>New ban</legend>' . - '<form action="?/ban" method="post">' . - ($continue ? '<input type="hidden" name="continue" value="' . htmlentities($continue) . '" />' : '') . - ($delete || $allow_public ? '<input type="hidden" name="' . (!$allow_public ? 'delete' : 'post') . '" value="' . htmlentities($delete) . '" />' : '') . - ($board ? '<input type="hidden" name="board" value="' . htmlentities($board) . '" />' : '') . - '<table>' . - '<tr>' . - '<th><label for="ip">IP ' . - ($config['ban_cidr'] ? '<span class="unimportant">(or subnet)' : '') . - '</span></label></th>' . - '<td><input type="text" name="ip" id="ip" size="30" maxlength="30" ' . - (isset($ip) ? - 'value="' . htmlentities($ip) . '" ' : '' - ) . - '/></td>' . - '</tr>' . - '<tr>' . - '<th><label for="reason">Reason</label></th>' . - '<td><textarea name="reason" id="reason" rows="5" cols="30">' . - htmlentities($reason) . - '</textarea></td>' . - '</tr>' . - ($mod['type'] >= $config['mod']['public_ban'] && $allow_public ? - '<tr>' . - '<th><label for="message">Message</label></th>' . - '<td><input type="checkbox" id="public_message" name="public_message"/>' . - ' <input type="text" name="message" id="message" size="35" maxlength="200" value="' . htmlentities($config['mod']['default_ban_message']) . '" />' . - ' <span class="unimportant">(public; attached to post)</span></td>' . - '<script type="text/javascript">' . - 'document.getElementById(\'message\').disabled = true;' . - 'document.getElementById(\'public_message\').onchange = function() {' . - 'document.getElementById(\'message\').disabled = !this.checked;' . - '}' . - - '</script>' . - '</tr>' - : '') . - '<tr>' . - '<th><label for="length">Length</label></th>' . - '<td><input type="text" name="length" id="length" size="20" maxlength="40" />' . - ' <span class="unimportant">(eg. "2d1h30m" or "2 days")</span></td>' . - '</tr>' . - - '<tr>' . - '<th>Board</th>' . - '<td><ul style="list-style:none;padding:2px 5px">' . $__boards . '</tl></td>' . - '</tr>' . - - '<tr>' . - '<td></td>' . - '<td><input name="new_ban" type="submit" value="New Ban" /></td>' . - '</tr>' . - '</table>' . - '</form>' . - '</fieldset>'; + $boards = listBoards(); + $__boards = '<li><input type="radio" checked="checked" name="board_id" id="board_*" value="-1"/> <label style="display:inline" for="board_*"><em>' . _('all boards') . '</em></label></li>'; + foreach($boards as &$_board) { + $__boards .= '<li>' . + '<input type="radio" name="board_id" id="board_' . $_board['uri'] . '" value="' . $_board['id'] . '">' . + '<label style="display:inline" for="board_' . $_board['uri'] . '"> ' . + ($_board['uri'] == '*' ? + '<em>"*"</em>' + : + sprintf($config['board_abbreviation'], $_board['uri']) + ) . + ' - ' . $_board['title'] . + '</label>' . + '</li>'; } - function form_newBoard() { - return '<fieldset><legend>New board</legend>' . - '<form action="?/new" method="post">' . - '<table>' . - '<tr>' . - '<th><label for="board">URI</label></th>' . - '<td><input type="text" name="uri" id="board" size="10" />' . - ' <span class="unimportant">(eg. "b"; "mu")</span></td>' . - '</tr>' . - '<tr>' . - '<th><label for="title">Title</label></th>' . - '<td><input type="text" name="title" id="title" size="25" />' . - ' <span class="unimportant">(eg. "Random")</span></td>' . - '</tr>' . - '<tr>' . - '<th><label for="subtitle">Subtitle</label></th>' . - '<td><input type="text" name="subtitle" id="subtitle" size="25" />' . - ' <span class="unimportant">(optional)</span></td>' . - '</tr>' . + return '<fieldset><legend>New ban</legend>' . + '<form action="?/ban" method="post">' . + ($continue ? '<input type="hidden" name="continue" value="' . htmlentities($continue) . '" />' : '') . + ($delete || $allow_public ? '<input type="hidden" name="' . (!$allow_public ? 'delete' : 'post') . '" value="' . htmlentities($delete) . '" />' : '') . + ($board ? '<input type="hidden" name="board" value="' . htmlentities($board) . '" />' : '') . + '<table>' . + '<tr>' . + '<th><label for="ip">IP ' . + ($config['ban_cidr'] ? '<span class="unimportant">(or subnet)' : '') . + '</span></label></th>' . + '<td><input type="text" name="ip" id="ip" size="30" maxlength="30" ' . + (isset($ip) ? + 'value="' . htmlentities($ip) . '" ' : '' + ) . + '/></td>' . + '</tr>' . + '<tr>' . + '<th><label for="reason">Reason</label></th>' . + '<td><textarea name="reason" id="reason" rows="5" cols="30">' . + htmlentities($reason) . + '</textarea></td>' . + '</tr>' . + ($mod['type'] >= $config['mod']['public_ban'] && $allow_public ? '<tr>' . - '<td></td>' . - '<td><input name="new_board" type="submit" value="New Board" /></td>' . - '</tr>' . - '</table>' . - '</form>' . - '</fieldset>'; - } + '<th><label for="message">Message</label></th>' . + '<td><input type="checkbox" id="public_message" name="public_message"/>' . + ' <input type="text" name="message" id="message" size="35" maxlength="200" value="' . htmlentities($config['mod']['default_ban_message']) . '" />' . + ' <span class="unimportant">(public; attached to post)</span></td>' . + '<script type="text/javascript">' . + 'document.getElementById(\'message\').disabled = true;' . + 'document.getElementById(\'public_message\').onchange = function() {' . + 'document.getElementById(\'message\').disabled = !this.checked;' . + '}' . + + '</script>' . + '</tr>' + : '') . + '<tr>' . + '<th><label for="length">Length</label></th>' . + '<td><input type="text" name="length" id="length" size="20" maxlength="40" />' . + ' <span class="unimportant">(eg. "2d1h30m" or "2 days")</span></td>' . + '</tr>' . + + '<tr>' . + '<th>Board</th>' . + '<td><ul style="list-style:none;padding:2px 5px">' . $__boards . '</tl></td>' . + '</tr>' . + + '<tr>' . + '<td></td>' . + '<td><input name="new_ban" type="submit" value="New Ban" /></td>' . + '</tr>' . + '</table>' . + '</form>' . + '</fieldset>'; +} + +function form_newBoard() { + return '<fieldset><legend>New board</legend>' . + '<form action="?/new" method="post">' . + '<table>' . + '<tr>' . + '<th><label for="board">URI</label></th>' . + '<td><input type="text" name="uri" id="board" size="10" />' . + ' <span class="unimportant">(eg. "b"; "mu")</span></td>' . + '</tr>' . + '<tr>' . + '<th><label for="title">Title</label></th>' . + '<td><input type="text" name="title" id="title" size="25" />' . + ' <span class="unimportant">(eg. "Random")</span></td>' . + '</tr>' . + '<tr>' . + '<th><label for="subtitle">Subtitle</label></th>' . + '<td><input type="text" name="subtitle" id="subtitle" size="25" />' . + ' <span class="unimportant">(optional)</span></td>' . + '</tr>' . + '<tr>' . + '<td></td>' . + '<td><input name="new_board" type="submit" value="New Board" /></td>' . + '</tr>' . + '</table>' . + '</form>' . + '</fieldset>'; +} + + +function removeBan($id) { + global $config, $memcached; + $query = prepare("DELETE FROM `bans` WHERE `id` = :id"); + $query->bindValue(':id', $id, PDO::PARAM_INT); + $query->execute() or error(db_error($query)); - function removeBan($id) { - global $config, $memcached; - - $query = prepare("DELETE FROM `bans` WHERE `id` = :id"); - $query->bindValue(':id', $id, PDO::PARAM_INT); - $query->execute() or error(db_error($query)); - - //if($config['memcached']['enabled']) { - // Remove cached ban - // TODO - // $memcached->delete("ban_{$id}"); - //} + //if($config['memcached']['enabled']) { + // Remove cached ban + // TODO + // $memcached->delete("ban_{$id}"); + //} +} + + +// Validate session + +if(isset($_COOKIE[$config['cookies']['mod']])) { + // Should be username:hash:salt + $cookie = explode(':', $_COOKIE[$config['cookies']['mod']]); + if(count($cookie) != 3) { + destroyCookies(); + error($config['error']['malformed']); } + $query = prepare("SELECT `id`, `type`, `boards`, `password` FROM `mods` WHERE `username` = :username LIMIT 1"); + $query->bindValue(':username', $cookie[0]); + $query->execute() or error(db_error($query)); + $user = $query->fetch(); - // Validate session - - if(isset($_COOKIE[$config['cookies']['mod']])) { - // Should be username:hash:salt - $cookie = explode(':', $_COOKIE[$config['cookies']['mod']]); - if(count($cookie) != 3) { - destroyCookies(); - error($config['error']['malformed']); - } - - $query = prepare("SELECT `id`, `type`, `boards`, `password` FROM `mods` WHERE `username` = :username LIMIT 1"); - $query->bindValue(':username', $cookie[0]); - $query->execute() or error(db_error($query)); - $user = $query->fetch(); - - // validate password hash - if($cookie[1] != mkhash($cookie[0], $user['password'], $cookie[2])) { - // Malformed cookies - destroyCookies(); - error($config['error']['malformed']); - } - - $mod = Array( - 'id' => $user['id'], - 'type' => $user['type'], - 'username' => $cookie[0], - 'boards' => explode(',', $user['boards']) - ); + // validate password hash + if($cookie[1] != mkhash($cookie[0], $user['password'], $cookie[2])) { + // Malformed cookies + destroyCookies(); + error($config['error']['malformed']); } + + $mod = Array( + 'id' => $user['id'], + 'type' => $user['type'], + 'username' => $cookie[0], + 'boards' => explode(',', $user['boards']) + ); +} diff --git a/inc/remote.php b/inc/remote.php index bf170486..664aa2bb 100644 --- a/inc/remote.php +++ b/inc/remote.php @@ -1,57 +1,67 @@ <?php - class Remote { - public function __construct($config) { - foreach($config as $name => $value) { - $this->{$name} = $value; - } - - $methods = Array(); - - if(!isset($this->auth['method'])) - error('Unspecified authentication method.'); - - // Connect - $this->connection = ssh2_connect($this->host, isset($this->port) ? $this->port : 22, $methods); - - switch($this->auth['method']) { - case 'pubkey': - - if(!isset($this->auth['public'])) - error('Public key filename not specified.'); - if(!isset($this->auth['private'])) - error('Private key filename not specified.'); - - if(!ssh2_auth_pubkey_file($this->connection, $this->auth['username'], $this->auth['public'], $this->auth['private'], isset($this->auth['passphrase']) ? $this->auth['passphrase']: null)) - error('Public key authentication failed.'); - break; - case 'plain': - if(!ssh2_auth_password($this->connection, $this->auth['username'], $this->auth['password'])) - error('Plain-text authentication failed.'); - break; - default: - error('Unknown authentication method: "' . $this->auth['method'] . '".'); - } - + +/* + * Copyright (c) 2010-2012 Tinyboard Development Group + */ + +if(realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { + // You cannot request this file directly. + exit; +} + +class Remote { + public function __construct($config) { + foreach($config as $name => $value) { + $this->{$name} = $value; } - public function write($data, $remote_path) { - global $config; - - switch($this->type) { - case 'sftp': - $sftp = ssh2_sftp($this->connection); - file_write('ssh2.sftp://' . $sftp . $remote_path, $data, true); - break; - case 'scp': - $file = tempnam($config['tmp'], 'tinyboard-scp'); - // Write to temp file - file_write($file, $data); - - ssh2_scp_send($this->connection, $file, $remote_path, 0755); - break; - default: - error('Unknown send method.'); - } + $methods = Array(); + + if(!isset($this->auth['method'])) + error('Unspecified authentication method.'); + + // Connect + $this->connection = ssh2_connect($this->host, isset($this->port) ? $this->port : 22, $methods); + + switch($this->auth['method']) { + case 'pubkey': + + if(!isset($this->auth['public'])) + error('Public key filename not specified.'); + if(!isset($this->auth['private'])) + error('Private key filename not specified.'); + + if(!ssh2_auth_pubkey_file($this->connection, $this->auth['username'], $this->auth['public'], $this->auth['private'], isset($this->auth['passphrase']) ? $this->auth['passphrase']: null)) + error('Public key authentication failed.'); + break; + case 'plain': + if(!ssh2_auth_password($this->connection, $this->auth['username'], $this->auth['password'])) + error('Plain-text authentication failed.'); + break; + default: + error('Unknown authentication method: "' . $this->auth['method'] . '".'); + } + + } + + public function write($data, $remote_path) { + global $config; + + switch($this->type) { + case 'sftp': + $sftp = ssh2_sftp($this->connection); + file_write('ssh2.sftp://' . $sftp . $remote_path, $data, true); + break; + case 'scp': + $file = tempnam($config['tmp'], 'tinyboard-scp'); + // Write to temp file + file_write($file, $data); + + ssh2_scp_send($this->connection, $file, $remote_path, 0755); + break; + default: + error('Unknown send method.'); } - }; -?> + } +}; + diff --git a/inc/template.php b/inc/template.php index 2a79f918..b348f153 100644 --- a/inc/template.php +++ b/inc/template.php @@ -1,57 +1,72 @@ <?php
- if($_SERVER['SCRIPT_FILENAME'] == str_replace('\\', '/', __FILE__)) {
- // You cannot request this file directly.
- header('Location: ../', true, 302);
- exit;
- }
+
+/*
+ * Copyright (c) 2010-2012 Tinyboard Development Group
+ */
+
+if(realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) {
+ // You cannot request this file directly.
+ exit;
+}
+
+$twig = false;
+
+function load_twig() {
+ global $twig, $config;
require 'lib/Twig/Autoloader.php';
Twig_Autoloader::register();
-
+
Twig_Autoloader::autoload('Twig_Extensions_Node_Trans');
Twig_Autoloader::autoload('Twig_Extensions_TokenParser_Trans');
Twig_Autoloader::autoload('Twig_Extensions_Extension_I18n');
Twig_Autoloader::autoload('Twig_Extensions_Extension_Tinyboard');
$loader = new Twig_Loader_Filesystem($config['dir']['template']);
+ $loader->setPaths($config['dir']['template']);
+ $twig = new Twig_Environment($loader, Array(
+ 'autoescape' => false,
+ 'cache' => "{$config['dir']['template']}/cache",
+ 'debug' => ($config['debug'] ? true : false),
+ ));
+ $twig->addExtension(new Twig_Extensions_Extension_Tinyboard());
+ $twig->addExtension(new Twig_Extensions_Extension_I18n());
+}
+
+function Element($templateFile, array $options) {
+ global $config, $debug, $twig;
- function Element($templateFile, array $options) {
- global $config, $debug, $loader;
-
- if(function_exists('create_pm_header') && ((isset($options['mod']) && $options['mod']) || isset($options['__mod']))) {
- $options['pm'] = create_pm_header();
+ if(!$twig)
+ load_twig();
+
+ if(function_exists('create_pm_header') && ((isset($options['mod']) && $options['mod']) || isset($options['__mod']))) {
+ $options['pm'] = create_pm_header();
+ }
+
+ if(isset($options['body']) && $config['debug']) {
+ if(isset($debug['start'])) {
+ $debug['time'] = '~' . round((microtime(true) - $debug['start']) * 1000, 2) . 'ms';
+ unset($debug['start']);
}
+ $debug['included'] = get_included_files();
+ $debug['memory'] = round(memory_get_usage(true) / (1024 * 1024), 2) . ' MiB';
+ $options['body'] .=
+ '<h3>Debug</h3><pre style="white-space: pre-wrap;font-size: 10px;">' .
+ str_replace("\n", '<br/>', utf8tohtml(print_r($debug, true))) .
+ '</pre>';
+ }
+
+ // Read the template file
+ if(@file_get_contents("{$config['dir']['template']}/${templateFile}")) {
+ $body = $twig->render($templateFile, $options);
- if(isset($options['body']) && $config['debug']) {
- if(isset($debug['start'])) {
- $debug['time'] = '~' . round((microtime(true) - $debug['start']) * 1000, 2) . 'ms';
- unset($debug['start']);
-
- }
- $options['body'] .= '<h3>Debug</h3><pre style="white-space: pre-wrap;font-size: 10px;">' . str_replace("\n", '<br/>', utf8tohtml(print_r($debug, true))) . '</pre>';
+ if($config['minify_html'] && preg_match('/\.html$/', $templateFile)) {
+ $body = trim(preg_replace("/[\t\r\n]/", '', $body));
}
- $loader->setPaths($config['dir']['template']);
-
- $twig = new Twig_Environment($loader, Array(
- 'autoescape' => false,
- 'cache' => "{$config['dir']['template']}/cache",
- 'debug' => ($config['debug'] ? true : false),
- ));
- $twig->addExtension(new Twig_Extensions_Extension_Tinyboard());
- $twig->addExtension(new Twig_Extensions_Extension_I18n());
-
- // Read the template file
- 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']}'!");
- }
+ return $body;
+ } else {
+ throw new Exception("Template file '${templateFile}' does not exist or is empty in '{$config['dir']['template']}'!");
}
-?>
+}
+
diff --git a/inc/user.php b/inc/user.php deleted file mode 100644 index 2c11ded0..00000000 --- a/inc/user.php +++ /dev/null @@ -1,10 +0,0 @@ -<?php - if($_SERVER['SCRIPT_FILENAME'] == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - header('Location: ../', true, 302); - exit; - } - - // 'false' means that the user is not logged in as a moderator - $mod = false; - |
