diff options
| author | czaks <marcin@6irc.net> | 2013-09-17 10:43:44 -0400 |
|---|---|---|
| committer | czaks <marcin@6irc.net> | 2013-09-17 10:43:44 -0400 |
| commit | 6cb7eb939e549f978ca6dd7d2afe2dabc0f18025 (patch) | |
| tree | 8b2342bbf5c15847717db733ecf4f2f46718dacb | |
| parent | 069f1def9bf8c8d769afdc5740e9ff13271065bd (diff) | |
| parent | 803f0c8ce1487ea791824197de9d1ee140127838 (diff) | |
Merge branch 'master' of https://github.com/savetheinternet/Tinyboard into vichan-devel-4.5
Conflicts:
inc/config.php
inc/display.php
inc/mod/pages.php
install.php
js/quick-reply.js
post.php
templates/index.html
46 files changed, 2978 insertions, 590 deletions
@@ -30,7 +30,7 @@ it need one. ### Recommended 1. PHP >= 5.3 2. MySQL server >= 5.5.3 -3. ImageMagick or command-line version (```convert``` and ```identify```) +3. ImageMagick (command-line ImageMagick or GraphicsMagick preferred). 4. [APC (Alternative PHP Cache)](http://php.net/manual/en/book.apc.php), [XCache](http://xcache.lighttpd.net/) or [Memcached](http://www.php.net/manual/en/intro.memcached.php) Contributing diff --git a/inc/anti-bot.php b/inc/anti-bot.php index 41e0a1d6..59f5351f 100644 --- a/inc/anti-bot.php +++ b/inc/anti-bot.php @@ -4,24 +4,26 @@ * Copyright (c) 2010-2013 Tinyboard Development Group */ -if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - exit; -} +defined('TINYBOARD') or exit; $hidden_inputs_twig = array(); class AntiBot { public $salt, $inputs = array(), $index = 0; - public static function randomString($length, $uppercase = false, $special_chars = false) { + public static function randomString($length, $uppercase = false, $special_chars = false, $unicode_chars = false) { $chars = 'abcdefghijklmnopqrstuvwxyz0123456789'; if ($uppercase) $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; if ($special_chars) $chars .= ' ~!@#$%^&*()_+,./;\'[]\\{}|:<>?=-` '; + if ($unicode_chars) { + $len = strlen($chars) / 10; + for ($n = 0; $n < $len; $n++) + $chars .= mb_convert_encoding('&#' . mt_rand(0x2600, 0x26FF) . ';', 'UTF-8', 'HTML-ENTITIES'); + } - $chars = str_split($chars); + $chars = preg_split('//u', $chars, -1, PREG_SPLIT_NO_EMPTY); $ch = array(); @@ -44,10 +46,10 @@ class AntiBot { } public static function make_confusing($string) { - $chars = str_split($string); + $chars = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY); foreach ($chars as &$c) { - if (rand(0, 2) != 0) + if (mt_rand(0, 3) != 0) $c = utf8tohtml($c); else $c = mb_encode_numericentity($c, array(0, 0xffff, 0, 0xffff), 'UTF-8'); @@ -68,13 +70,13 @@ class AntiBot { shuffle($config['spam']['hidden_input_names']); - $input_count = rand($config['spam']['hidden_inputs_min'], $config['spam']['hidden_inputs_max']); + $input_count = mt_rand($config['spam']['hidden_inputs_min'], $config['spam']['hidden_inputs_max']); $hidden_input_names_x = 0; for ($x = 0; $x < $input_count ; $x++) { - if ($hidden_input_names_x === false || rand(0, 2) == 0) { + if ($hidden_input_names_x === false || mt_rand(0, 2) == 0) { // Use an obscure name - $name = $this->randomString(rand(10, 40)); + $name = $this->randomString(mt_rand(10, 40), false, false, $config['spam']['unicode']); } else { // Use a pre-defined confusing name $name = $config['spam']['hidden_input_names'][$hidden_input_names_x++]; @@ -82,25 +84,33 @@ class AntiBot { $hidden_input_names_x = false; } - if (rand(0, 2) == 0) { + if (mt_rand(0, 2) == 0) { // Value must be null $this->inputs[$name] = ''; - } elseif (rand(0, 4) == 0) { + } elseif (mt_rand(0, 4) == 0) { // Numeric value - $this->inputs[$name] = (string)rand(0, 100); + $this->inputs[$name] = (string)mt_rand(0, 100000); } else { // Obscure value - $this->inputs[$name] = $this->randomString(rand(5, 100), true, true); + $this->inputs[$name] = $this->randomString(mt_rand(5, 100), true, true, $config['spam']['unicode']); } } } + public static function space() { + if (mt_rand(0, 3) != 0) + return ' '; + return str_repeat(' ', mt_rand(1, 3)); + } + public function html($count = false) { global $config; $elements = array( '<input type="hidden" name="%name%" value="%value%">', '<input type="hidden" value="%value%" name="%name%">', + '<input name="%name%" value="%value%" type="hidden">', + '<input value="%value%" name="%name%" type="hidden">', '<input style="display:none" type="text" name="%name%" value="%value%">', '<input style="display:none" type="text" value="%value%" name="%name%">', '<span style="display:none"><input type="text" name="%name%" value="%value%"></span>', @@ -113,7 +123,7 @@ class AntiBot { $html = ''; if ($count === false) { - $count = rand(1, count($this->inputs) / 15); + $count = mt_rand(1, abs(count($this->inputs) / 15) + 1); } if ($count === true) { @@ -128,6 +138,9 @@ class AntiBot { $element = false; while (!$element) { $element = $elements[array_rand($elements)]; + $element = str_replace(' ', self::space(), $element); + if (mt_rand(0, 5) == 0) + $element = str_replace('>', self::space() . '>', $element); if (strpos($element, 'textarea') !== false && $value == '') { // There have been some issues with mobile web browsers and empty <textarea>'s. $element = false; @@ -136,7 +149,7 @@ class AntiBot { $element = str_replace('%name%', utf8tohtml($name), $element); - if (rand(0, 2) == 0) + if (mt_rand(0, 2) == 0) $value = $this->make_confusing($value); else $value = utf8tohtml($value); diff --git a/inc/api.php b/inc/api.php index a8331590..74043912 100644 --- a/inc/api.php +++ b/inc/api.php @@ -3,6 +3,7 @@ * Copyright (c) 2010-2013 Tinyboard Development Group */ +defined('TINYBOARD') or exit; /** * Class for generating json API compatible with 4chan API diff --git a/inc/bans.php b/inc/bans.php new file mode 100644 index 00000000..652d42cc --- /dev/null +++ b/inc/bans.php @@ -0,0 +1,258 @@ +<?php + +require 'inc/lib/IP/Lifo/IP/IP.php'; +require 'inc/lib/IP/Lifo/IP/BC.php'; +require 'inc/lib/IP/Lifo/IP/CIDR.php'; + +use Lifo\IP\CIDR; + +class Bans { + static public function range_to_string($mask) { + list($ipstart, $ipend) = $mask; + + if (!isset($ipend) || $ipend === false) { + // Not a range. Single IP address. + $ipstr = inet_ntop($ipstart); + return $ipstr; + } + + if (strlen($ipstart) != strlen($ipend)) + return '???'; // What the fuck are you doing, son? + + $range = CIDR::range_to_cidr(inet_ntop($ipstart), inet_ntop($ipend)); + if ($range !== false) + return $range; + + return '???'; + } + + private static function calc_cidr($mask) { + $cidr = new CIDR($mask); + $range = $cidr->getRange(); + + return array(inet_pton($range[0]), inet_pton($range[1])); + } + + private static function parse_time($str) { + if (empty($str)) + return false; + + if (($time = @strtotime($str)) !== false) + return $time; + + if (!preg_match('/^((\d+)\s?ye?a?r?s?)?\s?+((\d+)\s?mon?t?h?s?)?\s?+((\d+)\s?we?e?k?s?)?\s?+((\d+)\s?da?y?s?)?((\d+)\s?ho?u?r?s?)?\s?+((\d+)\s?mi?n?u?t?e?s?)?\s?+((\d+)\s?se?c?o?n?d?s?)?$/', $str, $matches)) + return false; + + $expire = 0; + + if (isset($matches[2])) { + // Years + $expire += $matches[2]*60*60*24*365; + } + if (isset($matches[4])) { + // Months + $expire += $matches[4]*60*60*24*30; + } + if (isset($matches[6])) { + // Weeks + $expire += $matches[6]*60*60*24*7; + } + if (isset($matches[8])) { + // Days + $expire += $matches[8]*60*60*24; + } + if (isset($matches[10])) { + // Hours + $expire += $matches[10]*60*60; + } + if (isset($matches[12])) { + // Minutes + $expire += $matches[12]*60; + } + if (isset($matches[14])) { + // Seconds + $expire += $matches[14]; + } + + return time() + $expire; + } + + static public function parse_range($mask) { + $ipstart = false; + $ipend = false; + + if (preg_match('@^(\d{1,3}\.){1,3}([\d*]{1,3})?$@', $mask) && substr_count($mask, '*') == 1) { + // IPv4 wildcard mask + $parts = explode('.', $mask); + $ipv4 = ''; + foreach ($parts as $part) { + if ($part == '*') { + $ipstart = inet_pton($ipv4 . '0' . str_repeat('.0', 3 - substr_count($ipv4, '.'))); + $ipend = inet_pton($ipv4 . '255' . str_repeat('.255', 3 - substr_count($ipv4, '.'))); + break; + } elseif(($wc = strpos($part, '*')) !== false) { + $ipstart = inet_pton($ipv4 . substr($part, 0, $wc) . '0' . str_repeat('.0', 3 - substr_count($ipv4, '.'))); + $ipend = inet_pton($ipv4 . substr($part, 0, $wc) . '9' . str_repeat('.255', 3 - substr_count($ipv4, '.'))); + break; + } + $ipv4 .= "$part."; + } + } elseif (preg_match('@^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d+$@', $mask)) { + list($ipv4, $bits) = explode('/', $mask); + if ($bits > 32) + return false; + + list($ipstart, $ipend) = self::calc_cidr($mask); + } elseif (preg_match('@^[:a-z\d]+/\d+$@i', $mask)) { + list($ipv6, $bits) = explode('/', $mask); + if ($bits > 128) + return false; + + list($ipstart, $ipend) = self::calc_cidr($mask); + } else { + if (($ipstart = @inet_pton($mask)) === false) + return false; + } + + return array($ipstart, $ipend); + } + + static public function find($ip, $board = false, $get_mod_info = false) { + global $config; + + $query = prepare('SELECT ``bans``.*' . ($get_mod_info ? ', `username`' : '') . ' FROM ``bans`` + ' . ($get_mod_info ? 'LEFT JOIN ``mods`` ON ``mods``.`id` = `creator`' : '') . ' + WHERE + (' . ($board ? '(`board` IS NULL OR `board` = :board) AND' : '') . ' + (`ipstart` = :ip OR (:ip >= `ipstart` AND :ip <= `ipend`))) + ORDER BY `expires` IS NULL, `expires` DESC'); + + if ($board) + $query->bindValue(':board', $board); + + $query->bindValue(':ip', inet_pton($ip)); + $query->execute() or error(db_error($query)); + + $ban_list = array(); + + while ($ban = $query->fetch(PDO::FETCH_ASSOC)) { + if ($ban['expires'] && ($ban['seen'] || !$config['require_ban_view']) && $ban['expires'] < time()) { + $query = prepare("DELETE FROM ``bans`` WHERE `id` = :id"); + $query->bindValue(':id', $ban['id'], PDO::PARAM_INT); + $query->execute() or error(db_error($query)); + } else { + $ban['mask'] = self::range_to_string(array($ban['ipstart'], $ban['ipend'])); + $ban_list[] = $ban; + } + } + + return $ban_list; + } + + static public function list_all($offset = 0, $limit = 9001) { + $offset = (int)$offset; + $limit = (int)$limit; + + $query = query("SELECT ``bans``.*, `username` FROM ``bans`` + LEFT JOIN ``mods`` ON ``mods``.`id` = `creator` + ORDER BY `created` DESC LIMIT $offset, $limit") or error(db_error()); + $bans = $query->fetchAll(PDO::FETCH_ASSOC); + + foreach ($bans as &$ban) { + $ban['mask'] = self::range_to_string(array($ban['ipstart'], $ban['ipend'])); + } + + return $bans; + } + + static public function count() { + $query = query("SELECT COUNT(*) FROM ``bans``") or error(db_error()); + return (int)$query->fetchColumn(); + } + + static public function seen($ban_id) { + $query = query("UPDATE ``bans`` SET `seen` = 1 WHERE `id` = " . (int)$ban_id) or error(db_error()); + } + + static public function purge() { + $query = query("DELETE FROM ``bans`` WHERE `expires` IS NOT NULL AND `expires` < " . time() . " AND `seen` = 1") or error(db_error()); + } + + static public function delete($ban_id, $modlog = false) { + if ($modlog) { + $query = query("SELECT `ipstart`, `ipend` FROM ``bans`` WHERE `id` = " . (int)$ban_id) or error(db_error()); + if (!$ban = $query->fetch(PDO::FETCH_ASSOC)) { + // Ban doesn't exist + return false; + } + + $mask = self::range_to_string(array($ban['ipstart'], $ban['ipend'])); + + modLog("Removed ban #{$ban_id} for " . + (filter_var($mask, FILTER_VALIDATE_IP) !== false ? "<a href=\"?/IP/$mask\">$mask</a>" : $mask)); + } + + query("DELETE FROM ``bans`` WHERE `id` = " . (int)$ban_id) or error(db_error()); + + return true; + } + + static public function new_ban($mask, $reason, $length = false, $board = false, $mod_id = false) { + global $mod, $pdo; + + if ($mod_id === false) { + $mod_id = isset($mod['id']) ? $mod['id'] : -1; + } + + $range = self::parse_range($mask); + $mask = self::range_to_string($range); + + $query = prepare("INSERT INTO ``bans`` VALUES (NULL, :ipstart, :ipend, :time, :expires, :board, :mod, :reason, 0, NULL)"); + + $query->bindValue(':ipstart', $range[0]); + if ($range[1] !== false && $range[1] != $range[0]) + $query->bindValue(':ipend', $range[1]); + else + $query->bindValue(':ipend', null, PDO::PARAM_NULL); + + $query->bindValue(':mod', $mod_id); + $query->bindValue(':time', time()); + + if ($reason !== '') { + $reason = escape_markup_modifiers($reason); + markup($reason); + $query->bindValue(':reason', $reason); + } else + $query->bindValue(':reason', null, PDO::PARAM_NULL); + + if ($length) { + if (is_int($length) || ctype_digit($length)) { + $length = time() + $length; + } else { + $length = self::parse_time($length); + } + $query->bindValue(':expires', $length); + } else { + $query->bindValue(':expires', null, PDO::PARAM_NULL); + } + + if ($board) + $query->bindValue(':board', $board); + else + $query->bindValue(':board', null, PDO::PARAM_NULL); + + $query->execute() or error(db_error($query)); + + if (isset($mod['id']) && $mod['id'] == $mod_id) { + modLog('Created a new ' . + ($length > 0 ? preg_replace('/^(\d+) (\w+?)s?$/', '$1-$2', until($length)) : 'permanent') . + ' ban on ' . + ($board ? '/' . $board . '/' : 'all boards') . + ' for ' . + (filter_var($mask, FILTER_VALIDATE_IP) !== false ? "<a href=\"?/IP/$mask\">$mask</a>" : $mask) . + ' (<small>#' . $pdo->lastInsertId() . '</small>)' . + ' with ' . ($reason ? 'reason: ' . utf8tohtml($reason) . '' : 'no reason')); + } + return $pdo->lastInsertId(); + } +} diff --git a/inc/cache.php b/inc/cache.php index 2f3c746c..d1200919 100644 --- a/inc/cache.php +++ b/inc/cache.php @@ -4,10 +4,7 @@ * Copyright (c) 2010-2013 Tinyboard Development Group */ -if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - exit; -} +defined('TINYBOARD') or exit; class Cache { private static $cache; @@ -135,7 +132,7 @@ class Cache { case 'apc': return apc_clear_cache('user'); case 'php': - self::$cache[$key] = array(); + self::$cache = array(); break; case 'redis': if (!self::$cache) diff --git a/inc/config.php b/inc/config.php index fddeae9a..2a17edfa 100644 --- a/inc/config.php +++ b/inc/config.php @@ -44,6 +44,8 @@ $config['debug'] = false; // For development purposes. Displays (and "dies" on) all errors and warnings. Turn on with the above. $config['verbose_errors'] = true; + // EXPLAIN all SQL queries (when in debug mode). + $config['debug_explain'] = false; // Directory where temporary files will be created. $config['tmp'] = sys_get_temp_dir(); @@ -168,13 +170,6 @@ * ==================== */ - // Minimum time between between each post by the same IP address. - $config['flood_time'] = 10; - // Minimum time between between each post with the exact same content AND same IP address. - $config['flood_time_ip'] = 120; - // Same as above but by a different IP address. (Same content, not necessarily same IP address.) - $config['flood_time_same'] = 30; - /* * To further prevent spam and abuse, you can use DNS blacklists (DNSBL). A DNSBL is a list of IP * addresses published through the Internet Domain Name Service (DNS) either as a zone file that can be @@ -237,6 +232,9 @@ // How soon after regeneration do hashes expire (in seconds)? $config['spam']['hidden_inputs_expire'] = 60 * 60 * 3; // three hours + + // Whether to use Unicode characters in hidden input names and values. + $config['spam']['unicode'] = true; // 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( @@ -274,6 +272,7 @@ 'quick-reply', 'page', 'file_url', + 'json_response', ); // Enable reCaptcha to make spam even harder. Rarely necessary. @@ -283,6 +282,132 @@ $config['recaptcha_public'] = '6LcXTcUSAAAAAKBxyFWIt2SO8jwx4W7wcSMRoN3f'; $config['recaptcha_private'] = '6LcXTcUSAAAAAOGVbVdhmEM1_SyRF4xTKe8jbzf_'; + /* + * Custom filters detect certain posts and reject/ban accordingly. They are made up of a condition and an + * action (for when ALL conditions are met). As every single post has to be put through each filter, + * having hundreds probably isn't ideal as it could slow things down. + * + * By default, the custom filters array is populated with basic flood prevention conditions. This + * includes forcing users to wait at least 5 seconds between posts. To disable (or amend) these flood + * prevention settings, you will need to empty the $config['filters'] array first. You can do so by + * adding "$config['filters'] = array();" to inc/instance-config.php. Basic flood prevention used to be + * controlled solely by config variables such as $config['flood_time'] and $config['flood_time_ip'], and + * it still is, as long as you leave the relevant $config['filters'] intact. These old config variables + * still exist for backwards-compatability and general convenience. + * + * Read more: http://tinyboard.org/docs/index.php?p=Config/Filters + */ + + // Minimum time between between each post by the same IP address. + $config['flood_time'] = 10; + // Minimum time between between each post with the exact same content AND same IP address. + $config['flood_time_ip'] = 120; + // Same as above but by a different IP address. (Same content, not necessarily same IP address.) + $config['flood_time_same'] = 30; + + // Minimum time between posts by the same IP address (all boards). + $config['filters'][] = array( + 'condition' => array( + 'flood-match' => array('ip'), // Only match IP address + 'flood-time' => &$config['flood_time'] + ), + 'action' => 'reject', + 'message' => &$config['error']['flood'] + ); + + // Minimum time between posts by the same IP address with the same text. + $config['filters'][] = array( + 'condition' => array( + 'flood-match' => array('ip', 'body'), // Match IP address and post body + 'flood-time' => &$config['flood_time_ip'], + '!body' => '/^$/', // Post body is NOT empty + ), + 'action' => 'reject', + 'message' => &$config['error']['flood'] + ); + + // Minimum time between posts with the same text. (Same content, but not always the same IP address.) + $config['filters'][] = array( + 'condition' => array( + 'flood-match' => array('body'), // Match only post body + 'flood-time' => &$config['flood_time_same'] + ), + 'action' => 'reject', + 'message' => &$config['error']['flood'] + ); + + // Example: Minimum time between posts with the same file hash. + // $config['filters'][] = array( + // 'condition' => array( + // 'flood-match' => array('file'), // Match file hash + // 'flood-time' => 60 * 2 // 2 minutes minimum + // ), + // 'action' => 'reject', + // 'message' => &$config['error']['flood'] + // ); + + // Example: Use the "flood-count" condition to only match if the user has made at least two posts with + // the same content and IP address in the past 2 minutes. + // $config['filters'][] = array( + // 'condition' => array( + // 'flood-match' => array('ip', 'body'), // Match IP address and post body + // 'flood-time' => 60 * 2, // 2 minutes + // 'flood-count' => 2 // At least two recent posts + // ), + // '!body' => '/^$/', + // 'action' => 'reject', + // 'message' => &$config['error']['flood'] + // ); + + // Example: Blocking an imaginary known spammer, who keeps posting a reply with the name "surgeon", + // ending his posts with "regards, the surgeon" or similar. + // $config['filters'][] = array( + // 'condition' => array( + // 'name' => '/^surgeon$/', + // 'body' => '/regards,\s+(the )?surgeon$/i', + // 'OP' => false + // ), + // 'action' => 'reject', + // 'message' => 'Go away, spammer.' + // ); + + // Example: Same as above, but issuing a 3-hour ban instead of just reject the post. + // $config['filters'][] = array( + // 'condition' => array( + // 'name' => '/^surgeon$/', + // 'body' => '/regards,\s+(the )?surgeon$/i', + // 'OP' => false + // ), + // 'action' => 'ban', + // 'expires' => 60 * 60 * 3, // 3 hours + // 'reason' => 'Go away, spammer.' + // ); + + // Example: PHP 5.3+ (anonymous functions) + // There is also a "custom" condition, making the possibilities of this feature pretty much endless. + // This is a bad example, because there is already a "name" condition built-in. + // $config['filters'][] = array( + // 'condition' => array( + // 'body' => '/h$/i', + // 'OP' => false, + // 'custom' => function($post) { + // if($post['name'] == 'Anonymous') + // return true; + // else + // return false; + // } + // ), + // 'action' => 'reject' + // ); + + // Filter flood prevention conditions ("flood-match") depend on a table which contains a cache of recent + // posts across all boards. This table is automatically purged of older posts, determining the maximum + // "age" by looking at each filter. However, when determining the maximum age, Tinyboard does not look + // outside the current board. This means that if you have a special flood condition for a specific board + // (contained in a board configuration file) which has a flood-time greater than any of those in the + // global configuration, you need to set the following variable to the maximum flood-time condition value. + // $config['flood_cache'] = 60 * 60 * 24; // 24 hours + /* * ==================== * Post settings @@ -406,57 +531,6 @@ // Require users to see the ban page at least once for a ban even if it has since expired. $config['require_ban_view'] = true; - /* - * Custom filters detect certain posts and reject/ban accordingly. They are made up of a - * condition and an action (for when ALL conditions are met). As every single post has to - * be put through each filter, having hundreds probably isn’t ideal as it could slow things down. - * - * Read more: http://tinyboard.org/docs/index.php?p=Config/Filters - * - * This used to be named $config['flood_filters'] (still exists as an alias). - */ - - // An example of blocking an imaginary known spammer, who keeps posting a reply with the name "surgeon", - // ending his posts with "regards, the surgeon" or similar. - // $config['filters'][] = array( - // 'condition' => array( - // 'name' => '/^surgeon$/', - // 'body' => '/regards,\s+(the )?surgeon$/i', - // 'OP' => false - // ), - // 'action' => 'reject', - // 'message' => 'Go away, spammer.' - // ); - - // Same as above, but issuing a 3-hour ban instead of just reject the post. - // $config['filters'][] = array( - // 'condition' => array( - // 'name' => '/^surgeon$/', - // 'body' => '/regards,\s+(the )?surgeon$/i', - // 'OP' => false - // ), - // 'action' => 'ban', - // 'expires' => 60 * 60 * 3, // 3 hours - // 'reason' => 'Go away, spammer.' - // ); - - // PHP 5.3+ (anonymous functions) - // There is also a "custom" condition, making the possibilities of this feature pretty much endless. - // This is a bad example, because there is already a "name" condition built-in. - // $config['filters'][] = array( - // 'condition' => array( - // 'body' => '/h$/i', - // 'OP' => false, - // 'custom' => function($post) { - // if($post['name'] == 'Anonymous') - // return true; - // else - // return false; - // } - // ), - // 'action' => 'reject' - // ); - /* * ==================== * Markup settings @@ -598,10 +672,6 @@ // that as a thumbnail instead of resizing/redrawing. $config['minimum_copy_resize'] = false; - // Image hashing function. There's really no reason to change this. - // sha1_file, md5_file, etc. You can also define your own similar function. - $config['file_hash'] = 'sha1_file'; - // Maximum image upload size in bytes. $config['max_filesize'] = 10 * 1024 * 1024; // 10MB // Maximum image dimensions. @@ -752,6 +822,12 @@ // Whether or not to put brackets around the whole board list $config['boardlist_wrap_bracket'] = false; + // Show page navigation links at the top as well. + $config['page_nav_top'] = false; + + // Show "Catalog" link in page navigation. Use with the Catalog theme. + // $config['catalog_link'] = 'catalog.html'; + // Board categories. Only used in the "Categories" theme. // $config['categories'] = array( // 'Group Name' => array('a', 'b', 'c'), @@ -1010,8 +1086,8 @@ * ==================== */ - // Limit how many bans can be removed via the ban list. Set to -1 for no limit. - $config['mod']['unban_limit'] = -1; + // Limit how many bans can be removed via the ban list. Set to false (or zero) for no limit. + $config['mod']['unban_limit'] = false; // Whether or not to lock moderator sessions to IP addresses. This makes cookie theft ineffective. $config['mod']['lock_ip'] = true; @@ -1056,14 +1132,6 @@ // 'color:red;font-weight:bold' // Change tripcode style; optional //); - // Enable IP range bans (eg. "127.*.0.1", "127.0.0.*", and "12*.0.0.1" all match "127.0.0.1"). Puts a - // little more load on the database - $config['ban_range'] = true; - - // Enable CDIR netmask bans (eg. "10.0.0.0/8" for 10.0.0.0.0 - 10.255.255.255). Useful for stopping - // persistent spammers and ban evaders. Again, a little more database load. - $config['ban_cidr'] = true; - // Enable the moving of single replies $config['move_replies'] = false; @@ -1130,18 +1198,28 @@ * ==================== */ - // Probably best not to change these: - if (!defined('JANITOR')) { - define('JANITOR', 0, true); - define('MOD', 1, true); - define('ADMIN', 2, true); - define('DISABLED', 3, true); - } + // Probably best not to change this unless you are smart enough to figure out what you're doing. If you + // decide to change it, remember that it is impossible to redefinite/overwrite groups; you may only add + // new ones. + $config['mod']['groups'] = array( + 10 => 'Janitor', + 20 => 'Mod', + 30 => 'Admin', + // 98 => 'God', + 99 => 'Disabled' + ); + + // If you add stuff to the above, you'll need to call this function immediately after. + define_groups(); + + // Example: Adding a new permissions group. + // $config['mod']['groups'][0] = 'NearlyPowerless'; + // define_groups(); // Capcode permissions. $config['mod']['capcode'] = array( // JANITOR => array('Janitor'), - MOD => array('Mod'), + MOD => array('Mod'), ADMIN => true ); @@ -1193,7 +1271,8 @@ // Post bypass unoriginal content check on robot-enabled boards $config['mod']['postunoriginal'] = ADMIN; // Bypass flood check - $config['mod']['flood'] = ADMIN; + $config['mod']['bypass_filters'] = ADMIN; + $config['mod']['flood'] = &$config['mod']['bypass_filters']; // Raw HTML posting $config['mod']['rawhtml'] = ADMIN; @@ -1279,18 +1358,14 @@ $config['mod']['edit_config'] = ADMIN; // Config editor permissions - $config['mod']['config'] = array( - JANITOR => false, - MOD => false, - ADMIN => false, - DISABLED => false, - ); + $config['mod']['config'] = array(); // Disable the following configuration variables from being changed via ?/config. The following default // banned variables are considered somewhat dangerous. $config['mod']['config'][DISABLED] = array( 'mod>config', 'mod>config_editor_php', + 'mod>groups', 'convert_args', 'db>password', ); @@ -1421,6 +1496,3 @@ // is the absolute maximum, because MySQL cannot handle table names greater than 64 characters. $config['board_regex'] = '[0-9a-zA-Z$_\x{0080}-\x{FFFF}]{1,58}'; - // Regex for URLs. - $config['url_regex'] = '@^(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))$@'; - diff --git a/inc/database.php b/inc/database.php index 55e1ff81..84a050f2 100644 --- a/inc/database.php +++ b/inc/database.php @@ -4,27 +4,32 @@ * Copyright (c) 2010-2013 Tinyboard Development Group */ -if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - exit; -} +defined('TINYBOARD') or exit; class PreparedQueryDebug { - protected $query; + protected $query, $explain_query = false; public function __construct($query) { - global $pdo; + global $pdo, $config; $query = preg_replace("/[\n\t]+/", ' ', $query); $this->query = $pdo->prepare($query); + if ($config['debug'] && $config['debug_explain'] && preg_match('/^(SELECT|INSERT|UPDATE|DELETE) /i', $query)) + $this->explain_query = $pdo->prepare("EXPLAIN $query"); } public function __call($function, $args) { global $config, $debug; if ($config['debug'] && $function == 'execute') { + if ($this->explain_query) { + $this->explain_query->execute() or error(db_error($this->explain_query)); + } $start = microtime(true); } + if ($this->explain_query && $function == 'bindValue') + call_user_func_array(array($this->explain_query, $function), $args); + $return = call_user_func_array(array($this->query, $function), $args); if ($config['debug'] && $function == 'execute') { @@ -32,6 +37,7 @@ class PreparedQueryDebug { $debug['sql'][] = array( 'query' => $this->query->queryString, 'rows' => $this->query->rowCount(), + 'explain' => $this->explain_query ? $this->explain_query->fetchAll(PDO::FETCH_ASSOC) : null, 'time' => '~' . round($time * 1000, 2) . 'ms' ); $debug['time']['db_queries'] += $time; @@ -121,6 +127,9 @@ function query($query) { sql_open(); if ($config['debug']) { + if ($config['debug_explain'] && preg_match('/^(SELECT|INSERT|UPDATE|DELETE) /i', $query)) { + $explain = $pdo->query("EXPLAIN $query") or error(db_error()); + } $start = microtime(true); $query = $pdo->query($query); if (!$query) @@ -129,6 +138,7 @@ function query($query) { $debug['sql'][] = array( 'query' => $query->queryString, 'rows' => $query->rowCount(), + 'explain' => isset($explain) ? $explain->fetchAll(PDO::FETCH_ASSOC) : null, 'time' => '~' . round($time * 1000, 2) . 'ms' ); $debug['time']['db_queries'] += $time; diff --git a/inc/display.php b/inc/display.php index 736fdc03..6f42cdf9 100644 --- a/inc/display.php +++ b/inc/display.php @@ -88,6 +88,14 @@ function error($message, $priority = true, $debug_stuff = false) { // Return the bad request header, necessary for AJAX posts header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request'); + // Is there a reason to disable this? + if (isset($_POST['json_response'])) { + header('Content-Type: text/json; charset=utf-8'); + die(json_encode(array( + 'error' => $message + ))); + } + die(Element('page.html', array( 'config' => $config, 'title' => _('Error'), @@ -536,6 +544,8 @@ class Thread { $hasnoko50 = $this->postCount() >= $config['noko50_min']; + event('show-thread', $this); + $built = Element('post_thread.html', array('config' => $config, 'board' => $board, 'post' => &$this, 'index' => $index, 'hasnoko50' => $hasnoko50, 'isnoko50' => $isnoko50)); return $built; diff --git a/inc/events.php b/inc/events.php index cc330dfb..e5a1e036 100644 --- a/inc/events.php +++ b/inc/events.php @@ -4,10 +4,7 @@ * Copyright (c) 2010-2013 Tinyboard Development Group */ -if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - exit; -} +defined('TINYBOARD') or exit; function event() { global $events; diff --git a/inc/filters.php b/inc/filters.php index cd512821..f06154ba 100644 --- a/inc/filters.php +++ b/inc/filters.php @@ -4,12 +4,10 @@ * Copyright (c) 2010-2013 Tinyboard Development Group */ -if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - exit; -} +defined('TINYBOARD') or exit; class Filter { + public $flood_check; private $condition; public function __construct(array $arr) { @@ -25,6 +23,64 @@ class Filter { if (!is_callable($match)) error('Custom condition for filter is not callable!'); return $match($post); + case 'flood-match': + if (!is_array($match)) + error('Filter condition "flood-match" must be an array.'); + + // Filter out "flood" table entries which do not match this filter. + + $flood_check_matched = array(); + + foreach ($this->flood_check as $flood_post) { + foreach ($match as $flood_match_arg) { + switch ($flood_match_arg) { + case 'ip': + if ($flood_post['ip'] != $_SERVER['REMOTE_ADDR']) + continue 3; + break; + case 'body': + if ($flood_post['posthash'] != make_comment_hex($post['body_nomarkup'])) + continue 3; + break; + case 'file': + if (!isset($post['filehash'])) + return false; + if ($flood_post['filehash'] != $post['filehash']) + continue 3; + break; + case 'board': + if ($flood_post['board'] != $post['board']) + continue 3; + break; + case 'isreply': + if ($flood_post['isreply'] == $post['op']) + continue 3; + break; + default: + error('Invalid filter flood condition: ' . $flood_match_arg); + } + } + $flood_check_matched[] = $flood_post; + } + + $this->flood_check = $flood_check_matched; + + return !empty($this->flood_check); + case 'flood-time': + foreach ($this->flood_check as $flood_post) { + if (time() - $flood_post['time'] <= $match) { + return true; + } + } + return false; + case 'flood-count': + $count = 0; + foreach ($this->flood_check as $flood_post) { + if (time() - $flood_post['time'] <= $this->condition['flood-time']) { + ++$count; + } + } + return $count >= $match; case 'name': return preg_match($match, $post['name']); case 'trip': @@ -34,7 +90,7 @@ class Filter { case 'subject': return preg_match($match, $post['subject']); case 'body': - return preg_match($match, $post['body']); + return preg_match($match, $post['body_nomarkup']); case 'filename': if (!$post['has_file']) return false; @@ -59,52 +115,18 @@ class Filter { switch($this->action) { case 'reject': - error(isset($this->message) ? $this->message : 'Posting throttled by flood filter.'); + error(isset($this->message) ? $this->message : 'Posting throttled by filter.'); case 'ban': if (!isset($this->reason)) error('The ban action requires a reason.'); - $reason = $this->reason; - - if (isset($this->expires)) - $expires = time() + $this->expires; - else - $expires = 0; // Ban indefinitely - - if (isset($this->reject)) - $reject = $this->reject; - else - $reject = true; - - if (isset($this->all_boards)) - $all_boards = $this->all_boards; - else - $all_boards = false; - - $query = prepare("INSERT INTO ``bans`` VALUES (NULL, :ip, :mod, :set, :expires, :reason, :board, 0)"); - $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); - $query->bindValue(':mod', -1); - $query->bindValue(':set', time()); - - if ($expires) - $query->bindValue(':expires', $expires); - else - $query->bindValue(':expires', null, PDO::PARAM_NULL); - - if ($reason) - $query->bindValue(':reason', $reason); - else - $query->bindValue(':reason', null, PDO::PARAM_NULL); - - - if ($all_boards) - $query->bindValue(':board', null, PDO::PARAM_NULL); - else - $query->bindValue(':board', $board['uri']); + $this->expires = isset($this->expires) ? $this->expires : false; + $this->reject = isset($this->reject) ? $this->reject : true; + $this->all_boards = isset($this->all_boards) ? $this->all_boards : false; - $query->execute() or error(db_error($query)); + Bans::new_ban($_SERVER['REMOTE_ADDR'], $this->reason, $this->expires, $this->all_boards ? false : $board['uri'], -1); - if ($reject) { + if ($this->reject) { if (isset($this->message)) error($message); @@ -120,25 +142,77 @@ class Filter { public function check(array $post) { foreach ($this->condition as $condition => $value) { - if (!$this->match($post, $condition, $value)) + if ($condition[0] == '!') { + $NOT = true; + $condition = substr($condition, 1); + } else $NOT = false; + + if ($this->match($post, $condition, $value) == $NOT) return false; } - - /* match */ return true; } } +function purge_flood_table() { + global $config; + + // Determine how long we need to keep a cache of posts for flood prevention. Unfortunately, it is not + // aware of flood filters in other board configurations. You can solve this problem by settings the + // config variable $config['flood_cache'] (seconds). + + if (isset($config['flood_cache'])) { + $max_time = &$config['flood_cache']; + } else { + $max_time = 0; + foreach ($config['filters'] as $filter) { + if (isset($filter['condition']['flood-time'])) + $max_time = max($max_time, $filter['condition']['flood-time']); + } + } + + $time = time() - $max_time; + + query("DELETE FROM ``flood`` WHERE `time` < $time") or error(db_error()); +} + function do_filters(array $post) { global $config; - if (!isset($config['filters'])) + if (!isset($config['filters']) || empty($config['filters'])) return; - foreach ($config['filters'] as $arr) { - $filter = new Filter($arr); + foreach ($config['filters'] as $filter) { + if (isset($filter['condition']['flood-match'])) { + $has_flood = true; + break; + } + } + + if (isset($has_flood)) { + if ($post['has_file']) { + $query = prepare("SELECT * FROM ``flood`` WHERE `ip` = :ip OR `posthash` = :posthash OR `filehash` = :filehash"); + $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); + $query->bindValue(':posthash', make_comment_hex($post['body_nomarkup'])); + $query->bindValue(':filehash', $post['filehash']); + } else { + $query = prepare("SELECT * FROM ``flood`` WHERE `ip` = :ip OR `posthash` = :posthash"); + $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); + $query->bindValue(':posthash', make_comment_hex($post['body_nomarkup'])); + } + $query->execute() or error(db_error($query)); + $flood_check = $query->fetchAll(PDO::FETCH_ASSOC); + } else { + $flood_check = false; + } + + foreach ($config['filters'] as $filter_array) { + $filter = new Filter($filter_array); + $filter->flood_check = $flood_check; if ($filter->check($post)) $filter->action(); } + + purge_flood_table(); } diff --git a/inc/functions.php b/inc/functions.php index 40053133..ac74ac91 100644 --- a/inc/functions.php +++ b/inc/functions.php @@ -9,6 +9,8 @@ if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { exit; } +define('TINYBOARD', null); + $microtime_start = microtime(true); require_once 'inc/display.php'; @@ -16,6 +18,7 @@ require_once 'inc/template.php'; require_once 'inc/database.php'; require_once 'inc/events.php'; require_once 'inc/api.php'; +require_once 'inc/bans.php'; require_once 'inc/lib/gettext/gettext.inc'; // the user is not currently logged in as a moderator @@ -92,7 +95,7 @@ function loadConfig() { if (!isset($config['referer_match'])) if (isset($_SERVER['HTTP_HOST'])) { $config['referer_match'] = '/^' . - (preg_match($config['url_regex'], $config['root']) ? '' : + (preg_match('@^https?://@', $config['root']) ? '' : 'https?:\/\/' . $_SERVER['HTTP_HOST']) . preg_quote($config['root'], '/') . '(' . @@ -266,6 +269,15 @@ function verbose_error_handler($errno, $errstr, $errfile, $errline) { )); } +function define_groups() { + global $config; + + foreach ($config['mod']['groups'] as $group_value => $group_name) + defined($group_name) or define($group_name, $group_value, true); + + ksort($config['mod']['groups']); +} + function create_antibot($board, $thread = null) { require_once dirname(__FILE__) . '/anti-bot.php'; @@ -573,30 +585,6 @@ function listBoards() { return $boards; } -function checkFlood($post) { - global $board, $config; - - $query = prepare(sprintf("SELECT COUNT(*) FROM ``posts_%s`` WHERE - (`ip` = :ip AND `time` >= :floodtime) - OR - (`ip` = :ip AND :body != '' AND `body_nomarkup` = :body AND `time` >= :floodsameiptime) - OR - (:body != '' AND `body_nomarkup` = :body AND `time` >= :floodsametime) LIMIT 1", $board['uri'])); - $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); - $query->bindValue(':body', $post['body']); - $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->fetchColumn(); - - if (event('check-flood', $post)) - return true; - - return $flood; -} - function until($timestamp) { $difference = $timestamp - time(); if ($difference < 60) { @@ -635,9 +623,7 @@ function displayBan($ban) { global $config; if (!$ban['seen']) { - $query = prepare("UPDATE ``bans`` SET `seen` = 1 WHERE `id` = :id"); - $query->bindValue(':id', $ban['id'], PDO::PARAM_INT); - $query->execute() or error(db_error($query)); + Bans::seen($ban['id']); } $ban['ip'] = $_SERVER['REMOTE_ADDR']; @@ -655,7 +641,7 @@ function displayBan($ban) { )); } -function checkBan($board = 0) { +function checkBan($board = false) { global $config; if (!isset($_SERVER['REMOTE_ADDR'])) { @@ -665,67 +651,38 @@ function checkBan($board = 0) { if (event('check-ban', $board)) return true; - - $query = prepare("SELECT `set`, `expires`, `reason`, `board`, `seen`, `id` FROM ``bans`` WHERE (`board` IS NULL OR `board` = :board) AND `ip` = :ip 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_range']) { - $query = prepare("SELECT `set`, `expires`, `reason`, `board`, `seen`, `id` FROM ``bans`` WHERE (`board` IS NULL OR `board` = :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`, `seen`, ``bans``.`id` FROM ``bans`` WHERE (`board` IS NULL OR `board` = :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(PDO::FETCH_ASSOC)) { + + $bans = Bans::find($_SERVER['REMOTE_ADDR'], $board); + + foreach ($bans as &$ban) { if ($ban['expires'] && $ban['expires'] < time()) { - // Ban expired - $query = prepare("DELETE FROM ``bans`` WHERE `id` = :id"); - $query->bindValue(':id', $ban['id'], PDO::PARAM_INT); - $query->execute() or error(db_error($query)); - + Bans::delete($ban['id']); if ($config['require_ban_view'] && !$ban['seen']) { + if (!isset($_POST['json_response'])) { + displayBan($ban); + } else { + header('Content-Type: text/json'); + die(json_encode(array('error' => true, 'banned' => true))); + } + } + } else { + if (!isset($_POST['json_response'])) { displayBan($ban); + } else { + header('Content-Type: text/json'); + die(json_encode(array('error' => true, 'banned' => true))); } - - return; } - - displayBan($ban); } - // I'm not sure where else to put this. It doesn't really matter where; it just needs to be called every now and then to keep the ban list tidy. - purge_bans(); -} - -// No reason to keep expired bans in the database (except those that haven't been viewed yet) -function purge_bans() { - global $config; - + // I'm not sure where else to put this. It doesn't really matter where; it just needs to be called every + // now and then to keep the ban list tidy. if ($config['cache']['enabled'] && $last_time_purged = cache::get('purged_bans_last')) { if (time() - $last_time_purged < $config['purge_bans'] ) return; } - $query = prepare("DELETE FROM ``bans`` WHERE `expires` IS NOT NULL AND `expires` < :time AND `seen` = 1"); - $query->bindValue(':time', time()); - $query->execute() or error(db_error($query)); + Bans::purge(); if ($config['cache']['enabled']) cache::set('purged_bans_last', time()); @@ -781,6 +738,22 @@ function threadExists($id) { return false; } +function insertFloodPost(array $post) { + global $board; + + $query = prepare("INSERT INTO ``flood`` VALUES (NULL, :ip, :board, :time, :posthash, :filehash, :isreply)"); + $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']); + $query->bindValue(':board', $board['uri']); + $query->bindValue(':time', time()); + $query->bindValue(':posthash', make_comment_hex($post['body_nomarkup'])); + if ($post['has_file']) + $query->bindValue(':filehash', $post['filehash']); + else + $query->bindValue(':filehash', null, PDO::PARAM_NULL); + $query->bindValue(':isreply', !$post['op'], PDO::PARAM_INT); + $query->execute() or error(db_error($query)); +} + 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'])); @@ -789,19 +762,19 @@ function post(array $post) { if (!empty($post['subject'])) { $query->bindValue(':subject', $post['subject']); } else { - $query->bindValue(':subject', NULL, PDO::PARAM_NULL); + $query->bindValue(':subject', null, PDO::PARAM_NULL); } if (!empty($post['email'])) { $query->bindValue(':email', $post['email']); } else { - $query->bindValue(':email', NULL, PDO::PARAM_NULL); + $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(':trip', null, PDO::PARAM_NULL); } $query->bindValue(':name', $post['name']); @@ -812,27 +785,27 @@ function post(array $post) { $query->bindValue(':ip', isset($post['ip']) ? $post['ip'] : $_SERVER['REMOTE_ADDR']); if ($post['op'] && $post['mod'] && isset($post['sticky']) && $post['sticky']) { - $query->bindValue(':sticky', 1, PDO::PARAM_INT); + $query->bindValue(':sticky', true, PDO::PARAM_INT); } else { - $query->bindValue(':sticky', 0, PDO::PARAM_INT); + $query->bindValue(':sticky', false, PDO::PARAM_INT); } if ($post['op'] && $post['mod'] && isset($post['locked']) && $post['locked']) { - $query->bindValue(':locked', 1, PDO::PARAM_INT); + $query->bindValue(':locked', true, PDO::PARAM_INT); } else { - $query->bindValue(':locked', 0, PDO::PARAM_INT); + $query->bindValue(':locked', false, 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); + $query->bindValue(':capcode', null, PDO::PARAM_NULL); } if (!empty($post['embed'])) { $query->bindValue(':embed', $post['embed']); } else { - $query->bindValue(':embed', NULL, PDO::PARAM_NULL); + $query->bindValue(':embed', null, PDO::PARAM_NULL); } if ($post['op']) { @@ -1079,10 +1052,16 @@ function index($page, $mod=false) { while ($th = $query->fetch(PDO::FETCH_ASSOC)) { $thread = new Thread($th, $mod ? '?/' : $config['root'], $mod); - if ($config['cache']['enabled'] && $cached = cache::get("thread_index_{$board['uri']}_{$th['id']}")) { - $replies = $cached['replies']; - $omitted = $cached['omitted']; - } else { + if ($config['cache']['enabled']) { + $cached = cache::get("thread_index_{$board['uri']}_{$th['id']}"); + if (isset($cached['replies'], $cached['omitted'])) { + $replies = $cached['replies']; + $omitted = $cached['omitted']; + } else { + unset($cached); + } + } + if (!isset($cached)) { $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); @@ -1203,6 +1182,26 @@ function getPages($mod=false) { return $pages; } +// Stolen with permission from PlainIB (by Frank Usrs) +function make_comment_hex($str) { + // remove cross-board citations + // the numbers don't matter + $str = preg_replace('!>>>/[A-Za-z0-9]+/!', '', $str); + + if (function_exists('iconv')) { + // remove diacritics and other noise + // FIXME: this removes cyrillic entirely + $str = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $str); + } + + $str = strtolower($str); + + // strip all non-alphabet characters + $str = preg_replace('/[^a-z]/', '', $str); + + return md5($str); +} + function makerobot($body) { global $config; $body = strtolower($body); diff --git a/inc/image.php b/inc/image.php index d3692a39..1d591c25 100644 --- a/inc/image.php +++ b/inc/image.php @@ -4,10 +4,7 @@ * Copyright (c) 2010-2013 Tinyboard Development Group */ -if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - exit; -} +defined('TINYBOARD') or exit; class Image { public $src, $format, $image, $size; diff --git a/inc/lib/IP/LICENSE b/inc/lib/IP/LICENSE new file mode 100755 index 00000000..fb315548 --- /dev/null +++ b/inc/lib/IP/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2013 Jason Morriss + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/inc/lib/IP/Lifo/IP/BC.php b/inc/lib/IP/Lifo/IP/BC.php new file mode 100755 index 00000000..545fe372 --- /dev/null +++ b/inc/lib/IP/Lifo/IP/BC.php @@ -0,0 +1,293 @@ +<?php +/** + * This file is part of the Lifo\IP PHP Library. + * + * (c) Jason Morriss <lifo2013@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace Lifo\IP; + +/** + * BCMath helper class. + * + * Provides a handful of BCMath routines that are not included in the native + * PHP library. + * + * Note: The Bitwise functions operate on fixed byte boundaries. For example, + * comparing the following numbers uses X number of bits: + * 0xFFFF and 0xFF will result in comparison of 16 bits. + * 0xFFFFFFFF and 0xF will result in comparison of 32 bits. + * etc... + * + */ +abstract class BC +{ + // Some common (maybe useless) constants + const MAX_INT_32 = '2147483647'; // 7FFFFFFF + const MAX_UINT_32 = '4294967295'; // FFFFFFFF + const MAX_INT_64 = '9223372036854775807'; // 7FFFFFFFFFFFFFFF + const MAX_UINT_64 = '18446744073709551615'; // FFFFFFFFFFFFFFFF + const MAX_INT_96 = '39614081257132168796771975167'; // 7FFFFFFFFFFFFFFFFFFFFFFF + const MAX_UINT_96 = '79228162514264337593543950335'; // FFFFFFFFFFFFFFFFFFFFFFFF + const MAX_INT_128 = '170141183460469231731687303715884105727'; // 7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF + const MAX_UINT_128 = '340282366920938463463374607431768211455'; // FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF + + /** + * BC Math function to convert a HEX string into a DECIMAL + */ + public static function bchexdec($hex) + { + if (strlen($hex) == 1) { + return hexdec($hex); + } + + $remain = substr($hex, 0, -1); + $last = substr($hex, -1); + return bcadd(bcmul(16, self::bchexdec($remain), 0), hexdec($last), 0); + } + + /** + * BC Math function to convert a DECIMAL string into a BINARY string + */ + public static function bcdecbin($dec, $pad = null) + { + $bin = ''; + while ($dec) { + $m = bcmod($dec, 2); + $dec = bcdiv($dec, 2, 0); + $bin = abs($m) . $bin; + } + return $pad ? sprintf("%0{$pad}s", $bin) : $bin; + } + + /** + * BC Math function to convert a BINARY string into a DECIMAL string + */ + public static function bcbindec($bin) + { + $dec = '0'; + for ($i=0, $j=strlen($bin); $i<$j; $i++) { + $dec = bcmul($dec, '2', 0); + $dec = bcadd($dec, $bin[$i], 0); + } + return $dec; + } + + /** + * BC Math function to convert a BINARY string into a HEX string + */ + public static function bcbinhex($bin, $pad = 0) + { + return self::bcdechex(self::bcbindec($bin)); + } + + /** + * BC Math function to convert a DECIMAL into a HEX string + */ + public static function bcdechex($dec) + { + $last = bcmod($dec, 16); + $remain = bcdiv(bcsub($dec, $last, 0), 16, 0); + return $remain == 0 ? dechex($last) : self::bcdechex($remain) . dechex($last); + } + + /** + * Bitwise AND two arbitrarily large numbers together. + */ + public static function bcand($left, $right) + { + $len = self::_bitwise($left, $right); + + $value = ''; + for ($i=0; $i<$len; $i++) { + $value .= (($left{$i} + 0) & ($right{$i} + 0)) ? '1' : '0'; + } + return self::bcbindec($value != '' ? $value : '0'); + } + + /** + * Bitwise OR two arbitrarily large numbers together. + */ + public static function bcor($left, $right) + { + $len = self::_bitwise($left, $right); + + $value = ''; + for ($i=0; $i<$len; $i++) { + $value .= (($left{$i} + 0) | ($right{$i} + 0)) ? '1' : '0'; + } + return self::bcbindec($value != '' ? $value : '0'); + } + + /** + * Bitwise XOR two arbitrarily large numbers together. + */ + public static function bcxor($left, $right) + { + $len = self::_bitwise($left, $right); + + $value = ''; + for ($i=0; $i<$len; $i++) { + $value .= (($left{$i} + 0) ^ ($right{$i} + 0)) ? '1' : '0'; + } + return self::bcbindec($value != '' ? $value : '0'); + } + + /** + * Bitwise NOT two arbitrarily large numbers together. + */ + public static function bcnot($left, $bits = null) + { + $right = 0; + $len = self::_bitwise($left, $right, $bits); + $value = ''; + for ($i=0; $i<$len; $i++) { + $value .= $left{$i} == '1' ? '0' : '1'; + } + return self::bcbindec($value); + } + + /** + * Shift number to the left + * + * @param integer $bits Total bits to shift + */ + public static function bcleft($num, $bits) { + return bcmul($num, bcpow('2', $bits)); + } + + /** + * Shift number to the right + * + * @param integer $bits Total bits to shift + */ + public static function bcright($num, $bits) { + return bcdiv($num, bcpow('2', $bits)); + } + + /** + * Determine how many bits are needed to store the number rounded to the + * nearest bit boundary. + */ + public static function bits_needed($num, $boundary = 4) + { + $bits = 0; + while ($num > 0) { + $num = bcdiv($num, '2', 0); + $bits++; + } + // round to nearest boundrary + return $boundary ? ceil($bits / $boundary) * $boundary : $bits; + } + + /** + * BC Math function to return an arbitrarily large random number. + */ + public static function bcrand($min, $max = null) + { + if ($max === null) { + $max = $min; + $min = 0; + } + + // swap values if $min > $max + if (bccomp($min, $max) == 1) { + list($min,$max) = array($max,$min); + } + + return bcadd( + bcmul( + bcdiv( + mt_rand(0, mt_getrandmax()), + mt_getrandmax(), + strlen($max) + ), + bcsub( + bcadd($max, '1'), + $min + ) + ), + $min + ); + } + + /** + * Computes the natural logarithm using a series. + * @author Thomas Oldbury. + * @license Public domain. + */ + public static function bclog($num, $iter = 10, $scale = 100) + { + $log = "0.0"; + for($i = 0; $i < $iter; $i++) { + $pow = 1 + (2 * $i); + $mul = bcdiv("1.0", $pow, $scale); + $fraction = bcmul($mul, bcpow(bcsub($num, "1.0", $scale) / bcadd($num, "1.0", $scale), $pow, $scale), $scale); + $log = bcadd($fraction, $log, $scale); + } + return bcmul("2.0", $log, $scale); + } + + /** + * Computes the base2 log using baseN log. + */ + public static function bclog2($num, $iter = 10, $scale = 100) + { + return bcdiv(self::bclog($num, $iter, $scale), self::bclog("2", $iter, $scale), $scale); + } + + public static function bcfloor($num) + { + if (substr($num, 0, 1) == '-') { + return bcsub($num, 1, 0); + } + return bcadd($num, 0, 0); + } + + public static function bcceil($num) + { + if (substr($num, 0, 1) == '-') { + return bcsub($num, 0, 0); + } + return bcadd($num, 1, 0); + } + + /** + * Compare two numbers and return -1, 0, 1 depending if the LEFT number is + * < = > the RIGHT. + * + * @param string|integer $left Left side operand + * @param string|integer $right Right side operand + * @return integer Return -1,0,1 for <=> comparison + */ + public static function cmp($left, $right) + { + // @todo could an optimization be done to determine if a normal 32bit + // comparison could be done instead of using bccomp? But would + // the number verification cause too much overhead to be useful? + return bccomp($left, $right, 0); + } + + /** + * Internal function to prepare for bitwise operations + */ + private static function _bitwise(&$left, &$right, $bits = null) + { + if ($bits === null) { + $bits = max(self::bits_needed($left), self::bits_needed($right)); + } + + $left = self::bcdecbin($left); + $right = self::bcdecbin($right); + + $len = max(strlen($left), strlen($right), (int)$bits); + + $left = sprintf("%0{$len}s", $left); + $right = sprintf("%0{$len}s", $right); + + return $len; + } + +} diff --git a/inc/lib/IP/Lifo/IP/CIDR.php b/inc/lib/IP/Lifo/IP/CIDR.php new file mode 100755 index 00000000..e8fe32ce --- /dev/null +++ b/inc/lib/IP/Lifo/IP/CIDR.php @@ -0,0 +1,706 @@ +<?php +/** + * This file is part of the Lifo\IP PHP Library. + * + * (c) Jason Morriss <lifo2013@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace Lifo\IP; + +/** + * CIDR Block helper class. + * + * Most routines can be used statically or by instantiating an object and + * calling its methods. + * + * Provides routines to do various calculations on IP addresses and ranges. + * Convert to/from CIDR to ranges, etc. + */ +class CIDR +{ + const INTERSECT_NO = 0; + const INTERSECT_YES = 1; + const INTERSECT_LOW = 2; + const INTERSECT_HIGH = 3; + + protected $start; + protected $end; + protected $prefix; + protected $version; + protected $istart; + protected $iend; + + private $cache; + + /** + * Create a new CIDR object. + * + * The IP range can be arbitrary and does not have to fall on a valid CIDR + * range. Some methods will return different values depending if you ignore + * the prefix or not. By default all prefix sensitive methods will assume + * the prefix is used. + * + * @param string $cidr An IP address (1.2.3.4), CIDR block (1.2.3.4/24), + * or range "1.2.3.4-1.2.3.10" + * @param string $end Ending IP in range if no cidr/prefix is given + */ + public function __construct($cidr, $end = null) + { + if ($end !== null) { + $this->setRange($cidr, $end); + } else { + $this->setCidr($cidr); + } + } + + /** + * Returns the string representation of the CIDR block. + */ + public function __toString() + { + // do not include the prefix if its a single IP + try { + if ($this->isTrueCidr() && ( + ($this->version == 4 and $this->prefix != 32) || + ($this->version == 6 and $this->prefix != 128) + ) + ) { + return $this->start . '/' . $this->prefix; + } + } catch (\Exception $e) { + // isTrueCidr() calls getRange which can throw an exception + } + if (strcmp($this->start, $this->end) == 0) { + return $this->start; + } + return $this->start . ' - ' . $this->end; + } + + public function __clone() + { + // do not clone the cache. No real reason why. I just want to keep the + // memory foot print as low as possible, even though this is trivial. + $this->cache = array(); + } + + /** + * Set an arbitrary IP range. + * The closest matching prefix will be calculated but the actual range + * stored in the object can be arbitrary. + * @param string $start Starting IP or combination "start-end" string. + * @param string $end Ending IP or null. + */ + public function setRange($ip, $end = null) + { + if (strpos($ip, '-') !== false) { + list($ip, $end) = array_map('trim', explode('-', $ip, 2)); + } + + if (false === filter_var($ip, FILTER_VALIDATE_IP) || + false === filter_var($end, FILTER_VALIDATE_IP)) { + throw new \InvalidArgumentException("Invalid IP range \"$ip-$end\""); + } + + // determine version (4 or 6) + $this->version = (false === filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) ? 6 : 4; + + $this->istart = IP::inet_ptod($ip); + $this->iend = IP::inet_ptod($end); + + // fix order + if (bccomp($this->istart, $this->iend) == 1) { + list($this->istart, $this->iend) = array($this->iend, $this->istart); + list($ip, $end) = array($end, $ip); + } + + $this->start = $ip; + $this->end = $end; + + // calculate real prefix + $len = $this->version == 4 ? 32 : 128; + $this->prefix = $len - strlen(BC::bcdecbin(BC::bcxor($this->istart, $this->iend))); + } + + /** + * Returns true if the current IP is a true cidr block + */ + public function isTrueCidr() + { + return $this->start == $this->getNetwork() && $this->end == $this->getBroadcast(); + } + + /** + * Set the CIDR block. + * + * The prefix length is optional and will default to 32 ot 128 depending on + * the version detected. + * + * @param string $cidr CIDR block string, eg: "192.168.0.0/24" or "2001::1/64" + * @throws \InvalidArgumentException If the CIDR block is invalid + */ + public function setCidr($cidr) + { + if (strpos($cidr, '-') !== false) { + return $this->setRange($cidr); + } + + list($ip, $bits) = array_pad(array_map('trim', explode('/', $cidr, 2)), 2, null); + if (false === filter_var($ip, FILTER_VALIDATE_IP)) { + throw new \InvalidArgumentException("Invalid IP address \"$cidr\""); + } + + // determine version (4 or 6) + $this->version = (false === filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) ? 6 : 4; + + $this->start = $ip; + $this->istart = IP::inet_ptod($ip); + + if ($bits !== null and $bits !== '') { + $this->prefix = $bits; + } else { + $this->prefix = $this->version == 4 ? 32 : 128; + } + + if (($this->prefix < 0) + || ($this->prefix > 32 and $this->version == 4) + || ($this->prefix > 128 and $this->version == 6)) { + throw new \InvalidArgumentException("Invalid IP address \"$cidr\""); + } + + $this->end = $this->getBroadcast(); + $this->iend = IP::inet_ptod($this->end); + + $this->cache = array(); + } + + /** + * Get the IP version. 4 or 6. + * + * @return integer + */ + public function getVersion() + { + return $this->version; + } + + /** + * Get the prefix. + * + * Always returns the "proper" prefix, even if the IP range is arbitrary. + * + * @return integer + */ + public function getPrefix() + { + return $this->prefix; + } + + /** + * Return the starting presentational IP or Decimal value. + * + * Ignores prefix + */ + public function getStart($decimal = false) + { + return $decimal ? $this->istart : $this->start; + } + + /** + * Return the ending presentational IP or Decimal value. + * + * Ignores prefix + */ + public function getEnd($decimal = false) + { + return $decimal ? $this->iend : $this->end; + } + + /** + * Return the next presentational IP or Decimal value (following the + * broadcast address of the current CIDR block). + */ + public function getNext($decimal = false) + { + $next = bcadd($this->getEnd(true), '1'); + return $decimal ? $next : new self(IP::inet_dtop($next)); + } + + /** + * Returns true if the IP is an IPv4 + * + * @return boolean + */ + public function isIPv4() + { + return $this->version == 4; + } + + /** + * Returns true if the IP is an IPv6 + * + * @return boolean + */ + public function isIPv6() + { + return $this->version == 6; + } + + /** + * Get the cidr notation for the subnet block. + * + * This is useful for when you want a string representation of the IP/prefix + * and the starting IP is not on a valid network boundrary (eg: Displaying + * an IP from an interface). + * + * @return string IP in CIDR notation "ipaddr/prefix" + */ + public function getCidr() + { + return $this->start . '/' . $this->prefix; + } + + /** + * Get the [low,high] range of the CIDR block + * + * Prefix sensitive. + * + * @param boolean $ignorePrefix If true the arbitrary start-end range is + * returned. default=false. + */ + public function getRange($ignorePrefix = false) + { + $range = $ignorePrefix + ? array($this->start, $this->end) + : self::cidr_to_range($this->start, $this->prefix); + // watch out for IP '0' being converted to IPv6 '::' + if ($range[0] == '::' and strpos($range[1], ':') == false) { + $range[0] = '0.0.0.0'; + } + return $range; + } + + /** + * Return the IP in its fully expanded form. + * + * For example: 2001::1 == 2007:0000:0000:0000:0000:0000:0000:0001 + * + * @see IP::inet_expand + */ + public function getExpanded() + { + return IP::inet_expand($this->start); + } + + /** + * Get network IP of the CIDR block + * + * Prefix sensitive. + * + * @param boolean $ignorePrefix If true the arbitrary start-end range is + * returned. default=false. + */ + public function getNetwork($ignorePrefix = false) + { + // micro-optimization to prevent calling getRange repeatedly + $k = $ignorePrefix ? 1 : 0; + if (!isset($this->cache['range'][$k])) { + $this->cache['range'][$k] = $this->getRange($ignorePrefix); + } + return $this->cache['range'][$k][0]; + } + + /** + * Get broadcast IP of the CIDR block + * + * Prefix sensitive. + * + * @param boolean $ignorePrefix If true the arbitrary start-end range is + * returned. default=false. + */ + public function getBroadcast($ignorePrefix = false) + { + // micro-optimization to prevent calling getRange repeatedly + $k = $ignorePrefix ? 1 : 0; + if (!isset($this->cache['range'][$k])) { + $this->cache['range'][$k] = $this->getRange($ignorePrefix); + } + return $this->cache['range'][$k][1]; + } + + /** + * Get the network mask based on the prefix. + * + */ + public function getMask() + { + return self::prefix_to_mask($this->prefix, $this->version); + } + + /** + * Get total hosts within CIDR range + * + * Prefix sensitive. + * + * @param boolean $ignorePrefix If true the arbitrary start-end range is + * returned. default=false. + */ + public function getTotal($ignorePrefix = false) + { + // micro-optimization to prevent calling getRange repeatedly + $k = $ignorePrefix ? 1 : 0; + if (!isset($this->cache['range'][$k])) { + $this->cache['range'][$k] = $this->getRange($ignorePrefix); + } + return bcadd(bcsub(IP::inet_ptod($this->cache['range'][$k][1]), + IP::inet_ptod($this->cache['range'][$k][0])), '1'); + } + + public function intersects($cidr) + { + return self::cidr_intersect((string)$this, $cidr); + } + + /** + * Determines the intersection between an IP (with optional prefix) and a + * CIDR block. + * + * The IP will be checked against the CIDR block given and will either be + * inside or outside the CIDR completely, or partially. + * + * NOTE: The caller should explicitly check against the INTERSECT_* + * constants because this method will return a value > 1 even for partial + * matches. + * + * @param mixed $ip The IP/cidr to match + * @param mixed $cidr The CIDR block to match within + * @return integer Returns an INTERSECT_* constant + * @throws \InvalidArgumentException if either $ip or $cidr is invalid + */ + public static function cidr_intersect($ip, $cidr) + { + // use fixed length HEX strings so we can easily do STRING comparisons + // instead of using slower bccomp() math. + list($lo,$hi) = array_map(function($v){ return sprintf("%032s", IP::inet_ptoh($v)); }, CIDR::cidr_to_range($ip)); + list($min,$max) = array_map(function($v){ return sprintf("%032s", IP::inet_ptoh($v)); }, CIDR::cidr_to_range($cidr)); + + /** visualization of logic used below + lo-hi = $ip to check + min-max = $cidr block being checked against + --- --- --- lo --- --- hi --- --- --- --- --- IP/prefix to check + --- min --- --- max --- --- --- --- --- --- --- Partial "LOW" match + --- --- --- --- --- min --- --- max --- --- --- Partial "HIGH" match + --- --- --- --- min max --- --- --- --- --- --- No match "NO" + --- --- --- --- --- --- --- --- min --- max --- No match "NO" + min --- max --- --- --- --- --- --- --- --- --- No match "NO" + --- --- min --- --- --- --- max --- --- --- --- Full match "YES" + */ + + // IP is exact match or completely inside the CIDR block + if ($lo >= $min and $hi <= $max) { + return self::INTERSECT_YES; + } + + // IP is completely outside the CIDR block + if ($max < $lo or $min > $hi) { + return self::INTERSECT_NO; + } + + // @todo is it useful to return LOW/HIGH partial matches? + + // IP matches the lower end + if ($max <= $hi and $min <= $lo) { + return self::INTERSECT_LOW; + } + + // IP matches the higher end + if ($min >= $lo and $max >= $hi) { + return self::INTERSECT_HIGH; + } + + return self::INTERSECT_NO; + } + + /** + * Converts an IPv4 or IPv6 CIDR block into its range. + * + * @todo May not be the fastest way to do this. + * + * @static + * @param string $cidr CIDR block or IP address string. + * @param integer|null $bits If /bits is not specified on string they can be + * passed via this parameter instead. + * @return array A 2 element array with the low, high range + */ + public static function cidr_to_range($cidr, $bits = null) + { + if (strpos($cidr, '/') !== false) { + list($ip, $_bits) = array_pad(explode('/', $cidr, 2), 2, null); + } else { + $ip = $cidr; + $_bits = $bits; + } + + if (false === filter_var($ip, FILTER_VALIDATE_IP)) { + throw new \InvalidArgumentException("IP address \"$cidr\" is invalid"); + } + + // force bit length to 32 or 128 depending on type of IP + $bitlen = (false === filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) ? 128 : 32; + + if ($bits === null) { + // if no prefix is given use the length of the binary string which + // will give us 32 or 128 and result in a single IP being returned. + $bits = $_bits !== null ? $_bits : $bitlen; + } + + if ($bits > $bitlen) { + throw new \InvalidArgumentException("IP address \"$cidr\" is invalid"); + } + + $ipdec = IP::inet_ptod($ip); + $ipbin = BC::bcdecbin($ipdec, $bitlen); + + // calculate network + $netmask = BC::bcbindec(str_pad(str_repeat('1',$bits), $bitlen, '0')); + $ip1 = BC::bcand($ipdec, $netmask); + + // calculate "broadcast" (not technically a broadcast in IPv6) + $ip2 = BC::bcor($ip1, BC::bcnot($netmask)); + + return array(IP::inet_dtop($ip1), IP::inet_dtop($ip2)); + } + + /** + * Return the CIDR string from the range given + */ + public static function range_to_cidr($start, $end) + { + $cidr = new CIDR($start, $end); + return (string)$cidr; + } + + /** + * Return the maximum prefix length that would fit the IP address given. + * + * This is useful to determine how my bit would be needed to store the IP + * address when you don't already have a prefix for the IP. + * + * @example 216.240.32.0 would return 27 + * + * @param string $ip IP address without prefix + * @param integer $bits Maximum bits to check; defaults to 32 for IPv4 and 128 for IPv6 + */ + public static function max_prefix($ip, $bits = null) + { + static $mask = array(); + + $ver = (false === filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) ? 6 : 4; + $max = $ver == 6 ? 128 : 32; + if ($bits === null) { + $bits = $max; + + } + + $int = IP::inet_ptod($ip); + while ($bits > 0) { + // micro-optimization; calculate mask once ... + if (!isset($mask[$ver][$bits-1])) { + // 2^$max - 2^($max - $bits); + if ($ver == 4) { + $mask[$ver][$bits-1] = pow(2, $max) - pow(2, $max - ($bits-1)); + } else { + $mask[$ver][$bits-1] = bcsub(bcpow(2, $max), bcpow(2, $max - ($bits-1))); + } + } + + $m = $mask[$ver][$bits-1]; + //printf("%s/%d: %s & %s == %s\n", $ip, $bits-1, BC::bcdecbin($m, 32), BC::bcdecbin($int, 32), BC::bcdecbin(BC::bcand($int, $m))); + //echo "$ip/", $bits-1, ": ", IP::inet_dtop($m), " ($m) & $int == ", BC::bcand($int, $m), "\n"; + if (bccomp(BC::bcand($int, $m), $int) != 0) { + return $bits; + } + $bits--; + } + return $bits; + } + + /** + * Return a contiguous list of true CIDR blocks that span the range given. + * + * Note: It's not a good idea to call this with IPv6 addresses. While it may + * work for certain ranges this can be very slow. Also an IPv6 list won't be + * as accurate as an IPv4 list. + * + * @example + * range_to_cidrlist(192.168.0.0, 192.168.0.15) == + * 192.168.0.0/28 + * range_to_cidrlist(192.168.0.0, 192.168.0.20) == + * 192.168.0.0/28 + * 192.168.0.16/30 + * 192.168.0.20/32 + */ + public static function range_to_cidrlist($start, $end) + { + $ver = (false === filter_var($start, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) ? 6 : 4; + $start = IP::inet_ptod($start); + $end = IP::inet_ptod($end); + + $len = $ver == 4 ? 32 : 128; + $log2 = $ver == 4 ? log(2) : BC::bclog(2); + + $list = array(); + while (BC::cmp($end, $start) >= 0) { // $end >= $start + $prefix = self::max_prefix(IP::inet_dtop($start), $len); + if ($ver == 4) { + $diff = $len - floor( log($end - $start + 1) / $log2 ); + } else { + // this is not as accurate due to the bclog function + $diff = bcsub($len, BC::bcfloor(bcdiv(BC::bclog(bcadd(bcsub($end, $start), '1')), $log2))); + } + + if ($prefix < $diff) { + $prefix = $diff; + } + + $list[] = IP::inet_dtop($start) . "/" . $prefix; + + if ($ver == 4) { + $start += pow(2, $len - $prefix); + } else { + $start = bcadd($start, bcpow(2, $len - $prefix)); + } + } + return $list; + } + + /** + * Return an list of optimized CIDR blocks by collapsing adjacent CIDR + * blocks into larger blocks. + * + * @param array $cidrs List of CIDR block strings or objects + * @param integer $maxPrefix Maximum prefix to allow + * @return array Optimized list of CIDR objects + */ + public static function optimize_cidrlist($cidrs, $maxPrefix = 32) + { + // all indexes must be a CIDR object + $cidrs = array_map(function($o){ return $o instanceof CIDR ? $o : new CIDR($o); }, $cidrs); + // sort CIDR blocks in proper order so we can easily loop over them + $cidrs = self::cidr_sort($cidrs); + + $list = array(); + while ($cidrs) { + $c = array_shift($cidrs); + $start = $c->getStart(); + + $max = bcadd($c->getStart(true), $c->getTotal()); + + // loop through each cidr block until its ending range is more than + // the current maximum. + while (!empty($cidrs) and $cidrs[0]->getStart(true) <= $max) { + $b = array_shift($cidrs); + $newmax = bcadd($b->getStart(true), $b->getTotal()); + if ($newmax > $max) { + $max = $newmax; + } + } + + // add the new cidr range to the optimized list + $list = array_merge($list, self::range_to_cidrlist($start, IP::inet_dtop(bcsub($max, '1')))); + } + + return $list; + } + + /** + * Sort the list of CIDR blocks, optionally with a custom callback function. + * + * @param array $cidrs A list of CIDR blocks (strings or objects) + * @param Closure $callback Optional callback to perform the sorting. + * See PHP usort documentation for more details. + */ + public static function cidr_sort($cidrs, $callback = null) + { + // all indexes must be a CIDR object + $cidrs = array_map(function($o){ return $o instanceof CIDR ? $o : new CIDR($o); }, $cidrs); + + if ($callback === null) { + $callback = function($a, $b) { + if (0 != ($o = BC::cmp($a->getStart(true), $b->getStart(true)))) { + return $o; // < or > + } + if ($a->getPrefix() == $b->getPrefix()) { + return 0; + } + return $a->getPrefix() < $b->getPrefix() ? -1 : 1; + }; + } elseif (!($callback instanceof \Closure) or !is_callable($callback)) { + throw new \InvalidArgumentException("Invalid callback in CIDR::cidr_sort, expected Closure, got " . gettype($callback)); + } + + usort($cidrs, $callback); + return $cidrs; + } + + /** + * Return the Prefix bits from the IPv4 mask given. + * + * This is only valid for IPv4 addresses since IPv6 addressing does not + * have a concept of network masks. + * + * Example: 255.255.255.0 == 24 + * + * @param string $mask IPv4 network mask. + */ + public static function mask_to_prefix($mask) + { + if (false === filter_var($mask, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + throw new \InvalidArgumentException("Invalid IP netmask \"$mask\""); + } + return strrpos(IP::inet_ptob($mask, 32), '1') + 1; + } + + /** + * Return the network mask for the prefix given. + * + * Normally this is only useful for IPv4 addresses but you can generate a + * mask for IPv6 addresses as well, only because its mathematically + * possible. + * + * @param integer $prefix CIDR prefix bits (0-128) + * @param integer $version IP version. If null the version will be detected + * based on the prefix length given. + */ + public static function prefix_to_mask($prefix, $version = null) + { + if ($version === null) { + $version = $prefix > 32 ? 6 : 4; + } + if ($prefix < 0 or $prefix > 128) { + throw new \InvalidArgumentException("Invalid prefix length \"$prefix\""); + } + if ($version != 4 and $version != 6) { + throw new \InvalidArgumentException("Invalid version \"$version\". Must be 4 or 6"); + } + + if ($version == 4) { + return long2ip($prefix == 0 ? 0 : (0xFFFFFFFF >> (32 - $prefix)) << (32 - $prefix)); + } else { + return IP::inet_dtop($prefix == 0 ? 0 : BC::bcleft(BC::bcright(BC::MAX_UINT_128, 128-$prefix), 128-$prefix)); + } + } + + /** + * Return true if the $ip given is a true CIDR block. + * + * A true CIDR block is one where the $ip given is the actual Network + * address and broadcast matches the prefix appropriately. + */ + public static function cidr_is_true($ip) + { + $ip = new CIDR($ip); + return $ip->isTrueCidr(); + } +} diff --git a/inc/lib/IP/Lifo/IP/IP.php b/inc/lib/IP/Lifo/IP/IP.php new file mode 100755 index 00000000..4d22aa76 --- /dev/null +++ b/inc/lib/IP/Lifo/IP/IP.php @@ -0,0 +1,207 @@ +<?php +/** + * This file is part of the Lifo\IP PHP Library. + * + * (c) Jason Morriss <lifo2013@gmail.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace Lifo\IP; + +/** + * IP Address helper class. + * + * Provides routines to translate IPv4 and IPv6 addresses between human readable + * strings, decimal, hexidecimal and binary. + * + * Requires BCmath extension and IPv6 PHP support + */ +abstract class IP +{ + /** + * Convert a human readable (presentational) IP address string into a decimal string. + */ + public static function inet_ptod($ip) + { + // shortcut for IPv4 addresses + if (strpos($ip, ':') === false && strpos($ip, '.') !== false) { + return sprintf('%u', ip2long($ip)); + } + + // remove any cidr block notation + if (($o = strpos($ip, '/')) !== false) { + $ip = substr($ip, 0, $o); + } + + // unpack into 4 32bit integers + $parts = unpack('N*', inet_pton($ip)); + foreach ($parts as &$part) { + if ($part < 0) { + // convert signed int into unsigned + $part = sprintf('%u', $part); + //$part = bcadd($part, '4294967296'); + } + } + + // add each 32bit integer to the proper bit location in our big decimal + $decimal = $parts[4]; // << 0 + $decimal = bcadd($decimal, bcmul($parts[3], '4294967296')); // << 32 + $decimal = bcadd($decimal, bcmul($parts[2], '18446744073709551616')); // << 64 + $decimal = bcadd($decimal, bcmul($parts[1], '79228162514264337593543950336')); // << 96 + + return $decimal; + } + + /** + * Convert a decimal string into a human readable IP address. + */ + public static function inet_dtop($decimal, $expand = false) + { + $parts = array(); + $parts[1] = bcdiv($decimal, '79228162514264337593543950336', 0); // >> 96 + $decimal = bcsub($decimal, bcmul($parts[1], '79228162514264337593543950336')); + $parts[2] = bcdiv($decimal, '18446744073709551616', 0); // >> 64 + $decimal = bcsub($decimal, bcmul($parts[2], '18446744073709551616')); + $parts[3] = bcdiv($decimal, '4294967296', 0); // >> 32 + $decimal = bcsub($decimal, bcmul($parts[3], '4294967296')); + $parts[4] = $decimal; // >> 0 + + foreach ($parts as &$part) { + if (bccomp($part, '2147483647') == 1) { + $part = bcsub($part, '4294967296'); + } + $part = (int) $part; + } + + // if the first 96bits is all zeros then we can safely assume we + // actually have an IPv4 address. Even though it's technically possible + // you're not really ever going to see an IPv6 address in the range: + // ::0 - ::ffff + // It's feasible to see an IPv6 address of "::", in which case the + // caller is going to have to account for that on their own. + if (($parts[1] | $parts[2] | $parts[3]) == 0) { + $ip = long2ip($parts[4]); + } else { + $packed = pack('N4', $parts[1], $parts[2], $parts[3], $parts[4]); + $ip = inet_ntop($packed); + } + + // Turn IPv6 to IPv4 if it's IPv4 + if (preg_match('/^::\d+\./', $ip)) { + return substr($ip, 2); + } + + return $expand ? self::inet_expand($ip) : $ip; + } + + /** + * Convert a human readable (presentational) IP address into a HEX string. + */ + public static function inet_ptoh($ip) + { + return bin2hex(inet_pton($ip)); + //return BC::bcdechex(self::inet_ptod($ip)); + } + + /** + * Convert a human readable (presentational) IP address into a BINARY string. + */ + public static function inet_ptob($ip, $bits = 128) + { + return BC::bcdecbin(self::inet_ptod($ip), $bits); + } + + /** + * Convert a binary string into an IP address (presentational) string. + */ + public static function inet_btop($bin) + { + return self::inet_dtop(BC::bcbindec($bin)); + } + + /** + * Convert a HEX string into a human readable (presentational) IP address + */ + public static function inet_htop($hex) + { + return self::inet_dtop(BC::bchexdec($hex)); + } + + /** + * Expand an IP address. IPv4 addresses are returned as-is. + * + * Example: + * 2001::1 expands to 2001:0000:0000:0000:0000:0000:0000:0001 + * ::127.0.0.1 expands to 0000:0000:0000:0000:0000:0000:7f00:0001 + * 127.0.0.1 expands to 127.0.0.1 + */ + public static function inet_expand($ip) + { + // strip possible cidr notation off + if (($pos = strpos($ip, '/')) !== false) { + $ip = substr($ip, 0, $pos); + } + $bytes = unpack('n*', inet_pton($ip)); + if (count($bytes) > 2) { + return implode(':', array_map(function ($b) { + return sprintf("%04x", $b); + }, $bytes)); + } + return $ip; + } + + /** + * Convert an IPv4 address into an IPv6 address. + * + * One use-case for this is IP 6to4 tunnels used in networking. + * + * @example + * to_ipv4("10.10.10.10") == a0a:a0a + * + * @param string $ip IPv4 address. + * @param boolean $mapped If true a Full IPv6 address is returned within the + * official ipv4to6 mapped space "0:0:0:0:0:ffff:x:x" + */ + public static function to_ipv6($ip, $mapped = false) + { + if (!self::isIPv4($ip)) { + throw new \InvalidArgumentException("Invalid IPv4 address \"$ip\""); + } + + $num = IP::inet_ptod($ip); + $o1 = dechex($num >> 16); + $o2 = dechex($num & 0x0000FFFF); + + return $mapped ? "0:0:0:0:0:ffff:$o1:$o2" : "$o1:$o2"; + } + + /** + * Returns true if the IP address is a valid IPv4 address + */ + public static function isIPv4($ip) + { + return $ip === filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); + } + + /** + * Returns true if the IP address is a valid IPv6 address + */ + public static function isIPv6($ip) + { + return $ip === filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6); + } + + /** + * Compare two IP's (v4 or v6) and return -1, 0, 1 if the first is < = > + * the second. + * + * @param string $ip1 IP address + * @param string $ip2 IP address to compare against + * @return integer Return -1,0,1 depending if $ip1 is <=> $ip2 + */ + public static function cmp($ip1, $ip2) + { + return bccomp(self::inet_ptod($ip1), self::inet_ptod($ip2), 0); + } +} diff --git a/inc/mod.php b/inc/mod.php deleted file mode 100644 index 7b82c5d4..00000000 --- a/inc/mod.php +++ /dev/null @@ -1,15 +0,0 @@ -<?php - -/* - * Copyright (c) 2010-2013 Tinyboard Development Group - */ - -// WARNING: Including this file is DEPRECIATED. It's only here to support older versions and won't exist forever. - -if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - exit; -} - -require 'inc/mod/auth.php'; - diff --git a/inc/mod/auth.php b/inc/mod/auth.php index 0733646f..f2003dfe 100644 --- a/inc/mod/auth.php +++ b/inc/mod/auth.php @@ -4,10 +4,7 @@ * Copyright (c) 2010-2013 Tinyboard Development Group */ -if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - exit; -} +defined('TINYBOARD') or exit; // create a hash/salt pair for validate logins function mkhash($username, $password, $salt = false) { diff --git a/inc/mod/ban.php b/inc/mod/ban.php index 71173326..82260585 100644 --- a/inc/mod/ban.php +++ b/inc/mod/ban.php @@ -4,102 +4,7 @@ * Copyright (c) 2010-2013 Tinyboard Development Group */ -if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - exit; -} +defined('TINYBOARD') or exit; -function parse_time($str) { - if (empty($str)) - return false; - - if (($time = @strtotime($str)) !== false) - return $time; - - if (!preg_match('/^((\d+)\s?ye?a?r?s?)?\s?+((\d+)\s?mon?t?h?s?)?\s?+((\d+)\s?we?e?k?s?)?\s?+((\d+)\s?da?y?s?)?((\d+)\s?ho?u?r?s?)?\s?+((\d+)\s?mi?n?u?t?e?s?)?\s?+((\d+)\s?se?c?o?n?d?s?)?$/', $str, $matches)) - return false; - - $expire = 0; - - if (isset($matches[2])) { - // Years - $expire += $matches[2]*60*60*24*365; - } - if (isset($matches[4])) { - // Months - $expire += $matches[4]*60*60*24*30; - } - if (isset($matches[6])) { - // Weeks - $expire += $matches[6]*60*60*24*7; - } - if (isset($matches[8])) { - // Days - $expire += $matches[8]*60*60*24; - } - if (isset($matches[10])) { - // Hours - $expire += $matches[10]*60*60; - } - if (isset($matches[12])) { - // Minutes - $expire += $matches[12]*60; - } - if (isset($matches[14])) { - // Seconds - $expire += $matches[14]; - } - - return time() + $expire; -} - -function ban($mask, $reason, $length, $board) { - global $mod, $pdo; - - $query = prepare("INSERT INTO ``bans`` VALUES (NULL, :ip, :mod, :time, :expires, :reason, :board, 0)"); - $query->bindValue(':ip', $mask); - $query->bindValue(':mod', $mod['id']); - $query->bindValue(':time', time()); - if ($reason !== '') { - $reason = escape_markup_modifiers($reason); - markup($reason); - $query->bindValue(':reason', $reason); - } else - $query->bindValue(':reason', null, PDO::PARAM_NULL); - - if ($length > 0) - $query->bindValue(':expires', $length); - else - $query->bindValue(':expires', null, PDO::PARAM_NULL); - - if ($board) - $query->bindValue(':board', $board); - else - $query->bindValue(':board', null, PDO::PARAM_NULL); - - $query->execute() or error(db_error($query)); - - modLog('Created a new ' . - ($length > 0 ? preg_replace('/^(\d+) (\w+?)s?$/', '$1-$2', until($length)) : 'permanent') . - ' ban on ' . - ($board ? '/' . $board . '/' : 'all boards') . - ' for ' . - (filter_var($mask, FILTER_VALIDATE_IP) !== false ? "<a href=\"?/IP/$mask\">$mask</a>" : utf8tohtml($mask)) . - ' (<small>#' . $pdo->lastInsertId() . '</small>)' . - ' with ' . ($reason ? 'reason: ' . utf8tohtml($reason) . '' : 'no reason')); -} - -function unban($id) { - $query = prepare("SELECT `ip` FROM ``bans`` WHERE `id` = :id"); - $query->bindValue(':id', $id); - $query->execute() or error(db_error($query)); - $mask = $query->fetchColumn(); - - $query = prepare("DELETE FROM ``bans`` WHERE `id` = :id"); - $query->bindValue(':id', $id); - $query->execute() or error(db_error($query)); - - if ($mask) - modLog("Removed ban #{$id} for " . (filter_var($mask, FILTER_VALIDATE_IP) !== false ? "<a href=\"?/IP/$mask\">$mask</a>" : utf8tohtml($mask))); -} +// This file is no longer used. diff --git a/inc/mod/config-editor.php b/inc/mod/config-editor.php index 3f15ebe5..0f6dbc9a 100644 --- a/inc/mod/config-editor.php +++ b/inc/mod/config-editor.php @@ -1,9 +1,15 @@ <?php +/* + * Copyright (c) 2010-2013 Tinyboard Development Group + */ + +defined('TINYBOARD') or exit; + function permission_to_edit_config_var($varname) { global $config, $mod; - if (is_array($config['mod']['config'][DISABLED])) { + if (isset($config['mod']['config'][DISABLED])) { foreach ($config['mod']['config'][DISABLED] as $disabled_var_name) { $disabled_var_name = explode('>', $disabled_var_name); if (count($disabled_var_name) == 1) @@ -14,10 +20,11 @@ function permission_to_edit_config_var($varname) { } $allow_only = false; - // for ($perm = (int)$mod['type']; $perm >= JANITOR; $perm --) { - for ($perm = JANITOR; $perm <= (int)$mod['type']; $perm ++) { + foreach ($config['mod']['groups'] as $perm => $perm_name) { + if ($perm > $mod['type']) + break; $allow_only = false; - if (is_array($config['mod']['config'][$perm])) { + if (isset($config['mod']['config'][$perm]) && is_array($config['mod']['config'][$perm])) { foreach ($config['mod']['config'][$perm] as $perm_var_name) { if ($perm_var_name == '!') { $allow_only = true; @@ -92,7 +99,7 @@ function config_vars() { continue; // This is just an alias. if (!preg_match('/^array|\[\]|function/', $var['default']) && !preg_match('/^Example: /', trim(implode(' ', $var['comment'])))) { $syntax_error = true; - $temp = eval('$syntax_error = false;return ' . $var['default'] . ';'); + $temp = eval('$syntax_error = false;return @' . $var['default'] . ';'); if ($syntax_error && $temp === false) { error('Error parsing config.php (line ' . $line_no . ')!', null, $var); } elseif (!isset($temp)) { diff --git a/inc/mod/pages.php b/inc/mod/pages.php index 2bd33926..5166a348 100644 --- a/inc/mod/pages.php +++ b/inc/mod/pages.php @@ -4,10 +4,7 @@ * Copyright (c) 2010-2013 Tinyboard Development Group */ -if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - exit; -} +defined('TINYBOARD') or exit; function mod_page($title, $template, $args, $subtitle = false) { global $config, $mod; @@ -18,6 +15,7 @@ function mod_page($title, $template, $args, $subtitle = false) { 'hide_dashboard_link' => $template == 'mod/dashboard.html', 'title' => $title, 'subtitle' => $subtitle, + 'nojavascript' => true, 'body' => Element($template, array_merge( array('config' => $config, 'mod' => $mod), @@ -291,7 +289,7 @@ function mod_search($type, $search_query_escaped, $page_no = 1) { } if ($type == 'bans') { - $query = 'SELECT ``bans``.*, `username` FROM ``bans`` LEFT JOIN ``mods`` ON `mod` = ``mods``.`id` WHERE ' . $sql_like . ' ORDER BY (`expires` IS NOT NULL AND `expires` < UNIX_TIMESTAMP()), `set` DESC'; + $query = 'SELECT ``bans``.*, `username` FROM ``bans`` LEFT JOIN ``mods`` ON `creator` = ``mods``.`id` WHERE ' . $sql_like . ' ORDER BY (`expires` IS NOT NULL AND `expires` < UNIX_TIMESTAMP()), `created` DESC'; $sql_table = 'bans'; if (!hasPermission($config['mod']['view_banlist'])) error($config['error']['noaccess']); @@ -319,8 +317,9 @@ function mod_search($type, $search_query_escaped, $page_no = 1) { if ($type == 'bans') { foreach ($results as &$ban) { - if (filter_var($ban['ip'], FILTER_VALIDATE_IP) !== false) - $ban['real_ip'] = true; + $ban['mask'] = Bans::range_to_string(array($ban['ipstart'], $ban['ipend'])); + if (filter_var($ban['mask'], FILTER_VALIDATE_IP) !== false) + $ban['single_addr'] = true; } } @@ -752,9 +751,7 @@ function mod_page_ip($ip) { if (!hasPermission($config['mod']['unban'])) error($config['error']['noaccess']); - require_once 'inc/mod/ban.php'; - - unban($_POST['ban_id']); + Bans::delete($_POST['ban_id'], true); header('Location: ?/IP/' . $ip . '#bans', true, $config['redirect_http']); return; @@ -813,10 +810,7 @@ function mod_page_ip($ip) { $args['token'] = make_secure_link_token('ban'); if (hasPermission($config['mod']['view_ban'])) { - $query = prepare("SELECT ``bans``.*, `username` FROM ``bans`` LEFT JOIN ``mods`` ON `mod` = ``mods``.`id` WHERE `ip` = :ip ORDER BY `set` DESC"); - $query->bindValue(':ip', $ip); - $query->execute() or error(db_error($query)); - $args['bans'] = $query->fetchAll(PDO::FETCH_ASSOC); + $args['bans'] = Bans::find($ip, false, true); } if (hasPermission($config['mod']['view_notes'])) { @@ -851,7 +845,7 @@ function mod_ban() { require_once 'inc/mod/ban.php'; - ban($_POST['ip'], $_POST['reason'], parse_time($_POST['length']), $_POST['board'] == '*' ? false : $_POST['board']); + Bans::new_ban($_POST['ip'], $_POST['reason'], $_POST['length'], $_POST['board'] == '*' ? false : $_POST['board']); if (isset($_POST['redirect'])) header('Location: ' . $_POST['redirect'], true, $config['redirect_http']); @@ -877,58 +871,27 @@ function mod_bans($page_no = 1) { if (preg_match('/^ban_(\d+)$/', $name, $match)) $unban[] = $match[1]; } - if (isset($config['mod']['unban_limit'])){ - if (count($unban) <= $config['mod']['unban_limit'] || $config['mod']['unban_limit'] == -1){ - if (!empty($unban)) { - query('DELETE FROM ``bans`` WHERE `id` = ' . implode(' OR `id` = ', $unban)) or error(db_error()); + if (isset($config['mod']['unban_limit']) && $config['mod']['unban_limit'] && count($unban) > $config['mod']['unban_limit']) + error(sprintf($config['error']['toomanyunban'], $config['mod']['unban_limit'], count($unban))); - foreach ($unban as $id) { - modLog("Removed ban #{$id}"); - } - } - } else { - error(sprintf($config['error']['toomanyunban'], $config['mod']['unban_limit'], count($unban) )); + foreach ($unban as $id) { + Bans::delete($id, true); } - - } else { - - if (!empty($unban)) { - query('DELETE FROM ``bans`` WHERE `id` = ' . implode(' OR `id` = ', $unban)) or error(db_error()); - - foreach ($unban as $id) { - modLog("Removed ban #{$id}"); - } - } - - } header('Location: ?/bans', true, $config['redirect_http']); + return; } - if ($config['mod']['view_banexpired']) { - $query = prepare("SELECT ``bans``.*, `username` FROM ``bans`` LEFT JOIN ``mods`` ON `mod` = ``mods``.`id` ORDER BY (`expires` IS NOT NULL AND `expires` < :time), `set` DESC LIMIT :offset, :limit"); - } else { - // Filter out expired bans - $query = prepare("SELECT ``bans``.*, `username` FROM ``bans`` INNER JOIN ``mods`` ON `mod` = ``mods``.`id` WHERE `expires` = 0 OR `expires` > :time ORDER BY `set` DESC LIMIT :offset, :limit"); - } - $query->bindValue(':time', time(), PDO::PARAM_INT); - $query->bindValue(':limit', $config['mod']['banlist_page'], PDO::PARAM_INT); - $query->bindValue(':offset', ($page_no - 1) * $config['mod']['banlist_page'], PDO::PARAM_INT); - $query->execute() or error(db_error($query)); - $bans = $query->fetchAll(PDO::FETCH_ASSOC); + $bans = Bans::list_all(($page_no - 1) * $config['mod']['banlist_page'], $config['mod']['banlist_page']); if (empty($bans) && $page_no > 1) error($config['error']['404']); - $query = prepare("SELECT COUNT(*) FROM ``bans``"); - $query->execute() or error(db_error($query)); - $count = $query->fetchColumn(); - foreach ($bans as &$ban) { - if (filter_var($ban['ip'], FILTER_VALIDATE_IP) !== false) - $ban['real_ip'] = true; + if (filter_var($ban['mask'], FILTER_VALIDATE_IP) !== false) + $ban['single_addr'] = true; } - mod_page(_('Ban list'), 'mod/ban_list.html', array('bans' => $bans, 'count' => $count)); + mod_page(_('Ban list'), 'mod/ban_list.html', array('bans' => $bans, 'count' => Bans::count())); } @@ -1327,7 +1290,7 @@ function mod_ban_post($board, $delete, $post, $token = false) { if (isset($_POST['ip'])) $ip = $_POST['ip']; - ban($ip, $_POST['reason'], parse_time($_POST['length']), $_POST['board'] == '*' ? false : $_POST['board']); + Bans::new_ban($_POST['ip'], $_POST['reason'], $_POST['length'], $_POST['board'] == '*' ? false : $_POST['board']); if (isset($_POST['public_message'], $_POST['message'])) { // public ban message @@ -1740,8 +1703,8 @@ function mod_user_new() { } } - $_POST['type'] = (int) $_POST['type']; - if ($_POST['type'] !== JANITOR && $_POST['type'] !== MOD && $_POST['type'] !== ADMIN) + $type = (int)$_POST['type']; + if (!isset($config['mod']['groups'][$type]) || $type == DISABLED) error(sprintf($config['error']['invalidfield'], 'type')); $salt = generate_salt(); @@ -1751,7 +1714,7 @@ function mod_user_new() { $query->bindValue(':username', $_POST['username']); $query->bindValue(':password', $password); $query->bindValue(':salt', $salt); - $query->bindValue(':type', $_POST['type']); + $query->bindValue(':type', $type); $query->bindValue(':boards', implode(',', $boards)); $query->execute() or error(db_error($query)); @@ -1785,11 +1748,39 @@ function mod_user_promote($uid, $action) { if (!hasPermission($config['mod']['promoteusers'])) error($config['error']['noaccess']); - $query = prepare("UPDATE ``mods`` SET `type` = `type` " . ($action == 'promote' ? "+1 WHERE `type` < " . (int)ADMIN : "-1 WHERE `type` > " . (int)JANITOR) . " AND `id` = :id"); + $query = prepare("SELECT `type`, `username` FROM ``mods`` WHERE `id` = :id"); $query->bindValue(':id', $uid); $query->execute() or error(db_error($query)); - modLog(($action == 'promote' ? 'Promoted' : 'Demoted') . " user #{$uid}"); + if (!$mod = $query->fetch(PDO::FETCH_ASSOC)) + error($config['error']['404']); + + $new_group = false; + + $groups = $config['mod']['groups']; + if ($action == 'demote') + $groups = array_reverse($groups, true); + + foreach ($groups as $group_value => $group_name) { + if ($action == 'promote' && $group_value > $mod['type']) { + $new_group = $group_value; + break; + } elseif ($action == 'demote' && $group_value < $mod['type']) { + $new_group = $group_value; + break; + } + } + + if ($new_group === false || $new_group == DISABLED) + error(_('Impossible to promote/demote user.')); + + $query = prepare("UPDATE ``mods`` SET `type` = :group_value WHERE `id` = :id"); + $query->bindValue(':id', $uid); + $query->bindValue(':group_value', $new_group); + $query->execute() or error(db_error($query)); + + modLog(($action == 'promote' ? 'Promoted' : 'Demoted') . ' user "' . + utf8tohtml($mod['username']) . '" to ' . $config['mod']['groups'][$new_group]); header('Location: ?/users', true, $config['redirect_http']); } @@ -1922,7 +1913,7 @@ function mod_rebuild() { if (isset($_POST['rebuild'])) { @set_time_limit($config['mod']['rebuild_timelimit']); - + $log = array(); $boards = listBoards(); $rebuilt_scripts = array(); @@ -1954,6 +1945,7 @@ function mod_rebuild() { continue; openBoard($board['uri']); + $config['try_smarter'] = false; if (isset($_POST['rebuild_index'])) { buildIndex(); @@ -2180,14 +2172,8 @@ function mod_config($board_config = false) { $config_append .= ' = '; - if (@$var['permissions'] && in_array($value, array(JANITOR, MOD, ADMIN, DISABLED))) { - $perm_array = array( - JANITOR => 'JANITOR', - MOD => 'MOD', - ADMIN => 'ADMIN', - DISABLED => 'DISABLED' - ); - $config_append .= $perm_array[$value]; + if (@$var['permissions'] && isset($config['mod']['groups'][$value])) { + $config_append .= $config['mod']['groups'][$value]; } else { $config_append .= var_export($value, true); } @@ -2417,11 +2403,21 @@ function mod_debug_recent_posts() { $query = query($query) or error(db_error()); $posts = $query->fetchAll(PDO::FETCH_ASSOC); + // Fetch recent posts from flood prevention cache + $query = query("SELECT * FROM ``flood`` ORDER BY `time` DESC") or error(db_error()); + $flood_posts = $query->fetchAll(PDO::FETCH_ASSOC); + foreach ($posts as &$post) { $post['snippet'] = pm_snippet($post['body']); + foreach ($flood_posts as $flood_post) { + if ($flood_post['time'] == $post['time'] && + $flood_post['posthash'] == make_comment_hex($post['body_nomarkup']) && + $flood_post['filehash'] == $post['filehash']) + $post['in_flood_table'] = true; + } } - mod_page(_('Debug: Recent posts'), 'mod/debug/recent_posts.html', array('posts' => $posts)); + mod_page(_('Debug: Recent posts'), 'mod/debug/recent_posts.html', array('posts' => $posts, 'flood_posts' => $flood_posts)); } function mod_debug_sql() { diff --git a/inc/remote.php b/inc/remote.php index fbce8dab..6a685e82 100644 --- a/inc/remote.php +++ b/inc/remote.php @@ -4,10 +4,7 @@ * Copyright (c) 2010-2013 Tinyboard Development Group */ -if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - exit; -} +defined('TINYBOARD') or exit; class Remote { public function __construct($config) { diff --git a/inc/template.php b/inc/template.php index 378f36d0..c10ac454 100644 --- a/inc/template.php +++ b/inc/template.php @@ -4,10 +4,7 @@ * Copyright (c) 2010-2013 Tinyboard Development Group */ -if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) { - // You cannot request this file directly. - exit; -} +defined('TINYBOARD') or exit; $twig = false; diff --git a/install.php b/install.php index 808529ab..51d5f133 100644 --- a/install.php +++ b/install.php @@ -1,7 +1,7 @@ <?php // Installation/upgrade file -define('VERSION', 'v0.9.6-dev-16 + <a href="https://int.vichan.net/devel/">vichan-devel-4.0.13</a>'); +define('VERSION', 'v0.9.6-dev-21 + <a href="https://int.vichan.net/devel/">vichan-devel-4.4.90</a>'); require 'inc/functions.php'; @@ -401,6 +401,93 @@ if (file_exists($config['has_installed'])) { ADD INDEX `list_threads` (`thread`, `sticky`, `bump`)", $board['uri'])) or error(db_error()); } case 'v0.9.6-dev-16': + case 'v0.9.6-dev-16 + <a href="https://int.vichan.net/devel/">vichan-devel-4.0.13</a>': + query("ALTER TABLE ``bans`` ADD INDEX `seen` (`seen`)") or error(db_error()); + case 'v0.9.6-dev-17': + query("ALTER TABLE ``ip_notes`` + DROP INDEX `ip`, + ADD INDEX `ip_lookup` (`ip`, `time`)") or error(db_error()); + case 'v0.9.6-dev-18': + query("CREATE TABLE IF NOT EXISTS ``flood`` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `ip` varchar(39) NOT NULL, + `board` varchar(58) CHARACTER SET utf8 NOT NULL, + `time` int(11) NOT NULL, + `posthash` char(32) NOT NULL, + `filehash` char(32) DEFAULT NULL, + `isreply` tinyint(1) NOT NULL, + PRIMARY KEY (`id`), + KEY `ip` (`ip`), + KEY `posthash` (`posthash`), + KEY `filehash` (`filehash`), + KEY `time` (`time`) + ) ENGINE=MyISAM DEFAULT CHARSET=ascii COLLATE=ascii_bin AUTO_INCREMENT=1 ;") or error(db_error()); + case 'v0.9.6-dev-19': + query("UPDATE ``mods`` SET `type` = 10 WHERE `type` = 0") or error(db_error()); + query("UPDATE ``mods`` SET `type` = 20 WHERE `type` = 1") or error(db_error()); + query("UPDATE ``mods`` SET `type` = 30 WHERE `type` = 2") or error(db_error()); + query("ALTER TABLE ``mods`` CHANGE `type` `type` smallint(1) NOT NULL") or error(db_error()); + case 'v0.9.6-dev-20': + query("CREATE TABLE IF NOT EXISTS `bans_new_temp` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `ipstart` varbinary(16) NOT NULL, + `ipend` varbinary(16) DEFAULT NULL, + `created` int(10) unsigned NOT NULL, + `expires` int(10) unsigned DEFAULT NULL, + `board` varchar(58) DEFAULT NULL, + `creator` int(10) NOT NULL, + `reason` text, + `seen` tinyint(1) NOT NULL, + `post` blob, + PRIMARY KEY (`id`), + KEY `expires` (`expires`), + KEY `ipstart` (`ipstart`,`ipend`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1") or error(db_error()); + $listquery = query("SELECT * FROM ``bans`` ORDER BY `id`") or error(db_error()); + while ($ban = $listquery->fetch(PDO::FETCH_ASSOC)) { + $query = prepare("INSERT INTO ``bans_new_temp`` VALUES + (NULL, :ipstart, :ipend, :created, :expires, :board, :creator, :reason, :seen, NULL)"); + + $range = Bans::parse_range($ban['ip']); + if ($range === false) { + // Invalid retard ban; just skip it. + continue; + } + + $query->bindValue(':ipstart', $range[0]); + if ($range[1] !== false && $range[1] != $range[0]) + $query->bindValue(':ipend', $range[1]); + else + $query->bindValue(':ipend', null, PDO::PARAM_NULL); + + $query->bindValue(':created', $ban['set']); + + if ($ban['expires']) + $query->bindValue(':expires', $ban['expires']); + else + $query->bindValue(':expires', null, PDO::PARAM_NULL); + + if ($ban['board']) + $query->bindValue(':board', $ban['board']); + else + $query->bindValue(':board', null, PDO::PARAM_NULL); + + $query->bindValue(':creator', $ban['mod']); + + if ($ban['reason']) + $query->bindValue(':reason', $ban['reason']); + else + $query->bindValue(':reason', null, PDO::PARAM_NULL); + + $query->bindValue(':seen', $ban['seen']); + $query->execute() or error(db_error($query)); + } + + // Drop old bans table + query("DROP TABLE ``bans``") or error(db_error()); + // Replace with new table + query("RENAME TABLE ``bans_new_temp`` TO ``bans``") or error(db_error()); + case 'v0.9.6-dev-21': case false: // Update version number file_write($config['has_installed'], VERSION); diff --git a/install.sql b/install.sql index 6952b540..bb54b9b4 100644 --- a/install.sql +++ b/install.sql @@ -40,17 +40,20 @@ CREATE TABLE IF NOT EXISTS `antispam` ( -- CREATE TABLE IF NOT EXISTS `bans` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `ip` varchar(39) CHARACTER SET ascii NOT NULL, - `mod` int(11) NOT NULL COMMENT 'which mod made the ban', - `set` int(11) NOT NULL, - `expires` int(11) DEFAULT NULL, + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `ipstart` varbinary(16) NOT NULL, + `ipend` varbinary(16) DEFAULT NULL, + `created` int(10) unsigned NOT NULL, + `expires` int(10) unsigned DEFAULT NULL, + `board` varchar(58) DEFAULT NULL, + `creator` int(10) NOT NULL, `reason` text, - `board` varchar(58) CHARACTER SET utf8 DEFAULT NULL, `seen` tinyint(1) NOT NULL, + `post` blob, PRIMARY KEY (`id`), - KEY `ip` (`ip`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ; + KEY `expires` (`expires`), + KEY `ipstart` (`ipstart`,`ipend`) +) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- @@ -100,7 +103,7 @@ CREATE TABLE IF NOT EXISTS `ip_notes` ( `time` int(11) NOT NULL, `body` text NOT NULL, UNIQUE KEY `id` (`id`), - KEY `ip` (`ip`) + KEY `ip_lookup` (`ip`, `time`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- @@ -130,18 +133,18 @@ CREATE TABLE IF NOT EXISTS `mods` ( `username` varchar(30) NOT NULL, `password` char(64) CHARACTER SET ascii NOT NULL COMMENT 'SHA256', `salt` char(32) CHARACTER SET ascii NOT NULL, - `type` smallint(1) NOT NULL COMMENT '0: janitor, 1: mod, 2: admin', + `type` smallint(2) NOT NULL, `boards` text CHARACTER SET utf8 NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`,`username`) -) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=5 ; +) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ; -- -- Dumping data for table `mods` -- INSERT INTO `mods` VALUES -(1, 'admin', 'cedad442efeef7112fed0f50b011b2b9bf83f6898082f995f69dd7865ca19fb7', '4a44c6c55df862ae901b413feecb0d49', 2, '*'); +(1, 'admin', 'cedad442efeef7112fed0f50b011b2b9bf83f6898082f995f69dd7865ca19fb7', '4a44c6c55df862ae901b413feecb0d49', 30, '*'); -- -------------------------------------------------------- @@ -256,6 +259,27 @@ CREATE TABLE IF NOT EXISTS `theme_settings` ( KEY `theme` (`theme`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4; +-- -------------------------------------------------------- + +-- +-- Table structure for table `flood` +-- + +CREATE TABLE IF NOT EXISTS `flood` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `ip` varchar(39) NOT NULL, + `board` varchar(58) CHARACTER SET utf8 NOT NULL, + `time` int(11) NOT NULL, + `posthash` char(32) NOT NULL, + `filehash` char(32) DEFAULT NULL, + `isreply` tinyint(1) NOT NULL, + PRIMARY KEY (`id`), + KEY `ip` (`ip`), + KEY `posthash` (`posthash`), + KEY `filehash` (`filehash`), + KEY `time` (`time`) +) ENGINE=MyISAM DEFAULT CHARSET=ascii COLLATE=ascii_bin AUTO_INCREMENT=1 ; + /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/js/ajax-post-controls.js b/js/ajax-post-controls.js new file mode 100644 index 00000000..fcb3da9d --- /dev/null +++ b/js/ajax-post-controls.js @@ -0,0 +1,77 @@ +/* + * ajax-post-controls.js + * https://github.com/savetheinternet/Tinyboard/blob/master/js/ajax-post-controls.js + * + * Released under the MIT license + * Copyright (c) 2013 Michael Save <savetheinternet@tinyboard.org> + * + * Usage: + * $config['additional_javascript'][] = 'js/jquery.min.js'; + * $config['additional_javascript'][] = 'js/ajax-post-controls.js'; + * + */ + +$(window).ready(function() { + var do_not_ajax = false; + + var setup_form = function($form) { + $form.find('input[type="submit"]').click(function() { + $form.data('submit-btn', this); + });; + $form.submit(function(e) { + if (!$(this).data('submit-btn')) + return true; + if (do_not_ajax) + return true; + if (window.FormData === undefined) + return true; + + var form = this; + + var formData = new FormData(this); + formData.append('json_response', '1'); + formData.append($($(form).data('submit-btn')).attr('name'), $($(form).data('submit-btn')).val()); + + $.ajax({ + url: this.action, + type: 'POST', + success: function(post_response) { + if (post_response.error) { + alert(post_response.error); + } else if (post_response.success) { + if ($($(form).data('submit-btn')).attr('name') == 'report') { + alert(_('Reported post(s).')); + if ($(form).hasClass('post-actions')) { + $(form).parents('div.post').find('input[type="checkbox"].delete').click(); + } else { + $(form).find('input[name="reason"]').val(''); + } + } else { + window.location.reload(); + } + } else { + alert(_('An unknown error occured!')); + } + $($(form).data('submit-btn')).val($($(form).data('submit-btn')).data('orig-val')).removeAttr('disabled'); + }, + error: function(xhr, status, er) { + // An error occured + // TODO + alert(_('Something went wrong... An unknown error occured!')); + }, + data: formData, + cache: false, + contentType: false, + processData: false + }, 'json'); + + $($(form).data('submit-btn')).attr('disabled', true).data('orig-val', $($(form).data('submit-btn')).val()).val(_('Working...')); + + return false; + }); + }; + setup_form($('form[name="postcontrols"]')); + $(window).on('quick-post-controls', function(e, form) { + setup_form($(form)); + }); +}); diff --git a/js/ajax.js b/js/ajax.js new file mode 100644 index 00000000..74cfe9c0 --- /dev/null +++ b/js/ajax.js @@ -0,0 +1,128 @@ +/* + * ajax.js + * https://github.com/savetheinternet/Tinyboard/blob/master/js/ajax.js + * + * Released under the MIT license + * Copyright (c) 2013 Michael Save <savetheinternet@tinyboard.org> + * + * Usage: + * $config['additional_javascript'][] = 'js/jquery.min.js'; + * $config['additional_javascript'][] = 'js/ajax.js'; + * + */ + +$(window).ready(function() { + var do_not_ajax = false; + + var setup_form = function($form) { + $form.submit(function() { + if (do_not_ajax) + return true; + var form = this; + var submit_txt = $(this).find('input[type="submit"]').val(); + if (window.FormData === undefined) + return true; + + var formData = new FormData(this); + formData.append('json_response', '1'); + formData.append('post', submit_txt); + + var updateProgress = function(e) { + $(form).find('input[type="submit"]').val(_('Posting... (#%)').replace('#', Math.round(e.position / e.total * 100))); + }; + + $.ajax({ + url: this.action, + type: 'POST', + xhr: function() { + var xhr = $.ajaxSettings.xhr(); + if(xhr.upload) { + xhr.upload.addEventListener('progress', updateProgress, false); + } + return xhr; + }, + success: function(post_response) { + if (post_response.error) { + if (post_response.banned) { + // You are banned. Must post the form normally so the user can see the ban message. + do_not_ajax = true; + $(form).find('input[type="submit"]').each(function() { + var $replacement = $('<input type="hidden">'); + $replacement.attr('name', $(this).attr('name')); + $replacement.val(submit_txt); + $(this) + .after($replacement) + .replaceWith($('<input type="button">').val(submit_txt)); + }); + $(form).submit(); + } else { + alert(post_response.error); + $(form).find('input[type="submit"]').val(submit_txt); + $(form).find('input[type="submit"]').removeAttr('disabled'); + } + } else if (post_response.redirect && post_response.id) { + if (!$(form).find('input[name="thread"]').length) { + document.location = post_response.redirect; + } else { + $.ajax({ + url: document.location, + success: function(data) { + $(data).find('div.post.reply').each(function() { + var id = $(this).attr('id'); + if($('#' + id).length == 0) { + $(this).insertAfter($('div.post:last').next()).after('<br class="clear">'); + $(document).trigger('new_post', this); + } + }); + + highlightReply(post_response.id); + window.location.hash = post_response.id; + $(window).scrollTop($('div.post#reply_' + post_response.id).offset().top); + + $(form).find('input[type="submit"]').val(submit_txt); + $(form).find('input[type="submit"]').removeAttr('disabled'); + $(form).find('input[name="subject"],input[name="file_url"],\ + textarea[name="body"],input[type="file"]').val('').change(); + }, + cache: false, + contentType: false, + processData: false + }, 'html'); + } + $(form).find('input[type="submit"]').val(_('Posted...')); + } else { + alert(_('An unknown error occured when posting!')); + $(form).find('input[type="submit"]').val(submit_txt); + $(form).find('input[type="submit"]').removeAttr('disabled'); + } + }, + error: function(xhr, status, er) { + // An error occured + do_not_ajax = true; + $(form).find('input[type="submit"]').each(function() { + var $replacement = $('<input type="hidden">'); + $replacement.attr('name', $(this).attr('name')); + $replacement.val(submit_txt); + $(this) + .after($replacement) + .replaceWith($('<input type="button">').val(submit_txt)); + }); + $(form).submit(); + }, + data: formData, + cache: false, + contentType: false, + processData: false + }, 'json'); + + $(form).find('input[type="submit"]').val(_('Posting...')); + $(form).find('input[type="submit"]').attr('disabled', true); + + return false; + }); + }; + setup_form($('form[name="post"]')); + $(window).on('quick-reply', function() { + setup_form($('form#quick-reply')); + }); +}); diff --git a/js/jquery-ui.custom.min.js b/js/jquery-ui.custom.min.js new file mode 100755 index 00000000..8986e466 --- /dev/null +++ b/js/jquery-ui.custom.min.js @@ -0,0 +1,6 @@ +/*! jQuery UI - v1.10.3 - 2013-09-14 +* http://jqueryui.com +* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js +* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ + +(function(e,t){function i(t,i){var s,n,r,o=t.nodeName.toLowerCase();return"area"===o?(s=t.parentNode,n=s.name,t.href&&n&&"map"===s.nodeName.toLowerCase()?(r=e("img[usemap=#"+n+"]")[0],!!r&&a(r)):!1):(/input|select|textarea|button|object/.test(o)?!t.disabled:"a"===o?t.href||i:i)&&a(t)}function a(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}var s=0,n=/^ui-id-\d+$/;e.ui=e.ui||{},e.extend(e.ui,{version:"1.10.3",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({focus:function(t){return function(i,a){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),a&&a.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),scrollParent:function(){var t;return t=e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(i){if(i!==t)return this.css("zIndex",i);if(this.length)for(var a,s,n=e(this[0]);n.length&&n[0]!==document;){if(a=n.css("position"),("absolute"===a||"relative"===a||"fixed"===a)&&(s=parseInt(n.css("zIndex"),10),!isNaN(s)&&0!==s))return s;n=n.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++s)})},removeUniqueId:function(){return this.each(function(){n.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,a){return!!e.data(t,a[3])},focusable:function(t){return i(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var a=e.attr(t,"tabindex"),s=isNaN(a);return(s||a>=0)&&i(t,!s)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(i,a){function s(t,i,a,s){return e.each(n,function(){i-=parseFloat(e.css(t,"padding"+this))||0,a&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),s&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var n="Width"===a?["Left","Right"]:["Top","Bottom"],r=a.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+a]=function(i){return i===t?o["inner"+a].call(this):this.each(function(){e(this).css(r,s(this,i)+"px")})},e.fn["outer"+a]=function(t,i){return"number"!=typeof t?o["outer"+a].call(this,t):this.each(function(){e(this).css(r,s(this,t,!0,i)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.support.selectstart="onselectstart"in document.createElement("div"),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,i,a){var s,n=e.ui[t].prototype;for(s in a)n.plugins[s]=n.plugins[s]||[],n.plugins[s].push([i,a[s]])},call:function(e,t,i){var a,s=e.plugins[t];if(s&&e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType)for(a=0;s.length>a;a++)e.options[s[a][0]]&&s[a][1].apply(e.element,i)}},hasScroll:function(t,i){if("hidden"===e(t).css("overflow"))return!1;var a=i&&"left"===i?"scrollLeft":"scrollTop",s=!1;return t[a]>0?!0:(t[a]=1,s=t[a]>0,t[a]=0,s)}})})(jQuery);(function(e,t){var i=0,s=Array.prototype.slice,a=e.cleanData;e.cleanData=function(t){for(var i,s=0;null!=(i=t[s]);s++)try{e(i).triggerHandler("remove")}catch(n){}a(t)},e.widget=function(i,s,a){var n,r,o,h,l={},u=i.split(".")[0];i=i.split(".")[1],n=u+"-"+i,a||(a=s,s=e.Widget),e.expr[":"][n.toLowerCase()]=function(t){return!!e.data(t,n)},e[u]=e[u]||{},r=e[u][i],o=e[u][i]=function(e,i){return this._createWidget?(arguments.length&&this._createWidget(e,i),t):new o(e,i)},e.extend(o,r,{version:a.version,_proto:e.extend({},a),_childConstructors:[]}),h=new s,h.options=e.widget.extend({},h.options),e.each(a,function(i,a){return e.isFunction(a)?(l[i]=function(){var e=function(){return s.prototype[i].apply(this,arguments)},t=function(e){return s.prototype[i].apply(this,e)};return function(){var i,s=this._super,n=this._superApply;return this._super=e,this._superApply=t,i=a.apply(this,arguments),this._super=s,this._superApply=n,i}}(),t):(l[i]=a,t)}),o.prototype=e.widget.extend(h,{widgetEventPrefix:r?h.widgetEventPrefix:i},l,{constructor:o,namespace:u,widgetName:i,widgetFullName:n}),r?(e.each(r._childConstructors,function(t,i){var s=i.prototype;e.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete r._childConstructors):s._childConstructors.push(o),e.widget.bridge(i,o)},e.widget.extend=function(i){for(var a,n,r=s.call(arguments,1),o=0,h=r.length;h>o;o++)for(a in r[o])n=r[o][a],r[o].hasOwnProperty(a)&&n!==t&&(i[a]=e.isPlainObject(n)?e.isPlainObject(i[a])?e.widget.extend({},i[a],n):e.widget.extend({},n):n);return i},e.widget.bridge=function(i,a){var n=a.prototype.widgetFullName||i;e.fn[i]=function(r){var o="string"==typeof r,h=s.call(arguments,1),l=this;return r=!o&&h.length?e.widget.extend.apply(null,[r].concat(h)):r,o?this.each(function(){var s,a=e.data(this,n);return a?e.isFunction(a[r])&&"_"!==r.charAt(0)?(s=a[r].apply(a,h),s!==a&&s!==t?(l=s&&s.jquery?l.pushStack(s.get()):s,!1):t):e.error("no such method '"+r+"' for "+i+" widget instance"):e.error("cannot call methods on "+i+" prior to initialization; "+"attempted to call method '"+r+"'")}):this.each(function(){var t=e.data(this,n);t?t.option(r||{})._init():e.data(this,n,new a(r,this))}),l}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,s){s=e(s||this.defaultElement||this)[0],this.element=e(s),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this.bindings=e(),this.hoverable=e(),this.focusable=e(),s!==this&&(e.data(s,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===s&&this.destroy()}}),this.document=e(s.style?s.ownerDocument:s.document||s),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(i,s){var a,n,r,o=i;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof i)if(o={},a=i.split("."),i=a.shift(),a.length){for(n=o[i]=e.widget.extend({},this.options[i]),r=0;a.length-1>r;r++)n[a[r]]=n[a[r]]||{},n=n[a[r]];if(i=a.pop(),s===t)return n[i]===t?null:n[i];n[i]=s}else{if(s===t)return this.options[i]===t?null:this.options[i];o[i]=s}return this._setOptions(o),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,"disabled"===e&&(this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!t).attr("aria-disabled",t),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(i,s,a){var n,r=this;"boolean"!=typeof i&&(a=s,s=i,i=!1),a?(s=n=e(s),this.bindings=this.bindings.add(s)):(a=s,s=this.element,n=this.widget()),e.each(a,function(a,o){function h(){return i||r.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof o?r[o]:o).apply(r,arguments):t}"string"!=typeof o&&(h.guid=o.guid=o.guid||h.guid||e.guid++);var l=a.match(/^(\w+)\s*(.*)$/),u=l[1]+r.eventNamespace,c=l[2];c?n.delegate(c,u,h):s.bind(u,h)})},_off:function(e,t){t=(t||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.unbind(t).undelegate(t)},_delay:function(e,t){function i(){return("string"==typeof e?s[e]:e).apply(s,arguments)}var s=this;return setTimeout(i,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,i,s){var a,n,r=this.options[t];if(s=s||{},i=e.Event(i),i.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),i.target=this.element[0],n=i.originalEvent)for(a in n)a in i||(i[a]=n[a]);return this.element.trigger(i,s),!(e.isFunction(r)&&r.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,i){e.Widget.prototype["_"+t]=function(s,a,n){"string"==typeof a&&(a={effect:a});var r,o=a?a===!0||"number"==typeof a?i:a.effect||i:t;a=a||{},"number"==typeof a&&(a={duration:a}),r=!e.isEmptyObject(a),a.complete=n,a.delay&&s.delay(a.delay),r&&e.effects&&e.effects.effect[o]?s[t](a):o!==t&&s[o]?s[o](a.duration,a.easing,n):s.queue(function(i){e(this)[t](),n&&n.call(s[0]),i()})}})})(jQuery);(function(e){var t=!1;e(document).mouseup(function(){t=!1}),e.widget("ui.mouse",{version:"1.10.3",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(i){return!0===e.data(i.target,t.widgetName+".preventClickEvent")?(e.removeData(i.target,t.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):undefined}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(i){if(!t){this._mouseStarted&&this._mouseUp(i),this._mouseDownEvent=i;var s=this,a=1===i.which,n="string"==typeof this.options.cancel&&i.target.nodeName?e(i.target).closest(this.options.cancel).length:!1;return a&&!n&&this._mouseCapture(i)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){s.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(i)&&this._mouseDelayMet(i)&&(this._mouseStarted=this._mouseStart(i)!==!1,!this._mouseStarted)?(i.preventDefault(),!0):(!0===e.data(i.target,this.widgetName+".preventClickEvent")&&e.removeData(i.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return s._mouseMove(e)},this._mouseUpDelegate=function(e){return s._mouseUp(e)},e(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),i.preventDefault(),t=!0,!0)):!0}},_mouseMove:function(t){return e.ui.ie&&(!document.documentMode||9>document.documentMode)&&!t.button?this._mouseUp(t):this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1,this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted)},_mouseUp:function(t){return e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,t.target===this._mouseDownEvent.target&&e.data(t.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(t)),!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})})(jQuery);(function(e){e.widget("ui.draggable",e.ui.mouse,{version:"1.10.3",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"!==this.options.helper||/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},_destroy:function(){this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy()},_mouseCapture:function(t){var i=this.options;return this.helper||i.disabled||e(t.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(t),this.handle?(e(i.iframeFix===!0?"iframe":i.iframeFix).each(function(){e("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>").css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(e(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(t){var i=this.options;return this.helper=this._createHelper(t),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),e.ui.ddmanager&&(e.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offsetParent=this.helper.offsetParent(),this.offsetParentCssPosition=this.offsetParent.css("position"),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},this.offset.scroll=!1,e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",t)===!1?(this._clear(),!1):(this._cacheHelperProportions(),e.ui.ddmanager&&!i.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this._mouseDrag(t,!0),e.ui.ddmanager&&e.ui.ddmanager.dragStart(this,t),!0)},_mouseDrag:function(t,i){if("fixed"===this.offsetParentCssPosition&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),!i){var a=this._uiHash();if(this._trigger("drag",t,a)===!1)return this._mouseUp({}),!1;this.position=a.position}return this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var i=this,a=!1;return e.ui.ddmanager&&!this.options.dropBehaviour&&(a=e.ui.ddmanager.drop(this,t)),this.dropped&&(a=this.dropped,this.dropped=!1),"original"!==this.options.helper||e.contains(this.element[0].ownerDocument,this.element[0])?("invalid"===this.options.revert&&!a||"valid"===this.options.revert&&a||this.options.revert===!0||e.isFunction(this.options.revert)&&this.options.revert.call(this.element,a)?e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",t)!==!1&&i._clear()}):this._trigger("stop",t)!==!1&&this._clear(),!1):!1},_mouseUp:function(t){return e("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),e.ui.ddmanager&&e.ui.ddmanager.dragStop(this,t),e.ui.mouse.prototype._mouseUp.call(this,t)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(t){return this.options.handle?!!e(t.target).closest(this.element.find(this.options.handle)).length:!0},_createHelper:function(t){var i=this.options,a=e.isFunction(i.helper)?e(i.helper.apply(this.element[0],[t])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return a.parents("body").length||a.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),a[0]===this.element[0]||/(fixed|absolute)/.test(a.css("position"))||a.css("position","absolute"),a},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){var t=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&e.ui.ie)&&(t={top:0,left:0}),{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var e=this.element.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,i,a,s=this.options;return s.containment?"window"===s.containment?(this.containment=[e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,e(window).scrollLeft()+e(window).width()-this.helperProportions.width-this.margins.left,e(window).scrollTop()+(e(window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],undefined):"document"===s.containment?(this.containment=[0,0,e(document).width()-this.helperProportions.width-this.margins.left,(e(document).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],undefined):s.containment.constructor===Array?(this.containment=s.containment,undefined):("parent"===s.containment&&(s.containment=this.helper[0].parentNode),i=e(s.containment),a=i[0],a&&(t="hidden"!==i.css("overflow"),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(t?Math.max(a.scrollWidth,a.offsetWidth):a.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(t?Math.max(a.scrollHeight,a.offsetHeight):a.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=i),undefined):(this.containment=null,undefined)},_convertPositionTo:function(t,i){i||(i=this.position);var a="absolute"===t?1:-1,s="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent;return this.offset.scroll||(this.offset.scroll={top:s.scrollTop(),left:s.scrollLeft()}),{top:i.top+this.offset.relative.top*a+this.offset.parent.top*a-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():this.offset.scroll.top)*a,left:i.left+this.offset.relative.left*a+this.offset.parent.left*a-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():this.offset.scroll.left)*a}},_generatePosition:function(t){var i,a,s,n,r=this.options,o="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,l=t.pageX,h=t.pageY;return this.offset.scroll||(this.offset.scroll={top:o.scrollTop(),left:o.scrollLeft()}),this.originalPosition&&(this.containment&&(this.relative_container?(a=this.relative_container.offset(),i=[this.containment[0]+a.left,this.containment[1]+a.top,this.containment[2]+a.left,this.containment[3]+a.top]):i=this.containment,t.pageX-this.offset.click.left<i[0]&&(l=i[0]+this.offset.click.left),t.pageY-this.offset.click.top<i[1]&&(h=i[1]+this.offset.click.top),t.pageX-this.offset.click.left>i[2]&&(l=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(h=i[3]+this.offset.click.top)),r.grid&&(s=r.grid[1]?this.originalPageY+Math.round((h-this.originalPageY)/r.grid[1])*r.grid[1]:this.originalPageY,h=i?s-this.offset.click.top>=i[1]||s-this.offset.click.top>i[3]?s:s-this.offset.click.top>=i[1]?s-r.grid[1]:s+r.grid[1]:s,n=r.grid[0]?this.originalPageX+Math.round((l-this.originalPageX)/r.grid[0])*r.grid[0]:this.originalPageX,l=i?n-this.offset.click.left>=i[0]||n-this.offset.click.left>i[2]?n:n-this.offset.click.left>=i[0]?n-r.grid[0]:n+r.grid[0]:n)),{top:h-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():this.offset.scroll.top),left:l-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():this.offset.scroll.left)}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(t,i,a){return a=a||this._uiHash(),e.ui.plugin.call(this,t,[i,a]),"drag"===t&&(this.positionAbs=this._convertPositionTo("absolute")),e.Widget.prototype._trigger.call(this,t,i,a)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),e.ui.plugin.add("draggable","connectToSortable",{start:function(t,i){var a=e(this).data("ui-draggable"),s=a.options,n=e.extend({},i,{item:a.element});a.sortables=[],e(s.connectToSortable).each(function(){var i=e.data(this,"ui-sortable");i&&!i.options.disabled&&(a.sortables.push({instance:i,shouldRevert:i.options.revert}),i.refreshPositions(),i._trigger("activate",t,n))})},stop:function(t,i){var a=e(this).data("ui-draggable"),s=e.extend({},i,{item:a.element});e.each(a.sortables,function(){this.instance.isOver?(this.instance.isOver=0,a.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=this.shouldRevert),this.instance._mouseStop(t),this.instance.options.helper=this.instance.options._helper,"original"===a.options.helper&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",t,s))})},drag:function(t,i){var a=e(this).data("ui-draggable"),s=this;e.each(a.sortables,function(){var n=!1,r=this;this.instance.positionAbs=a.positionAbs,this.instance.helperProportions=a.helperProportions,this.instance.offset.click=a.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(n=!0,e.each(a.sortables,function(){return this.instance.positionAbs=a.positionAbs,this.instance.helperProportions=a.helperProportions,this.instance.offset.click=a.offset.click,this!==r&&this.instance._intersectsWith(this.instance.containerCache)&&e.contains(r.instance.element[0],this.instance.element[0])&&(n=!1),n})),n?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=e(s).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return i.helper[0]},t.target=this.instance.currentItem[0],this.instance._mouseCapture(t,!0),this.instance._mouseStart(t,!0,!0),this.instance.offset.click.top=a.offset.click.top,this.instance.offset.click.left=a.offset.click.left,this.instance.offset.parent.left-=a.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=a.offset.parent.top-this.instance.offset.parent.top,a._trigger("toSortable",t),a.dropped=this.instance.element,a.currentItem=a.element,this.instance.fromOutside=a),this.instance.currentItem&&this.instance._mouseDrag(t)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",t,this.instance._uiHash(this.instance)),this.instance._mouseStop(t,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),a._trigger("fromSortable",t),a.dropped=!1)})}}),e.ui.plugin.add("draggable","cursor",{start:function(){var t=e("body"),i=e(this).data("ui-draggable").options;t.css("cursor")&&(i._cursor=t.css("cursor")),t.css("cursor",i.cursor)},stop:function(){var t=e(this).data("ui-draggable").options;t._cursor&&e("body").css("cursor",t._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,i){var a=e(i.helper),s=e(this).data("ui-draggable").options;a.css("opacity")&&(s._opacity=a.css("opacity")),a.css("opacity",s.opacity)},stop:function(t,i){var a=e(this).data("ui-draggable").options;a._opacity&&e(i.helper).css("opacity",a._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(){var t=e(this).data("ui-draggable");t.scrollParent[0]!==document&&"HTML"!==t.scrollParent[0].tagName&&(t.overflowOffset=t.scrollParent.offset())},drag:function(t){var i=e(this).data("ui-draggable"),a=i.options,s=!1;i.scrollParent[0]!==document&&"HTML"!==i.scrollParent[0].tagName?(a.axis&&"x"===a.axis||(i.overflowOffset.top+i.scrollParent[0].offsetHeight-t.pageY<a.scrollSensitivity?i.scrollParent[0].scrollTop=s=i.scrollParent[0].scrollTop+a.scrollSpeed:t.pageY-i.overflowOffset.top<a.scrollSensitivity&&(i.scrollParent[0].scrollTop=s=i.scrollParent[0].scrollTop-a.scrollSpeed)),a.axis&&"y"===a.axis||(i.overflowOffset.left+i.scrollParent[0].offsetWidth-t.pageX<a.scrollSensitivity?i.scrollParent[0].scrollLeft=s=i.scrollParent[0].scrollLeft+a.scrollSpeed:t.pageX-i.overflowOffset.left<a.scrollSensitivity&&(i.scrollParent[0].scrollLeft=s=i.scrollParent[0].scrollLeft-a.scrollSpeed))):(a.axis&&"x"===a.axis||(t.pageY-e(document).scrollTop()<a.scrollSensitivity?s=e(document).scrollTop(e(document).scrollTop()-a.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<a.scrollSensitivity&&(s=e(document).scrollTop(e(document).scrollTop()+a.scrollSpeed))),a.axis&&"y"===a.axis||(t.pageX-e(document).scrollLeft()<a.scrollSensitivity?s=e(document).scrollLeft(e(document).scrollLeft()-a.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<a.scrollSensitivity&&(s=e(document).scrollLeft(e(document).scrollLeft()+a.scrollSpeed)))),s!==!1&&e.ui.ddmanager&&!a.dropBehaviour&&e.ui.ddmanager.prepareOffsets(i,t)}}),e.ui.plugin.add("draggable","snap",{start:function(){var t=e(this).data("ui-draggable"),i=t.options;t.snapElements=[],e(i.snap.constructor!==String?i.snap.items||":data(ui-draggable)":i.snap).each(function(){var i=e(this),a=i.offset();this!==t.element[0]&&t.snapElements.push({item:this,width:i.outerWidth(),height:i.outerHeight(),top:a.top,left:a.left})})},drag:function(t,i){var a,s,n,r,o,l,h,u,d,c,p=e(this).data("ui-draggable"),f=p.options,m=f.snapTolerance,g=i.offset.left,v=g+p.helperProportions.width,y=i.offset.top,b=y+p.helperProportions.height;for(d=p.snapElements.length-1;d>=0;d--)o=p.snapElements[d].left,l=o+p.snapElements[d].width,h=p.snapElements[d].top,u=h+p.snapElements[d].height,o-m>v||g>l+m||h-m>b||y>u+m||!e.contains(p.snapElements[d].item.ownerDocument,p.snapElements[d].item)?(p.snapElements[d].snapping&&p.options.snap.release&&p.options.snap.release.call(p.element,t,e.extend(p._uiHash(),{snapItem:p.snapElements[d].item})),p.snapElements[d].snapping=!1):("inner"!==f.snapMode&&(a=m>=Math.abs(h-b),s=m>=Math.abs(u-y),n=m>=Math.abs(o-v),r=m>=Math.abs(l-g),a&&(i.position.top=p._convertPositionTo("relative",{top:h-p.helperProportions.height,left:0}).top-p.margins.top),s&&(i.position.top=p._convertPositionTo("relative",{top:u,left:0}).top-p.margins.top),n&&(i.position.left=p._convertPositionTo("relative",{top:0,left:o-p.helperProportions.width}).left-p.margins.left),r&&(i.position.left=p._convertPositionTo("relative",{top:0,left:l}).left-p.margins.left)),c=a||s||n||r,"outer"!==f.snapMode&&(a=m>=Math.abs(h-y),s=m>=Math.abs(u-b),n=m>=Math.abs(o-g),r=m>=Math.abs(l-v),a&&(i.position.top=p._convertPositionTo("relative",{top:h,left:0}).top-p.margins.top),s&&(i.position.top=p._convertPositionTo("relative",{top:u-p.helperProportions.height,left:0}).top-p.margins.top),n&&(i.position.left=p._convertPositionTo("relative",{top:0,left:o}).left-p.margins.left),r&&(i.position.left=p._convertPositionTo("relative",{top:0,left:l-p.helperProportions.width}).left-p.margins.left)),!p.snapElements[d].snapping&&(a||s||n||r||c)&&p.options.snap.snap&&p.options.snap.snap.call(p.element,t,e.extend(p._uiHash(),{snapItem:p.snapElements[d].item})),p.snapElements[d].snapping=a||s||n||r||c)}}),e.ui.plugin.add("draggable","stack",{start:function(){var t,i=this.data("ui-draggable").options,a=e.makeArray(e(i.stack)).sort(function(t,i){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(i).css("zIndex"),10)||0)});a.length&&(t=parseInt(e(a[0]).css("zIndex"),10)||0,e(a).each(function(i){e(this).css("zIndex",t+i)}),this.css("zIndex",t+a.length))}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,i){var a=e(i.helper),s=e(this).data("ui-draggable").options;a.css("zIndex")&&(s._zIndex=a.css("zIndex")),a.css("zIndex",s.zIndex)},stop:function(t,i){var a=e(this).data("ui-draggable").options;a._zIndex&&e(i.helper).css("zIndex",a._zIndex)}})})(jQuery);(function(e){function t(e,t,i){return e>t&&t+i>e}e.widget("ui.droppable",{version:"1.10.3",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var t=this.options,i=t.accept;this.isover=!1,this.isout=!0,this.accept=e.isFunction(i)?i:function(e){return e.is(i)},this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight},e.ui.ddmanager.droppables[t.scope]=e.ui.ddmanager.droppables[t.scope]||[],e.ui.ddmanager.droppables[t.scope].push(this),t.addClasses&&this.element.addClass("ui-droppable")},_destroy:function(){for(var t=0,i=e.ui.ddmanager.droppables[this.options.scope];i.length>t;t++)i[t]===this&&i.splice(t,1);this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(t,i){"accept"===t&&(this.accept=e.isFunction(i)?i:function(e){return e.is(i)}),e.Widget.prototype._setOption.apply(this,arguments)},_activate:function(t){var i=e.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),i&&this._trigger("activate",t,this.ui(i))},_deactivate:function(t){var i=e.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),i&&this._trigger("deactivate",t,this.ui(i))},_over:function(t){var i=e.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",t,this.ui(i)))},_out:function(t){var i=e.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",t,this.ui(i)))},_drop:function(t,i){var a=i||e.ui.ddmanager.current,s=!1;return a&&(a.currentItem||a.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var t=e.data(this,"ui-droppable");return t.options.greedy&&!t.options.disabled&&t.options.scope===a.options.scope&&t.accept.call(t.element[0],a.currentItem||a.element)&&e.ui.intersect(a,e.extend(t,{offset:t.element.offset()}),t.options.tolerance)?(s=!0,!1):undefined}),s?!1:this.accept.call(this.element[0],a.currentItem||a.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",t,this.ui(a)),this.element):!1):!1},ui:function(e){return{draggable:e.currentItem||e.element,helper:e.helper,position:e.position,offset:e.positionAbs}}}),e.ui.intersect=function(e,i,a){if(!i.offset)return!1;var s,n,r=(e.positionAbs||e.position.absolute).left,o=r+e.helperProportions.width,l=(e.positionAbs||e.position.absolute).top,h=l+e.helperProportions.height,u=i.offset.left,d=u+i.proportions.width,c=i.offset.top,p=c+i.proportions.height;switch(a){case"fit":return r>=u&&d>=o&&l>=c&&p>=h;case"intersect":return r+e.helperProportions.width/2>u&&d>o-e.helperProportions.width/2&&l+e.helperProportions.height/2>c&&p>h-e.helperProportions.height/2;case"pointer":return s=(e.positionAbs||e.position.absolute).left+(e.clickOffset||e.offset.click).left,n=(e.positionAbs||e.position.absolute).top+(e.clickOffset||e.offset.click).top,t(n,c,i.proportions.height)&&t(s,u,i.proportions.width);case"touch":return(l>=c&&p>=l||h>=c&&p>=h||c>l&&h>p)&&(r>=u&&d>=r||o>=u&&d>=o||u>r&&o>d);default:return!1}},e.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,i){var a,s,n=e.ui.ddmanager.droppables[t.options.scope]||[],r=i?i.type:null,o=(t.currentItem||t.element).find(":data(ui-droppable)").addBack();e:for(a=0;n.length>a;a++)if(!(n[a].options.disabled||t&&!n[a].accept.call(n[a].element[0],t.currentItem||t.element))){for(s=0;o.length>s;s++)if(o[s]===n[a].element[0]){n[a].proportions.height=0;continue e}n[a].visible="none"!==n[a].element.css("display"),n[a].visible&&("mousedown"===r&&n[a]._activate.call(n[a],i),n[a].offset=n[a].element.offset(),n[a].proportions={width:n[a].element[0].offsetWidth,height:n[a].element[0].offsetHeight})}},drop:function(t,i){var a=!1;return e.each((e.ui.ddmanager.droppables[t.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&e.ui.intersect(t,this,this.options.tolerance)&&(a=this._drop.call(this,i)||a),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],t.currentItem||t.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),a},dragStart:function(t,i){t.element.parentsUntil("body").bind("scroll.droppable",function(){t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,i)})},drag:function(t,i){t.options.refreshPositions&&e.ui.ddmanager.prepareOffsets(t,i),e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var a,s,n,r=e.ui.intersect(t,this,this.options.tolerance),o=!r&&this.isover?"isout":r&&!this.isover?"isover":null;o&&(this.options.greedy&&(s=this.options.scope,n=this.element.parents(":data(ui-droppable)").filter(function(){return e.data(this,"ui-droppable").options.scope===s}),n.length&&(a=e.data(n[0],"ui-droppable"),a.greedyChild="isover"===o)),a&&"isover"===o&&(a.isover=!1,a.isout=!0,a._out.call(a,i)),this[o]=!0,this["isout"===o?"isover":"isout"]=!1,this["isover"===o?"_over":"_out"].call(this,i),a&&"isout"===o&&(a.isout=!1,a.isover=!0,a._over.call(a,i)))}})},dragStop:function(t,i){t.element.parentsUntil("body").unbind("scroll.droppable"),t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,i)}}})(jQuery);(function(e){function t(e){return parseInt(e,10)||0}function i(e){return!isNaN(parseInt(e,10))}e.widget("ui.resizable",e.ui.mouse,{version:"1.10.3",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_create:function(){var t,i,s,a,n,r=this,o=this.options;if(this.element.addClass("ui-resizable"),e.extend(this,{_aspectRatio:!!o.aspectRatio,aspectRatio:o.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:o.helper||o.ghost||o.animate?o.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(e("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.data("ui-resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=o.handles||(e(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),t=this.handles.split(","),this.handles={},i=0;t.length>i;i++)s=e.trim(t[i]),n="ui-resizable-"+s,a=e("<div class='ui-resizable-handle "+n+"'></div>"),a.css({zIndex:o.zIndex}),"se"===s&&a.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[s]=".ui-resizable-"+s,this.element.append(a);this._renderAxis=function(t){var i,s,a,n;t=t||this.element;for(i in this.handles)this.handles[i].constructor===String&&(this.handles[i]=e(this.handles[i],this.element).show()),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)&&(s=e(this.handles[i],this.element),n=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),a=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),t.css(a,n),this._proportionallyResize()),e(this.handles[i]).length},this._renderAxis(this.element),this._handles=e(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){r.resizing||(this.className&&(a=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),r.axis=a&&a[1]?a[1]:"se")}),o.autoHide&&(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){o.disabled||(e(this).removeClass("ui-resizable-autohide"),r._handles.show())}).mouseleave(function(){o.disabled||r.resizing||(e(this).addClass("ui-resizable-autohide"),r._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t,i=function(t){e(t).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(i(this.element),t=this.element,this.originalElement.css({position:t.css("position"),width:t.outerWidth(),height:t.outerHeight(),top:t.css("top"),left:t.css("left")}).insertAfter(t),t.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_mouseCapture:function(t){var i,s,a=!1;for(i in this.handles)s=e(this.handles[i])[0],(s===t.target||e.contains(s,t.target))&&(a=!0);return!this.options.disabled&&a},_mouseStart:function(i){var s,a,n,r=this.options,o=this.element.position(),h=this.element;return this.resizing=!0,/absolute/.test(h.css("position"))?h.css({position:"absolute",top:h.css("top"),left:h.css("left")}):h.is(".ui-draggable")&&h.css({position:"absolute",top:o.top,left:o.left}),this._renderProxy(),s=t(this.helper.css("left")),a=t(this.helper.css("top")),r.containment&&(s+=e(r.containment).scrollLeft()||0,a+=e(r.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:s,top:a},this.size=this._helper?{width:h.outerWidth(),height:h.outerHeight()}:{width:h.width(),height:h.height()},this.originalSize=this._helper?{width:h.outerWidth(),height:h.outerHeight()}:{width:h.width(),height:h.height()},this.originalPosition={left:s,top:a},this.sizeDiff={width:h.outerWidth()-h.width(),height:h.outerHeight()-h.height()},this.originalMousePosition={left:i.pageX,top:i.pageY},this.aspectRatio="number"==typeof r.aspectRatio?r.aspectRatio:this.originalSize.width/this.originalSize.height||1,n=e(".ui-resizable-"+this.axis).css("cursor"),e("body").css("cursor","auto"===n?this.axis+"-resize":n),h.addClass("ui-resizable-resizing"),this._propagate("start",i),!0},_mouseDrag:function(t){var i,s=this.helper,a={},n=this.originalMousePosition,r=this.axis,o=this.position.top,h=this.position.left,l=this.size.width,u=this.size.height,c=t.pageX-n.left||0,d=t.pageY-n.top||0,p=this._change[r];return p?(i=p.apply(this,[t,c,d]),this._updateVirtualBoundaries(t.shiftKey),(this._aspectRatio||t.shiftKey)&&(i=this._updateRatio(i,t)),i=this._respectSize(i,t),this._updateCache(i),this._propagate("resize",t),this.position.top!==o&&(a.top=this.position.top+"px"),this.position.left!==h&&(a.left=this.position.left+"px"),this.size.width!==l&&(a.width=this.size.width+"px"),this.size.height!==u&&(a.height=this.size.height+"px"),s.css(a),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),e.isEmptyObject(a)||this._trigger("resize",t,this.ui()),!1):!1},_mouseStop:function(t){this.resizing=!1;var i,s,a,n,r,o,h,l=this.options,u=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),a=s&&e.ui.hasScroll(i[0],"left")?0:u.sizeDiff.height,n=s?0:u.sizeDiff.width,r={width:u.helper.width()-n,height:u.helper.height()-a},o=parseInt(u.element.css("left"),10)+(u.position.left-u.originalPosition.left)||null,h=parseInt(u.element.css("top"),10)+(u.position.top-u.originalPosition.top)||null,l.animate||this.element.css(e.extend(r,{top:h,left:o})),u.helper.height(u.size.height),u.helper.width(u.size.width),this._helper&&!l.animate&&this._proportionallyResize()),e("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(e){var t,s,a,n,r,o=this.options;r={minWidth:i(o.minWidth)?o.minWidth:0,maxWidth:i(o.maxWidth)?o.maxWidth:1/0,minHeight:i(o.minHeight)?o.minHeight:0,maxHeight:i(o.maxHeight)?o.maxHeight:1/0},(this._aspectRatio||e)&&(t=r.minHeight*this.aspectRatio,a=r.minWidth/this.aspectRatio,s=r.maxHeight*this.aspectRatio,n=r.maxWidth/this.aspectRatio,t>r.minWidth&&(r.minWidth=t),a>r.minHeight&&(r.minHeight=a),r.maxWidth>s&&(r.maxWidth=s),r.maxHeight>n&&(r.maxHeight=n)),this._vBoundaries=r},_updateCache:function(e){this.offset=this.helper.offset(),i(e.left)&&(this.position.left=e.left),i(e.top)&&(this.position.top=e.top),i(e.height)&&(this.size.height=e.height),i(e.width)&&(this.size.width=e.width)},_updateRatio:function(e){var t=this.position,s=this.size,a=this.axis;return i(e.height)?e.width=e.height*this.aspectRatio:i(e.width)&&(e.height=e.width/this.aspectRatio),"sw"===a&&(e.left=t.left+(s.width-e.width),e.top=null),"nw"===a&&(e.top=t.top+(s.height-e.height),e.left=t.left+(s.width-e.width)),e},_respectSize:function(e){var t=this._vBoundaries,s=this.axis,a=i(e.width)&&t.maxWidth&&t.maxWidth<e.width,n=i(e.height)&&t.maxHeight&&t.maxHeight<e.height,r=i(e.width)&&t.minWidth&&t.minWidth>e.width,o=i(e.height)&&t.minHeight&&t.minHeight>e.height,h=this.originalPosition.left+this.originalSize.width,l=this.position.top+this.size.height,u=/sw|nw|w/.test(s),c=/nw|ne|n/.test(s);return r&&(e.width=t.minWidth),o&&(e.height=t.minHeight),a&&(e.width=t.maxWidth),n&&(e.height=t.maxHeight),r&&u&&(e.left=h-t.minWidth),a&&u&&(e.left=h-t.maxWidth),o&&c&&(e.top=l-t.minHeight),n&&c&&(e.top=l-t.maxHeight),e.width||e.height||e.left||!e.top?e.width||e.height||e.top||!e.left||(e.left=null):e.top=null,e},_proportionallyResize:function(){if(this._proportionallyResizeElements.length){var e,t,i,s,a,n=this.helper||this.element;for(e=0;this._proportionallyResizeElements.length>e;e++){if(a=this._proportionallyResizeElements[e],!this.borderDif)for(this.borderDif=[],i=[a.css("borderTopWidth"),a.css("borderRightWidth"),a.css("borderBottomWidth"),a.css("borderLeftWidth")],s=[a.css("paddingTop"),a.css("paddingRight"),a.css("paddingBottom"),a.css("paddingLeft")],t=0;i.length>t;t++)this.borderDif[t]=(parseInt(i[t],10)||0)+(parseInt(s[t],10)||0);a.css({height:n.height()-this.borderDif[0]-this.borderDif[2]||0,width:n.width()-this.borderDif[1]-this.borderDif[3]||0})}}},_renderProxy:function(){var t=this.element,i=this.options;this.elementOffset=t.offset(),this._helper?(this.helper=this.helper||e("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(e,t){return{width:this.originalSize.width+t}},w:function(e,t){var i=this.originalSize,s=this.originalPosition;return{left:s.left+t,width:i.width-t}},n:function(e,t,i){var s=this.originalSize,a=this.originalPosition;return{top:a.top+i,height:s.height-i}},s:function(e,t,i){return{height:this.originalSize.height+i}},se:function(t,i,s){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,i,s]))},sw:function(t,i,s){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,i,s]))},ne:function(t,i,s){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,i,s]))},nw:function(t,i,s){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,i,s]))}},_propagate:function(t,i){e.ui.plugin.call(this,t,[i,this.ui()]),"resize"!==t&&this._trigger(t,i,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),e.ui.plugin.add("resizable","animate",{stop:function(t){var i=e(this).data("ui-resizable"),s=i.options,a=i._proportionallyResizeElements,n=a.length&&/textarea/i.test(a[0].nodeName),r=n&&e.ui.hasScroll(a[0],"left")?0:i.sizeDiff.height,o=n?0:i.sizeDiff.width,h={width:i.size.width-o,height:i.size.height-r},l=parseInt(i.element.css("left"),10)+(i.position.left-i.originalPosition.left)||null,u=parseInt(i.element.css("top"),10)+(i.position.top-i.originalPosition.top)||null;i.element.animate(e.extend(h,u&&l?{top:u,left:l}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseInt(i.element.css("width"),10),height:parseInt(i.element.css("height"),10),top:parseInt(i.element.css("top"),10),left:parseInt(i.element.css("left"),10)};a&&a.length&&e(a[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(){var i,s,a,n,r,o,h,l=e(this).data("ui-resizable"),u=l.options,c=l.element,d=u.containment,p=d instanceof e?d.get(0):/parent/.test(d)?c.parent().get(0):d;p&&(l.containerElement=e(p),/document/.test(d)||d===document?(l.containerOffset={left:0,top:0},l.containerPosition={left:0,top:0},l.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight}):(i=e(p),s=[],e(["Top","Right","Left","Bottom"]).each(function(e,a){s[e]=t(i.css("padding"+a))}),l.containerOffset=i.offset(),l.containerPosition=i.position(),l.containerSize={height:i.innerHeight()-s[3],width:i.innerWidth()-s[1]},a=l.containerOffset,n=l.containerSize.height,r=l.containerSize.width,o=e.ui.hasScroll(p,"left")?p.scrollWidth:r,h=e.ui.hasScroll(p)?p.scrollHeight:n,l.parentData={element:p,left:a.left,top:a.top,width:o,height:h}))},resize:function(t){var i,s,a,n,r=e(this).data("ui-resizable"),o=r.options,h=r.containerOffset,l=r.position,u=r._aspectRatio||t.shiftKey,c={top:0,left:0},d=r.containerElement;d[0]!==document&&/static/.test(d.css("position"))&&(c=h),l.left<(r._helper?h.left:0)&&(r.size.width=r.size.width+(r._helper?r.position.left-h.left:r.position.left-c.left),u&&(r.size.height=r.size.width/r.aspectRatio),r.position.left=o.helper?h.left:0),l.top<(r._helper?h.top:0)&&(r.size.height=r.size.height+(r._helper?r.position.top-h.top:r.position.top),u&&(r.size.width=r.size.height*r.aspectRatio),r.position.top=r._helper?h.top:0),r.offset.left=r.parentData.left+r.position.left,r.offset.top=r.parentData.top+r.position.top,i=Math.abs((r._helper?r.offset.left-c.left:r.offset.left-c.left)+r.sizeDiff.width),s=Math.abs((r._helper?r.offset.top-c.top:r.offset.top-h.top)+r.sizeDiff.height),a=r.containerElement.get(0)===r.element.parent().get(0),n=/relative|absolute/.test(r.containerElement.css("position")),a&&n&&(i-=r.parentData.left),i+r.size.width>=r.parentData.width&&(r.size.width=r.parentData.width-i,u&&(r.size.height=r.size.width/r.aspectRatio)),s+r.size.height>=r.parentData.height&&(r.size.height=r.parentData.height-s,u&&(r.size.width=r.size.height*r.aspectRatio))},stop:function(){var t=e(this).data("ui-resizable"),i=t.options,s=t.containerOffset,a=t.containerPosition,n=t.containerElement,r=e(t.helper),o=r.offset(),h=r.outerWidth()-t.sizeDiff.width,l=r.outerHeight()-t.sizeDiff.height;t._helper&&!i.animate&&/relative/.test(n.css("position"))&&e(this).css({left:o.left-a.left-s.left,width:h,height:l}),t._helper&&!i.animate&&/static/.test(n.css("position"))&&e(this).css({left:o.left-a.left-s.left,width:h,height:l})}}),e.ui.plugin.add("resizable","alsoResize",{start:function(){var t=e(this).data("ui-resizable"),i=t.options,s=function(t){e(t).each(function(){var t=e(this);t.data("ui-resizable-alsoresize",{width:parseInt(t.width(),10),height:parseInt(t.height(),10),left:parseInt(t.css("left"),10),top:parseInt(t.css("top"),10)})})};"object"!=typeof i.alsoResize||i.alsoResize.parentNode?s(i.alsoResize):i.alsoResize.length?(i.alsoResize=i.alsoResize[0],s(i.alsoResize)):e.each(i.alsoResize,function(e){s(e)})},resize:function(t,i){var s=e(this).data("ui-resizable"),a=s.options,n=s.originalSize,r=s.originalPosition,o={height:s.size.height-n.height||0,width:s.size.width-n.width||0,top:s.position.top-r.top||0,left:s.position.left-r.left||0},h=function(t,s){e(t).each(function(){var t=e(this),a=e(this).data("ui-resizable-alsoresize"),n={},r=s&&s.length?s:t.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(r,function(e,t){var i=(a[t]||0)+(o[t]||0);i&&i>=0&&(n[t]=i||null)}),t.css(n)})};"object"!=typeof a.alsoResize||a.alsoResize.nodeType?h(a.alsoResize):e.each(a.alsoResize,function(e,t){h(e,t)})},stop:function(){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","ghost",{start:function(){var t=e(this).data("ui-resizable"),i=t.options,s=t.size;t.ghost=t.originalElement.clone(),t.ghost.css({opacity:.25,display:"block",position:"relative",height:s.height,width:s.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass("string"==typeof i.ghost?i.ghost:""),t.ghost.appendTo(t.helper)},resize:function(){var t=e(this).data("ui-resizable");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=e(this).data("ui-resizable");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(){var t=e(this).data("ui-resizable"),i=t.options,s=t.size,a=t.originalSize,n=t.originalPosition,r=t.axis,o="number"==typeof i.grid?[i.grid,i.grid]:i.grid,h=o[0]||1,l=o[1]||1,u=Math.round((s.width-a.width)/h)*h,c=Math.round((s.height-a.height)/l)*l,d=a.width+u,p=a.height+c,f=i.maxWidth&&d>i.maxWidth,m=i.maxHeight&&p>i.maxHeight,g=i.minWidth&&i.minWidth>d,v=i.minHeight&&i.minHeight>p;i.grid=o,g&&(d+=h),v&&(p+=l),f&&(d-=h),m&&(p-=l),/^(se|s|e)$/.test(r)?(t.size.width=d,t.size.height=p):/^(ne)$/.test(r)?(t.size.width=d,t.size.height=p,t.position.top=n.top-c):/^(sw)$/.test(r)?(t.size.width=d,t.size.height=p,t.position.left=n.left-u):(t.size.width=d,t.size.height=p,t.position.top=n.top-c,t.position.left=n.left-u)}})})(jQuery);(function(e){e.widget("ui.selectable",e.ui.mouse,{version:"1.10.3",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var t,i=this;this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){t=e(i.options.filter,i.element[0]),t.addClass("ui-selectee"),t.each(function(){var t=e(this),i=t.offset();e.data(this,"selectable-item",{element:this,$element:t,left:i.left,top:i.top,right:i.left+t.outerWidth(),bottom:i.top+t.outerHeight(),startselected:!1,selected:t.hasClass("ui-selected"),selecting:t.hasClass("ui-selecting"),unselecting:t.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=t.addClass("ui-selectee"),this._mouseInit(),this.helper=e("<div class='ui-selectable-helper'></div>")},_destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled"),this._mouseDestroy()},_mouseStart:function(t){var i=this,s=this.options;this.opos=[t.pageX,t.pageY],this.options.disabled||(this.selectees=e(s.filter,this.element[0]),this._trigger("start",t),e(s.appendTo).append(this.helper),this.helper.css({left:t.pageX,top:t.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=e.data(this,"selectable-item");s.startselected=!0,t.metaKey||t.ctrlKey||(s.$element.removeClass("ui-selected"),s.selected=!1,s.$element.addClass("ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",t,{unselecting:s.element}))}),e(t.target).parents().addBack().each(function(){var s,a=e.data(this,"selectable-item");return a?(s=!t.metaKey&&!t.ctrlKey||!a.$element.hasClass("ui-selected"),a.$element.removeClass(s?"ui-unselecting":"ui-selected").addClass(s?"ui-selecting":"ui-unselecting"),a.unselecting=!s,a.selecting=s,a.selected=s,s?i._trigger("selecting",t,{selecting:a.element}):i._trigger("unselecting",t,{unselecting:a.element}),!1):undefined}))},_mouseDrag:function(t){if(this.dragged=!0,!this.options.disabled){var i,s=this,a=this.options,n=this.opos[0],r=this.opos[1],o=t.pageX,h=t.pageY;return n>o&&(i=o,o=n,n=i),r>h&&(i=h,h=r,r=i),this.helper.css({left:n,top:r,width:o-n,height:h-r}),this.selectees.each(function(){var i=e.data(this,"selectable-item"),l=!1;i&&i.element!==s.element[0]&&("touch"===a.tolerance?l=!(i.left>o||n>i.right||i.top>h||r>i.bottom):"fit"===a.tolerance&&(l=i.left>n&&o>i.right&&i.top>r&&h>i.bottom),l?(i.selected&&(i.$element.removeClass("ui-selected"),i.selected=!1),i.unselecting&&(i.$element.removeClass("ui-unselecting"),i.unselecting=!1),i.selecting||(i.$element.addClass("ui-selecting"),i.selecting=!0,s._trigger("selecting",t,{selecting:i.element}))):(i.selecting&&((t.metaKey||t.ctrlKey)&&i.startselected?(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.$element.addClass("ui-selected"),i.selected=!0):(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.startselected&&(i.$element.addClass("ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",t,{unselecting:i.element}))),i.selected&&(t.metaKey||t.ctrlKey||i.startselected||(i.$element.removeClass("ui-selected"),i.selected=!1,i.$element.addClass("ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",t,{unselecting:i.element})))))}),!1}},_mouseStop:function(t){var i=this;return this.dragged=!1,e(".ui-unselecting",this.element[0]).each(function(){var s=e.data(this,"selectable-item");s.$element.removeClass("ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",t,{unselected:s.element})}),e(".ui-selecting",this.element[0]).each(function(){var s=e.data(this,"selectable-item");s.$element.removeClass("ui-selecting").addClass("ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",t,{selected:s.element})}),this._trigger("stop",t),this.helper.remove(),!1}})})(jQuery);(function(e){function t(e,t,i){return e>t&&t+i>e}function i(e){return/left|right/.test(e.css("float"))||/inline|table-cell/.test(e.css("display"))}e.widget("ui.sortable",e.ui.mouse,{version:"1.10.3",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_create:function(){var e=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?"x"===e.axis||i(this.items[0].item):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_setOption:function(t,i){"disabled"===t?(this.options[t]=i,this.widget().toggleClass("ui-sortable-disabled",!!i)):e.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(t,i){var s=null,a=!1,n=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(t),e(t.target).parents().each(function(){return e.data(this,n.widgetName+"-item")===n?(s=e(this),!1):undefined}),e.data(t.target,n.widgetName+"-item")===n&&(s=e(t.target)),s?!this.options.handle||i||(e(this.options.handle,s).find("*").addBack().each(function(){this===t.target&&(a=!0)}),a)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(t,i,s){var a,n,r=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(t),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,r.cursorAt&&this._adjustOffsetFromHelper(r.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),r.containment&&this._setContainment(),r.cursor&&"auto"!==r.cursor&&(n=this.document.find("body"),this.storedCursor=n.css("cursor"),n.css("cursor",r.cursor),this.storedStylesheet=e("<style>*{ cursor: "+r.cursor+" !important; }</style>").appendTo(n)),r.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",r.opacity)),r.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",r.zIndex)),this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(a=this.containers.length-1;a>=0;a--)this.containers[a]._trigger("activate",t,this._uiHash(this));return e.ui.ddmanager&&(e.ui.ddmanager.current=this),e.ui.ddmanager&&!r.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){var i,s,a,n,r=this.options,o=!1;for(this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<r.scrollSensitivity?this.scrollParent[0].scrollTop=o=this.scrollParent[0].scrollTop+r.scrollSpeed:t.pageY-this.overflowOffset.top<r.scrollSensitivity&&(this.scrollParent[0].scrollTop=o=this.scrollParent[0].scrollTop-r.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<r.scrollSensitivity?this.scrollParent[0].scrollLeft=o=this.scrollParent[0].scrollLeft+r.scrollSpeed:t.pageX-this.overflowOffset.left<r.scrollSensitivity&&(this.scrollParent[0].scrollLeft=o=this.scrollParent[0].scrollLeft-r.scrollSpeed)):(t.pageY-e(document).scrollTop()<r.scrollSensitivity?o=e(document).scrollTop(e(document).scrollTop()-r.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<r.scrollSensitivity&&(o=e(document).scrollTop(e(document).scrollTop()+r.scrollSpeed)),t.pageX-e(document).scrollLeft()<r.scrollSensitivity?o=e(document).scrollLeft(e(document).scrollLeft()-r.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<r.scrollSensitivity&&(o=e(document).scrollLeft(e(document).scrollLeft()+r.scrollSpeed))),o!==!1&&e.ui.ddmanager&&!r.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],a=s.item[0],n=this._intersectsWithPointer(s),n&&s.instance===this.currentContainer&&a!==this.currentItem[0]&&this.placeholder[1===n?"next":"prev"]()[0]!==a&&!e.contains(this.placeholder[0],a)&&("semi-dynamic"===this.options.type?!e.contains(this.element[0],a):!0)){if(this.direction=1===n?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break;this._rearrange(t,s),this._trigger("change",t,this._uiHash());break}return this._contactContainers(t),e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),this._trigger("sort",t,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(t,i){if(t){if(e.ui.ddmanager&&!this.options.dropBehaviour&&e.ui.ddmanager.drop(this,t),this.options.revert){var s=this,a=this.placeholder.offset(),n=this.options.axis,r={};n&&"x"!==n||(r.left=a.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft)),n&&"y"!==n||(r.top=a.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,e(this.helper).animate(r,parseInt(this.options.revert,10)||500,function(){s._clear(t)})}else this._clear(t,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null}),"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var t=this.containers.length-1;t>=0;t--)this.containers[t]._trigger("deactivate",null,this._uiHash(this)),this.containers[t].containerCache.over&&(this.containers[t]._trigger("out",null,this._uiHash(this)),this.containers[t].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),e.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?e(this.domPosition.prev).after(this.currentItem):e(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(t){var i=this._getItemsAsjQuery(t&&t.connected),s=[];return t=t||{},e(i).each(function(){var i=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[\-=_](.+)/);i&&s.push((t.key||i[1]+"[]")+"="+(t.key&&t.expression?i[1]:i[2]))}),!s.length&&t.key&&s.push(t.key+"="),s.join("&")},toArray:function(t){var i=this._getItemsAsjQuery(t&&t.connected),s=[];return t=t||{},i.each(function(){s.push(e(t.item||this).attr(t.attribute||"id")||"")}),s},_intersectsWith:function(e){var t=this.positionAbs.left,i=t+this.helperProportions.width,s=this.positionAbs.top,a=s+this.helperProportions.height,n=e.left,r=n+e.width,o=e.top,h=o+e.height,l=this.offset.click.top,u=this.offset.click.left,c="x"===this.options.axis||s+l>o&&h>s+l,d="y"===this.options.axis||t+u>n&&r>t+u,p=c&&d;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>e[this.floating?"width":"height"]?p:t+this.helperProportions.width/2>n&&r>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>o&&h>a-this.helperProportions.height/2},_intersectsWithPointer:function(e){var i="x"===this.options.axis||t(this.positionAbs.top+this.offset.click.top,e.top,e.height),s="y"===this.options.axis||t(this.positionAbs.left+this.offset.click.left,e.left,e.width),a=i&&s,n=this._getDragVerticalDirection(),r=this._getDragHorizontalDirection();return a?this.floating?r&&"right"===r||"down"===n?2:1:n&&("down"===n?2:1):!1},_intersectsWithSides:function(e){var i=t(this.positionAbs.top+this.offset.click.top,e.top+e.height/2,e.height),s=t(this.positionAbs.left+this.offset.click.left,e.left+e.width/2,e.width),a=this._getDragVerticalDirection(),n=this._getDragHorizontalDirection();return this.floating&&n?"right"===n&&s||"left"===n&&!s:a&&("down"===a&&i||"up"===a&&!i)},_getDragVerticalDirection:function(){var e=this.positionAbs.top-this.lastPositionAbs.top;return 0!==e&&(e>0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return 0!==e&&(e>0?"right":"left")},refresh:function(e){return this._refreshItems(e),this.refreshPositions(),this},_connectWith:function(){var e=this.options;return e.connectWith.constructor===String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){var i,s,a,n,r=[],o=[],h=this._connectWith();if(h&&t)for(i=h.length-1;i>=0;i--)for(a=e(h[i]),s=a.length-1;s>=0;s--)n=e.data(a[s],this.widgetFullName),n&&n!==this&&!n.options.disabled&&o.push([e.isFunction(n.options.items)?n.options.items.call(n.element):e(n.options.items,n.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),n]);for(o.push([e.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):e(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),i=o.length-1;i>=0;i--)o[i][0].each(function(){r.push(this)});return e(r)},_removeCurrentsFromItems:function(){var t=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=e.grep(this.items,function(e){for(var i=0;t.length>i;i++)if(t[i]===e.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[],this.containers=[this];var i,s,a,n,r,o,h,l,u=this.items,c=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(i=d.length-1;i>=0;i--)for(a=e(d[i]),s=a.length-1;s>=0;s--)n=e.data(a[s],this.widgetFullName),n&&n!==this&&!n.options.disabled&&(c.push([e.isFunction(n.options.items)?n.options.items.call(n.element[0],t,{item:this.currentItem}):e(n.options.items,n.element),n]),this.containers.push(n));for(i=c.length-1;i>=0;i--)for(r=c[i][1],o=c[i][0],s=0,l=o.length;l>s;s++)h=e(o[s]),h.data(this.widgetName+"-item",r),u.push({item:h,instance:r,width:0,height:0,left:0,top:0})},refreshPositions:function(t){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,a,n;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(a=this.options.toleranceElement?e(this.options.toleranceElement,s.item):s.item,t||(s.width=a.outerWidth(),s.height=a.outerHeight()),n=a.offset(),s.left=n.left,s.top=n.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)n=this.containers[i].element.offset(),this.containers[i].containerCache.left=n.left,this.containers[i].containerCache.top=n.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(t){t=t||this;var i,s=t.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=t.currentItem[0].nodeName.toLowerCase(),a=e("<"+s+">",t.document[0]).addClass(i||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");return"tr"===s?t.currentItem.children().each(function(){e("<td> </td>",t.document[0]).attr("colspan",e(this).attr("colspan")||1).appendTo(a)}):"img"===s&&a.attr("src",t.currentItem.attr("src")),i||a.css("visibility","hidden"),a},update:function(e,a){(!i||s.forcePlaceholderSize)&&(a.height()||a.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10)),a.width()||a.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10)))}}),t.placeholder=e(s.placeholder.element.call(t.element,t.currentItem)),t.currentItem.after(t.placeholder),s.placeholder.update(t,t.placeholder)},_contactContainers:function(s){var a,n,r,o,h,l,u,c,d,p,f=null,m=null;for(a=this.containers.length-1;a>=0;a--)if(!e.contains(this.currentItem[0],this.containers[a].element[0]))if(this._intersectsWith(this.containers[a].containerCache)){if(f&&e.contains(this.containers[a].element[0],f.element[0]))continue;f=this.containers[a],m=a}else this.containers[a].containerCache.over&&(this.containers[a]._trigger("out",s,this._uiHash(this)),this.containers[a].containerCache.over=0);if(f)if(1===this.containers.length)this.containers[m].containerCache.over||(this.containers[m]._trigger("over",s,this._uiHash(this)),this.containers[m].containerCache.over=1);else{for(r=1e4,o=null,p=f.floating||i(this.currentItem),h=p?"left":"top",l=p?"width":"height",u=this.positionAbs[h]+this.offset.click[h],n=this.items.length-1;n>=0;n--)e.contains(this.containers[m].element[0],this.items[n].item[0])&&this.items[n].item[0]!==this.currentItem[0]&&(!p||t(this.positionAbs.top+this.offset.click.top,this.items[n].top,this.items[n].height))&&(c=this.items[n].item.offset()[h],d=!1,Math.abs(c-u)>Math.abs(c+this.items[n][l]-u)&&(d=!0,c+=this.items[n][l]),r>Math.abs(c-u)&&(r=Math.abs(c-u),o=this.items[n],this.direction=d?"up":"down"));if(!o&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[m])return;o?this._rearrange(s,o,null,!0):this._rearrange(s,null,this.containers[m].element,!0),this._trigger("change",s,this._uiHash()),this.containers[m]._trigger("change",s,this._uiHash(this)),this.currentContainer=this.containers[m],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[m]._trigger("over",s,this._uiHash(this)),this.containers[m].containerCache.over=1}},_createHelper:function(t){var i=this.options,s=e.isFunction(i.helper)?e(i.helper.apply(this.element[0],[t,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||e("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&e.ui.ie)&&(t={top:0,left:0}),{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var e=this.currentItem.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,i,s,a=this.options;"parent"===a.containment&&(a.containment=this.helper[0].parentNode),("document"===a.containment||"window"===a.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,e("document"===a.containment?document:window).width()-this.helperProportions.width-this.margins.left,(e("document"===a.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(a.containment)||(t=e(a.containment)[0],i=e(a.containment).offset(),s="hidden"!==e(t).css("overflow"),this.containment=[i.left+(parseInt(e(t).css("borderLeftWidth"),10)||0)+(parseInt(e(t).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(e(t).css("borderTopWidth"),10)||0)+(parseInt(e(t).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(t.scrollWidth,t.offsetWidth):t.offsetWidth)-(parseInt(e(t).css("borderLeftWidth"),10)||0)-(parseInt(e(t).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(t.scrollHeight,t.offsetHeight):t.offsetHeight)-(parseInt(e(t).css("borderTopWidth"),10)||0)-(parseInt(e(t).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(t,i){i||(i=this.position);var s="absolute"===t?1:-1,a="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,n=/(html|body)/i.test(a[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():n?0:a.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():n?0:a.scrollLeft())*s}},_generatePosition:function(t){var i,s,a=this.options,n=t.pageX,r=t.pageY,o="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(o[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(t.pageX-this.offset.click.left<this.containment[0]&&(n=this.containment[0]+this.offset.click.left),t.pageY-this.offset.click.top<this.containment[1]&&(r=this.containment[1]+this.offset.click.top),t.pageX-this.offset.click.left>this.containment[2]&&(n=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top>this.containment[3]&&(r=this.containment[3]+this.offset.click.top)),a.grid&&(i=this.originalPageY+Math.round((r-this.originalPageY)/a.grid[1])*a.grid[1],r=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-a.grid[1]:i+a.grid[1]:i,s=this.originalPageX+Math.round((n-this.originalPageX)/a.grid[0])*a.grid[0],n=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-a.grid[0]:s+a.grid[0]:s)),{top:r-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:o.scrollTop()),left:n-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:o.scrollLeft())}},_rearrange:function(e,t,i,s){i?i[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?t.item[0]:t.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var a=this.counter;this._delay(function(){a===this.counter&&this.refreshPositions(!s)})},_clear:function(e,t){this.reverting=!1;var i,s=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(i in this._storedCSS)("auto"===this._storedCSS[i]||"static"===this._storedCSS[i])&&(this._storedCSS[i]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!t&&s.push(function(e){this._trigger("receive",e,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||t||s.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&&(t||(s.push(function(e){this._trigger("remove",e,this._uiHash())}),s.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),s.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer)))),i=this.containers.length-1;i>=0;i--)t||s.push(function(e){return function(t){e._trigger("deactivate",t,this._uiHash(this))}}.call(this,this.containers[i])),this.containers[i].containerCache.over&&(s.push(function(e){return function(t){e._trigger("out",t,this._uiHash(this))}}.call(this,this.containers[i])),this.containers[i].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,this.cancelHelperRemoval){if(!t){for(this._trigger("beforeStop",e,this._uiHash()),i=0;s.length>i;i++)s[i].call(this,e);this._trigger("stop",e,this._uiHash())}return this.fromOutside=!1,!1}if(t||this._trigger("beforeStop",e,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null,!t){for(i=0;s.length>i;i++)s[i].call(this,e);this._trigger("stop",e,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){e.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(t){var i=t||this;return{helper:i.helper,placeholder:i.placeholder||e([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:t?t.element:null}}})})(jQuery);
\ No newline at end of file diff --git a/js/quick-post-controls.js b/js/quick-post-controls.js index 1cbc0711..efce3371 100644 --- a/js/quick-post-controls.js +++ b/js/quick-post-controls.js @@ -63,6 +63,8 @@ $(document).ready(function(){ post_form.appendTo($(this).parent().parent()); //post_form.insertBefore($(this)); } + + $(window).trigger('quick-post-controls', post_form); } else { var elm = $(this).parent().parent().find('form'); diff --git a/js/quick-reply-old.js b/js/quick-reply-old.js new file mode 100644 index 00000000..ea504b48 --- /dev/null +++ b/js/quick-reply-old.js @@ -0,0 +1,46 @@ +/* + * quick-reply.js + * https://github.com/savetheinternet/Tinyboard/blob/master/js/quick-reply.js + * + * Released under the MIT license + * Copyright (c) 2012 Michael Save <savetheinternet@tinyboard.org> + * + * Usage: + * $config['quick_reply'] = true; + * $config['additional_javascript'][] = 'js/jquery.min.js'; + * $config['additional_javascript'][] = 'js/quick-reply.js'; + * + */ + +$(document).ready(function(){ + if($('div.banner').length != 0) + return; // not index + + txt_new_topic = $('form[name=post] input[type=submit]').val(); + txt_new_reply = txt_new_topic == _('Submit') ? txt_new_topic : new_reply_string; + + undo_quick_reply = function() { + $('div.banner').remove(); + $('form[name=post] input[type=submit]').val(txt_new_topic); + $('form[name=post] input[name=quick-reply]').remove(); + } + + $('div.post.op').each(function() { + var id = $(this).children('p.intro').children('a.post_no:eq(1)').text(); + $('<a href="#">['+_("Quick reply")+']</a>').insertAfter($(this).children('p.intro').children('a:last')).click(function() { + $('div.banner').remove(); + $('<div class="banner">'+fmt(_("Posting mode: Replying to <small>>>{0}</small>"), [id])+' <a class="unimportant" onclick="undo_quick_reply()" href="javascript:void(0)">['+_("Return")+']</a></div>') + .insertBefore('form[name=post]'); + $('form[name=post] input[type=submit]').val(txt_new_reply); + + $('<input type="hidden" name="quick-reply" value="' + id + '">').appendTo($('form[name=post]')); + + $('form[name=post] textarea').select(); + + window.scrollTo(0, 0); + + return false; + }); + }); +}); + diff --git a/js/quick-reply-vd-old.js b/js/quick-reply-vd-old.js new file mode 100644 index 00000000..bee204b7 --- /dev/null +++ b/js/quick-reply-vd-old.js @@ -0,0 +1,47 @@ +/* + * quick-reply.js + * https://github.com/savetheinternet/Tinyboard/blob/master/js/quick-reply.js + * + * Released under the MIT license + * Copyright (c) 2012 Michael Save <savetheinternet@tinyboard.org> + * + * Usage: + * $config['quick_reply'] = true; + * $config['additional_javascript'][] = 'js/jquery.min.js'; + * $config['additional_javascript'][] = 'js/quick-reply.js'; + * + */ + +if (active_page == 'index') { +$(document).ready(function(){ + if($('div.banner').length != 0) + return; // not index + + txt_new_topic = $('form[name=post] input[type=submit]').val(); + txt_new_reply = txt_new_topic == _('Submit') ? txt_new_topic : new_reply_string; + + undo_quick_reply = function() { + $('div.banner').remove(); + $('form[name=post] input[type=submit]').val(txt_new_topic); + $('form[name=post] input[name=quick-reply]').remove(); + } + + $('div.post.op').each(function() { + var id = $(this).children('p.intro').children('a.post_no:eq(1)').text(); + $('<a href="#">['+_("Quick reply")+']</a>').insertAfter($(this).children('p.intro').children('a:last')).click(function() { + $('div.banner').remove(); + $('<div class="banner">'+fmt(_("Posting mode: Replying to <small>>>{0}</small>"), [id])+' <a class="unimportant" onclick="undo_quick_reply()" href="javascript:void(0)">['+_("Return")+']</a></div>') + .insertBefore('form[name=post]'); + $('form[name=post] input[type=submit]').val(txt_new_reply); + + $('<input type="hidden" name="quick-reply" value="' + id + '">').appendTo($('form[name=post]')); + + $('form[name=post] textarea').select(); + + window.scrollTo(0, 0); + + return false; + }); + }); +}); +} diff --git a/js/quick-reply.js b/js/quick-reply.js index bee204b7..267b6915 100644 --- a/js/quick-reply.js +++ b/js/quick-reply.js @@ -3,45 +3,363 @@ * https://github.com/savetheinternet/Tinyboard/blob/master/js/quick-reply.js * * Released under the MIT license - * Copyright (c) 2012 Michael Save <savetheinternet@tinyboard.org> + * Copyright (c) 2013 Michael Save <savetheinternet@tinyboard.org> * * Usage: - * $config['quick_reply'] = true; * $config['additional_javascript'][] = 'js/jquery.min.js'; + * $config['additional_javascript'][] = 'js/jquery-ui.custom.min.js'; // Optional; if you want the form to be draggable. * $config['additional_javascript'][] = 'js/quick-reply.js'; * */ -if (active_page == 'index') { -$(document).ready(function(){ - if($('div.banner').length != 0) - return; // not index +var do_css = function() { + $('#quick-reply-css').remove(); - txt_new_topic = $('form[name=post] input[type=submit]').val(); - txt_new_reply = txt_new_topic == _('Submit') ? txt_new_topic : new_reply_string; + // Find background of reply posts + var dummy_reply = $('<div class="post reply"></div>').appendTo($('body')); + var reply_background = dummy_reply.css('backgroundColor'); + var reply_border_style = dummy_reply.css('borderStyle'); + var reply_border_color = dummy_reply.css('borderColor'); + var reply_border_width = dummy_reply.css('borderWidth'); + dummy_reply.remove(); - undo_quick_reply = function() { - $('div.banner').remove(); - $('form[name=post] input[type=submit]').val(txt_new_topic); - $('form[name=post] input[name=quick-reply]').remove(); - } + $('<style type="text/css" id="quick-reply-css">\ + #quick-reply {\ + position: fixed;\ + right: 0;\ + top: 5%;\ + float: right;\ + display: block;\ + padding: 0 0 0 0;\ + width: 300px;\ + }\ + #quick-reply table {\ + border-collapse: collapse;\ + background: ' + reply_background + ';\ + border-style: ' + reply_border_style + ';\ + border-width: ' + reply_border_width + ';\ + border-color: ' + reply_border_color + ';\ + margin: 0;\ + width: 100%;\ + }\ + #quick-reply tr td:nth-child(2) {\ + white-space: nowrap;\ + text-align: right;\ + padding-right: 4px;\ + }\ + #quick-reply tr td:nth-child(2) input[type="submit"] {\ + width: 100%;\ + }\ + #quick-reply th, #quick-reply td {\ + margin: 0;\ + padding: 0;\ + }\ + #quick-reply th {\ + text-align: center;\ + padding: 2px 0;\ + border: 1px solid #222;\ + }\ + #quick-reply th .handle {\ + float: left;\ + width: 100%;\ + display: inline-block;\ + }\ + #quick-reply th .close-btn {\ + float: right;\ + padding: 0 5px;\ + }\ + #quick-reply input[type="text"], #quick-reply select {\ + width: 100%;\ + padding: 2px;\ + font-size: 10pt;\ + box-sizing: border-box;\ + -webkit-box-sizing:border-box;\ + -moz-box-sizing: border-box;\ + }\ + #quick-reply textarea {\ + width: 100%;\ + box-sizing: border-box;\ + -webkit-box-sizing:border-box;\ + -moz-box-sizing: border-box;\ + font-size: 10pt;\ + resize: vertical;\ + }\ + #quick-reply input, #quick-reply select, #quick-reply textarea {\ + margin: 0 0 1px 0;\ + }\ + #quick-reply input[type="file"] {\ + padding: 5px 2px;\ + }\ + #quick-reply .nonsense {\ + display: none;\ + }\ + #quick-reply td.submit {\ + width: 1%;\ + }\ + #quick-reply td.recaptcha {\ + text-align: center;\ + padding: 0 0 1px 0;\ + }\ + #quick-reply td.recaptcha span {\ + display: inline-block;\ + width: 100%;\ + background: white;\ + border: 1px solid #ccc;\ + cursor: pointer;\ + }\ + #quick-reply td.recaptcha-response {\ + padding: 0 0 1px 0;\ + }\ + @media screen and (max-width: 800px) {\ + #quick-reply {\ + display: none !important;\ + }\ + }\ + </style>').appendTo($('head')); +}; + +var show_quick_reply = function(){ + if($('div.banner').length == 0) + return; + if($('#quick-reply').length != 0) + return; - $('div.post.op').each(function() { - var id = $(this).children('p.intro').children('a.post_no:eq(1)').text(); - $('<a href="#">['+_("Quick reply")+']</a>').insertAfter($(this).children('p.intro').children('a:last')).click(function() { - $('div.banner').remove(); - $('<div class="banner">'+fmt(_("Posting mode: Replying to <small>>>{0}</small>"), [id])+' <a class="unimportant" onclick="undo_quick_reply()" href="javascript:void(0)">['+_("Return")+']</a></div>') - .insertBefore('form[name=post]'); - $('form[name=post] input[type=submit]').val(txt_new_reply); - - $('<input type="hidden" name="quick-reply" value="' + id + '">').appendTo($('form[name=post]')); - - $('form[name=post] textarea').select(); + do_css(); + + var $postForm = $('form[name="post"]').clone(); + + $postForm.clone(); + + $dummyStuff = $('<div class="nonsense"></div>').appendTo($postForm); + + $postForm.find('table tr').each(function() { + var $th = $(this).children('th:first'); + var $td = $(this).children('td:first'); + if ($th.length && $td.length) { + $td.attr('colspan', 2); + + if ($td.find('input[type="text"]').length) { + // Replace <th> with input placeholders + $td.find('input[type="text"]') + .removeAttr('size') + .attr('placeholder', $th.clone().children().remove().end().text()); + } + + // Move anti-spam nonsense and remove <th> + $th.contents().filter(function() { + return this.nodeType == 3; // Node.TEXT_NODE + }).remove(); + $th.contents().appendTo($dummyStuff); + $th.remove(); + + if ($td.find('input[name="password"]').length) { + // Hide password field + $(this).hide(); + } + + // Fix submit button + if ($td.find('input[type="submit"]').length) { + $td.removeAttr('colspan'); + $('<td class="submit"></td>').append($td.find('input[type="submit"]')).insertAfter($td); + } + + // reCAPTCHA + if ($td.find('#recaptcha_widget_div').length) { + // Just show the image, and have it interact with the real form. + var $captchaimg = $td.find('#recaptcha_image img'); + + $captchaimg + .removeAttr('id') + .removeAttr('style') + .addClass('recaptcha_image') + .click(function() { + $('#recaptcha_reload').click(); + }); + + // When we get a new captcha... + $('#recaptcha_response_field').focus(function() { + if ($captchaimg.attr('src') != $('#recaptcha_image img').attr('src')) { + $captchaimg.attr('src', $('#recaptcha_image img').attr('src')); + $postForm.find('input[name="recaptcha_challenge_field"]').val($('#recaptcha_challenge_field').val()); + $postForm.find('input[name="recaptcha_response_field"]').val('').focus(); + } + }); + + $postForm.submit(function() { + setTimeout(function() { + $('#recaptcha_reload').click(); + }, 200); + }); + + // Make a new row for the response text + var $newRow = $('<tr><td class="recaptcha-response" colspan="2"></td></tr>'); + $newRow.children().first().append( + $td.find('input').removeAttr('style') + ); + $newRow.find('#recaptcha_response_field') + .removeAttr('id') + .addClass('recaptcha_response_field') + .attr('placeholder', $('#recaptcha_response_field').attr('placeholder')); + + $('#recaptcha_response_field').addClass('recaptcha_response_field') + + $td.replaceWith($('<td class="recaptcha" colspan="2"></td>').append($('<span></span>').append($captchaimg))); + + $newRow.insertAfter(this); + } + + // Upload section + if ($td.find('input[type="file"]').length) { + if ($td.find('input[name="file_url"]').length) { + $file_url = $td.find('input[name="file_url"]'); + + // Make a new row for it + var $newRow = $('<tr><td colspan="2"></td></tr>'); + + $file_url.clone().attr('placeholder', _('Upload URL')).appendTo($newRow.find('td')); + $file_url.parent().remove(); + + $newRow.insertBefore(this); + + $td.find('label').remove(); + $td.contents().filter(function() { + return this.nodeType == 3; // Node.TEXT_NODE + }).remove(); + $td.find('input[name="file_url"]').removeAttr('id'); + } + + if ($(this).find('input[name="spoiler"]').length) { + $td.removeAttr('colspan'); + } + } - window.scrollTo(0, 0); + // Remove mod controls, because it looks shit. + if ($td.find('input[type="checkbox"]').length) { + var tr = this; + $td.find('input[type="checkbox"]').each(function() { + if ($(this).attr('name') == 'spoiler') { + $td.find('label').remove(); + $(this).attr('id', 'q-spoiler-image'); + $postForm.find('input[type="file"]').parent() + .removeAttr('colspan') + .after($('<td class="spoiler"></td>').append(this, ' ', $('<label for="q-spoiler-image">').text(_('Spoiler Image')))); + } else { + $(tr).remove(); + } + }); + } - return false; - }); + $td.find('small').hide(); + } + }); + + $postForm.find('textarea[name="body"]').removeAttr('id').removeAttr('cols').attr('placeholder', _('Comment')); + + $postForm.find('textarea:not([name="body"]),input[type="hidden"]').removeAttr('id').appendTo($dummyStuff); + + $postForm.find('br').remove(); + $postForm.find('table').prepend('<tr><th colspan="2">\ + <span class="handle">\ + <a class="close-btn" href="javascript:void(0)">X</a>\ + ' + _('Quick Reply') + '\ + </span>\ + </th></tr>'); + + $postForm.attr('id', 'quick-reply'); + + $postForm.appendTo($('body')).hide(); + $origPostForm = $('form[name="post"]:first'); + + // Synchronise body text with original post form + $origPostForm.find('textarea[name="body"]').bind('change input propertychange', function() { + $postForm.find('textarea[name="body"]').val($(this).val()); + }); + $postForm.find('textarea[name="body"]').bind('change input propertychange', function() { + $origPostForm.find('textarea[name="body"]').val($(this).val()); + }); + $postForm.find('textarea[name="body"]').focus(function() { + $origPostForm.find('textarea[name="body"]').removeAttr('id'); + $(this).attr('id', 'body'); + }); + $origPostForm.find('textarea[name="body"]').focus(function() { + $postForm.find('textarea[name="body"]').removeAttr('id'); + $(this).attr('id', 'body'); + }); + // Synchronise other inputs + $origPostForm.find('input[type="text"],select').bind('change input propertychange', function() { + $postForm.find('[name="' + $(this).attr('name') + '"]').val($(this).val()); + }); + $postForm.find('input[type="text"],select').bind('change input propertychange', function() { + $origPostForm.find('[name="' + $(this).attr('name') + '"]').val($(this).val()); + }); + + if (typeof $postForm.draggable != 'undefined') { + if (localStorage.quickReplyPosition) { + var offset = JSON.parse(localStorage.quickReplyPosition); + if (offset.right > $(window).width() - $postForm.width()) + offset.right = $(window).width() - $postForm.width(); + if (offset.top > $(window).height() - $postForm.height()) + offset.top = $(window).height() - $postForm.height(); + $postForm.css('right', offset.right).css('top', offset.top); + } + $postForm.draggable({ + handle: 'th .handle', + containment: 'window', + distance: 10, + scroll: false, + stop: function() { + var offset = { + top: $(this).offset().top - $(window).scrollTop(), + right: $(window).width() - $(this).offset().left - $(this).width(), + }; + localStorage.quickReplyPosition = JSON.stringify(offset); + + $postForm.css('right', offset.right).css('top', offset.top).css('left', 'auto'); + } + }); + $postForm.find('th .handle').css('cursor', 'move'); + } + + $postForm.find('th .close-btn').click(function() { + $origPostForm.find('textarea[name="body"]').attr('id', 'body'); + $postForm.remove(); }); + + // Fix bug when table gets too big for form. Shouldn't exist, but crappy CSS etc. + $postForm.show(); + $postForm.width($postForm.find('table').width()); + $postForm.hide(); + + $(window).trigger('quick-reply'); + + $(window).ready(function() { + $(window).scroll(function() { + if ($(this).width() <= 800) + return; + if ($(this).scrollTop() < $origPostForm.offset().top + $origPostForm.height() - 100) + $postForm.fadeOut(100); + else + $postForm.fadeIn(100); + }).on('stylesheet', function() { + do_css(); + if ($('link#stylesheet').attr('href')) { + $('link#stylesheet')[0].onload = do_css; + } + }).scroll(); + }); +}; + +$(window).on('cite', function(e, id, with_link) { + if ($(this).width() <= 800) + return; + show_quick_reply(); + $('#quick-reply textarea').focus(); + if (with_link) { + $(window).ready(function() { + if ($('#' + id).length) { + highlightReply(id); + $(window).scrollTop($('#' + id).offset().top); + } + }); + } }); -} @@ -1,5 +1,7 @@ <?php +file_put_contents('post.txt', var_export($_POST, true)); + /* * Copyright (c) 2010-2013 Tinyboard Development Group */ @@ -56,7 +58,7 @@ if (isset($_POST['delete'])) { if ($password != '' && $post['password'] != $password) error($config['error']['invalidpassword']); - if ($post['time'] >= time() - $config['delete_time']) { + if ($post['time'] > time() - $config['delete_time']) { error(sprintf($config['error']['delete_too_soon'], until($post['time'] + $config['delete_time']))); } @@ -82,9 +84,12 @@ if (isset($_POST['delete'])) { $is_mod = isset($_POST['mod']) && $_POST['mod']; $root = $is_mod ? $config['root'] . $config['file_mod'] . '?/' : $config['root']; - if (!$is_mod) header('X-Associated-Content: "' . $root . $board['dir'] . $config['file_index'] . '"'); - header('Location: ' . $root . $board['dir'] . $config['file_index'], true, $config['redirect_http']); - + if (!isset($_POST['json_response'])) { + header('Location: ' . $root . $board['dir'] . $config['file_index'], true, $config['redirect_http']); + } else { + header('Content-Type: text/json'); + echo json_encode(array('success' => true)); + } } elseif (isset($_POST['report'])) { if (!isset($_POST['board'], $_POST['password'], $_POST['reason'])) error($config['error']['bot']); @@ -138,10 +143,13 @@ if (isset($_POST['delete'])) { $is_mod = isset($_POST['mod']) && $_POST['mod']; $root = $is_mod ? $config['root'] . $config['file_mod'] . '?/' : $config['root']; - if (!$is_mod) header('X-Associated-Content: "' . $root . $board['dir'] . $config['file_index'] . '"'); - header('Location: ' . $root . $board['dir'] . $config['file_index'], true, $config['redirect_http']); + if (!isset($_POST['json_response'])) { + header('Location: ' . $root . $board['dir'] . $config['file_index'], true, $config['redirect_http']); + } else { + header('Content-Type: text/json'); + echo json_encode(array('success' => true)); + } } elseif (isset($_POST['post'])) { - if (!isset($_POST['body'], $_POST['board'])) error($config['error']['bot']); @@ -200,7 +208,7 @@ if (isset($_POST['delete'])) { } if ($post['mod'] = isset($_POST['mod']) && $_POST['mod']) { - require 'inc/mod.php'; + require 'inc/mod/auth.php'; if (!$mod) { // Liar. You're not a mod. error($config['error']['notamod']); @@ -275,7 +283,7 @@ if (isset($_POST['delete'])) { if ($config['allow_upload_by_url'] && isset($_POST['file_url']) && !empty($_POST['file_url'])) { $post['file_url'] = $_POST['file_url']; - if (!preg_match($config['url_regex'], $post['file_url'])) + if (!preg_match('@^https?://@', $post['file_url'])) error($config['error']['invalidimg']); if (mb_strpos($post['file_url'], '?') !== false) @@ -430,11 +438,6 @@ if (isset($_POST['delete'])) { wordfilters($post['body']); - // Check for a flood - if (!hasPermission($config['mod']['flood'], $board['uri']) && checkFlood($post)) { - error($config['error']['flood']); - } - $post['body'] = escape_markup_modifiers($post['body']); if ($mod && isset($post['raw']) && $post['raw']) { @@ -470,10 +473,8 @@ if (isset($_POST['delete'])) { } $post['tracked_cites'] = markup($post['body'], true); + - require_once 'inc/filters.php'; - - do_filters($post); if ($post['has_file']) { if (!in_array($post['extension'], $config['allowed_ext']) && !in_array($post['extension'], $config['allowed_ext_files'])) @@ -489,9 +490,17 @@ if (isset($_POST['delete'])) { if (!is_readable($upload)) error($config['error']['nomove']); - $post['filehash'] = $config['file_hash']($upload); + $post['filehash'] = md5_file($upload); $post['filesize'] = filesize($upload); + } + + if (!hasPermission($config['mod']['bypass_filters'], $board['uri'])) { + require_once 'inc/filters.php'; + do_filters($post); + } + + if ($post['has_file']) { if ($is_an_image && $config['ie_mime_type_detection'] !== false) { // Check IE MIME type detection XSS exploit $buffer = file_get_contents($upload, null, null, null, 255); @@ -681,6 +690,8 @@ if (isset($_POST['delete'])) { $post['id'] = $id = post($post); + insertFloodPost($post); + if (isset($post['antispam_hash'])) { incrementSpamHash($post['antispam_hash']); } @@ -758,7 +769,15 @@ if (isset($_POST['delete'])) { else rebuildThemes('post', $board['uri']); - header('Location: ' . $redirect, true, $config['redirect_http']); + if (!isset($_POST['json_response'])) { + header('Location: ' . $redirect, true, $config['redirect_http']); + } else { + header('Content-Type: text/json; charset=utf-8'); + echo json_encode(array( + 'redirect' => $redirect, + 'id' => $id + )); + } } else { if (!file_exists($config['has_installed'])) { header('Location: install.php', true, $config['redirect_http']); diff --git a/stylesheets/style.css b/stylesheets/style.css index 43733ed1..cfc37980 100644 --- a/stylesheets/style.css +++ b/stylesheets/style.css @@ -320,6 +320,20 @@ div.pages { border-right: 1px solid #B7C5D9; border-bottom: 1px solid #B7C5D9; } +div.pages.top { + display: block; + padding: 5px 8px; + margin-bottom: 5px; + position: fixed; + top: 0; + right: 0; + opacity: 0.9; +} +@media screen and (max-width: 800px) { + div.pages.top { + display: none !important; + } +} div.pages a.selected { color: black; font-weight: bolder; diff --git a/templates/banned.html b/templates/banned.html index a4498cf5..065d61e2 100644 --- a/templates/banned.html +++ b/templates/banned.html @@ -30,7 +30,7 @@ {% endif %} <p> {% trans %}Your ban was filed on{% endtrans %} - <strong>{{ ban.set|date(config.ban_date) }}</strong> {% trans %}and{% endtrans %} <span id="expires"> + <strong>{{ ban.created|date(config.ban_date) }}</strong> {% trans %}and{% endtrans %} <span id="expires"> {% if ban.expires and time() >= ban.expires %} {% trans %} has since expired. Refresh the page to continue.{% endtrans %} {% elseif ban.expires %} diff --git a/templates/index.html b/templates/index.html index 39576e13..fb7bab07 100644 --- a/templates/index.html +++ b/templates/index.html @@ -19,8 +19,10 @@ </head> <body> {{ boardlist.top }} + {% if pm %}<div class="top_notice">You have <a href="?/PM/{{ pm.id }}">an unread PM</a>{% if pm.waiting > 0 %}, plus {{ pm.waiting }} more waiting{% endif %}.</div><hr />{% endif %} {% if config.url_banner %}<img class="banner" src="{{ config.url_banner }}" {% if config.banner_width or config.banner_height %}style="{% if config.banner_width %}width:{{ config.banner_width }}px{% endif %};{% if config.banner_width %}height:{{ config.banner_height }}px{% endif %}" {% endif %}alt="" />{% endif %} + <header> <h1>{{ board.url }} - {{ board.title|e }}</h1> <div class="subtitle"> @@ -44,6 +46,15 @@ {{ config.ad.top }} + {% if config.page_nav_top %} + <div class="pages top"> + {% for page in pages %} + [<a {% if page.selected %}class="selected"{% endif %}{% if not page.selected %}href="{{ page.link }}"{% endif %}>{{ page.num }}</a>]{% if loop.last %} {% endif %} + {% endfor %} + {{ btn.next }} + </div> + {% endif %} + {% if config.global_message %}<hr /><div class="blotter">{{ config.global_message }}</div>{% endif %} <hr /> <form name="postcontrols" action="{{ config.post_url }}" method="post"> @@ -52,9 +63,16 @@ {{ body }} {% include 'report_delete.html' %} </form> - <div class="pages">{{ btn.prev }} {% for page in pages %} + + <div class="pages"> + {{ btn.prev }} {% for page in pages %} [<a {% if page.selected %}class="selected"{% endif %}{% if not page.selected %}href="{{ page.link }}"{% endif %}>{{ page.num }}</a>]{% if loop.last %} {% endif %} - {% endfor %} {{ btn.next }}</div> + {% endfor %} {{ btn.next }} + {% if config.catalog_link %} + | <a href="{{ config.root }}{{ board.dir }}{{ config.catalog_link }}">Catalog</a> + {% endif %} + </div> + {{ boardlist.bottom }} {{ config.ad.bottom }} diff --git a/templates/main.js b/templates/main.js index 7e8793cb..6136b11f 100644 --- a/templates/main.js +++ b/templates/main.js @@ -67,6 +67,9 @@ function changeStyle(styleName, link) { if (link) { link.className = 'selected'; } + + if (typeof $ != 'undefined') + $(window).trigger('stylesheet', styleName); } @@ -181,22 +184,28 @@ function dopost(form) { return form.elements['body'].value != "" || form.elements['file'].value != "" || (form.elements.file_url && form.elements['file_url'].value != ""); } -function citeReply(id) { - var body = document.getElementById('body'); +function citeReply(id, with_link) { + var textarea = document.getElementById('body'); if (document.selection) { // IE - body.focus(); + textarea.focus(); var sel = document.selection.createRange(); sel.text = '>>' + id + '\n'; - } else if (body.selectionStart || body.selectionStart == '0') { - // Mozilla - var start = body.selectionStart; - var end = body.selectionEnd; - body.value = body.value.substring(0, start) + '>>' + id + '\n' + body.value.substring(end, body.value.length); + } else if (textarea.selectionStart || textarea.selectionStart == '0') { + var start = textarea.selectionStart; + var end = textarea.selectionEnd; + textarea.value = textarea.value.substring(0, start) + '>>' + id + '\n' + textarea.value.substring(end, textarea.value.length); + + textarea.selectionStart += ('>>' + id).length + 1; + textarea.selectionEnd = textarea.selectionStart; } else { // ??? - body.value += '>>' + id + '\n'; + textarea.value += '>>' + id + '\n'; + } + if (typeof $ != 'undefined') { + $(window).trigger('cite', [id, with_link]); + $(textarea).change(); } } @@ -214,7 +223,7 @@ function rememberStuff() { document.forms.post.elements['email'].value = localStorage.email; if (window.location.hash.indexOf('q') == 1) - citeReply(window.location.hash.substring(2)); + citeReply(window.location.hash.substring(2), true); if (sessionStorage.body) { var saved = JSON.parse(sessionStorage.body); diff --git a/templates/mod/ban_list.html b/templates/mod/ban_list.html index f8826ade..b41cef28 100644 --- a/templates/mod/ban_list.html +++ b/templates/mod/ban_list.html @@ -17,10 +17,10 @@ <tr{% if ban.expires != 0 and ban.expires < time() %} style="text-decoration:line-through"{% endif %}> <td style="white-space: nowrap"> <input type="checkbox" name="ban_{{ ban.id }}"> - {% if ban.real_ip %} - <a href="?/IP/{{ ban.ip }}">{{ ban.ip }}</a> + {% if ban.single_addr %} + <a href="?/IP/{{ ban.mask }}">{{ ban.mask }}</a> {% else %} - {{ ban.ip|e }} + {{ ban.mask }} {% endif %} </td> <td> @@ -38,15 +38,15 @@ {% endif %} </td> <td style="white-space: nowrap"> - <span title="{{ ban.set|date(config.post_date) }}"> - {{ ban.set|ago }} ago + <span title="{{ ban.created|date(config.post_date) }}"> + {{ ban.created|ago }} ago </span> </td> <td style="white-space: nowrap"> {% if ban.expires == 0 %} - {% else %} - {{ (ban.expires - ban.set + time()) | until }} + {{ (ban.expires - ban.created + time()) | until }} {% endif %} </td> <td style="white-space: nowrap"> @@ -77,7 +77,7 @@ {% endif %} {% endif %} - {% elseif ban.mod == -1 %} + {% elseif ban.creator == -1 %} <em>system</em> {% else %} <em>{% trans 'deleted?' %}</em> diff --git a/templates/mod/config-editor.html b/templates/mod/config-editor.html index a43f8cf7..4f4cba93 100644 --- a/templates/mod/config-editor.html +++ b/templates/mod/config-editor.html @@ -42,10 +42,11 @@ <input name="{{ name }}" type="text" value="{{ var.value|e }}"> {% elseif var.permissions %} <select name="{{ name }}"> - <option value="{{ constant('JANITOR') }}"{% if var.value == constant('JANITOR')%} selected{% endif %}>JANITOR</option> - <option value="{{ constant('MOD') }}"{% if var.value == constant('MOD')%} selected{% endif %}>MOD</option> - <option value="{{ constant('ADMIN') }}"{% if var.value == constant('ADMIN')%} selected{% endif %}>ADMIN</option> - <option value="{{ constant('DISABLED') }}"{% if var.value == constant('DISABLED')%} selected{% endif %}>DISABLED</option> + {% for group_value, group_name in config.mod.groups %} + <option value="{{ group_value }}"{% if var.value == group_value %} selected{% endif %}> + {{ group_name }} + </option> + {% endfor %} </select> {% elseif var.type == 'integer' %} <input name="{{ name }}" type="number" value="{{ var.value|e }}"> diff --git a/templates/mod/debug/antispam.html b/templates/mod/debug/antispam.html index 95aa61a6..9979a093 100644 --- a/templates/mod/debug/antispam.html +++ b/templates/mod/debug/antispam.html @@ -14,11 +14,14 @@ <tr> <td>{{ config.board_abbreviation|sprintf(hash.board) }}</td> <td> - {% if hash.thread %} + {% if hash.thread > 0 %} {{ hash.thread }} + {% elseif hash.thread < 0 %} + Index (page {{ - hash.thread }}) {% else %} - - {% endif %}</td> + {% endif %} + </td> <td> <small><code>{{ hash.hash }}</code></small> </td> @@ -28,7 +31,11 @@ <td> {% if hash.expires %} <span title="{{ hash.expires|date(config.post_date) }}"> - {{ hash.expires|until }} + {% if hash.expires < time() %} + {{ hash.expires|ago }} ago + {% else %} + {{ hash.expires|until }} + {% endif %} </span> {% else %} - @@ -55,11 +62,14 @@ <tr> <td>{{ config.board_abbreviation|sprintf(hash.board) }}</td> <td> - {% if hash.thread %} + {% if hash.thread > 0 %} {{ hash.thread }} + {% elseif hash.thread < 0 %} + Index (page {{ - hash.thread }}) {% else %} - - {% endif %}</td> + {% endif %} + </td> <td> <small><code>{{ hash.hash }}</code></small> </td> @@ -69,7 +79,11 @@ <td> {% if hash.expires %} <span title="{{ hash.expires|date(config.post_date) }}"> - {{ hash.expires|until }} + {% if hash.expires < time() %} + {{ hash.expires|ago }} ago + {% else %} + {{ hash.expires|until }} + {% endif %} </span> {% else %} - diff --git a/templates/mod/debug/recent_posts.html b/templates/mod/debug/recent_posts.html index b84d24ab..e4eb4f3a 100644 --- a/templates/mod/debug/recent_posts.html +++ b/templates/mod/debug/recent_posts.html @@ -1,3 +1,40 @@ +<p style="text-align:center"> + Flood prevention cache: +</p> +<table class="modlog" style="width:1%;"> + <tr> + <th>#</th> + <th>Time</th> + <th>Board</th> + <th>Post hash</th> + <th>File hash</th> + </tr> + {% for post in flood_posts %} + <tr> + <td class="minimal">{{ post.id }}</td> + <td class="minimal"{% if post.in_flood_table %} style="color:red" title="Still in flood prevention cache."{% endif %}> + <small>{{ post.time | ago }} ago</small> + </td> + <td class="minimal"> + <a href="?/{{ config.board_path|sprintf(post.board) }}{{ config.file_index }}"> + {{ config.board_abbreviation|sprintf(post.board) }} + </a> + </td> + <td><code>{{ post.posthash }}</code></td> + <td> + {% if post.filehash %} + <code>{{ post.filehash }}</code> + {% else %} + <em>No file</em> + {% endif %} + </td> + </tr> + {% endfor %} +</table> + +<p style="text-align:center"> + Most recent {{ posts|count }} posts: +</p> <table class="modlog" style="word-wrap: break-word;"> <tr> <th>Time</th> @@ -12,11 +49,13 @@ </tr> {% for post in posts %} <tr> - <td class="minimal"> + <td class="minimal"{% if post.in_flood_table %} style="color:red" title="Still in flood prevention cache."{% endif %}> <small>{{ post.time | ago }} ago</small> </td> <td class="minimal"> - <a href="?/{{ config.board_path|sprintf(post.board) }}{{ config.file_index }}">{{ config.board_abbreviation|sprintf(post.board) }}</a> + <a href="?/{{ config.board_path|sprintf(post.board) }}{{ config.file_index }}"> + {{ config.board_abbreviation|sprintf(post.board) }} + </a> </td> <td class="minimal" > {% if post.thread %} diff --git a/templates/mod/debug/sql.html b/templates/mod/debug/sql.html index 755995f9..249d05e3 100644 --- a/templates/mod/debug/sql.html +++ b/templates/mod/debug/sql.html @@ -16,7 +16,13 @@ {% for row in result %} <tr> {% for col in row %} - <td>{{ col | e }}</td> + <td> + {% if col != null %} + {{ col | e }} + {% else %} + <em>NULL</em> + {% endif %} + </td> {% endfor %} </tr> {% endfor %} diff --git a/templates/mod/search_results.html b/templates/mod/search_results.html index 0c87f75f..0d3c2a10 100644 --- a/templates/mod/search_results.html +++ b/templates/mod/search_results.html @@ -56,10 +56,10 @@ {% for ban in results %} <tr{% if ban.expires != 0 and ban.expires < time() %} style="text-decoration:line-through"{% endif %}> <td style="white-space: nowrap"> - {% if ban.real_ip %} - <a href="?/IP/{{ ban.ip }}#bans">{{ ban.ip }}</a> + {% if ban.single_addr %} + <a href="?/IP/{{ ban.mask }}#bans">{{ ban.mask }}</a> {% else %} - {{ ban.ip|e }} + {{ ban.mask|e }} {% endif %} </td> <td> @@ -77,15 +77,15 @@ {% endif %} </td> <td style="white-space: nowrap"> - <span title="{{ ban.set|date(config.post_date) }}"> - {{ ban.set|ago }} ago + <span title="{{ ban.created|date(config.post_date) }}"> + {{ ban.created|ago }} ago </span> </td> <td style="white-space: nowrap"> {% if ban.expires == 0 %} - {% else %} - {{ (ban.expires - ban.set + time()) | until }} + {{ (ban.expires - ban.created + time()) | until }} {% endif %} </td> <td style="white-space: nowrap"> @@ -116,7 +116,7 @@ {% endif %} {% endif %} - {% elseif ban.mod == -1 %} + {% elseif ban.creator == -1 %} <em>system</em> {% else %} <em>{% trans 'deleted?' %}</em> diff --git a/templates/mod/user.html b/templates/mod/user.html index 1bb297af..89240824 100644 --- a/templates/mod/user.html +++ b/templates/mod/user.html @@ -28,21 +28,15 @@ </tr> {% if new %} <tr> - <th>{% trans 'Class' %}</th> + <th>{% trans 'Group' %}</th> <td> <ul style="padding:5px 8px;list-style:none"> - <li> - <input type="radio" name="type" id="janitor" value="{{ constant('JANITOR') }}"> - <label for="janitor">{% trans 'Janitor' %}</label> - </li> - <li> - <input type="radio" name="type" id="mod" value="{{ constant('MOD') }}" checked> - <label for="mod">{% trans 'Mod' %}</label> - </li> - <li> - <input type="radio" name="type" id="admin" value="{{ constant('Admin') }}"> - <label for="admin">{% trans 'Admin' %}</label> - </li> + {% for group_value, group_name in config.mod.groups if group_name != 'Disabled' %} + <li> + <input type="radio" name="type" id="group_{{ group_name }}" value="{{ group_value }}"> + <label for="group_{{ group_name }}">{% trans group_name %}</label> + </li> + {% endfor %} </ul> </td> </tr> diff --git a/templates/mod/users.html b/templates/mod/users.html index fbd43b32..b4c666e1 100644 --- a/templates/mod/users.html +++ b/templates/mod/users.html @@ -15,9 +15,10 @@ <td><small>{{ user.id }}</small></td> <td>{{ user.username|e }}</td> <td> - {% if user.type == constant('JANITOR') %}{% trans 'Janitor' %} - {% elseif user.type == constant('MOD') %}{% trans 'Mod' %} - {% elseif user.type == constant('ADMIN') %}{% trans 'Admin' %} + {% if config.mod.groups[user.type] %} + {{ config.mod.groups[user.type] }} + {% else %} + <em>{% trans 'Unknown' %}</em> ({{ user.type }}) {% endif %} </td> <td> @@ -46,11 +47,11 @@ </td> {% endif %} <td> - {% if mod|hasPermission(config.mod.promoteusers) and user.type < constant('ADMIN') %} + {% if mod|hasPermission(config.mod.promoteusers) and user.type < constant(config.mod.groups[0:-1]|last) %} <a style="float:left;text-decoration:none" href="?/users/{{ user.id }}/promote" title="{% trans 'Promote' %}">▲</a> {% endif %} - {% if mod|hasPermission(config.mod.promoteusers) and user.type > constant('JANITOR') %} - <a style="float:left;text-decoration:none" href="?/users/{{ user.id }}/demote" title="{% trans 'Demote' %}">▼</a> + {% if mod|hasPermission(config.mod.promoteusers) and user.type > constant(config.mod.groups|first) %} + <a style="float:left;text-decoration:none" href="?/users/{{ user.id }}/demote" title="{% trans 'Demote' %}"{% if mod.id == user.id %} onclick="return confirm('{% trans 'Are you sure you want to demote yourself?' %}')"{% endif %}>▼</a> {% endif %} {% if mod|hasPermission(config.mod.modlog) %} <a class="unimportant" style="margin-left:5px;float:right" href="?/log:{{ user.username|e }}">[{% trans 'log' %}]</a> diff --git a/templates/mod/view_ip.html b/templates/mod/view_ip.html index e2dad7af..f73c5d5a 100644 --- a/templates/mod/view_ip.html +++ b/templates/mod/view_ip.html @@ -100,7 +100,7 @@ </tr> <tr> <th>{% trans 'IP' %}</th> - <td>{{ ban.ip }}</td> + <td>{{ ban.mask }}</td> </tr> <tr> <th>{% trans 'Reason' %}</th> @@ -124,7 +124,7 @@ </tr> <tr> <th>{% trans 'Set' %}</th> - <td>{{ ban.set|date(config.post_date) }}</td> + <td>{{ ban.created|date(config.post_date) }}</td> </tr> <tr> <th>{% trans 'Expires' %}</th> |
