Source code of Leftypol imageboard
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3129 lines
106 KiB

<?php
/*
* Copyright (c) 2010-2012 Tinyboard Development Group
*/
// WARNING: This file is currently a clusterfuck of code. I will be rewriting it very soon.
require 'inc/functions.php';
require 'inc/mod.php';
if (get_magic_quotes_gpc()) {
function strip_array($var) {
return is_array($var) ? array_map('strip_array', $var) : stripslashes($var);
}
$_GET = strip_array($_GET);
$_POST = strip_array($_POST);
}
$query = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
// If not logged in
if(!$mod) {
if(isset($_POST['login'])) {
// Check if inputs are set and not empty
if( !isset($_POST['username']) ||
!isset($_POST['password']) ||
empty($_POST['username']) ||
empty($_POST['password'])
) loginForm($config['error']['invalid'], $_POST['username'], '?' . $query);
if(!login($_POST['username'], $_POST['password'])) {
if($config['syslog'])
_syslog(LOG_WARNING, 'Unauthorized login attempt!');
loginForm($config['error']['invalid'], $_POST['username'], '?' . $query);
}
modLog("Logged in.");
// Login successful
// Set cookies
setCookies();
// Redirect
if(isset($_POST['redirect']))
header('Location: ' . $_POST['redirect'], true, $config['redirect_http']);
else
header('Location: ?' . $config['mod']['default'], true, $config['redirect_http']);
} else {
loginForm(false, false, '?' . $query);
}
} else {
// Redirect (for index pages)
if(count($_GET) == 2 && isset($_GET['status']) && isset($_GET['r'])) {
header('Location: ' . $_GET['r'], true, $_GET['status']);
exit;
}
// A sort of "cache"
// Stops calling preg_quote and str_replace when not needed; only does it once
$regex = array(
'board' => str_replace('%s', '(\w{1,8})', preg_quote($config['board_path'], '/')),
'page' => str_replace('%d', '(\d+)', preg_quote($config['file_page'], '/')),
'img' => preg_quote($config['dir']['img'], '/'),
'thumb' => preg_quote($config['dir']['thumb'], '/'),
'res' => preg_quote($config['dir']['res'], '/'),
'index' => preg_quote($config['file_index'], '/')
);
if(preg_match('/^\/?$/', $query)) {
// Dashboard
$fieldset = array(
'Boards' => '',
'Noticeboard' => '',
'Administration' => '',
'Themes' => '',
'Search' => '',
'Update' => '',
'Logout' => ''
);
// Boards
$fieldset['Boards'] .= ulBoards();
if(hasPermission($config['mod']['noticeboard'])) {
if(!$config['cache']['enabled'] || !($fieldset['Noticeboard'] = cache::get('noticeboard_preview'))) {
$query = prepare("SELECT `noticeboard`.*, `username` FROM `noticeboard` LEFT JOIN `mods` ON `mods`.`id` = `mod` ORDER BY `id` DESC LIMIT :limit");
$query->bindValue(':limit', $config['mod']['noticeboard_dashboard'], PDO::PARAM_INT);
$query->execute() or error(db_error($query));
$fieldset['Noticeboard'] .= '<li>';
$_body = '';
while($notice = $query->fetch()) {
$_body .= '<li><a href="?/noticeboard#' .
$notice['id'] .
'">' .
($notice['subject'] ?
$notice['subject']
:
'<em>' . _('no subject') . '</em>'
) .
'</a><span class="unimportant"> &mdash; by ' .
(isset($notice['username']) ?
utf8tohtml($notice['username'])
: '<em>???</em>') .
' at ' .
strftime($config['post_date'], $notice['time']) .
'</span></li>';
}
if(!empty($_body)) {
$fieldset['Noticeboard'] .= '<ul>' . $_body . '</ul></li><li>';
}
if($config['cache']['enabled'])
cache::set('noticeboard_preview', $fieldset['Noticeboard']);
}
$fieldset['Noticeboard'] .= '<a href="?/noticeboard">' . _('View all entries') . '</a></li>';
$query = prepare("SELECT COUNT(*) AS `count` FROM `pms` WHERE `to` = :id AND `unread` = 1");
$query->bindValue(':id', $mod['id']);
$query->execute() or error(db_error($query));
$count = $query->fetch();
$count = $count['count'];
$fieldset['Noticeboard'] .= '<li><a href="?/inbox">' . _('PM Inbox') .
($count > 0
?
' <strong>(' . $count . ' unread)</strong>'
: '') .
'</a></li>';
$fieldset['Noticeboard'] .= '<li><a href="?/news">' . _('News') . '</a></li>';
}
if(hasPermission($config['mod']['reports'])) {
$fieldset['Administration'] .= '<li><a href="?/reports">' . _('Report queue') . '</a></li>';
}
if(hasPermission($config['mod']['view_banlist'])) {
$fieldset['Administration'] .= '<li><a href="?/bans">' . _('Ban list') . '</a></li>';
}
if(hasPermission($config['mod']['manageusers'])) {
$fieldset['Administration'] .= '<li><a href="?/users">' . _('Manage users') . '</a></li>';
} elseif(hasPermission($config['mod']['change_password'])) {
$fieldset['Administration'] .= '<li><a href="?/users/' . $user['id'] . '">' . _('Change own password') . '</a></li>';
}
if(hasPermission($config['mod']['modlog'])) {
$fieldset['Administration'] .= '<li><a href="?/log">' . _('Moderation log') . '</a></li>';
}
if(hasPermission($config['mod']['rebuild'])) {
$fieldset['Administration'] .= '<li><a href="?/rebuild">' . _('Rebuild static files') . '</a></li>';
}
if(hasPermission($config['mod']['rebuild']) && $config['cache']['enabled']) {
$fieldset['Administration'] .= '<li><a href="?/flush">' . _('Clear cache') . '</a></li>';
}
if(hasPermission($config['mod']['show_config'])) {
$fieldset['Administration'] .= '<li><a href="?/config">' . _('Show configuration') . '</a></li>';
}
if(hasPermission($config['mod']['themes'])) {
$fieldset['Themes'] .= '<li><a href="?/themes">' . _('Manage themes') . '</a></li>';
}
if(hasPermission($config['mod']['search'])) {
$fieldset['Search'] .= '<li><form style="display:inline" action="?/search" method="post">' .
'<label style="display:inline" for="search">' . _('Phrase:') . '</label> ' .
'<input id="search" name="search" type="text" size="35" />' .
'<input type="submit" value="' . _('Search') . '" />' .
'</form>' .
'<p class="unimportant">' . _('(Search is case-insensitive, and based on keywords. To match exact phrases, use "quotes". Use an asterisk (*) for wildcard.)') . '</p>' .
'</li>';
}
if($mod['type'] >= ADMIN && $config['check_updates']) {
if(!$config['version'])
error(_('Could not find current version! (Check .installed)'));
if(isset($_COOKIE['update'])) {
$latest = unserialize($_COOKIE['update']);
} else {
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 3
)
)
);
if($code = @file_get_contents('http://tinyboard.org/version.txt', 0, $ctx)) {
eval($code);
if(preg_match('/v(\d+)\.(\d)\.(\d+)(-dev.+)?$/', $config['version'], $m)) {
$current = array(
'massive' => (int)$m[1],
'major' => (int)$m[2],
'minor' => (int)$m[3]
);
if(isset($m[4])) {
// Development versions are always ahead in the versioning numbers
$current['minor'] --;
}
}
// Check if it's newer
if( $latest['massive'] > $current['massive'] ||
$latest['major'] > $current['major'] ||
($latest['massive'] == $current['massive'] &&
$latest['major'] == $current['major'] &&
$latest['minor'] > $current['minor']
)) {
$latest = $latest;
} else $latest = false;
} else {
// Couldn't get latest version
// TODO: Display some sort of warning message
$latest = false;
}
setcookie('update', serialize($latest), time() + $config['check_updates_time'], $config['cookies']['jail'] ? $config['cookies']['path'] : '/', null, false, true);
}
if($latest) {
$fieldset['Update'] .=
'<li>A newer version of Tinyboard (<strong>v' .
$latest['massive'] . '.' .
$latest['major'] . '.' .
$latest['minor'] .
'</strong>) is available! See <a href="http://tinyboard.org">http://tinyboard.org/</a> for upgrade instructions.</li>';
}
}
$fieldset['Logout'] .= '<li><a href="?/logout">' . _('Logout') . '</a></li>';
// TODO: Statistics, etc, in the dashboard.
$body = '';
foreach($fieldset as $title => $data) {
if($data)
$body .= '<fieldset><legend>' . _($title) . '</legend><ul>' . $data . '</ul></fieldset>';
}
echo Element('page.html', array(
'config'=>$config,
'title'=>_('Dashboard'),
'body'=>$body,
'__mod'=>true
));
} elseif(preg_match('/^\/logout$/', $query)) {
destroyCookies();
header('Location: ?/', true, $config['redirect_http']);
} elseif(preg_match('/^\/confirm\/(.+)$/', $query, $matches)) {
$uri = &$matches[1];
$body = '<p style="text-align:center">' .
'<span class="heading" style="margin-bottom:6px">Are you sure you want to do that?</span>' .
'We were unable to serve a confirmation dialog for ' .
'<strong>?/' . utf8tohtml($uri) . '</strong>' .
', probably due to Javascript being disabled.' .
'</p>' .
'<p style="text-align:center"><a style="margin:block;font-size:150%;font-weight:bold" href="?/' . utf8tohtml($uri) . '">Confirm</a></p>';
echo Element('page.html', array(
'config'=>$config,
'title'=>'Confirm',
'body'=>$body,
'mod'=>true
)
);
} elseif(preg_match('/^\/upgrade$/', $query)) {
if($mod['type'] != ADMIN)
error($config['error']['noaccess']);
if(is_dir('.git')) {
// use git instead
$body = '<div class="ban"><h2>git pull</h2>';
$body .= '<p>' . str_replace("\n", '<br/>', shell_exec('git pull')) . '</p>';
$body .= '</div>';
echo Element('page.html', array(
'config' => $config,
'title' => 'Upgraded',
'body' => $body
));
exit;
}
if(!extension_loaded('curl'))
error('You need the cURL PHP extension to do that.');
if(!class_exists('ZipArchive'))
error('You need <a href="http://php.net/manual/en/class.ziparchive.php">the ZipArchive class</a> to do that.');
if(!in_array('zip', stream_get_wrappers()))
error('You need the zip:// stream wrapper to do that.');
$temp = tempnam($config['tmp'], 'tinyboard');
$fp = fopen($temp, 'w+');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://github.com/savetheinternet/Tinyboard/zipball/master');
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl, CURLOPT_TIMEOUT, 45);
curl_setopt($curl, CURLOPT_FILE, $fp);
curl_setopt($curl, CURLOPT_WRITEHEADER, $header = tmpfile());
curl_setopt($curl, CURLOPT_HEADER, true);
curl_exec($curl);
if(curl_errno($curl))
error('Failed downloading newest revision: ' . curl_error($curl));
curl_close($curl);
fflush($fp);
fclose($fp);
fseek($header, 0);
$version = false;
while($line = fgets($header)) {
if(preg_match('/^Content-Disposition: attachment; filename=savetheinternet-Tinyboard-(.+)\.zip\s?$/', $line, $m)) {
$version = $m[1];
}
}
fclose($header);
$zip = new ZipArchive();
if(!$zip->open($temp))
error('Could not make sense of the ZIP archive.');
$version = preg_replace('/^savetheinternet-Tinyboard-(\w+)\//', '$1', $dir = $zip->getNameIndex(0));
$errors = array();
for($i = 1; $i < $zip->numFiles; $i++) {
$filename = str_replace($dir, '', $zip->getNameIndex($i));
if($filename == 'inc/instance-config.php')
continue; // don't override config
// are we able to write here?
if(!((file_exists($filename) && is_writable($filename)) || (!file_exists($filename) && is_writable(dirname($filename))))) {
// nope
$errors[] = 'Cannot write to ' . $filename . '!';
}
}
$zip->close();
if($errors) {
$body = '<div class="ban"><h2>Error(s) upgrading</h2><p>Tinyboard can not self-upgrade until the following is fixed:</p><ul>';
foreach($errors as $error) {
$body .= '<li>' . $error . '</li>';
}
$body .= '</ul><p>Please fix the above errors and refresh to try again.</p></div>';
unlink($temp);
echo Element('page.html', array(
'config' => $config,
'title' => 'Error(s) upgrading',
'body' => $body
));
exit;
}
// For some reason, reading the ZIP entries in PHP doesn't seem to work very well.
// Use shell instead.
shell_exec('TEMP_DIR=$(mktemp -d); unzip -q ' . escapeshellarg($temp) . ' -d $TEMP_DIR -x "' . escapeshellarg($dir) . 'inc/instance-config.php"; mv -v $TEMP_DIR/' . escapeshellarg($dir) . '* "' . getcwd() . '"; rm -rf $TEMP_DIR');
unlink($temp);
echo Element('page.html', array(
'config' => $config,
'title' => 'Upgraded',
'body' => '<p style="text-align:center">Upgrading seems to have gone okay. You are now at revision <strong>' . $version . '</strong>.</p>'
));
} elseif(preg_match('/^\/log(\/(\d+))?$/', $query, $match)) {
if(!hasPermission($config['mod']['modlog'])) error($config['error']['noaccess']);
$page = isset($match[2]) ? $match[2] : 1;
$boards = array();
$_boards = listBoards();
foreach($_boards as &$_b) {
$boards[$_b['id']] = $_b['uri'];
}
$query = prepare("SELECT `mod` as `id`, `username`, `ip`, `board`, `time`, `text` FROM `modlogs` LEFT JOIN `mods` ON `mod` = `mods`.`id` ORDER BY `time` DESC LIMIT :offset, :limit");
$query->bindValue(':limit', $config['mod']['modlog_page'], PDO::PARAM_INT);
$query->bindValue(':offset', ($page - 1) * $config['mod']['modlog_page'], PDO::PARAM_INT);
$query->execute() or error(db_error($query));
if(!$query->rowCount()) {
$body = '<p class="unimportant" style="text-align:center">(Nothing to display.)</p>';
} else {
$body = '<table class="modlog">' .
'<tr>' .
'<th>' . _('User') . '</th>' .
'<th>' . _('IP address') . '</th>' .
'<th>' . _('Ago') . '</th>' .
'<th>' . _('Board') . '</th>' .
'<th>' . _('Action') . '</th>' .
'</tr>';
while($log = $query->fetch()) {
$log_id = 'log_' . md5($log['text']);
if($config['cache']['enabled'] && $_log = cache::get($log_id))
$log['text'] = $_log;
else {
$log['text'] = utf8tohtml($log['text']);
$log['text'] = preg_replace('/(\d+\.\d+\.\d+\.\d+)/', '<a href="?/IP/$1">$1</a>', $log['text']);
if(isset($boards[$log['board']])) {
if(preg_match('/post #(\d+)/', $log['text'], $match)) {
$post_query = prepare(sprintf("SELECT `thread` FROM `posts_%s` WHERE `id` = :id", $boards[$log['board']]));
$post_query->bindValue(':id', $match[1], PDO::PARAM_INT);
$post_query->execute() or error(db_error($query));
if($post = $post_query->fetch()) {
$log['text'] = preg_replace('/post (#(\d+))/',
'post <a href="' .
'?/' .
sprintf($config['board_path'], $boards[$log['board']]) .
$config['dir']['res'] .
($post['thread'] ?
sprintf($config['file_page'], $post['thread']) . '#' . $match[1]
: sprintf($config['file_page'], $match[1])) .
'">$1</a>', $log['text']);
} else {
$log['text'] = preg_replace('/post (#(\d+))/', 'post <s>$1</s>', $log['text']);
}
if($config['cache']['enabled'])
cache::set($log_id, $log['text']);
}
}
}
$body .= '<tr>' .
'<td class="minimal">' .
($log['username'] ?
'<a href="?/new_PM/' . $log['id'] . '">' . $log['username'] . '</a>'
: '<em>' . ($log['id'] < 0 ? 'system' : 'deleted?') . '</em>') .
'</td>' .
'<td class="minimal">' . ($log['id'] < 0 ? '&ndash;' : '<a href="?/IP/' . $log['ip'] . '">' . $log['ip'] . '</a>') . '</td>' .
'<td class="minimal">' . ago($log['time']) . '</td>' .
'<td class="minimal">' .
($log['board'] ?
'<a href="?/' . sprintf($config['board_path'], $log['board']) . $config['file_index'] . '">' . sprintf($config['board_abbreviation'], $log['board']) . '</a></td>'
: '-') .
'<td>' . $log['text'] . '</td>' .
'</tr>';
}
$body .= '</table>';
$query = prepare("SELECT COUNT(*) AS `count` FROM `modlogs`");
$query->execute() or error(db_error($query));
$count = $query->fetch();
$body .= '<p class="unimportant" style="text-align:center;word-wrap:break-word">';
for($x = 0; $x < $count['count'] / $config['mod']['modlog_page']; $x ++) {
$body .= '<a href="?/log/' . ($x+1) . '">[' . ($x + 1) . ']</a> ';
}
$body .= '</p>';
}
echo Element('page.html', array(
'config'=>$config,
'title'=>_('Moderation log'),
'body'=>$body,
'mod'=>true
)
);
} elseif(preg_match('/^\/themes\/none$/', $query, $match)) {
if(!hasPermission($config['mod']['themes'])) error($config['error']['noaccess']);
// Clearsettings
query("TRUNCATE TABLE `theme_settings`") or error(db_error());
echo Element('page.html', array(
'config'=>$config,
'title'=>'No theme',
'body'=>'<p style="text-align:center">Successfully uninstalled all themes.</p>' .
'<p style="text-align:center"><a href="?/themes">Go back to themes</a>.</p>',
'mod'=>true
)
);
} elseif(preg_match('/^\/themes\/([\w\-]+)\/rebuild$/', $query, $match)) {
if(!hasPermission($config['mod']['themes'])) error($config['error']['noaccess']);
rebuildTheme($match[1], 'all');
echo Element('page.html', array(
'config'=>$config,
'title'=>'Rebuilt',
'body'=>'<p style="text-align:center">Successfully rebuilt the <strong>' . $match[1] . '</strong> theme.</p>' .
'<p style="text-align:center"><a href="?/themes">Go back to themes</a>.</p>',
'mod'=>true
)
);
} elseif(preg_match('/^\/themes\/(\w+)\/uninstall$/', $query, $match)) {
if(!hasPermission($config['mod']['themes'])) error($config['error']['noaccess']);
$query = prepare("DELETE FROM `theme_settings` WHERE `theme` = :theme");
$query->bindValue(':theme', $match[1]);
$query->execute() or error(db_error($query));
echo Element('page.html', array(
'config'=>$config,
'title'=>'Uninstalled',
'body'=>'<p style="text-align:center">Successfully uninstalled the <strong>' . $match[1] . '</strong> theme.</p>' .
'<p style="text-align:center"><a href="?/themes">Go back to themes</a>.</p>',
'mod'=>true
)
);
} elseif(preg_match('/^\/themes(\/([\w\-]+))?$/', $query, $match)) {
if(!hasPermission($config['mod']['themes'])) error($config['error']['noaccess']);
if(!is_dir($config['dir']['themes']))
error(_('Themes directory doesn\'t exist!'));
if(!$dir = opendir($config['dir']['themes']))
error(_('Cannot open themes directory; check permissions.'));
if(isset($match[2])) {
$_theme = &$match[2];
if(!$theme = loadThemeConfig($_theme)) {
error($config['error']['invalidtheme']);
}
if(isset($_POST['install'])) {
// Check if everything is submitted
foreach($theme['config'] as &$c) {
if(!isset($_POST[$c['name']]) && $c['type'] != 'checkbox')
error(sprintf($config['error']['required'], $c['title']));
}
// Clear previous settings
$query = prepare("DELETE FROM `theme_settings` WHERE `theme` = :theme");
$query->bindValue(':theme', $_theme);
$query->execute() or error(db_error($query));
foreach($theme['config'] as &$c) {
$query = prepare("INSERT INTO `theme_settings` VALUES(:theme, :name, :value)");
$query->bindValue(':theme', $_theme);
$query->bindValue(':name', $c['name']);
$query->bindValue(':value', $_POST[$c['name']]);
$query->execute() or error(db_error($query));
}
$query = prepare("INSERT INTO `theme_settings` VALUES(:theme, NULL, NULL)");
$query->bindValue(':theme', $_theme);
$query->execute() or error(db_error($query));
$result = true;
$body = '';
if(isset($theme['install_callback'])) {
$ret = $theme['install_callback'](themeSettings($_theme));
if($ret && !empty($ret)) {
if(is_array($ret) && count($ret) == 2) {
$result = $ret[0];
$ret = $ret[1];
}
$body .= '<div style="border:1px dashed maroon;padding:20px;margin:auto;max-width:800px">' . $ret . '</div>';
}
}
if($result) {
$body .= '<p style="text-align:center">Successfully installed and built theme.</p>';
} else {
// install failed
$query = prepare("DELETE FROM `theme_settings` WHERE `theme` = :theme");
$query->bindValue(':theme', $_theme);
$query->execute() or error(db_error($query));
}
$body .= '<p style="text-align:center"><a href="?/themes">Go back to themes</a>.</p>';
// Build themes
rebuildThemes('all');
echo Element('page.html', array(
'config'=>$config,
'title'=>($result ? 'Installed "' . utf8tohtml($theme['name']) . '"' : 'Installation failed!'),
'body'=>$body,
'mod'=>true
)
);
} else {
$body = '<form action="" method="post">';
if(!isset($theme['config']) || empty($theme['config'])) {
$body .= '<p style="text-align:center" class="unimportant">(No configuration required.)</p>';
} else {
$settings = themeSettings($_theme);
$body .= '<table>';
foreach($theme['config'] as &$c) {
$body .= '<tr><th>' . $c['title'] . '</th><td>';
switch($c['type']) {
case 'text':
default:
$body .= '<input type="text" name="' . utf8tohtml($c['name']) . '" ' .
(isset($settings[$c['name']]) ?
' value="' . utf8tohtml($settings[$c['name']]) . '" '
:
(isset($c['default']) ?
'value="' . utf8tohtml($c['default']) . '" '
: '')
) .
(isset($c['size']) ? 'size="' . (int)$c['size'] . '" ' :'') .
'/>';
}
if(isset($c['comment']))
$body .= ' <span class="unimportant">' . $c['comment'] . '</span>';
$body .= '</td></tr>';
}
$body .= '</table>';
}
$body .= '<p style="text-align:center"><input name="install" type="submit" value="Install theme" /></p></form>';
echo Element('page.html', array(
'config'=>$config,
'title'=>'Installing "' . utf8tohtml($theme['name']) . '"',
'body'=>$body,
'mod'=>true
)
);
}
} else {
$themes_in_use = array();
$query = query("SELECT `theme` FROM `theme_settings` WHERE `name` IS NULL AND `value` IS NULL") or error(db_error());
while($theme = $query->fetch()) {
$themes_in_use[$theme['theme']] = true;
}
// Scan directory for themes
$themes = array();
while($file = readdir($dir)) {
if($file[0] != '.' && is_dir($config['dir']['themes'] . '/' . $file)) {
$themes[] = $file;
}
}
closedir($dir);
$body = '';
if(empty($themes)) {
$body = '<p style="text-align:center" class="unimportant">(No themes installed.)</p>';
} else {
$body .= '<table class="modlog">';
foreach($themes as &$_theme) {
$theme = loadThemeConfig($_theme);
markup($theme['description']);
$body .= '<tr>' .
'<th class="minimal">' . _('Name') . '</th>' .
'<td>' . utf8tohtml($theme['name']) . '</td>' .
'</tr>' .
'<tr>' .
'<th class="minimal">' . _('Version') . '</th>' .
'<td>' . utf8tohtml($theme['version']) . '</td>' .
'</tr>' .
'<tr>' .
'<th class="minimal">' . _('Description') . '</th>' .
'<td>' . $theme['description'] . '</td>' .
'</tr>' .
'<tr>' .
'<th class="minimal">' . _('Thumbnail') . '</th>' .
'<td><img style="float:none;margin:4px' .
(isset($themes_in_use[$_theme]) ?
';border:2px solid red;padding:4px'
: '') .
'" src="' . $config['dir']['themes_uri'] . '/' . $_theme . '/thumb.png" /></td>' .
'</tr>' .
'<tr>' .
'<th class="minimal">' . _('Actions') . '</th>' .
'<td><ul style="padding:0 20px">' .
'<li><a title="' . _('Use theme') . '" href="?/themes/' . $_theme . '">' .
(isset($themes_in_use[$_theme]) ? _('Reconfigure') : _('Install')) .
'</a></li>' .
(isset($themes_in_use[$_theme]) ?
'<li><a href="?/themes/' . $_theme . '/rebuild">' . _('Rebuild') . '</a></li>' .
'<li><a href="?/themes/' . $_theme . '/uninstall">' . _('Uninstall') . '</a></li>'
:
'') .
'</ul></td>' .
'</tr>' .
'<tr style="height:40px"><td colspan="2"><hr/></td></tr>';
}
$body .= '</table>';
}
if(!empty($themes_in_use))
$body .= '<p style="text-align:center"><a href="?/themes/none">' . _('Uninstall all themes.') . '</a></p>';
echo Element('page.html', array(
'config'=>$config,
'title'=>_('Manage themes'),
'body'=>$body,
'mod'=>true
)
);
}
} elseif(preg_match('/^\/noticeboard\/delete\/(\d+)$/', $query, $match)) {
if(!hasPermission($config['mod']['noticeboard_delete'])) error($config['error']['noaccess']);
$query = prepare("DELETE FROM `noticeboard` WHERE `id` = :id");
$query->bindValue(':id', $match[1], PDO::PARAM_INT);
$query->execute() or error(db_error($query));
if($config['cache']['enabled'])
cache::delete('noticeboard_preview');
header('Location: ?/noticeboard', true, $config['redirect_http']);
} elseif(preg_match('/^\/noticeboard$/', $query)) {
if(!hasPermission($config['mod']['noticeboard'])) error($config['error']['noaccess']);
$body = '';
if(hasPermission($config['mod']['noticeboard_post']) && isset($_POST['subject']) && isset($_POST['body']) && !empty($_POST['body'])) {
$query = prepare("INSERT INTO `noticeboard` VALUES (NULL, :mod, :time, :subject, :body)");
$query->bindValue(':mod', $mod['id'], PDO::PARAM_INT);
$query->bindvalue(':time', time(), PDO::PARAM_INT);
$query->bindValue(':subject', utf8tohtml($_POST['subject']));
markup($_POST['body']);
$query->bindValue(':body', $_POST['body']);
$query->execute() or error(db_error($query));
if($config['cache']['enabled'])
cache::delete('noticeboard_preview');
header('Location: ?/noticeboard#' . $pdo->lastInsertId(), true, $config['redirect_http']);
} else {
if(hasPermission($config['mod']['noticeboard_post'])) {
$body .= '<fieldset><legend>New post</legend><form style="display:inline" action="" method="post"><table>' .
'<tr>' .
'<th><label for="subject">' . _('Name') . '</label></th>' .
'<td>' . $mod['username'] . '</td>' .
'</tr><tr>' .
'<th>' . _('Subject') . '</th>' .
'<td><input type="text" size="55" name="subject" id="subject" /></td>' .
'</tr><tr>' .
'<th>' . _('Body') . '</th>' .
'<td><textarea name="body" style="width:100%;height:100px"></textarea></td>' .
'</tr><tr>' .
'<td></td><td><input type="submit" value="' . _('Post to noticeboard') . '" /></td>' .
'</tr></table>' .
'</form></fieldset>';
}
$query = prepare("SELECT `noticeboard`.*, `username` FROM `noticeboard` LEFT JOIN `mods` ON `mods`.`id` = `mod` ORDER BY `id` DESC LIMIT :limit");
$query->bindValue(':limit', $config['mod']['noticeboard_display'], PDO::PARAM_INT);
$query->execute() or error(db_error($query));
while($notice = $query->fetch()) {
$body .= '<div class="ban">' .
(hasPermission($config['mod']['noticeboard_delete']) ?
'<span style="float:right;padding:2px"><a class="unimportant" href="?/noticeboard/delete/' . $notice['id'] . '">[delete]</a></span>'
: '') .
'<h2 id="' . $notice['id'] . '">' .
($notice['subject'] ?
$notice['subject']
:
'<em>' . _('no subject') . '</em>'
) .
'<span class="unimportant"> &mdash; by ' .
(isset($notice['username']) ?
utf8tohtml($notice['username'])
:
'<em>???</em>'
) .
' at ' .
strftime($config['post_date'], $notice['time']) .
'</span></h2><p>' . $notice['body'] . '</p></div>';
}
echo Element('page.html', array(
'config'=>$config,
'title'=>_('Noticeboard'),
'body'=>$body,
'mod'=>true
)
);
}
} elseif(preg_match('/^\/news\/delete\/(\d+)$/', $query, $match)) {
if(!hasPermission($config['mod']['noticeboard_delete'])) error($config['error']['noaccess']);
$query = prepare("DELETE FROM `news` WHERE `id` = :id");
$query->bindValue(':id', $match[1], PDO::PARAM_INT);
$query->execute() or error(db_error($query));
rebuildThemes('news');
header('Location: ?/news', true, $config['redirect_http']);
} elseif(preg_match('/^\/news$/', $query)) {
$body = '';
if(hasPermission($config['mod']['news'])) {
if(isset($_POST['subject']) && isset($_POST['body']) && !empty($_POST['body'])) {
$query = prepare("INSERT INTO `news` VALUES (NULL, :name, :time, :subject, :body)");
if(isset($_POST['name']) && hasPermission($config['mod']['news_custom']))
$name = &$_POST['name'];
else
$name = &$mod['username'];
$query->bindValue(':name', utf8tohtml($name), PDO::PARAM_INT);
$query->bindvalue(':time', time(), PDO::PARAM_INT);
$query->bindValue(':subject', utf8tohtml($_POST['subject']));
markup($_POST['body']);
$query->bindValue(':body', $_POST['body']);
$query->execute() or error(db_error($query));
rebuildThemes('news');
}
$body .= '<fieldset><legend>New post</legend><form style="display:inline" action="" method="post"><table>' .
'<tr>' .
'<th>' . _('Name') . '</th>' .
(hasPermission($config['mod']['news_custom']) ?
'<td><input type="text" size="55" name="name" id="name" value="' . utf8tohtml($mod['username']) . '" /></td>'
:
'<td>' . $mod['username'] . '</td>') .
'</tr><tr>' .
'<th>' . _('Subject') . '</th>' .
'<td><input type="text" size="55" name="subject" id="subject" /></td>' .
'</tr><tr>' .
'<th>' . _('Body') . '</th>' .
'<td><textarea name="body" style="width:100%;height:100px"></textarea></td>' .
'</tr><tr>' .
'<td></td><td><input type="submit" value="' . _('Post to news') . '" /></td>' .
'</tr></table>' .
'</form></fieldset>';
}
$query = prepare("SELECT * FROM `news` ORDER BY `id` DESC LIMIT :limit");
$query->bindValue(':limit', $config['mod']['noticeboard_display'], PDO::PARAM_INT);
$query->execute() or error(db_error($query));
while($news = $query->fetch()) {
$body .= '<div class="ban">' .
(hasPermission($config['mod']['news_delete']) ?
'<span style="float:right;padding:2px"><a class="unimportant" href="?/news/delete/' . $news['id'] . '">[delete]</a></span>'
: '') .
'<h2 id="' . $news['id'] . '">' .
($news['subject'] ?
$news['subject']
:
'<em>' . _('no subject') . '</em>'
) .
'<span class="unimportant"> &mdash; by ' .
$news['name'] .
' at ' .
strftime($config['post_date'], $news['time']) .
'</span></h2><p>' . $news['body'] . '</p></div>';
}
echo Element('page.html', array(
'config'=>$config,
'title'=>_('News'),
'body'=>$body,
'mod'=>true
)
);
} elseif(preg_match('/^\/inbox\/readall$/', $query, $match)) {
$query = prepare("UPDATE `pms` SET `unread` = 0 WHERE `to` = :id");
$query->bindValue(':id', $mod['id'], PDO::PARAM_INT);
$query->execute() or error(db_error($query));
modLog('Marked all PMs as read');
header('Location: ?/inbox', true, $config['redirect_http']);
} elseif(preg_match('/^\/inbox$/', $query, $match)) {
$query = prepare("SELECT `unread`,`pms`.`id`, `time`, `sender`, `to`, `message`, `username` FROM `pms` LEFT JOIN `mods` ON `mods`.`id` = `sender` WHERE `to` = :mod ORDER BY `unread` DESC, `time` DESC");
$query->bindValue(':mod', $mod['id'], PDO::PARAM_INT);
$query->execute() or error(db_error($query));
if($query->rowCount() == 0) {
$body = '<p style="text-align:center" class="unimportant">(' . _('No private messages for you.') . ')</p>';
} else {
$unread_pms = 0;
$body = '<table class="modlog"><tr><th>ID</th><th>From</th><th>Date</th><th>Message snippet</th></tr>';
while($pm = $query->fetch()) {
$body .= '<tr' . ($pm['unread'] ? ' style="font-weight:bold"' : '') . '>' .
'<td class="minimal"><a href="?/PM/' . $pm['id'] . '">' . $pm['id'] . '</a></td>' .
'<td class="minimal">' .
($pm['username'] ?
'<a href="?/new_PM/' . $pm['sender'] . '">' . $pm['username'] . '</a>'
: '<em>deleted?</em>') .
'</td>' .
'<td class="minimal">' . strftime($config['post_date'], $pm['time']) . '</td>' .
'<td><a href="?/PM/' . $pm['id'] . '">' . pm_snippet($pm['message']) . '</a></td>' .
'</tr>';
if($pm['unread'])
$unread_pms++;
}
$body .= '</table>';
if($unread_pms) {
$body = '<p style="text-align:center" class="unimportant">(<a href="?/inbox/readall">Mark all as read</a>)</p>' . $body;
}
}
echo Element('page.html', array(
'config'=>$config,
'title'=>_('PM Inbox') . ' (' . ($query->rowCount() == 0 ? _('empty') : $unread_pms . ' ' . _('unread')) . ')',
'body'=>$body,
'mod'=>true
)
);
} elseif(preg_match('/^\/PM\/(\d+)$/', $query, $match)) {
$id = &$match[1];
if(hasPermission($config['mod']['master_pm'])) {
$query = prepare("SELECT `pms`.`id`, `time`, `sender`, `unread`, `to`, `message`, `username` FROM `pms` LEFT JOIN `mods` ON `mods`.`id` = `sender` WHERE `pms`.`id` = :id");
} else {
$query = prepare("SELECT `pms`.`id`, `time`, `sender`, `unread`, `to`, `message`, `username` FROM `pms` LEFT JOIN `mods` ON `mods`.`id` = `sender` WHERE `pms`.`id` = :id AND `to` = :mod");
$query->bindValue(':mod', $mod['id'], PDO::PARAM_INT);
}
$query->bindValue(':id', $id, PDO::PARAM_INT);
$query->execute() or error(db_error($query));
if(!$pm = $query->fetch()) {
// Mod doesn't exist
error($config['error']['404']);
}
if(isset($_POST['delete'])) {
$query = prepare("DELETE FROM `pms` WHERE `id` = :id");
$query->bindValue(':id', $id, PDO::PARAM_INT);
$query->execute() or error(db_error($query));
modLog('Deleted a PM');
header('Location: ?/inbox', true, $config['redirect_http']);
} else {
if($pm['unread']) {
$query = prepare("UPDATE `pms` SET `unread` = 0 WHERE `id` = :id");
$query->bindValue(':id', $id, PDO::PARAM_INT);
$query->execute() or error(db_error($query));
modLog('Read a PM');
}
if($pm['to'] != $mod['id']) {
$query = prepare("SELECT `username` FROM `mods` WHERE `id` = :id");
$query->bindValue(':id', $pm['to'], PDO::PARAM_INT);
$query->execute() or error(db_error($query));
if($_mod = $query->fetch()) {
$__to = &$_mod['username'];
} else {
$__to = false;
}
}
$body = '<form action="" method="post" style="margin:0"><table>' .
'<th>From</th><td>' .
(!$pm['username'] ?
'<em>???</em>'
:
'<a href="?/new_PM/' . $pm['sender'] . '">' . utf8tohtml($pm['username']) . '</a>'
) .
'</td></tr>' .
(isset($__to) ?
'<th>To</th><td>' .
($__to === false ?
'<em>???</em>'
:
'<a href="?/new_PM/' . $pm['to'] . '">' . utf8tohtml($__to) . '</a>'
) .
'</td></tr>'
: '') .
'<tr><th>Date</th><td> ' . strftime($config['post_date'], $pm['time']) . '</td></tr>' .
'<tr><th>Message</th><td> ' . $pm['message'] . '</td></tr>' .
'</table>' .
'<p style="text-align:center"><input type="submit" name="delete" value="Delete forever" /></p>' .
'</form>' .
'<p style="text-align:center"><a href="?/new_PM/' . $pm['sender'] . '/' . $pm['id'] . '">Reply with quote</a></p>';
echo Element('page.html', array(
'config'=>$config,
'title'=>'Private message',
'body'=>$body,
'mod'=>true
)
);
}
} elseif(preg_match('/^\/new_PM\/(\d+)(\/(\d+))?$/', $query, $match)) {
if(!hasPermission($config['mod']['create_pm'])) error($config['error']['noaccess']);
$to = &$match[1];
$query = prepare("SELECT `username`,`id` FROM `mods` WHERE `id` = :id");
$query->bindValue(':id', $to, PDO::PARAM_INT);
$query->execute() or error(db_error($query));
if(!$to = $query->fetch()) {
// Mod doesn't exist
error($config['error']['404']);
}
if(isset($_POST['message'])) {
// Post message
$message = &$_POST['message'];
if(empty($message))
error($config['error']['tooshort_body']);
markup($message);
$query = prepare("INSERT INTO `pms` VALUES (NULL, :sender, :to, :message, :time, 1)");
$query->bindValue(':sender', $mod['id'], PDO::PARAM_INT);
$query->bindValue(':to', $to['id'], PDO::PARAM_INT);
$query->bindValue(':message', $message);
$query->bindValue(':time', time(), PDO::PARAM_INT);
$query->execute() or error(db_error($query));
modLog('Sent a PM to ' . $to['username']);
echo Element('page.html', array(
'config'=>$config,
'title'=>'PM sent',
'body'=>'<p style="text-align:center">Message sent successfully to ' . utf8tohtml($to['username']) . '.</p>',
'mod'=>true
)
);
} else {
$value = '';
if(isset($match[3])) {
$reply = &$match[3];
$query = prepare("SELECT `message` FROM `pms` WHERE `sender` = :sender AND `to` = :mod AND `id` = :id");
$query->bindValue(':sender', $to['id'], PDO::PARAM_INT);
$query->bindValue(':mod', $mod['id'], PDO::PARAM_INT);
$query->bindValue(':id', $reply, PDO::PARAM_INT);
$query->execute() or error(db_error($query));
if($pm = $query->fetch()) {
$value = quote($pm['message']);
}
}
$body = '<form action="" method="post">' .
'<table>' .
'<tr><th>To</th><td>' .
(hasPermission($config['mod']['editusers']) ?
'<a href="?/users/' . $to['id'] . '">' . utf8tohtml($to['username']) . '</a>' :
utf8tohtml($to['username'])
) .
'</td>' .
'<tr><th>Message</th><td><textarea name="message" rows="10" cols="40">' . $value . '</textarea></td>' .
'</table>' .
'<p style="text-align:center"><input type="submit" value="Send message" /></p>' .
'</form>';
echo Element('page.html', array(
'config'=>$config,
'title'=>'New PM for ' . utf8tohtml($to['username']),
'body'=>$body,
'mod'=>true
)
);
}
} elseif(preg_match('/^\/search$/', $query)) {
if(!hasPermission($config['mod']['search'])) error($config['error']['noaccess']);
$body = '<div class="ban"><h2>Search</h2><form style="display:inline" action="?/search" method="post">' .
'<p><label style="display:inline" for="search">Phrase:</label> ' .
'<input id="search" name="search" type="text" size="35" ' .
(isset($_POST['search']) ? 'value="' . str_replace('"', '&quot;', utf8tohtml($_POST['search'])) . '" ' : '') .
'/>' .
'<input type="submit" value="Search" />' .
'</p></form>' .
'<p><span class="unimportant">(Search is case-insensitive, and based on keywords. To match exact phrases, use "quotes". Use an asterisk (*) for wildcard.)</span></p>' .
'</div>';
if(isset($_POST['search']) && !empty($_POST['search'])) {
$phrase = &$_POST['search'];
$_body = '';
$filters = array();
function search_filters($m) {
global $filters;
$name = $m[2];
$value = isset($m[4]) ? $m[4] : $m[3];
if(!in_array($name, array('id', 'thread', 'subject', 'email', 'name', 'trip', 'capcode', 'filename', 'filehash', 'ip'))) {
// unknown filter
return $m[0];
}
$filters[$name] = $value;
return $m[1];
}
$phrase = trim(preg_replace_callback('/(^|\s)(\w+):("(.*)?"|[^\s]*)/', 'search_filters', $phrase));
// Escape escape character
$phrase = str_replace('!', '!!', $phrase);
// Remove SQL wildcard
$phrase = str_replace('%', '!%', $phrase);
// Use asterisk as wildcard to suit convention
$phrase = str_replace('*', '%', $phrase);
$like = '';
$match = array();
// Find exact phrases
if(preg_match_all('/"(.+?)"/', $phrase, $m)) {
foreach($m[1] as &$quote) {
$phrase = str_replace("\"{$quote}\"", '', $phrase);
$match[] = $pdo->quote($quote);
}
}
$words = explode(' ', $phrase);
foreach($words as &$word) {
if(empty($word))
continue;
$match[] = $pdo->quote($word);
}
$like = '';
foreach($match as &$phrase) {
if(!empty($like))
$like .= ' AND ';
$phrase = preg_replace('/^\'(.+)\'$/', '\'%$1%\'', $phrase);
$like .= '`body` LIKE ' . $phrase . ' ESCAPE \'!\'';
}
foreach($filters as $name => $value) {
if(!empty($like))
$like .= ' AND ';
$like .= '`' . $name . '` = '. $pdo->quote($value);
}
$like = str_replace('%', '%%', $like);
$boards = listBoards();
foreach($boards as &$_b) {
openBoard($_b['uri']);
$query = prepare(sprintf("SELECT * FROM `posts_%s` WHERE " . $like . " ORDER BY `time` DESC LIMIT :limit", $board['uri']));
$query->bindValue(':limit', $config['mod']['search_results'], PDO::PARAM_INT);
$query->execute() or error(db_error($query));
$temp = '';
while($post = $query->fetch()) {
if(!$post['thread']) {
$po = new Thread($post['id'], $post['subject'], $post['email'], $post['name'], $post['trip'], $post['capcode'], $post['body'], $post['time'], $post['thumb'], $post['thumbwidth'], $post['thumbheight'], $post['file'], $post['filewidth'], $post['fileheight'], $post['filesize'], $post['filename'], $post['ip'], $post['sticky'], $post['locked'], $post['sage'], $post['embed'], '?/', $mod, false);
} else {
$po = new Post($post['id'], $post['thread'], $post['subject'], $post['email'], $post['name'], $post['trip'], $post['capcode'], $post['body'], $post['time'], $post['thumb'], $post['thumbwidth'], $post['thumbheight'], $post['file'], $post['filewidth'], $post['fileheight'], $post['filesize'], $post['filename'], $post['ip'], $post['embed'], '?/', $mod);
}
$temp .= $po->build(true) . '<hr/>';
}
if(!empty($temp))
$_body .= '<fieldset><legend>' . $query->rowCount() . ' result' . ($query->rowCount() != 1 ? 's' : '') . ' on <a href="?/' .
sprintf($config['board_path'], $board['uri']) . $config['file_index'] .
'">' .
sprintf($config['board_abbreviation'], $board['uri']) . ' - ' . $board['title'] .
'</a></legend>' . $temp . '</fieldset>';
}
$body .= '<hr/>';
if(!empty($_body))
$body .= $_body;
else
$body .= '<p style="text-align:center" class="unimportant">(No results.)</p>';
}
echo Element('page.html', array(
'config'=>$config,
'title'=>'Search',
'body'=>$body,
'mod'=>true
)
);
} elseif(preg_match('/^\/users$/', $query)) {
if(!hasPermission($config['mod']['manageusers'])) error($config['error']['noaccess']);
$body = '<form action="" method="post"><table class="modlog" style="width:auto"><tr><th>' . _('ID') . '</th><th>' . _('Username') . '</th><th>' . _('Type') . '</th><th>' . _('Boards') . '</th><th>' . _('Last action') . '</th><th>&hellip;</th></tr>';
$query = query("SELECT *, (SELECT `time` FROM `modlogs` WHERE `mod` = `id` ORDER BY `time` DESC LIMIT 1) AS `last`, (SELECT `text` FROM `modlogs` WHERE `mod` = `id` ORDER BY `time` DESC LIMIT 1) AS `action` FROM `mods` ORDER BY `type` DESC,`id`") or error(db_error());
while($_mod = $query->fetch()) {
$type = $_mod['type'] == JANITOR ? 'Janitor' : ($_mod['type'] == MOD ? 'Mod' : 'Admin');
$_mod['boards'] = explode(',', $_mod['boards']);
foreach($_mod['boards'] as &$_board) {
if($_board != '*')
$_board = '/' . $_board . '/';
}
$body .= '<tr>' .
'<td>' .
$_mod['id'] .
'</td>' .
'<td>' .
utf8tohtml($_mod['username']) .
'</td>' .
'<td>' .
$type .
'</td>' .
'<td>' .
implode(', ', $_mod['boards']) .
'</td>' .
'<td>' .
($_mod['last'] ?
(hasPermission($config['mod']['modlog']) ?
'<span title="' . str_replace('"', '&quot;', utf8tohtml($_mod['action'])) . '">' . ago($_mod['last']) . '</span>'
: ago($_mod['last']))
: '<em>never</em>') .
'</td>' .
'<td style="white-space:nowrap">' .
(hasPermission($config['mod']['promoteusers']) ?