The version of vichan running on lainchan.org
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.

2697 lines
87KB

  1. <?php
  2. /*
  3. * Copyright (c) 2010-2013 Tinyboard Development Group
  4. */
  5. defined('TINYBOARD') or exit;
  6. function mod_page($title, $template, $args, $subtitle = false) {
  7. global $config, $mod;
  8. echo Element('page.html', array(
  9. 'config' => $config,
  10. 'mod' => $mod,
  11. 'hide_dashboard_link' => $template == 'mod/dashboard.html',
  12. 'title' => $title,
  13. 'subtitle' => $subtitle,
  14. 'nojavascript' => true,
  15. 'body' => Element($template,
  16. array_merge(
  17. array('config' => $config, 'mod' => $mod),
  18. $args
  19. )
  20. )
  21. )
  22. );
  23. }
  24. function mod_login($redirect = false) {
  25. global $config;
  26. $args = array();
  27. if (isset($_POST['login'])) {
  28. // Check if inputs are set and not empty
  29. if (!isset($_POST['username'], $_POST['password']) || $_POST['username'] == '' || $_POST['password'] == '') {
  30. $args['error'] = $config['error']['invalid'];
  31. } elseif (!login($_POST['username'], $_POST['password'])) {
  32. if ($config['syslog'])
  33. _syslog(LOG_WARNING, 'Unauthorized login attempt!');
  34. $args['error'] = $config['error']['invalid'];
  35. } else {
  36. modLog('Logged in');
  37. // Login successful
  38. // Set cookies
  39. setCookies();
  40. if ($redirect)
  41. header('Location: ?' . $redirect, true, $config['redirect_http']);
  42. else
  43. header('Location: ?/', true, $config['redirect_http']);
  44. }
  45. }
  46. if (isset($_POST['username']))
  47. $args['username'] = $_POST['username'];
  48. mod_page(_('Login'), 'mod/login.html', $args);
  49. }
  50. function mod_confirm($request) {
  51. mod_page(_('Confirm action'), 'mod/confirm.html', array('request' => $request, 'token' => make_secure_link_token($request)));
  52. }
  53. function mod_logout() {
  54. global $config;
  55. destroyCookies();
  56. header('Location: ?/', true, $config['redirect_http']);
  57. }
  58. function mod_dashboard() {
  59. global $config, $mod;
  60. $args = array();
  61. $args['boards'] = listBoards();
  62. if (hasPermission($config['mod']['noticeboard'])) {
  63. if (!$config['cache']['enabled'] || !$args['noticeboard'] = cache::get('noticeboard_preview')) {
  64. $query = prepare("SELECT ``noticeboard``.*, `username` FROM ``noticeboard`` LEFT JOIN ``mods`` ON ``mods``.`id` = `mod` ORDER BY `id` DESC LIMIT :limit");
  65. $query->bindValue(':limit', $config['mod']['noticeboard_dashboard'], PDO::PARAM_INT);
  66. $query->execute() or error(db_error($query));
  67. $args['noticeboard'] = $query->fetchAll(PDO::FETCH_ASSOC);
  68. if ($config['cache']['enabled'])
  69. cache::set('noticeboard_preview', $args['noticeboard']);
  70. }
  71. }
  72. if (!$config['cache']['enabled'] || ($args['unread_pms'] = cache::get('pm_unreadcount_' . $mod['id'])) === false) {
  73. $query = prepare('SELECT COUNT(*) FROM ``pms`` WHERE `to` = :id AND `unread` = 1');
  74. $query->bindValue(':id', $mod['id']);
  75. $query->execute() or error(db_error($query));
  76. $args['unread_pms'] = $query->fetchColumn();
  77. if ($config['cache']['enabled'])
  78. cache::set('pm_unreadcount_' . $mod['id'], $args['unread_pms']);
  79. }
  80. $query = query('SELECT COUNT(*) FROM ``reports``') or error(db_error($query));
  81. $args['reports'] = $query->fetchColumn();
  82. if ($mod['type'] >= ADMIN && $config['check_updates']) {
  83. if (!$config['version'])
  84. error(_('Could not find current version! (Check .installed)'));
  85. if (isset($_COOKIE['update'])) {
  86. $latest = unserialize($_COOKIE['update']);
  87. } else {
  88. $ctx = stream_context_create(array('http' => array('timeout' => 5)));
  89. if ($code = @file_get_contents('http://engine.vichan.net/version.txt', 0, $ctx)) {
  90. $ver = strtok($code, "\n");
  91. if (preg_match('@^// v(\d+)\.(\d+)\.(\d+)\s*?$@', $ver, $matches)) {
  92. $latest = array(
  93. 'massive' => $matches[1],
  94. 'major' => $matches[2],
  95. 'minor' => $matches[3]
  96. );
  97. if (preg_match('/(\d+)\.(\d)\.(\d+)(-dev.+)?$/', $config['version'], $matches)) {
  98. $current = array(
  99. 'massive' => (int) $matches[1],
  100. 'major' => (int) $matches[2],
  101. 'minor' => (int) $matches[3]
  102. );
  103. if (isset($m[4])) {
  104. // Development versions are always ahead in the versioning numbers
  105. $current['minor'] --;
  106. }
  107. // Check if it's newer
  108. if (!( $latest['massive'] > $current['massive'] ||
  109. $latest['major'] > $current['major'] ||
  110. ($latest['massive'] == $current['massive'] &&
  111. $latest['major'] == $current['major'] &&
  112. $latest['minor'] > $current['minor']
  113. )))
  114. $latest = false;
  115. } else {
  116. $latest = false;
  117. }
  118. } else {
  119. // Couldn't get latest version
  120. $latest = false;
  121. }
  122. } else {
  123. // Couldn't get latest version
  124. $latest = false;
  125. }
  126. setcookie('update', serialize($latest), time() + $config['check_updates_time'], $config['cookies']['jail'] ? $config['cookies']['path'] : '/', null, !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off', true);
  127. }
  128. if ($latest)
  129. $args['newer_release'] = $latest;
  130. }
  131. $args['logout_token'] = make_secure_link_token('logout');
  132. mod_page(_('Dashboard'), 'mod/dashboard.html', $args);
  133. }
  134. function mod_search_redirect() {
  135. global $config;
  136. if (!hasPermission($config['mod']['search']))
  137. error($config['error']['noaccess']);
  138. if (isset($_POST['query'], $_POST['type']) && in_array($_POST['type'], array('posts', 'IP_notes', 'bans', 'log'))) {
  139. $query = $_POST['query'];
  140. $query = urlencode($query);
  141. $query = str_replace('_', '%5F', $query);
  142. $query = str_replace('+', '_', $query);
  143. if ($query === '') {
  144. header('Location: ?/', true, $config['redirect_http']);
  145. return;
  146. }
  147. header('Location: ?/search/' . $_POST['type'] . '/' . $query, true, $config['redirect_http']);
  148. } else {
  149. header('Location: ?/', true, $config['redirect_http']);
  150. }
  151. }
  152. function mod_search($type, $search_query_escaped, $page_no = 1) {
  153. global $pdo, $config;
  154. if (!hasPermission($config['mod']['search']))
  155. error($config['error']['noaccess']);
  156. // Unescape query
  157. $query = str_replace('_', ' ', $search_query_escaped);
  158. $query = urldecode($query);
  159. $search_query = $query;
  160. // Form a series of LIKE clauses for the query.
  161. // This gets a little complicated.
  162. // Escape "escape" character
  163. $query = str_replace('!', '!!', $query);
  164. // Escape SQL wildcard
  165. $query = str_replace('%', '!%', $query);
  166. // Use asterisk as wildcard instead
  167. $query = str_replace('*', '%', $query);
  168. $query = str_replace('`', '!`', $query);
  169. // Array of phrases to match
  170. $match = array();
  171. // Exact phrases ("like this")
  172. if (preg_match_all('/"(.+?)"/', $query, $exact_phrases)) {
  173. $exact_phrases = $exact_phrases[1];
  174. foreach ($exact_phrases as $phrase) {
  175. $query = str_replace("\"{$phrase}\"", '', $query);
  176. $match[] = $pdo->quote($phrase);
  177. }
  178. }
  179. // Non-exact phrases (ie. plain keywords)
  180. $keywords = explode(' ', $query);
  181. foreach ($keywords as $word) {
  182. if (empty($word))
  183. continue;
  184. $match[] = $pdo->quote($word);
  185. }
  186. // Which `field` to search?
  187. if ($type == 'posts')
  188. $sql_field = array('body_nomarkup', 'files', 'subject', 'filehash', 'ip', 'name', 'trip');
  189. if ($type == 'IP_notes')
  190. $sql_field = 'body';
  191. if ($type == 'bans')
  192. $sql_field = 'reason';
  193. if ($type == 'log')
  194. $sql_field = 'text';
  195. // Build the "LIKE 'this' AND LIKE 'that'" etc. part of the SQL query
  196. $sql_like = '';
  197. foreach ($match as $phrase) {
  198. if (!empty($sql_like))
  199. $sql_like .= ' AND ';
  200. $phrase = preg_replace('/^\'(.+)\'$/', '\'%$1%\'', $phrase);
  201. if (is_array($sql_field)) {
  202. foreach ($sql_field as $field) {
  203. $sql_like .= '`' . $field . '` LIKE ' . $phrase . ' ESCAPE \'!\' OR';
  204. }
  205. $sql_like = preg_replace('/ OR$/', '', $sql_like);
  206. } else {
  207. $sql_like .= '`' . $sql_field . '` LIKE ' . $phrase . ' ESCAPE \'!\'';
  208. }
  209. }
  210. // Compile SQL query
  211. if ($type == 'posts') {
  212. $query = '';
  213. $boards = listBoards();
  214. if (empty($boards))
  215. error(_('There are no boards to search!'));
  216. foreach ($boards as $board) {
  217. openBoard($board['uri']);
  218. if (!hasPermission($config['mod']['search_posts'], $board['uri']))
  219. continue;
  220. if (!empty($query))
  221. $query .= ' UNION ALL ';
  222. $query .= sprintf("SELECT *, '%s' AS `board` FROM ``posts_%s`` WHERE %s", $board['uri'], $board['uri'], $sql_like);
  223. }
  224. // You weren't allowed to search any boards
  225. if (empty($query))
  226. error($config['error']['noaccess']);
  227. $query .= ' ORDER BY `sticky` DESC, `id` DESC';
  228. }
  229. if ($type == 'IP_notes') {
  230. $query = 'SELECT * FROM ``ip_notes`` LEFT JOIN ``mods`` ON `mod` = ``mods``.`id` WHERE ' . $sql_like . ' ORDER BY `time` DESC';
  231. $sql_table = 'ip_notes';
  232. if (!hasPermission($config['mod']['view_notes']) || !hasPermission($config['mod']['show_ip']))
  233. error($config['error']['noaccess']);
  234. }
  235. if ($type == 'bans') {
  236. $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';
  237. $sql_table = 'bans';
  238. if (!hasPermission($config['mod']['view_banlist']))
  239. error($config['error']['noaccess']);
  240. }
  241. if ($type == 'log') {
  242. $query = 'SELECT `username`, `mod`, `ip`, `board`, `time`, `text` FROM ``modlogs`` LEFT JOIN ``mods`` ON `mod` = ``mods``.`id` WHERE ' . $sql_like . ' ORDER BY `time` DESC';
  243. $sql_table = 'modlogs';
  244. if (!hasPermission($config['mod']['modlog']))
  245. error($config['error']['noaccess']);
  246. }
  247. // Execute SQL query (with pages)
  248. $q = query($query . ' LIMIT ' . (($page_no - 1) * $config['mod']['search_page']) . ', ' . $config['mod']['search_page']) or error(db_error());
  249. $results = $q->fetchAll(PDO::FETCH_ASSOC);
  250. // Get total result count
  251. if ($type == 'posts') {
  252. $q = query("SELECT COUNT(*) FROM ($query) AS `tmp_table`") or error(db_error());
  253. $result_count = $q->fetchColumn();
  254. } else {
  255. $q = query('SELECT COUNT(*) FROM `' . $sql_table . '` WHERE ' . $sql_like) or error(db_error());
  256. $result_count = $q->fetchColumn();
  257. }
  258. if ($type == 'bans') {
  259. foreach ($results as &$ban) {
  260. $ban['mask'] = Bans::range_to_string(array($ban['ipstart'], $ban['ipend']));
  261. if (filter_var($ban['mask'], FILTER_VALIDATE_IP) !== false)
  262. $ban['single_addr'] = true;
  263. }
  264. }
  265. if ($type == 'posts') {
  266. foreach ($results as &$post) {
  267. $post['snippet'] = pm_snippet($post['body']);
  268. }
  269. }
  270. // $results now contains the search results
  271. mod_page(_('Search results'), 'mod/search_results.html', array(
  272. 'search_type' => $type,
  273. 'search_query' => $search_query,
  274. 'search_query_escaped' => $search_query_escaped,
  275. 'result_count' => $result_count,
  276. 'results' => $results
  277. ));
  278. }
  279. function mod_edit_board($boardName) {
  280. global $board, $config;
  281. if (!openBoard($boardName))
  282. error($config['error']['noboard']);
  283. if (!hasPermission($config['mod']['manageboards'], $board['uri']))
  284. error($config['error']['noaccess']);
  285. if (isset($_POST['title'], $_POST['subtitle'])) {
  286. if (isset($_POST['delete'])) {
  287. if (!hasPermission($config['mod']['manageboards'], $board['uri']))
  288. error($config['error']['deleteboard']);
  289. $query = prepare('DELETE FROM ``boards`` WHERE `uri` = :uri');
  290. $query->bindValue(':uri', $board['uri']);
  291. $query->execute() or error(db_error($query));
  292. if ($config['cache']['enabled']) {
  293. cache::delete('board_' . $board['uri']);
  294. cache::delete('all_boards');
  295. }
  296. modLog('Deleted board: ' . sprintf($config['board_abbreviation'], $board['uri']), false);
  297. // Delete posting table
  298. $query = query(sprintf('DROP TABLE IF EXISTS ``posts_%s``', $board['uri'])) or error(db_error());
  299. // Clear reports
  300. $query = prepare('DELETE FROM ``reports`` WHERE `board` = :id');
  301. $query->bindValue(':id', $board['uri'], PDO::PARAM_INT);
  302. $query->execute() or error(db_error($query));
  303. // Delete from table
  304. $query = prepare('DELETE FROM ``boards`` WHERE `uri` = :uri');
  305. $query->bindValue(':uri', $board['uri'], PDO::PARAM_INT);
  306. $query->execute() or error(db_error($query));
  307. $query = prepare("SELECT `board`, `post` FROM ``cites`` WHERE `target_board` = :board ORDER BY `board`");
  308. $query->bindValue(':board', $board['uri']);
  309. $query->execute() or error(db_error($query));
  310. while ($cite = $query->fetch(PDO::FETCH_ASSOC)) {
  311. if ($board['uri'] != $cite['board']) {
  312. if (!isset($tmp_board))
  313. $tmp_board = $board;
  314. openBoard($cite['board']);
  315. rebuildPost($cite['post']);
  316. }
  317. }
  318. if (isset($tmp_board))
  319. $board = $tmp_board;
  320. $query = prepare('DELETE FROM ``cites`` WHERE `board` = :board OR `target_board` = :board');
  321. $query->bindValue(':board', $board['uri']);
  322. $query->execute() or error(db_error($query));
  323. $query = prepare('DELETE FROM ``antispam`` WHERE `board` = :board');
  324. $query->bindValue(':board', $board['uri']);
  325. $query->execute() or error(db_error($query));
  326. // Remove board from users/permissions table
  327. $query = query('SELECT `id`,`boards` FROM ``mods``') or error(db_error());
  328. while ($user = $query->fetch(PDO::FETCH_ASSOC)) {
  329. $user_boards = explode(',', $user['boards']);
  330. if (in_array($board['uri'], $user_boards)) {
  331. unset($user_boards[array_search($board['uri'], $user_boards)]);
  332. $_query = prepare('UPDATE ``mods`` SET `boards` = :boards WHERE `id` = :id');
  333. $_query->bindValue(':boards', implode(',', $user_boards));
  334. $_query->bindValue(':id', $user['id']);
  335. $_query->execute() or error(db_error($_query));
  336. }
  337. }
  338. // Delete entire board directory
  339. rrmdir($board['uri'] . '/');
  340. } else {
  341. $query = prepare('UPDATE ``boards`` SET `title` = :title, `subtitle` = :subtitle WHERE `uri` = :uri');
  342. $query->bindValue(':uri', $board['uri']);
  343. $query->bindValue(':title', $_POST['title']);
  344. $query->bindValue(':subtitle', $_POST['subtitle']);
  345. $query->execute() or error(db_error($query));
  346. modLog('Edited board information for ' . sprintf($config['board_abbreviation'], $board['uri']), false);
  347. }
  348. if ($config['cache']['enabled']) {
  349. cache::delete('board_' . $board['uri']);
  350. cache::delete('all_boards');
  351. }
  352. rebuildThemes('boards');
  353. header('Location: ?/', true, $config['redirect_http']);
  354. } else {
  355. mod_page(sprintf('%s: ' . $config['board_abbreviation'], _('Edit board'), $board['uri']), 'mod/board.html', array(
  356. 'board' => $board,
  357. 'token' => make_secure_link_token('edit/' . $board['uri'])
  358. ));
  359. }
  360. }
  361. function mod_new_board() {
  362. global $config, $board;
  363. if (!hasPermission($config['mod']['newboard']))
  364. error($config['error']['noaccess']);
  365. if (isset($_POST['uri'], $_POST['title'], $_POST['subtitle'])) {
  366. if ($_POST['uri'] == '')
  367. error(sprintf($config['error']['required'], 'URI'));
  368. if ($_POST['title'] == '')
  369. error(sprintf($config['error']['required'], 'title'));
  370. if (!preg_match('/^' . $config['board_regex'] . '$/u', $_POST['uri']))
  371. error(sprintf($config['error']['invalidfield'], 'URI'));
  372. $bytes = 0;
  373. $chars = preg_split('//u', $_POST['uri'], -1, PREG_SPLIT_NO_EMPTY);
  374. foreach ($chars as $char) {
  375. $o = 0;
  376. $ord = ordutf8($char, $o);
  377. if ($ord > 0x0080)
  378. $bytes += 5; // @01ff
  379. else
  380. $bytes ++;
  381. }
  382. $bytes + strlen('posts_.frm');
  383. if ($bytes > 255) {
  384. error('Your filesystem cannot handle a board URI of that length (' . $bytes . '/255 bytes)');
  385. exit;
  386. }
  387. if (openBoard($_POST['uri'])) {
  388. error(sprintf($config['error']['boardexists'], $board['url']));
  389. }
  390. $query = prepare('INSERT INTO ``boards`` VALUES (:uri, :title, :subtitle)');
  391. $query->bindValue(':uri', $_POST['uri']);
  392. $query->bindValue(':title', $_POST['title']);
  393. $query->bindValue(':subtitle', $_POST['subtitle']);
  394. $query->execute() or error(db_error($query));
  395. modLog('Created a new board: ' . sprintf($config['board_abbreviation'], $_POST['uri']));
  396. if (!openBoard($_POST['uri']))
  397. error(_("Couldn't open board after creation."));
  398. $query = Element('posts.sql', array('board' => $board['uri']));
  399. if (mysql_version() < 50503)
  400. $query = preg_replace('/(CHARSET=|CHARACTER SET )utf8mb4/', '$1utf8', $query);
  401. query($query) or error(db_error());
  402. if ($config['cache']['enabled'])
  403. cache::delete('all_boards');
  404. // Build the board
  405. buildIndex();
  406. rebuildThemes('boards');
  407. header('Location: ?/' . $board['uri'] . '/' . $config['file_index'], true, $config['redirect_http']);
  408. }
  409. mod_page(_('New board'), 'mod/board.html', array('new' => true, 'token' => make_secure_link_token('new-board')));
  410. }
  411. function mod_noticeboard($page_no = 1) {
  412. global $config, $pdo, $mod;
  413. if ($page_no < 1)
  414. error($config['error']['404']);
  415. if (!hasPermission($config['mod']['noticeboard']))
  416. error($config['error']['noaccess']);
  417. if (isset($_POST['subject'], $_POST['body'])) {
  418. if (!hasPermission($config['mod']['noticeboard_post']))
  419. error($config['error']['noaccess']);
  420. $_POST['body'] = escape_markup_modifiers($_POST['body']);
  421. markup($_POST['body']);
  422. $query = prepare('INSERT INTO ``noticeboard`` VALUES (NULL, :mod, :time, :subject, :body)');
  423. $query->bindValue(':mod', $mod['id']);
  424. $query->bindvalue(':time', time());
  425. $query->bindValue(':subject', $_POST['subject']);
  426. $query->bindValue(':body', $_POST['body']);
  427. $query->execute() or error(db_error($query));
  428. if ($config['cache']['enabled'])
  429. cache::delete('noticeboard_preview');
  430. modLog('Posted a noticeboard entry');
  431. header('Location: ?/noticeboard#' . $pdo->lastInsertId(), true, $config['redirect_http']);
  432. }
  433. $query = prepare("SELECT ``noticeboard``.*, `username` FROM ``noticeboard`` LEFT JOIN ``mods`` ON ``mods``.`id` = `mod` ORDER BY `id` DESC LIMIT :offset, :limit");
  434. $query->bindValue(':limit', $config['mod']['noticeboard_page'], PDO::PARAM_INT);
  435. $query->bindValue(':offset', ($page_no - 1) * $config['mod']['noticeboard_page'], PDO::PARAM_INT);
  436. $query->execute() or error(db_error($query));
  437. $noticeboard = $query->fetchAll(PDO::FETCH_ASSOC);
  438. if (empty($noticeboard) && $page_no > 1)
  439. error($config['error']['404']);
  440. foreach ($noticeboard as &$entry) {
  441. $entry['delete_token'] = make_secure_link_token('noticeboard/delete/' . $entry['id']);
  442. }
  443. $query = prepare("SELECT COUNT(*) FROM ``noticeboard``");
  444. $query->execute() or error(db_error($query));
  445. $count = $query->fetchColumn();
  446. mod_page(_('Noticeboard'), 'mod/noticeboard.html', array(
  447. 'noticeboard' => $noticeboard,
  448. 'count' => $count,
  449. 'token' => make_secure_link_token('noticeboard')
  450. ));
  451. }
  452. function mod_noticeboard_delete($id) {
  453. global $config;
  454. if (!hasPermission($config['mod']['noticeboard_delete']))
  455. error($config['error']['noaccess']);
  456. $query = prepare('DELETE FROM ``noticeboard`` WHERE `id` = :id');
  457. $query->bindValue(':id', $id);
  458. $query->execute() or error(db_error($query));
  459. modLog('Deleted a noticeboard entry');
  460. if ($config['cache']['enabled'])
  461. cache::delete('noticeboard_preview');
  462. header('Location: ?/noticeboard', true, $config['redirect_http']);
  463. }
  464. function mod_news($page_no = 1) {
  465. global $config, $pdo, $mod;
  466. if ($page_no < 1)
  467. error($config['error']['404']);
  468. if (isset($_POST['subject'], $_POST['body'])) {
  469. if (!hasPermission($config['mod']['news']))
  470. error($config['error']['noaccess']);
  471. $_POST['body'] = escape_markup_modifiers($_POST['body']);
  472. markup($_POST['body']);
  473. $query = prepare('INSERT INTO ``news`` VALUES (NULL, :name, :time, :subject, :body)');
  474. $query->bindValue(':name', isset($_POST['name']) && hasPermission($config['mod']['news_custom']) ? $_POST['name'] : $mod['username']);
  475. $query->bindvalue(':time', time());
  476. $query->bindValue(':subject', $_POST['subject']);
  477. $query->bindValue(':body', $_POST['body']);
  478. $query->execute() or error(db_error($query));
  479. modLog('Posted a news entry');
  480. rebuildThemes('news');
  481. header('Location: ?/news#' . $pdo->lastInsertId(), true, $config['redirect_http']);
  482. }
  483. $query = prepare("SELECT * FROM ``news`` ORDER BY `id` DESC LIMIT :offset, :limit");
  484. $query->bindValue(':limit', $config['mod']['news_page'], PDO::PARAM_INT);
  485. $query->bindValue(':offset', ($page_no - 1) * $config['mod']['news_page'], PDO::PARAM_INT);
  486. $query->execute() or error(db_error($query));
  487. $news = $query->fetchAll(PDO::FETCH_ASSOC);
  488. if (empty($news) && $page_no > 1)
  489. error($config['error']['404']);
  490. foreach ($news as &$entry) {
  491. $entry['delete_token'] = make_secure_link_token('news/delete/' . $entry['id']);
  492. }
  493. $query = prepare("SELECT COUNT(*) FROM ``news``");
  494. $query->execute() or error(db_error($query));
  495. $count = $query->fetchColumn();
  496. mod_page(_('News'), 'mod/news.html', array('news' => $news, 'count' => $count, 'token' => make_secure_link_token('news')));
  497. }
  498. function mod_news_delete($id) {
  499. global $config;
  500. if (!hasPermission($config['mod']['news_delete']))
  501. error($config['error']['noaccess']);
  502. $query = prepare('DELETE FROM ``news`` WHERE `id` = :id');
  503. $query->bindValue(':id', $id);
  504. $query->execute() or error(db_error($query));
  505. modLog('Deleted a news entry');
  506. header('Location: ?/news', true, $config['redirect_http']);
  507. }
  508. function mod_log($page_no = 1) {
  509. global $config;
  510. if ($page_no < 1)
  511. error($config['error']['404']);
  512. if (!hasPermission($config['mod']['modlog']))
  513. error($config['error']['noaccess']);
  514. $query = prepare("SELECT `username`, `mod`, `ip`, `board`, `time`, `text` FROM ``modlogs`` LEFT JOIN ``mods`` ON `mod` = ``mods``.`id` ORDER BY `time` DESC LIMIT :offset, :limit");
  515. $query->bindValue(':limit', $config['mod']['modlog_page'], PDO::PARAM_INT);
  516. $query->bindValue(':offset', ($page_no - 1) * $config['mod']['modlog_page'], PDO::PARAM_INT);
  517. $query->execute() or error(db_error($query));
  518. $logs = $query->fetchAll(PDO::FETCH_ASSOC);
  519. if (empty($logs) && $page_no > 1)
  520. error($config['error']['404']);
  521. $query = prepare("SELECT COUNT(*) FROM ``modlogs``");
  522. $query->execute() or error(db_error($query));
  523. $count = $query->fetchColumn();
  524. mod_page(_('Moderation log'), 'mod/log.html', array('logs' => $logs, 'count' => $count));
  525. }
  526. function mod_user_log($username, $page_no = 1) {
  527. global $config;
  528. if ($page_no < 1)
  529. error($config['error']['404']);
  530. if (!hasPermission($config['mod']['modlog']))
  531. error($config['error']['noaccess']);
  532. $query = prepare("SELECT `username`, `mod`, `ip`, `board`, `time`, `text` FROM ``modlogs`` LEFT JOIN ``mods`` ON `mod` = ``mods``.`id` WHERE `username` = :username ORDER BY `time` DESC LIMIT :offset, :limit");
  533. $query->bindValue(':username', $username);
  534. $query->bindValue(':limit', $config['mod']['modlog_page'], PDO::PARAM_INT);
  535. $query->bindValue(':offset', ($page_no - 1) * $config['mod']['modlog_page'], PDO::PARAM_INT);
  536. $query->execute() or error(db_error($query));
  537. $logs = $query->fetchAll(PDO::FETCH_ASSOC);
  538. if (empty($logs) && $page_no > 1)
  539. error($config['error']['404']);
  540. $query = prepare("SELECT COUNT(*) FROM ``modlogs`` LEFT JOIN ``mods`` ON `mod` = ``mods``.`id` WHERE `username` = :username");
  541. $query->bindValue(':username', $username);
  542. $query->execute() or error(db_error($query));
  543. $count = $query->fetchColumn();
  544. mod_page(_('Moderation log'), 'mod/log.html', array('logs' => $logs, 'count' => $count, 'username' => $username));
  545. }
  546. function mod_view_board($boardName, $page_no = 1) {
  547. global $config, $mod;
  548. if (!openBoard($boardName))
  549. error($config['error']['noboard']);
  550. if (!$page = index($page_no, $mod)) {
  551. error($config['error']['404']);
  552. }
  553. $page['pages'] = getPages(true);
  554. $page['pages'][$page_no-1]['selected'] = true;
  555. $page['btn'] = getPageButtons($page['pages'], true);
  556. $page['mod'] = true;
  557. $page['config'] = $config;
  558. echo Element('index.html', $page);
  559. }
  560. function mod_view_thread($boardName, $thread) {
  561. global $config, $mod;
  562. if (!openBoard($boardName))
  563. error($config['error']['noboard']);
  564. $page = buildThread($thread, true, $mod);
  565. echo $page;
  566. }
  567. function mod_view_thread50($boardName, $thread) {
  568. global $config, $mod;
  569. if (!openBoard($boardName))
  570. error($config['error']['noboard']);
  571. $page = buildThread50($thread, true, $mod);
  572. echo $page;
  573. }
  574. function mod_ip_remove_note($ip, $id) {
  575. global $config, $mod;
  576. if (!hasPermission($config['mod']['remove_notes']))
  577. error($config['error']['noaccess']);
  578. if (filter_var($ip, FILTER_VALIDATE_IP) === false)
  579. error("Invalid IP address.");
  580. $query = prepare('DELETE FROM ``ip_notes`` WHERE `ip` = :ip AND `id` = :id');
  581. $query->bindValue(':ip', $ip);
  582. $query->bindValue(':id', $id);
  583. $query->execute() or error(db_error($query));
  584. modLog("Removed a note for <a href=\"?/IP/{$ip}\">{$ip}</a>");
  585. header('Location: ?/IP/' . $ip . '#notes', true, $config['redirect_http']);
  586. }
  587. function mod_page_ip($ip) {
  588. global $config, $mod;
  589. if (filter_var($ip, FILTER_VALIDATE_IP) === false)
  590. error("Invalid IP address.");
  591. if (isset($_POST['ban_id'], $_POST['unban'])) {
  592. if (!hasPermission($config['mod']['unban']))
  593. error($config['error']['noaccess']);
  594. Bans::delete($_POST['ban_id'], true, $mod['boards']);
  595. header('Location: ?/IP/' . $ip . '#bans', true, $config['redirect_http']);
  596. return;
  597. }
  598. if (isset($_POST['note'])) {
  599. if (!hasPermission($config['mod']['create_notes']))
  600. error($config['error']['noaccess']);
  601. $_POST['note'] = escape_markup_modifiers($_POST['note']);
  602. markup($_POST['note']);
  603. $query = prepare('INSERT INTO ``ip_notes`` VALUES (NULL, :ip, :mod, :time, :body)');
  604. $query->bindValue(':ip', $ip);
  605. $query->bindValue(':mod', $mod['id']);
  606. $query->bindValue(':time', time());
  607. $query->bindValue(':body', $_POST['note']);
  608. $query->execute() or error(db_error($query));
  609. modLog("Added a note for <a href=\"?/IP/{$ip}\">{$ip}</a>");
  610. header('Location: ?/IP/' . $ip . '#notes', true, $config['redirect_http']);
  611. return;
  612. }
  613. $args = array();
  614. $args['ip'] = $ip;
  615. $args['posts'] = array();
  616. if ($config['mod']['dns_lookup'])
  617. $args['hostname'] = rDNS($ip);
  618. $boards = listBoards();
  619. foreach ($boards as $board) {
  620. openBoard($board['uri']);
  621. if (!hasPermission($config['mod']['show_ip'], $board['uri']))
  622. continue;
  623. $query = prepare(sprintf('SELECT * FROM ``posts_%s`` WHERE `ip` = :ip ORDER BY `sticky` DESC, `id` DESC LIMIT :limit', $board['uri']));
  624. $query->bindValue(':ip', $ip);
  625. $query->bindValue(':limit', $config['mod']['ip_recentposts'], PDO::PARAM_INT);
  626. $query->execute() or error(db_error($query));
  627. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  628. if (!$post['thread']) {
  629. $po = new Thread($post, '?/', $mod, false);
  630. } else {
  631. $po = new Post($post, '?/', $mod);
  632. }
  633. if (!isset($args['posts'][$board['uri']]))
  634. $args['posts'][$board['uri']] = array('board' => $board, 'posts' => array());
  635. $args['posts'][$board['uri']]['posts'][] = $po->build(true);
  636. }
  637. }
  638. $args['boards'] = $boards;
  639. $args['token'] = make_secure_link_token('ban');
  640. if (hasPermission($config['mod']['view_ban'])) {
  641. $args['bans'] = Bans::find($ip, false, true);
  642. }
  643. if (hasPermission($config['mod']['view_notes'])) {
  644. $query = prepare("SELECT ``ip_notes``.*, `username` FROM ``ip_notes`` LEFT JOIN ``mods`` ON `mod` = ``mods``.`id` WHERE `ip` = :ip ORDER BY `time` DESC");
  645. $query->bindValue(':ip', $ip);
  646. $query->execute() or error(db_error($query));
  647. $args['notes'] = $query->fetchAll(PDO::FETCH_ASSOC);
  648. }
  649. if (hasPermission($config['mod']['modlog_ip'])) {
  650. $query = prepare("SELECT `username`, `mod`, `ip`, `board`, `time`, `text` FROM ``modlogs`` LEFT JOIN ``mods`` ON `mod` = ``mods``.`id` WHERE `text` LIKE :search ORDER BY `time` DESC LIMIT 50");
  651. $query->bindValue(':search', '%' . $ip . '%');
  652. $query->execute() or error(db_error($query));
  653. $args['logs'] = $query->fetchAll(PDO::FETCH_ASSOC);
  654. } else {
  655. $args['logs'] = array();
  656. }
  657. $args['security_token'] = make_secure_link_token('IP/' . $ip);
  658. mod_page(sprintf('%s: %s', _('IP'), $ip), 'mod/view_ip.html', $args, $args['hostname']);
  659. }
  660. function mod_ban() {
  661. global $config;
  662. if (!hasPermission($config['mod']['ban']))
  663. error($config['error']['noaccess']);
  664. if (!isset($_POST['ip'], $_POST['reason'], $_POST['length'], $_POST['board'])) {
  665. mod_page(_('New ban'), 'mod/ban_form.html', array('token' => make_secure_link_token('ban')));
  666. return;
  667. }
  668. require_once 'inc/mod/ban.php';
  669. Bans::new_ban($_POST['ip'], $_POST['reason'], $_POST['length'], $_POST['board'] == '*' ? false : $_POST['board']);
  670. if (isset($_POST['redirect']))
  671. header('Location: ' . $_POST['redirect'], true, $config['redirect_http']);
  672. else
  673. header('Location: ?/', true, $config['redirect_http']);
  674. }
  675. function mod_bans() {
  676. global $config;
  677. global $mod;
  678. if (!hasPermission($config['mod']['view_banlist']))
  679. error($config['error']['noaccess']);
  680. if (isset($_POST['unban'])) {
  681. if (!hasPermission($config['mod']['unban']))
  682. error($config['error']['noaccess']);
  683. $unban = array();
  684. foreach ($_POST as $name => $unused) {
  685. if (preg_match('/^ban_(\d+)$/', $name, $match))
  686. $unban[] = $match[1];
  687. }
  688. if (isset($config['mod']['unban_limit']) && $config['mod']['unban_limit'] && count($unban) > $config['mod']['unban_limit'])
  689. error(sprintf($config['error']['toomanyunban'], $config['mod']['unban_limit'], count($unban)));
  690. foreach ($unban as $id) {
  691. Bans::delete($id, true, $mod['boards'], true);
  692. }
  693. rebuildThemes('bans');
  694. header('Location: ?/bans', true, $config['redirect_http']);
  695. return;
  696. }
  697. mod_page(_('Ban list'), 'mod/ban_list.html', array(
  698. 'mod' => $mod,
  699. 'boards' => json_encode($mod['boards']),
  700. 'token' => make_secure_link_token('bans'),
  701. 'token_json' => make_secure_link_token('bans.json')
  702. ));
  703. }
  704. function mod_bans_json() {
  705. global $config, $mod;
  706. if (!hasPermission($config['mod']['ban']))
  707. error($config['error']['noaccess']);
  708. // Compress the json for faster loads
  709. if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler");
  710. Bans::stream_json(false, false, !hasPermission($config['mod']['view_banstaff']), $mod['boards']);
  711. }
  712. function mod_ban_appeals() {
  713. global $config, $board;
  714. if (!hasPermission($config['mod']['view_ban_appeals']))
  715. error($config['error']['noaccess']);
  716. // Remove stale ban appeals
  717. query("DELETE FROM ``ban_appeals`` WHERE NOT EXISTS (SELECT 1 FROM ``bans`` WHERE `ban_id` = ``bans``.`id`)")
  718. or error(db_error());
  719. if (isset($_POST['appeal_id']) && (isset($_POST['unban']) || isset($_POST['deny']))) {
  720. if (!hasPermission($config['mod']['ban_appeals']))
  721. error($config['error']['noaccess']);
  722. $query = query("SELECT *, ``ban_appeals``.`id` AS `id` FROM ``ban_appeals``
  723. LEFT JOIN ``bans`` ON `ban_id` = ``bans``.`id`
  724. WHERE ``ban_appeals``.`id` = " . (int)$_POST['appeal_id']) or error(db_error());
  725. if (!$ban = $query->fetch(PDO::FETCH_ASSOC)) {
  726. error(_('Ban appeal not found!'));
  727. }
  728. $ban['mask'] = Bans::range_to_string(array($ban['ipstart'], $ban['ipend']));
  729. if (isset($_POST['unban'])) {
  730. modLog('Accepted ban appeal #' . $ban['id'] . ' for ' . $ban['mask']);
  731. Bans::delete($ban['ban_id'], true);
  732. query("DELETE FROM ``ban_appeals`` WHERE `id` = " . $ban['id']) or error(db_error());
  733. } else {
  734. modLog('Denied ban appeal #' . $ban['id'] . ' for ' . $ban['mask']);
  735. query("UPDATE ``ban_appeals`` SET `denied` = 1 WHERE `id` = " . $ban['id']) or error(db_error());
  736. }
  737. header('Location: ?/ban-appeals', true, $config['redirect_http']);
  738. return;
  739. }
  740. $query = query("SELECT *, ``ban_appeals``.`id` AS `id` FROM ``ban_appeals``
  741. LEFT JOIN ``bans`` ON `ban_id` = ``bans``.`id`
  742. LEFT JOIN ``mods`` ON ``bans``.`creator` = ``mods``.`id`
  743. WHERE `denied` != 1 ORDER BY `time`") or error(db_error());
  744. $ban_appeals = $query->fetchAll(PDO::FETCH_ASSOC);
  745. foreach ($ban_appeals as &$ban) {
  746. if ($ban['post'])
  747. $ban['post'] = json_decode($ban['post'], true);
  748. $ban['mask'] = Bans::range_to_string(array($ban['ipstart'], $ban['ipend']));
  749. if ($ban['post'] && isset($ban['post']['board'], $ban['post']['id'])) {
  750. if (openBoard($ban['post']['board'])) {
  751. $query = query(sprintf("SELECT `num_files`, `files` FROM ``posts_%s`` WHERE `id` = " .
  752. (int)$ban['post']['id'], $board['uri']));
  753. if ($_post = $query->fetch(PDO::FETCH_ASSOC)) {
  754. $_post['files'] = $_post['files'] ? json_decode($_post['files']) : array();
  755. $ban['post'] = array_merge($ban['post'], $_post);
  756. } else {
  757. $ban['post']['files'] = array(array());
  758. $ban['post']['files'][0]['file'] = 'deleted';
  759. $ban['post']['files'][0]['thumb'] = false;
  760. $ban['post']['num_files'] = 1;
  761. }
  762. } else {
  763. $ban['post']['files'] = array(array());
  764. $ban['post']['files'][0]['file'] = 'deleted';
  765. $ban['post']['files'][0]['thumb'] = false;
  766. $ban['post']['num_files'] = 1;
  767. }
  768. if ($ban['post']['thread']) {
  769. $ban['post'] = new Post($ban['post']);
  770. } else {
  771. $ban['post'] = new Thread($ban['post'], null, false, false);
  772. }
  773. }
  774. }
  775. mod_page(_('Ban appeals'), 'mod/ban_appeals.html', array(
  776. 'ban_appeals' => $ban_appeals,
  777. 'token' => make_secure_link_token('ban-appeals')
  778. ));
  779. }
  780. function mod_lock($board, $unlock, $post) {
  781. global $config;
  782. if (!openBoard($board))
  783. error($config['error']['noboard']);
  784. if (!hasPermission($config['mod']['lock'], $board))
  785. error($config['error']['noaccess']);
  786. $query = prepare(sprintf('UPDATE ``posts_%s`` SET `locked` = :locked WHERE `id` = :id AND `thread` IS NULL', $board));
  787. $query->bindValue(':id', $post);
  788. $query->bindValue(':locked', $unlock ? 0 : 1);
  789. $query->execute() or error(db_error($query));
  790. if ($query->rowCount()) {
  791. modLog(($unlock ? 'Unlocked' : 'Locked') . " thread #{$post}");
  792. buildThread($post);
  793. buildIndex();
  794. }
  795. if ($config['mod']['dismiss_reports_on_lock']) {
  796. $query = prepare('DELETE FROM ``reports`` WHERE `board` = :board AND `post` = :id');
  797. $query->bindValue(':board', $board);
  798. $query->bindValue(':id', $post);
  799. $query->execute() or error(db_error($query));
  800. }
  801. header('Location: ?/' . sprintf($config['board_path'], $board) . $config['file_index'], true, $config['redirect_http']);
  802. if ($unlock)
  803. event('unlock', $post);
  804. else
  805. event('lock', $post);
  806. }
  807. function mod_sticky($board, $unsticky, $post) {
  808. global $config;
  809. if (!openBoard($board))
  810. error($config['error']['noboard']);
  811. if (!hasPermission($config['mod']['sticky'], $board))
  812. error($config['error']['noaccess']);
  813. $query = prepare(sprintf('UPDATE ``posts_%s`` SET `sticky` = :sticky WHERE `id` = :id AND `thread` IS NULL', $board));
  814. $query->bindValue(':id', $post);
  815. $query->bindValue(':sticky', $unsticky ? 0 : 1);
  816. $query->execute() or error(db_error($query));
  817. if ($query->rowCount()) {
  818. modLog(($unsticky ? 'Unstickied' : 'Stickied') . " thread #{$post}");
  819. buildThread($post);
  820. buildIndex();
  821. }
  822. header('Location: ?/' . sprintf($config['board_path'], $board) . $config['file_index'], true, $config['redirect_http']);
  823. }
  824. function mod_bumplock($board, $unbumplock, $post) {
  825. global $config;
  826. if (!openBoard($board))
  827. error($config['error']['noboard']);
  828. if (!hasPermission($config['mod']['bumplock'], $board))
  829. error($config['error']['noaccess']);
  830. $query = prepare(sprintf('UPDATE ``posts_%s`` SET `sage` = :bumplock WHERE `id` = :id AND `thread` IS NULL', $board));
  831. $query->bindValue(':id', $post);
  832. $query->bindValue(':bumplock', $unbumplock ? 0 : 1);
  833. $query->execute() or error(db_error($query));
  834. if ($query->rowCount()) {
  835. modLog(($unbumplock ? 'Unbumplocked' : 'Bumplocked') . " thread #{$post}");
  836. buildThread($post);
  837. buildIndex();
  838. }
  839. header('Location: ?/' . sprintf($config['board_path'], $board) . $config['file_index'], true, $config['redirect_http']);
  840. }
  841. function mod_move_reply($originBoard, $postID) {
  842. global $board, $config, $mod;
  843. if (!openBoard($originBoard))
  844. error($config['error']['noboard']);
  845. if (!hasPermission($config['mod']['move'], $originBoard))
  846. error($config['error']['noaccess']);
  847. $query = prepare(sprintf('SELECT * FROM ``posts_%s`` WHERE `id` = :id', $originBoard));
  848. $query->bindValue(':id', $postID);
  849. $query->execute() or error(db_error($query));
  850. if (!$post = $query->fetch(PDO::FETCH_ASSOC))
  851. error($config['error']['404']);
  852. if (isset($_POST['board'])) {
  853. $targetBoard = $_POST['board'];
  854. if ($_POST['target_thread']) {
  855. $query = prepare(sprintf('SELECT * FROM ``posts_%s`` WHERE `id` = :id', $targetBoard));
  856. $query->bindValue(':id', $_POST['target_thread']);
  857. $query->execute() or error(db_error($query)); // If it fails, thread probably does not exist
  858. $post['op'] = false;
  859. $post['thread'] = $_POST['target_thread'];
  860. }
  861. else {
  862. $post['op'] = true;
  863. }
  864. if ($post['files']) {
  865. $post['files'] = json_decode($post['files'], TRUE);
  866. $post['has_file'] = true;
  867. foreach ($post['files'] as $i => &$file) {
  868. $file['file_path'] = sprintf($config['board_path'], $board['uri']) . $config['dir']['img'] . $file['file'];
  869. $file['thumb_path'] = sprintf($config['board_path'], $board['uri']) . $config['dir']['thumb'] . $file['thumb'];
  870. }
  871. } else {
  872. $post['has_file'] = false;
  873. }
  874. // allow thread to keep its same traits (stickied, locked, etc.)
  875. $post['mod'] = true;
  876. if (!openBoard($targetBoard))
  877. error($config['error']['noboard']);
  878. // create the new post
  879. $newID = post($post);
  880. if ($post['has_file']) {
  881. foreach ($post['files'] as $i => &$file) {
  882. // move the image
  883. rename($file['file_path'], sprintf($config['board_path'], $board['uri']) . $config['dir']['img'] . $file['file']);
  884. if ($file['thumb'] != 'spoiler') { //trying to move/copy the spoiler thumb raises an error
  885. rename($file['thumb_path'], sprintf($config['board_path'], $board['uri']) . $config['dir']['thumb'] . $file['thumb']);
  886. }
  887. }
  888. }
  889. // build index
  890. buildIndex();
  891. // build new thread
  892. buildThread($newID);
  893. // trigger themes
  894. rebuildThemes('post', $targetBoard);
  895. // mod log
  896. modLog("Moved post #${postID} to " . sprintf($config['board_abbreviation'], $targetBoard) . " (#${newID})", $originBoard);
  897. // return to original board
  898. openBoard($originBoard);
  899. // delete original post
  900. deletePost($postID);
  901. buildIndex();
  902. // open target board for redirect
  903. openBoard($targetBoard);
  904. // Find new thread on our target board
  905. $query = prepare(sprintf('SELECT thread FROM ``posts_%s`` WHERE `id` = :id', $targetBoard));
  906. $query->bindValue(':id', $newID);
  907. $query->execute() or error(db_error($query));
  908. $post = $query->fetch(PDO::FETCH_ASSOC);
  909. // redirect
  910. header('Location: ?/' . sprintf($config['board_path'], $board['uri']) . $config['dir']['res'] . link_for($post) . '#' . $newID, true, $config['redirect_http']);
  911. }
  912. else {
  913. $boards = listBoards();
  914. $security_token = make_secure_link_token($originBoard . '/move_reply/' . $postID);
  915. mod_page(_('Move reply'), 'mod/move_reply.html', array('post' => $postID, 'board' => $originBoard, 'boards' => $boards, 'token' => $security_token));
  916. }
  917. }
  918. function mod_move($originBoard, $postID) {
  919. global $board, $config, $mod, $pdo;
  920. if (!openBoard($originBoard))
  921. error($config['error']['noboard']);
  922. if (!hasPermission($config['mod']['move'], $originBoard))
  923. error($config['error']['noaccess']);
  924. $query = prepare(sprintf('SELECT * FROM ``posts_%s`` WHERE `id` = :id AND `thread` IS NULL', $originBoard));
  925. $query->bindValue(':id', $postID);
  926. $query->execute() or error(db_error($query));
  927. if (!$post = $query->fetch(PDO::FETCH_ASSOC))
  928. error($config['error']['404']);
  929. if (isset($_POST['board'])) {
  930. $targetBoard = $_POST['board'];
  931. $shadow = isset($_POST['shadow']);
  932. if ($targetBoard === $originBoard)
  933. error(_('Target and source board are the same.'));
  934. // copy() if leaving a shadow thread behind; else, rename().
  935. $clone = $shadow ? 'copy' : 'rename';
  936. // indicate that the post is a thread
  937. $post['op'] = true;
  938. if ($post['files']) {
  939. $post['files'] = json_decode($post['files'], TRUE);
  940. $post['has_file'] = true;
  941. foreach ($post['files'] as $i => &$file) {
  942. if ($file['file'] === 'deleted')
  943. continue;
  944. $file['file_path'] = sprintf($config['board_path'], $board['uri']) . $config['dir']['img'] . $file['file'];
  945. $file['thumb_path'] = sprintf($config['board_path'], $board['uri']) . $config['dir']['thumb'] . $file['thumb'];
  946. }
  947. } else {
  948. $post['has_file'] = false;
  949. }
  950. // allow thread to keep its same traits (stickied, locked, etc.)
  951. $post['mod'] = true;
  952. if (!openBoard($targetBoard))
  953. error($config['error']['noboard']);
  954. // create the new thread
  955. $newID = post($post);
  956. $op = $post;
  957. $op['id'] = $newID;
  958. if ($post['has_file']) {
  959. // copy image
  960. foreach ($post['files'] as $i => &$file) {
  961. if ($file['file'] !== 'deleted')
  962. $clone($file['file_path'], sprintf($config['board_path'], $board['uri']) . $config['dir']['img'] . $file['file']);
  963. if (isset($file['thumb']) && !in_array($file['thumb'], array('spoiler', 'deleted', 'file')))
  964. $clone($file['thumb_path'], sprintf($config['board_path'], $board['uri']) . $config['dir']['thumb'] . $file['thumb']);
  965. }
  966. }
  967. // go back to the original board to fetch replies
  968. openBoard($originBoard);
  969. $query = prepare(sprintf('SELECT * FROM ``posts_%s`` WHERE `thread` = :id ORDER BY `id`', $originBoard));
  970. $query->bindValue(':id', $postID, PDO::PARAM_INT);
  971. $query->execute() or error(db_error($query));
  972. $replies = array();
  973. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  974. $post['mod'] = true;
  975. $post['thread'] = $newID;
  976. if ($post['files']) {
  977. $post['files'] = json_decode($post['files'], TRUE);
  978. $post['has_file'] = true;
  979. foreach ($post['files'] as $i => &$file) {
  980. $file['file_path'] = sprintf($config['board_path'], $board['uri']) . $config['dir']['img'] . $file['file'];
  981. $file['thumb_path'] = sprintf($config['board_path'], $board['uri']) . $config['dir']['thumb'] . $file['thumb'];
  982. }
  983. } else {
  984. $post['has_file'] = false;
  985. }
  986. $replies[] = $post;
  987. }
  988. $newIDs = array($postID => $newID);
  989. openBoard($targetBoard);
  990. foreach ($replies as &$post) {
  991. $query = prepare('SELECT `target` FROM ``cites`` WHERE `target_board` = :board AND `board` = :board AND `post` = :post');
  992. $query->bindValue(':board', $originBoard);
  993. $query->bindValue(':post', $post['id'], PDO::PARAM_INT);
  994. $query->execute() or error(db_error($qurey));
  995. // correct >>X links
  996. while ($cite = $query->fetch(PDO::FETCH_ASSOC)) {
  997. if (isset($newIDs[$cite['target']])) {
  998. $post['body_nomarkup'] = preg_replace(
  999. '/(>>(>\/' . preg_quote($originBoard, '/') . '\/)?)' . preg_quote($cite['target'], '/') . '/',
  1000. '>>' . $newIDs[$cite['target']],
  1001. $post['body_nomarkup']);
  1002. $post['body'] = $post['body_nomarkup'];
  1003. }
  1004. }
  1005. $post['body'] = $post['body_nomarkup'];
  1006. $post['op'] = false;
  1007. $post['tracked_cites'] = markup($post['body'], true);
  1008. if ($post['has_file']) {
  1009. // copy image
  1010. foreach ($post['files'] as $i => &$file) {
  1011. $clone($file['file_path'], sprintf($config['board_path'], $board['uri']) . $config['dir']['img'] . $file['file']);
  1012. $clone($file['thumb_path'], sprintf($config['board_path'], $board['uri']) . $config['dir']['thumb'] . $file['thumb']);
  1013. }
  1014. }
  1015. // insert reply
  1016. $newIDs[$post['id']] = $newPostID = post($post);
  1017. if (!empty($post['tracked_cites'])) {
  1018. $insert_rows = array();
  1019. foreach ($post['tracked_cites'] as $cite) {
  1020. $insert_rows[] = '(' .
  1021. $pdo->quote($board['uri']) . ', ' . $newPostID . ', ' .
  1022. $pdo->quote($cite[0]) . ', ' . (int)$cite[1] . ')';
  1023. }
  1024. query('INSERT INTO ``cites`` VALUES ' . implode(', ', $insert_rows)) or error(db_error());
  1025. }
  1026. }
  1027. modLog("Moved thread #${postID} to " . sprintf($config['board_abbreviation'], $targetBoard) . " (#${newID})", $originBoard);
  1028. // build new thread
  1029. buildThread($newID);
  1030. clean();
  1031. buildIndex();
  1032. // trigger themes
  1033. rebuildThemes('post', $targetBoard);
  1034. $newboard = $board;
  1035. // return to original board
  1036. openBoard($originBoard);
  1037. if ($shadow) {
  1038. // lock old thread
  1039. $query = prepare(sprintf('UPDATE ``posts_%s`` SET `locked` = 1 WHERE `id` = :id', $originBoard));
  1040. $query->bindValue(':id', $postID, PDO::PARAM_INT);
  1041. $query->execute() or error(db_error($query));
  1042. // leave a reply, linking to the new thread
  1043. $spost = array(
  1044. 'mod' => true,
  1045. 'subject' => '',
  1046. 'email' => '',
  1047. 'name' => (!$config['mod']['shadow_name'] ? $config['anonymous'] : $config['mod']['shadow_name']),
  1048. 'capcode' => $config['mod']['shadow_capcode'],
  1049. 'trip' => '',
  1050. 'password' => '',
  1051. 'has_file' => false,
  1052. // attach to original thread
  1053. 'thread' => $postID,
  1054. 'op' => false
  1055. );
  1056. $spost['body'] = $spost['body_nomarkup'] = sprintf($config['mod']['shadow_mesage'], '>>>/' . $targetBoard . '/' . $newID);
  1057. markup($spost['body']);
  1058. $botID = post($spost);
  1059. buildThread($postID);
  1060. buildIndex();
  1061. header('Location: ?/' . sprintf($config['board_path'], $newboard['uri']) . $config['dir']['res'] . link_for($op, false, $newboard) .
  1062. '#' . $botID, true, $config['redirect_http']);
  1063. } else {
  1064. deletePost($postID);
  1065. buildIndex();
  1066. openBoard($targetBoard);
  1067. header('Location: ?/' . sprintf($config['board_path'], $newboard['uri']) . $config['dir']['res'] . link_for($op, false, $newboard), true, $config['redirect_http']);
  1068. }
  1069. }
  1070. $boards = listBoards();
  1071. if (count($boards) <= 1)
  1072. error(_('Impossible to move thread; there is only one board.'));
  1073. $security_token = make_secure_link_token($originBoard . '/move/' . $postID);
  1074. mod_page(_('Move thread'), 'mod/move.html', array('post' => $postID, 'board' => $originBoard, 'boards' => $boards, 'token' => $security_token));
  1075. }
  1076. function mod_ban_post($board, $delete, $post, $token = false) {
  1077. global $config, $mod;
  1078. if (!openBoard($board))
  1079. error($config['error']['noboard']);
  1080. if (!hasPermission($config['mod']['delete'], $board))
  1081. error($config['error']['noaccess']);
  1082. $security_token = make_secure_link_token($board . '/ban/' . $post);
  1083. $query = prepare(sprintf('SELECT ' . ($config['ban_show_post'] ? '*' : '`ip`, `thread`') .
  1084. ' FROM ``posts_%s`` WHERE `id` = :id', $board));
  1085. $query->bindValue(':id', $post);
  1086. $query->execute() or error(db_error($query));
  1087. if (!$_post = $query->fetch(PDO::FETCH_ASSOC))
  1088. error($config['error']['404']);
  1089. $thread = $_post['thread'];
  1090. $ip = $_post['ip'];
  1091. if (isset($_POST['new_ban'], $_POST['reason'], $_POST['length'], $_POST['board'])) {
  1092. require_once 'inc/mod/ban.php';
  1093. if (isset($_POST['ip']))
  1094. $ip = $_POST['ip'];
  1095. Bans::new_ban($_POST['ip'], $_POST['reason'], $_POST['length'], $_POST['board'] == '*' ? false : $_POST['board'],
  1096. false, $config['ban_show_post'] ? $_post : false);
  1097. if (isset($_POST['public_message'], $_POST['message'])) {
  1098. // public ban message
  1099. $length_english = Bans::parse_time($_POST['length']) ? 'for ' . until(Bans::parse_time($_POST['length'])) : 'permanently';
  1100. $_POST['message'] = preg_replace('/[\r\n]/', '', $_POST['message']);
  1101. $_POST['message'] = str_replace('%length%', $length_english, $_POST['message']);
  1102. $_POST['message'] = str_replace('%LENGTH%', strtoupper($length_english), $_POST['message']);
  1103. $query = prepare(sprintf('UPDATE ``posts_%s`` SET `body_nomarkup` = CONCAT(`body_nomarkup`, :body_nomarkup) WHERE `id` = :id', $board));
  1104. $query->bindValue(':id', $post);
  1105. $query->bindValue(':body_nomarkup', sprintf("\n<tinyboard ban message>%s</tinyboard>", utf8tohtml($_POST['message'])));
  1106. $query->execute() or error(db_error($query));
  1107. rebuildPost($post);
  1108. modLog("Attached a public ban message to post #{$post}: " . utf8tohtml($_POST['message']));
  1109. buildThread($thread ? $thread : $post);
  1110. buildIndex();
  1111. } elseif (isset($_POST['delete']) && (int) $_POST['delete']) {
  1112. // Delete post
  1113. deletePost($post);
  1114. modLog("Deleted post #{$post}");
  1115. // Rebuild board
  1116. buildIndex();
  1117. // Rebuild themes
  1118. rebuildThemes('post-delete', $board);
  1119. }
  1120. header('Location: ?/' . sprintf($config['board_path'], $board) . $config['file_index'], true, $config['redirect_http']);
  1121. }
  1122. $args = array(
  1123. 'ip' => $ip,
  1124. 'hide_ip' => !hasPermission($config['mod']['show_ip'], $board),
  1125. 'post' => $post,
  1126. 'board' => $board,
  1127. 'delete' => (bool)$delete,
  1128. 'boards' => listBoards(),
  1129. 'token' => $security_token
  1130. );
  1131. mod_page(_('New ban'), 'mod/ban_form.html', $args);
  1132. }
  1133. function mod_edit_post($board, $edit_raw_html, $postID) {
  1134. global $config, $mod;
  1135. if (!openBoard($board))
  1136. error($config['error']['noboard']);
  1137. if (!hasPermission($config['mod']['editpost'], $board))
  1138. error($config['error']['noaccess']);
  1139. if ($edit_raw_html && !hasPermission($config['mod']['rawhtml'], $board))
  1140. error($config['error']['noaccess']);
  1141. $security_token = make_secure_link_token($board . '/edit' . ($edit_raw_html ? '_raw' : '') . '/' . $postID);
  1142. $query = prepare(sprintf('SELECT * FROM ``posts_%s`` WHERE `id` = :id', $board));
  1143. $query->bindValue(':id', $postID);
  1144. $query->execute() or error(db_error($query));
  1145. if (!$post = $query->fetch(PDO::FETCH_ASSOC))
  1146. error($config['error']['404']);
  1147. if (isset($_POST['name'], $_POST['email'], $_POST['subject'], $_POST['body'])) {
  1148. if ($edit_raw_html)
  1149. $query = prepare(sprintf('UPDATE ``posts_%s`` SET `name` = :name, `email` = :email, `subject` = :subject, `body` = :body, `body_nomarkup` = :body_nomarkup WHERE `id` = :id', $board));
  1150. else
  1151. $query = prepare(sprintf('UPDATE ``posts_%s`` SET `name` = :name, `email` = :email, `subject` = :subject, `body_nomarkup` = :body WHERE `id` = :id', $board));
  1152. $query->bindValue(':id', $postID);
  1153. $query->bindValue('name', $_POST['name']);
  1154. $query->bindValue(':email', $_POST['email']);
  1155. $query->bindValue(':subject', $_POST['subject']);
  1156. $query->bindValue(':body', $_POST['body']);
  1157. if ($edit_raw_html) {
  1158. $body_nomarkup = $_POST['body'] . "\n<tinyboard raw html>1</tinyboard>";
  1159. $query->bindValue(':body_nomarkup', $body_nomarkup);
  1160. }
  1161. $query->execute() or error(db_error($query));
  1162. if ($edit_raw_html) {
  1163. modLog("Edited raw HTML of post #{$postID}");
  1164. } else {
  1165. modLog("Edited post #{$postID}");
  1166. rebuildPost($postID);
  1167. }
  1168. buildIndex();
  1169. rebuildThemes('post', $board);
  1170. header('Location: ?/' . sprintf($config['board_path'], $board) . $config['dir']['res'] . link_for($post) . '#' . $postID, true, $config['redirect_http']);
  1171. } else {
  1172. if ($config['minify_html']) {
  1173. $post['body_nomarkup'] = str_replace("\n", '&#010;', utf8tohtml($post['body_nomarkup']));
  1174. $post['body'] = str_replace("\n", '&#010;', utf8tohtml($post['body']));
  1175. $post['body_nomarkup'] = str_replace("\r", '', $post['body_nomarkup']);
  1176. $post['body'] = str_replace("\r", '', $post['body']);
  1177. $post['body_nomarkup'] = str_replace("\t", '&#09;', $post['body_nomarkup']);
  1178. $post['body'] = str_replace("\t", '&#09;', $post['body']);
  1179. }
  1180. mod_page(_('Edit post'), 'mod/edit_post_form.html', array('token' => $security_token, 'board' => $board, 'raw' => $edit_raw_html, 'post' => $post));
  1181. }
  1182. }
  1183. function mod_delete($board, $post) {
  1184. global $config, $mod;
  1185. if (!openBoard($board))
  1186. error($config['error']['noboard']);
  1187. if (!hasPermission($config['mod']['delete'], $board))
  1188. error($config['error']['noaccess']);
  1189. // Delete post
  1190. deletePost($post);
  1191. // Record the action
  1192. modLog("Deleted post #{$post}");
  1193. // Rebuild board
  1194. buildIndex();
  1195. // Rebuild themes
  1196. rebuildThemes('post-delete', $board);
  1197. // Redirect
  1198. header('Location: ?/' . sprintf($config['board_path'], $board) . $config['file_index'], true, $config['redirect_http']);
  1199. }
  1200. function mod_deletefile($board, $post, $file) {
  1201. global $config, $mod;
  1202. if (!openBoard($board))
  1203. error($config['error']['noboard']);
  1204. if (!hasPermission($config['mod']['deletefile'], $board))
  1205. error($config['error']['noaccess']);
  1206. // Delete file
  1207. deleteFile($post, TRUE, $file);
  1208. // Record the action
  1209. modLog("Deleted file from post #{$post}");
  1210. // Rebuild board
  1211. buildIndex();
  1212. // Rebuild themes
  1213. rebuildThemes('post-delete', $board);
  1214. // Redirect
  1215. header('Location: ?/' . sprintf($config['board_path'], $board) . $config['file_index'], true, $config['redirect_http']);
  1216. }
  1217. function mod_spoiler_image($board, $post, $file) {
  1218. global $config, $mod;
  1219. if (!openBoard($board))
  1220. error($config['error']['noboard']);
  1221. if (!hasPermission($config['mod']['spoilerimage'], $board))
  1222. error($config['error']['noaccess']);
  1223. // Delete file thumbnail
  1224. $query = prepare(sprintf("SELECT `files`, `thread` FROM ``posts_%s`` WHERE id = :id", $board));
  1225. $query->bindValue(':id', $post, PDO::PARAM_INT);
  1226. $query->execute() or error(db_error($query));
  1227. $result = $query->fetch(PDO::FETCH_ASSOC);
  1228. $files = json_decode($result['files']);
  1229. $size_spoiler_image = @getimagesize($config['spoiler_image']);
  1230. file_unlink($board . '/' . $config['dir']['thumb'] . $files[$file]->thumb);
  1231. $files[$file]->thumb = 'spoiler';
  1232. $files[$file]->thumbwidth = $size_spoiler_image[0];
  1233. $files[$file]->thumbheight = $size_spoiler_image[1];
  1234. // Make thumbnail spoiler
  1235. $query = prepare(sprintf("UPDATE ``posts_%s`` SET `files` = :files WHERE `id` = :id", $board));
  1236. $query->bindValue(':files', json_encode($files));
  1237. $query->bindValue(':id', $post, PDO::PARAM_INT);
  1238. $query->execute() or error(db_error($query));
  1239. // Record the action
  1240. modLog("Spoilered file from post #{$post}");
  1241. // Rebuild thread
  1242. buildThread($result['thread'] ? $result['thread'] : $post);
  1243. // Rebuild board
  1244. buildIndex();
  1245. // Rebuild themes
  1246. rebuildThemes('post-delete', $board);
  1247. // Redirect
  1248. header('Location: ?/' . sprintf($config['board_path'], $board) . $config['file_index'], true, $config['redirect_http']);
  1249. }
  1250. function mod_deletebyip($boardName, $post, $global = false) {
  1251. global $config, $mod, $board;
  1252. $global = (bool)$global;
  1253. if (!openBoard($boardName))
  1254. error($config['error']['noboard']);
  1255. if (!$global && !hasPermission($config['mod']['deletebyip'], $boardName))
  1256. error($config['error']['noaccess']);
  1257. if ($global && !hasPermission($config['mod']['deletebyip_global'], $boardName))
  1258. error($config['error']['noaccess']);
  1259. // Find IP address
  1260. $query = prepare(sprintf('SELECT `ip` FROM ``posts_%s`` WHERE `id` = :id', $boardName));
  1261. $query->bindValue(':id', $post);
  1262. $query->execute() or error(db_error($query));
  1263. if (!$ip = $query->fetchColumn())
  1264. error($config['error']['invalidpost']);
  1265. $boards = $global ? listBoards() : array(array('uri' => $boardName));
  1266. $query = '';
  1267. foreach ($boards as $_board) {
  1268. $query .= sprintf("SELECT `thread`, `id`, '%s' AS `board` FROM ``posts_%s`` WHERE `ip` = :ip UNION ALL ", $_board['uri'], $_board['uri']);
  1269. }
  1270. $query = preg_replace('/UNION ALL $/', '', $query);
  1271. $query = prepare($query);
  1272. $query->bindValue(':ip', $ip);
  1273. $query->execute() or error(db_error($query));
  1274. if ($query->rowCount() < 1)
  1275. error($config['error']['invalidpost']);
  1276. @set_time_limit($config['mod']['rebuild_timelimit']);
  1277. $threads_to_rebuild = array();
  1278. $threads_deleted = array();
  1279. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1280. openBoard($post['board']);
  1281. deletePost($post['id'], false, false);
  1282. rebuildThemes('post-delete', $board['uri']);
  1283. if ($post['thread'])
  1284. $threads_to_rebuild[$post['board']][$post['thread']] = true;
  1285. else
  1286. $threads_deleted[$post['board']][$post['id']] = true;
  1287. }
  1288. foreach ($threads_to_rebuild as $_board => $_threads) {
  1289. openBoard($_board);
  1290. foreach ($_threads as $_thread => $_dummy) {
  1291. if ($_dummy && !isset($threads_deleted[$_board][$_thread]))
  1292. buildThread($_thread);
  1293. }
  1294. buildIndex();
  1295. }
  1296. if ($global) {
  1297. $board = false;
  1298. }
  1299. // Record the action
  1300. modLog("Deleted all posts by IP address: <a href=\"?/IP/$ip\">$ip</a>");
  1301. // Redirect
  1302. header('Location: ?/' . sprintf($config['board_path'], $boardName) . $config['file_index'], true, $config['redirect_http']);
  1303. }
  1304. function mod_user($uid) {
  1305. global $config, $mod;
  1306. if (!hasPermission($config['mod']['editusers']) && !(hasPermission($config['mod']['change_password']) && $uid == $mod['id']))
  1307. error($config['error']['noaccess']);
  1308. $query = prepare('SELECT * FROM ``mods`` WHERE `id` = :id');
  1309. $query->bindValue(':id', $uid);
  1310. $query->execute() or error(db_error($query));
  1311. if (!$user = $query->fetch(PDO::FETCH_ASSOC))
  1312. error($config['error']['404']);
  1313. if (hasPermission($config['mod']['editusers']) && isset($_POST['username'], $_POST['password'])) {
  1314. if (isset($_POST['allboards'])) {
  1315. $boards = array('*');
  1316. } else {
  1317. $_boards = listBoards();
  1318. foreach ($_boards as &$board) {
  1319. $board = $board['uri'];
  1320. }
  1321. $boards = array();
  1322. foreach ($_POST as $name => $value) {
  1323. if (preg_match('/^board_(' . $config['board_regex'] . ')$/u', $name, $matches) && in_array($matches[1], $_boards))
  1324. $boards[] = $matches[1];
  1325. }
  1326. }
  1327. if (isset($_POST['delete'])) {
  1328. if (!hasPermission($config['mod']['deleteusers']))
  1329. error($config['error']['noaccess']);
  1330. $query = prepare('DELETE FROM ``mods`` WHERE `id` = :id');
  1331. $query->bindValue(':id', $uid);
  1332. $query->execute() or error(db_error($query));
  1333. modLog('Deleted user ' . utf8tohtml($user['username']) . ' <small>(#' . $user['id'] . ')</small>');
  1334. header('Location: ?/users', true, $config['redirect_http']);
  1335. return;
  1336. }
  1337. if ($_POST['username'] == '')
  1338. error(sprintf($config['error']['required'], 'username'));
  1339. $query = prepare('UPDATE ``mods`` SET `username` = :username, `boards` = :boards WHERE `id` = :id');
  1340. $query->bindValue(':id', $uid);
  1341. $query->bindValue(':username', $_POST['username']);
  1342. $query->bindValue(':boards', implode(',', $boards));
  1343. $query->execute() or error(db_error($query));
  1344. if ($user['username'] !== $_POST['username']) {
  1345. // account was renamed
  1346. modLog('Renamed user "' . utf8tohtml($user['username']) . '" <small>(#' . $user['id'] . ')</small> to "' . utf8tohtml($_POST['username']) . '"');
  1347. }
  1348. if ($_POST['password'] != '') {
  1349. list($version, $password) = crypt_password($_POST['password']);
  1350. $query = prepare('UPDATE ``mods`` SET `password` = :password, `version` = :version WHERE `id` = :id');
  1351. $query->bindValue(':id', $uid);
  1352. $query->bindValue(':password', $password);
  1353. $query->bindValue(':version', $version);
  1354. $query->execute() or error(db_error($query));
  1355. modLog('Changed password for ' . utf8tohtml($_POST['username']) . ' <small>(#' . $user['id'] . ')</small>');
  1356. if ($uid == $mod['id']) {
  1357. login($_POST['username'], $_POST['password']);
  1358. setCookies();
  1359. }
  1360. }
  1361. if (hasPermission($config['mod']['manageusers']))
  1362. header('Location: ?/users', true, $config['redirect_http']);
  1363. else
  1364. header('Location: ?/', true, $config['redirect_http']);
  1365. return;
  1366. }
  1367. if (hasPermission($config['mod']['change_password']) && $uid == $mod['id'] && isset($_POST['password'])) {
  1368. if ($_POST['password'] != '') {
  1369. list($version, $password) = crypt_password($_POST['password']);
  1370. $query = prepare('UPDATE ``mods`` SET `password` = :password, `version` = :version WHERE `id` = :id');
  1371. $query->bindValue(':id', $uid);
  1372. $query->bindValue(':password', $password);
  1373. $query->bindValue(':version', $version);
  1374. $query->execute() or error(db_error($query));
  1375. modLog('Changed own password');
  1376. login($user['username'], $_POST['password']);
  1377. setCookies();
  1378. }
  1379. if (hasPermission($config['mod']['manageusers']))
  1380. header('Location: ?/users', true, $config['redirect_http']);
  1381. else
  1382. header('Location: ?/', true, $config['redirect_http']);
  1383. return;
  1384. }
  1385. if (hasPermission($config['mod']['modlog'])) {
  1386. $query = prepare('SELECT * FROM ``modlogs`` WHERE `mod` = :id ORDER BY `time` DESC LIMIT 5');
  1387. $query->bindValue(':id', $uid);
  1388. $query->execute() or error(db_error($query));
  1389. $log = $query->fetchAll(PDO::FETCH_ASSOC);
  1390. } else {
  1391. $log = array();
  1392. }
  1393. $user['boards'] = explode(',', $user['boards']);
  1394. mod_page(_('Edit user'), 'mod/user.html', array(
  1395. 'user' => $user,
  1396. 'logs' => $log,
  1397. 'boards' => listBoards(),
  1398. 'token' => make_secure_link_token('users/' . $user['id'])
  1399. ));
  1400. }
  1401. function mod_user_new() {
  1402. global $pdo, $config;
  1403. if (!hasPermission($config['mod']['createusers']))
  1404. error($config['error']['noaccess']);
  1405. if (isset($_POST['username'], $_POST['password'], $_POST['type'])) {
  1406. if ($_POST['username'] == '')
  1407. error(sprintf($config['error']['required'], 'username'));
  1408. if ($_POST['password'] == '')
  1409. error(sprintf($config['error']['required'], 'password'));
  1410. if (isset($_POST['allboards'])) {
  1411. $boards = array('*');
  1412. } else {
  1413. $_boards = listBoards();
  1414. foreach ($_boards as &$board) {
  1415. $board = $board['uri'];
  1416. }
  1417. $boards = array();
  1418. foreach ($_POST as $name => $value) {
  1419. if (preg_match('/^board_(' . $config['board_regex'] . ')$/u', $name, $matches) && in_array($matches[1], $_boards))
  1420. $boards[] = $matches[1];
  1421. }
  1422. }
  1423. $type = (int)$_POST['type'];
  1424. if (!isset($config['mod']['groups'][$type]) || $type == DISABLED)
  1425. error(sprintf($config['error']['invalidfield'], 'type'));
  1426. list($version, $password) = crypt_password($_POST['password']);
  1427. $query = prepare('INSERT INTO ``mods`` VALUES (NULL, :username, :password, :version, :type, :boards)');
  1428. $query->bindValue(':username', $_POST['username']);
  1429. $query->bindValue(':password', $password);
  1430. $query->bindValue(':version', $version);
  1431. $query->bindValue(':type', $type);
  1432. $query->bindValue(':boards', implode(',', $boards));
  1433. $query->execute() or error(db_error($query));
  1434. $userID = $pdo->lastInsertId();
  1435. modLog('Created a new user: ' . utf8tohtml($_POST['username']) . ' <small>(#' . $userID . ')</small>');
  1436. header('Location: ?/users', true, $config['redirect_http']);
  1437. return;
  1438. }
  1439. mod_page(_('New user'), 'mod/user.html', array('new' => true, 'boards' => listBoards(), 'token' => make_secure_link_token('users/new')));
  1440. }
  1441. function mod_users() {
  1442. global $config;
  1443. if (!hasPermission($config['mod']['manageusers']))
  1444. error($config['error']['noaccess']);
  1445. $query = query("SELECT
  1446. *,
  1447. (SELECT `time` FROM ``modlogs`` WHERE `mod` = `id` ORDER BY `time` DESC LIMIT 1) AS `last`,
  1448. (SELECT `text` FROM ``modlogs`` WHERE `mod` = `id` ORDER BY `time` DESC LIMIT 1) AS `action`
  1449. FROM ``mods`` ORDER BY `type` DESC,`id`") or error(db_error());
  1450. $users = $query->fetchAll(PDO::FETCH_ASSOC);
  1451. foreach ($users as &$user) {
  1452. $user['promote_token'] = make_secure_link_token("users/{$user['id']}/promote");
  1453. $user['demote_token'] = make_secure_link_token("users/{$user['id']}/demote");
  1454. }
  1455. mod_page(sprintf('%s (%d)', _('Manage users'), count($users)), 'mod/users.html', array('users' => $users));
  1456. }
  1457. function mod_user_promote($uid, $action) {
  1458. global $config;
  1459. if (!hasPermission($config['mod']['promoteusers']))
  1460. error($config['error']['noaccess']);
  1461. $query = prepare("SELECT `type`, `username` FROM ``mods`` WHERE `id` = :id");
  1462. $query->bindValue(':id', $uid);
  1463. $query->execute() or error(db_error($query));
  1464. if (!$mod = $query->fetch(PDO::FETCH_ASSOC))
  1465. error($config['error']['404']);
  1466. $new_group = false;
  1467. $groups = $config['mod']['groups'];
  1468. if ($action == 'demote')
  1469. $groups = array_reverse($groups, true);
  1470. foreach ($groups as $group_value => $group_name) {
  1471. if ($action == 'promote' && $group_value > $mod['type']) {
  1472. $new_group = $group_value;
  1473. break;
  1474. } elseif ($action == 'demote' && $group_value < $mod['type']) {
  1475. $new_group = $group_value;
  1476. break;
  1477. }
  1478. }
  1479. if ($new_group === false || $new_group == DISABLED)
  1480. error(_('Impossible to promote/demote user.'));
  1481. $query = prepare("UPDATE ``mods`` SET `type` = :group_value WHERE `id` = :id");
  1482. $query->bindValue(':id', $uid);
  1483. $query->bindValue(':group_value', $new_group);
  1484. $query->execute() or error(db_error($query));
  1485. modLog(($action == 'promote' ? 'Promoted' : 'Demoted') . ' user "' .
  1486. utf8tohtml($mod['username']) . '" to ' . $config['mod']['groups'][$new_group]);
  1487. header('Location: ?/users', true, $config['redirect_http']);
  1488. }
  1489. function mod_pm($id, $reply = false) {
  1490. global $mod, $config;
  1491. if ($reply && !hasPermission($config['mod']['create_pm']))
  1492. error($config['error']['noaccess']);
  1493. $query = prepare("SELECT ``mods``.`username`, `mods_to`.`username` AS `to_username`, ``pms``.* FROM ``pms`` LEFT JOIN ``mods`` ON ``mods``.`id` = `sender` LEFT JOIN ``mods`` AS `mods_to` ON `mods_to`.`id` = `to` WHERE ``pms``.`id` = :id");
  1494. $query->bindValue(':id', $id);
  1495. $query->execute() or error(db_error($query));
  1496. if ((!$pm = $query->fetch(PDO::FETCH_ASSOC)) || ($pm['to'] != $mod['id'] && !hasPermission($config['mod']['master_pm'])))
  1497. error($config['error']['404']);
  1498. if (isset($_POST['delete'])) {
  1499. $query = prepare("DELETE FROM ``pms`` WHERE `id` = :id");
  1500. $query->bindValue(':id', $id);
  1501. $query->execute() or error(db_error($query));
  1502. if ($config['cache']['enabled']) {
  1503. cache::delete('pm_unread_' . $mod['id']);
  1504. cache::delete('pm_unreadcount_' . $mod['id']);
  1505. }
  1506. header('Location: ?/', true, $config['redirect_http']);
  1507. return;
  1508. }
  1509. if ($pm['unread'] && $pm['to'] == $mod['id']) {
  1510. $query = prepare("UPDATE ``pms`` SET `unread` = 0 WHERE `id` = :id");
  1511. $query->bindValue(':id', $id);
  1512. $query->execute() or error(db_error($query));
  1513. if ($config['cache']['enabled']) {
  1514. cache::delete('pm_unread_' . $mod['id']);
  1515. cache::delete('pm_unreadcount_' . $mod['id']);
  1516. }
  1517. modLog('Read a PM');
  1518. }
  1519. if ($reply) {
  1520. if (!$pm['to_username'])
  1521. error($config['error']['404']); // deleted?
  1522. mod_page(sprintf('%s %s', _('New PM for'), $pm['to_username']), 'mod/new_pm.html', array(
  1523. 'username' => $pm['username'],
  1524. 'id' => $pm['sender'],
  1525. 'message' => quote($pm['message']),
  1526. 'token' => make_secure_link_token('new_PM/' . $pm['username'])
  1527. ));
  1528. } else {
  1529. mod_page(sprintf('%s &ndash; #%d', _('Private message'), $id), 'mod/pm.html', $pm);
  1530. }
  1531. }
  1532. function mod_inbox() {
  1533. global $config, $mod;
  1534. $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');
  1535. $query->bindValue(':mod', $mod['id']);
  1536. $query->execute() or error(db_error($query));
  1537. $messages = $query->fetchAll(PDO::FETCH_ASSOC);
  1538. $query = prepare('SELECT COUNT(*) FROM ``pms`` WHERE `to` = :mod AND `unread` = 1');
  1539. $query->bindValue(':mod', $mod['id']);
  1540. $query->execute() or error(db_error($query));
  1541. $unread = $query->fetchColumn();
  1542. foreach ($messages as &$message) {
  1543. $message['snippet'] = pm_snippet($message['message']);
  1544. }
  1545. mod_page(sprintf('%s (%s)', _('PM inbox'), count($messages) > 0 ? $unread . ' unread' : 'empty'), 'mod/inbox.html', array(
  1546. 'messages' => $messages,
  1547. 'unread' => $unread
  1548. ));
  1549. }
  1550. function mod_new_pm($username) {
  1551. global $config, $mod;
  1552. if (!hasPermission($config['mod']['create_pm']))
  1553. error($config['error']['noaccess']);
  1554. $query = prepare("SELECT `id` FROM ``mods`` WHERE `username` = :username");
  1555. $query->bindValue(':username', $username);
  1556. $query->execute() or error(db_error($query));
  1557. if (!$id = $query->fetchColumn()) {
  1558. // Old style ?/PM: by user ID
  1559. $query = prepare("SELECT `username` FROM ``mods`` WHERE `id` = :username");
  1560. $query->bindValue(':username', $username);
  1561. $query->execute() or error(db_error($query));
  1562. if ($username = $query->fetchColumn())
  1563. header('Location: ?/new_PM/' . $username, true, $config['redirect_http']);
  1564. else
  1565. error($config['error']['404']);
  1566. }
  1567. if (isset($_POST['message'])) {
  1568. $_POST['message'] = escape_markup_modifiers($_POST['message']);
  1569. markup($_POST['message']);
  1570. $query = prepare("INSERT INTO ``pms`` VALUES (NULL, :me, :id, :message, :time, 1)");
  1571. $query->bindValue(':me', $mod['id']);
  1572. $query->bindValue(':id', $id);
  1573. $query->bindValue(':message', $_POST['message']);
  1574. $query->bindValue(':time', time());
  1575. $query->execute() or error(db_error($query));
  1576. if ($config['cache']['enabled']) {
  1577. cache::delete('pm_unread_' . $id);
  1578. cache::delete('pm_unreadcount_' . $id);
  1579. }
  1580. modLog('Sent a PM to ' . utf8tohtml($username));
  1581. header('Location: ?/', true, $config['redirect_http']);
  1582. }
  1583. mod_page(sprintf('%s %s', _('New PM for'), $username), 'mod/new_pm.html', array(
  1584. 'username' => $username,
  1585. 'id' => $id,
  1586. 'token' => make_secure_link_token('new_PM/' . $username)
  1587. ));
  1588. }
  1589. function mod_rebuild() {
  1590. global $config, $twig;
  1591. if (!hasPermission($config['mod']['rebuild']))
  1592. error($config['error']['noaccess']);
  1593. if (isset($_POST['rebuild'])) {
  1594. @set_time_limit($config['mod']['rebuild_timelimit']);
  1595. $log = array();
  1596. $boards = listBoards();
  1597. $rebuilt_scripts = array();
  1598. if (isset($_POST['rebuild_cache'])) {
  1599. if ($config['cache']['enabled']) {
  1600. $log[] = 'Flushing cache';
  1601. Cache::flush();
  1602. }
  1603. $log[] = 'Clearing template cache';
  1604. load_twig();
  1605. $twig->clearCacheFiles();
  1606. }
  1607. if (isset($_POST['rebuild_themes'])) {
  1608. $log[] = 'Regenerating theme files';
  1609. rebuildThemes('all');
  1610. }
  1611. if (isset($_POST['rebuild_javascript'])) {
  1612. $log[] = 'Rebuilding <strong>' . $config['file_script'] . '</strong>';
  1613. buildJavascript();
  1614. $rebuilt_scripts[] = $config['file_script'];
  1615. }
  1616. foreach ($boards as $board) {
  1617. if (!(isset($_POST['boards_all']) || isset($_POST['board_' . $board['uri']])))
  1618. continue;
  1619. openBoard($board['uri']);
  1620. $config['try_smarter'] = false;
  1621. if (isset($_POST['rebuild_index'])) {
  1622. buildIndex();
  1623. $log[] = '<strong>' . sprintf($config['board_abbreviation'], $board['uri']) . '</strong>: Creating index pages';
  1624. }
  1625. if (isset($_POST['rebuild_javascript']) && !in_array($config['file_script'], $rebuilt_scripts)) {
  1626. $log[] = '<strong>' . sprintf($config['board_abbreviation'], $board['uri']) . '</strong>: Rebuilding <strong>' . $config['file_script'] . '</strong>';
  1627. buildJavascript();
  1628. $rebuilt_scripts[] = $config['file_script'];
  1629. }
  1630. if (isset($_POST['rebuild_thread'])) {
  1631. $query = query(sprintf("SELECT `id` FROM ``posts_%s`` WHERE `thread` IS NULL", $board['uri'])) or error(db_error());
  1632. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1633. $log[] = '<strong>' . sprintf($config['board_abbreviation'], $board['uri']) . '</strong>: Rebuilding thread #' . $post['id'];
  1634. buildThread($post['id']);
  1635. }
  1636. }
  1637. }
  1638. mod_page(_('Rebuild'), 'mod/rebuilt.html', array('logs' => $log));
  1639. return;
  1640. }
  1641. mod_page(_('Rebuild'), 'mod/rebuild.html', array(
  1642. 'boards' => listBoards(),
  1643. 'token' => make_secure_link_token('rebuild')
  1644. ));
  1645. }
  1646. function mod_reports() {
  1647. global $config, $mod;
  1648. if (!hasPermission($config['mod']['reports']))
  1649. error($config['error']['noaccess']);
  1650. $query = prepare("SELECT * FROM ``reports`` ORDER BY `time` DESC LIMIT :limit");
  1651. $query->bindValue(':limit', $config['mod']['recent_reports'], PDO::PARAM_INT);
  1652. $query->execute() or error(db_error($query));
  1653. $reports = $query->fetchAll(PDO::FETCH_ASSOC);
  1654. $report_queries = array();
  1655. foreach ($reports as $report) {
  1656. if (!isset($report_queries[$report['board']]))
  1657. $report_queries[$report['board']] = array();
  1658. $report_queries[$report['board']][] = $report['post'];
  1659. }
  1660. $report_posts = array();
  1661. foreach ($report_queries as $board => $posts) {
  1662. $report_posts[$board] = array();
  1663. $query = query(sprintf('SELECT * FROM ``posts_%s`` WHERE `id` = ' . implode(' OR `id` = ', $posts), $board)) or error(db_error());
  1664. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1665. $report_posts[$board][$post['id']] = $post;
  1666. }
  1667. }
  1668. $count = 0;
  1669. $body = '';
  1670. foreach ($reports as $report) {
  1671. if (!isset($report_posts[$report['board']][$report['post']])) {
  1672. // // Invalid report (post has since been deleted)
  1673. $query = prepare("DELETE FROM ``reports`` WHERE `post` = :id AND `board` = :board");
  1674. $query->bindValue(':id', $report['post'], PDO::PARAM_INT);
  1675. $query->bindValue(':board', $report['board']);
  1676. $query->execute() or error(db_error($query));
  1677. continue;
  1678. }
  1679. openBoard($report['board']);
  1680. $post = &$report_posts[$report['board']][$report['post']];
  1681. if (!$post['thread']) {
  1682. // Still need to fix this:
  1683. $po = new Thread($post, '?/', $mod, false);
  1684. } else {
  1685. $po = new Post($post, '?/', $mod);
  1686. }
  1687. // a little messy and inefficient
  1688. $append_html = Element('mod/report.html', array(
  1689. 'report' => $report,
  1690. 'config' => $config,
  1691. 'mod' => $mod,
  1692. 'token' => make_secure_link_token('reports/' . $report['id'] . '/dismiss'),
  1693. 'token_all' => make_secure_link_token('reports/' . $report['id'] . '/dismissall')
  1694. ));
  1695. // Bug fix for https://github.com/savetheinternet/Tinyboard/issues/21
  1696. $po->body = truncate($po->body, $po->link(), $config['body_truncate'] - substr_count($append_html, '<br>'));
  1697. if (mb_strlen($po->body) + mb_strlen($append_html) > $config['body_truncate_char']) {
  1698. // still too long; temporarily increase limit in the config
  1699. $__old_body_truncate_char = $config['body_truncate_char'];
  1700. $config['body_truncate_char'] = mb_strlen($po->body) + mb_strlen($append_html);
  1701. }
  1702. $po->body .= $append_html;
  1703. $body .= $po->build(true) . '<hr>';
  1704. if (isset($__old_body_truncate_char))
  1705. $config['body_truncate_char'] = $__old_body_truncate_char;
  1706. $count++;
  1707. }
  1708. mod_page(sprintf('%s (%d)', _('Report queue'), $count), 'mod/reports.html', array('reports' => $body, 'count' => $count));
  1709. }
  1710. function mod_report_dismiss($id, $all = false) {
  1711. global $config;
  1712. $query = prepare("SELECT `post`, `board`, `ip` FROM ``reports`` WHERE `id` = :id");
  1713. $query->bindValue(':id', $id);
  1714. $query->execute() or error(db_error($query));
  1715. if ($report = $query->fetch(PDO::FETCH_ASSOC)) {
  1716. $ip = $report['ip'];
  1717. $board = $report['board'];
  1718. $post = $report['post'];
  1719. } else
  1720. error($config['error']['404']);
  1721. if (!$all && !hasPermission($config['mod']['report_dismiss'], $board))
  1722. error($config['error']['noaccess']);
  1723. if ($all && !hasPermission($config['mod']['report_dismiss_ip'], $board))
  1724. error($config['error']['noaccess']);
  1725. if ($all) {
  1726. $query = prepare("DELETE FROM ``reports`` WHERE `ip` = :ip");
  1727. $query->bindValue(':ip', $ip);
  1728. } else {
  1729. $query = prepare("DELETE FROM ``reports`` WHERE `id` = :id");
  1730. $query->bindValue(':id', $id);
  1731. }
  1732. $query->execute() or error(db_error($query));
  1733. if ($all)
  1734. modLog("Dismissed all reports by <a href=\"?/IP/$ip\">$ip</a>");
  1735. else
  1736. modLog("Dismissed a report for post #{$id}", $board);
  1737. header('Location: ?/reports', true, $config['redirect_http']);
  1738. }
  1739. function mod_recent_posts($lim) {
  1740. global $config, $mod, $pdo;
  1741. if (!hasPermission($config['mod']['recent']))
  1742. error($config['error']['noaccess']);
  1743. $limit = (is_numeric($lim))? $lim : 25;
  1744. $last_time = (isset($_GET['last']) && is_numeric($_GET['last'])) ? $_GET['last'] : 0;
  1745. $mod_boards = array();
  1746. $boards = listBoards();
  1747. //if not all boards
  1748. if ($mod['boards'][0]!='*') {
  1749. foreach ($boards as $board) {
  1750. if (in_array($board['uri'], $mod['boards']))
  1751. $mod_boards[] = $board;
  1752. }
  1753. } else {
  1754. $mod_boards = $boards;
  1755. }
  1756. // Manually build an SQL query
  1757. $query = 'SELECT * FROM (';
  1758. foreach ($mod_boards as $board) {
  1759. $query .= sprintf('SELECT *, %s AS `board` FROM ``posts_%s`` UNION ALL ', $pdo->quote($board['uri']), $board['uri']);
  1760. }
  1761. // Remove the last "UNION ALL" seperator and complete the query
  1762. $query = preg_replace('/UNION ALL $/', ') AS `all_posts` WHERE (`time` < :last_time OR NOT :last_time) ORDER BY `time` DESC LIMIT ' . $limit, $query);
  1763. $query = prepare($query);
  1764. $query->bindValue(':last_time', $last_time);
  1765. $query->execute() or error(db_error($query));
  1766. $posts = $query->fetchAll(PDO::FETCH_ASSOC);
  1767. foreach ($posts as &$post) {
  1768. openBoard($post['board']);
  1769. if (!$post['thread']) {
  1770. // Still need to fix this:
  1771. $po = new Thread($post, '?/', $mod, false);
  1772. $post['built'] = $po->build(true);
  1773. } else {
  1774. $po = new Post($post, '?/', $mod);
  1775. $post['built'] = $po->build(true);
  1776. }
  1777. $last_time = $post['time'];
  1778. }
  1779. echo mod_page(_('Recent posts'), 'mod/recent_posts.html', array(
  1780. 'posts' => $posts,
  1781. 'limit' => $limit,
  1782. 'last_time' => $last_time
  1783. )
  1784. );
  1785. }
  1786. function mod_config($board_config = false) {
  1787. global $config, $mod, $board;
  1788. if ($board_config && !openBoard($board_config))
  1789. error($config['error']['noboard']);
  1790. if (!hasPermission($config['mod']['edit_config'], $board_config))
  1791. error($config['error']['noaccess']);
  1792. $config_file = $board_config ? $board['dir'] . 'config.php' : 'inc/instance-config.php';
  1793. if ($config['mod']['config_editor_php']) {
  1794. $readonly = !(is_file($config_file) ? is_writable($config_file) : is_writable(dirname($config_file)));
  1795. if (!$readonly && isset($_POST['code'])) {
  1796. $code = $_POST['code'];
  1797. // Save previous instance_config if php_check_syntax fails
  1798. $old_code = file_get_contents($config_file);
  1799. file_put_contents($config_file, $code);
  1800. $resp = shell_exec_error('php -l ' . $config_file);
  1801. if (preg_match('/No syntax errors detected/', $resp)) {
  1802. header('Location: ?/config' . ($board_config ? '/' . $board_config : ''), true, $config['redirect_http']);
  1803. return;
  1804. }
  1805. else {
  1806. file_put_contents($config_file, $old_code);
  1807. error($config['error']['badsyntax'] . $resp);
  1808. }
  1809. }
  1810. $instance_config = @file_get_contents($config_file);
  1811. if ($instance_config === false) {
  1812. $instance_config = "<?php\n\n// This file does not exist yet. You are creating it.";
  1813. }
  1814. $instance_config = str_replace("\n", '&#010;', utf8tohtml($instance_config));
  1815. mod_page(_('Config editor'), 'mod/config-editor-php.html', array(
  1816. 'php' => $instance_config,
  1817. 'readonly' => $readonly,
  1818. 'boards' => listBoards(),
  1819. 'board' => $board_config,
  1820. 'file' => $config_file,
  1821. 'token' => make_secure_link_token('config' . ($board_config ? '/' . $board_config : ''))
  1822. ));
  1823. return;
  1824. }
  1825. require_once 'inc/mod/config-editor.php';
  1826. $conf = config_vars();
  1827. foreach ($conf as &$var) {
  1828. if (is_array($var['name'])) {
  1829. $c = &$config;
  1830. foreach ($var['name'] as $n)
  1831. $c = &$c[$n];
  1832. } else {
  1833. $c = @$config[$var['name']];
  1834. }
  1835. $var['value'] = $c;
  1836. }
  1837. unset($var);
  1838. if (isset($_POST['save'])) {
  1839. $config_append = '';
  1840. foreach ($conf as $var) {
  1841. $field_name = 'cf_' . (is_array($var['name']) ? implode('/', $var['name']) : $var['name']);
  1842. if ($var['type'] == 'boolean')
  1843. $value = isset($_POST[$field_name]);
  1844. elseif (isset($_POST[$field_name]))
  1845. $value = $_POST[$field_name];
  1846. else
  1847. continue; // ???
  1848. if (!settype($value, $var['type']))
  1849. continue; // invalid
  1850. if ($value != $var['value']) {
  1851. // This value has been changed.
  1852. $config_append .= '$config';
  1853. if (is_array($var['name'])) {
  1854. foreach ($var['name'] as $name)
  1855. $config_append .= '[' . var_export($name, true) . ']';
  1856. } else {
  1857. $config_append .= '[' . var_export($var['name'], true) . ']';
  1858. }
  1859. $config_append .= ' = ';
  1860. if (@$var['permissions'] && isset($config['mod']['groups'][$value])) {
  1861. $config_append .= $config['mod']['groups'][$value];
  1862. } else {
  1863. $config_append .= var_export($value, true);
  1864. }
  1865. $config_append .= ";\n";
  1866. }
  1867. }
  1868. if (!empty($config_append)) {
  1869. $config_append = "\n// Changes made via web editor by \"" . $mod['username'] . "\" @ " . date('r') . ":\n" . $config_append . "\n";
  1870. if (!is_file($config_file))
  1871. $config_append = "<?php\n\n$config_append";
  1872. if (!@file_put_contents($config_file, $config_append, FILE_APPEND)) {
  1873. $config_append = htmlentities($config_append);
  1874. if ($config['minify_html'])
  1875. $config_append = str_replace("\n", '&#010;', $config_append);
  1876. $page = array();
  1877. $page['title'] = 'Cannot write to file!';
  1878. $page['config'] = $config;
  1879. $page['body'] = '
  1880. <p style="text-align:center">Tinyboard could not write to <strong>' . $config_file . '</strong> with the ammended configuration, probably due to a permissions error.</p>
  1881. <p style="text-align:center">You may proceed with these changes manually by copying and pasting the following code to the end of <strong>' . $config_file . '</strong>:</p>
  1882. <textarea style="width:700px;height:370px;margin:auto;display:block;background:white;color:black" readonly>' . $config_append . '</textarea>
  1883. ';
  1884. echo Element('page.html', $page);
  1885. exit;
  1886. }
  1887. }
  1888. header('Location: ?/config' . ($board_config ? '/' . $board_config : ''), true, $config['redirect_http']);
  1889. exit;
  1890. }
  1891. mod_page(_('Config editor') . ($board_config ? ': ' . sprintf($config['board_abbreviation'], $board_config) : ''),
  1892. 'mod/config-editor.html', array(
  1893. 'boards' => listBoards(),
  1894. 'board' => $board_config,
  1895. 'conf' => $conf,
  1896. 'file' => $config_file,
  1897. 'token' => make_secure_link_token('config' . ($board_config ? '/' . $board_config : ''))
  1898. ));
  1899. }
  1900. function mod_themes_list() {
  1901. global $config;
  1902. if (!hasPermission($config['mod']['themes']))
  1903. error($config['error']['noaccess']);
  1904. if (!is_dir($config['dir']['themes']))
  1905. error(_('Themes directory doesn\'t exist!'));
  1906. if (!$dir = opendir($config['dir']['themes']))
  1907. error(_('Cannot open themes directory; check permissions.'));
  1908. $query = query('SELECT `theme` FROM ``theme_settings`` WHERE `name` IS NULL AND `value` IS NULL') or error(db_error());
  1909. $themes_in_use = $query->fetchAll(PDO::FETCH_COLUMN);
  1910. // Scan directory for themes
  1911. $themes = array();
  1912. while ($file = readdir($dir)) {
  1913. if ($file[0] != '.' && is_dir($config['dir']['themes'] . '/' . $file)) {
  1914. $themes[$file] = loadThemeConfig($file);
  1915. }
  1916. }
  1917. closedir($dir);
  1918. foreach ($themes as $theme_name => &$theme) {
  1919. $theme['rebuild_token'] = make_secure_link_token('themes/' . $theme_name . '/rebuild');
  1920. $theme['uninstall_token'] = make_secure_link_token('themes/' . $theme_name . '/uninstall');
  1921. }
  1922. mod_page(_('Manage themes'), 'mod/themes.html', array(
  1923. 'themes' => $themes,
  1924. 'themes_in_use' => $themes_in_use,
  1925. ));
  1926. }
  1927. function mod_theme_configure($theme_name) {
  1928. global $config;
  1929. if (!hasPermission($config['mod']['themes']))
  1930. error($config['error']['noaccess']);
  1931. if (!$theme = loadThemeConfig($theme_name)) {
  1932. error($config['error']['invalidtheme']);
  1933. }
  1934. if (isset($_POST['install'])) {
  1935. // Check if everything is submitted
  1936. foreach ($theme['config'] as &$conf) {
  1937. if (!isset($_POST[$conf['name']]) && $conf['type'] != 'checkbox')
  1938. error(sprintf($config['error']['required'], $c['title']));
  1939. }
  1940. // Clear previous settings
  1941. $query = prepare("DELETE FROM ``theme_settings`` WHERE `theme` = :theme");
  1942. $query->bindValue(':theme', $theme_name);
  1943. $query->execute() or error(db_error($query));
  1944. foreach ($theme['config'] as &$conf) {
  1945. $query = prepare("INSERT INTO ``theme_settings`` VALUES(:theme, :name, :value)");
  1946. $query->bindValue(':theme', $theme_name);
  1947. $query->bindValue(':name', $conf['name']);
  1948. if ($conf['type'] == 'checkbox')
  1949. $query->bindValue(':value', isset($_POST[$conf['name']]) ? 1 : 0);
  1950. else
  1951. $query->bindValue(':value', $_POST[$conf['name']]);
  1952. $query->execute() or error(db_error($query));
  1953. }
  1954. $query = prepare("INSERT INTO ``theme_settings`` VALUES(:theme, NULL, NULL)");
  1955. $query->bindValue(':theme', $theme_name);
  1956. $query->execute() or error(db_error($query));
  1957. // Clean cache
  1958. Cache::delete("themes");
  1959. Cache::delete("theme_settings_".$theme_name);
  1960. $result = true;
  1961. $message = false;
  1962. if (isset($theme['install_callback'])) {
  1963. $ret = $theme['install_callback'](themeSettings($theme_name));
  1964. if ($ret && !empty($ret)) {
  1965. if (is_array($ret) && count($ret) == 2) {
  1966. $result = $ret[0];
  1967. $message = $ret[1];
  1968. }
  1969. }
  1970. }
  1971. if (!$result) {
  1972. // Install failed
  1973. $query = prepare("DELETE FROM ``theme_settings`` WHERE `theme` = :theme");
  1974. $query->bindValue(':theme', $theme_name);
  1975. $query->execute() or error(db_error($query));
  1976. }
  1977. // Build themes
  1978. rebuildThemes('all');
  1979. mod_page(sprintf(_($result ? 'Installed theme: %s' : 'Installation failed: %s'), $theme['name']), 'mod/theme_installed.html', array(
  1980. 'theme_name' => $theme_name,
  1981. 'theme' => $theme,
  1982. 'result' => $result,
  1983. 'message' => $message
  1984. ));
  1985. return;
  1986. }
  1987. $settings = themeSettings($theme_name);
  1988. mod_page(sprintf(_('Configuring theme: %s'), $theme['name']), 'mod/theme_config.html', array(
  1989. 'theme_name' => $theme_name,
  1990. 'theme' => $theme,
  1991. 'settings' => $settings,
  1992. 'token' => make_secure_link_token('themes/' . $theme_name)
  1993. ));
  1994. }
  1995. function mod_theme_uninstall($theme_name) {
  1996. global $config;
  1997. if (!hasPermission($config['mod']['themes']))
  1998. error($config['error']['noaccess']);
  1999. $query = prepare("DELETE FROM ``theme_settings`` WHERE `theme` = :theme");
  2000. $query->bindValue(':theme', $theme_name);
  2001. $query->execute() or error(db_error($query));
  2002. // Clean cache
  2003. Cache::delete("themes");
  2004. Cache::delete("theme_settings_".$theme);
  2005. header('Location: ?/themes', true, $config['redirect_http']);
  2006. }
  2007. function mod_theme_rebuild($theme_name) {
  2008. global $config;
  2009. if (!hasPermission($config['mod']['themes']))
  2010. error($config['error']['noaccess']);
  2011. rebuildTheme($theme_name, 'all');
  2012. mod_page(sprintf(_('Rebuilt theme: %s'), $theme_name), 'mod/theme_rebuilt.html', array(
  2013. 'theme_name' => $theme_name,
  2014. ));
  2015. }
  2016. function mod_debug_antispam() {
  2017. global $pdo, $config;
  2018. $args = array();
  2019. if (isset($_POST['board'], $_POST['thread'])) {
  2020. $where = '`board` = ' . $pdo->quote($_POST['board']);
  2021. if ($_POST['thread'] != '')
  2022. $where .= ' AND `thread` = ' . $pdo->quote($_POST['thread']);
  2023. if (isset($_POST['purge'])) {
  2024. $query = prepare(', DATE ``antispam`` SET `expires` = UNIX_TIMESTAMP() + :expires WHERE' . $where);
  2025. $query->bindValue(':expires', $config['spam']['hidden_inputs_expire']);
  2026. $query->execute() or error(db_error());
  2027. }
  2028. $args['board'] = $_POST['board'];
  2029. $args['thread'] = $_POST['thread'];
  2030. } else {
  2031. $where = '';
  2032. }
  2033. $query = query('SELECT COUNT(*) FROM ``antispam``' . ($where ? " WHERE $where" : '')) or error(db_error());
  2034. $args['total'] = number_format($query->fetchColumn());
  2035. $query = query('SELECT COUNT(*) FROM ``antispam`` WHERE `expires` IS NOT NULL' . ($where ? " AND $where" : '')) or error(db_error());
  2036. $args['expiring'] = number_format($query->fetchColumn());
  2037. $query = query('SELECT * FROM ``antispam`` ' . ($where ? "WHERE $where" : '') . ' ORDER BY `passed` DESC LIMIT 40') or error(db_error());
  2038. $args['top'] = $query->fetchAll(PDO::FETCH_ASSOC);
  2039. $query = query('SELECT * FROM ``antispam`` ' . ($where ? "WHERE $where" : '') . ' ORDER BY `created` DESC LIMIT 20') or error(db_error());
  2040. $args['recent'] = $query->fetchAll(PDO::FETCH_ASSOC);
  2041. mod_page(_('Debug: Anti-spam'), 'mod/debug/antispam.html', $args);
  2042. }
  2043. function mod_debug_recent_posts() {
  2044. global $pdo, $config;
  2045. $limit = 500;
  2046. $boards = listBoards();
  2047. // Manually build an SQL query
  2048. $query = 'SELECT * FROM (';
  2049. foreach ($boards as $board) {
  2050. $query .= sprintf('SELECT *, %s AS `board` FROM ``posts_%s`` UNION ALL ', $pdo->quote($board['uri']), $board['uri']);
  2051. }
  2052. // Remove the last "UNION ALL" seperator and complete the query
  2053. $query = preg_replace('/UNION ALL $/', ') AS `all_posts` ORDER BY `time` DESC LIMIT ' . $limit, $query);
  2054. $query = query($query) or error(db_error());
  2055. $posts = $query->fetchAll(PDO::FETCH_ASSOC);
  2056. // Fetch recent posts from flood prevention cache
  2057. $query = query("SELECT * FROM ``flood`` ORDER BY `time` DESC") or error(db_error());
  2058. $flood_posts = $query->fetchAll(PDO::FETCH_ASSOC);
  2059. foreach ($posts as &$post) {
  2060. $post['snippet'] = pm_snippet($post['body']);
  2061. foreach ($flood_posts as $flood_post) {
  2062. if ($flood_post['time'] == $post['time'] &&
  2063. $flood_post['posthash'] == make_comment_hex($post['body_nomarkup']) &&
  2064. $flood_post['filehash'] == $post['filehash'])
  2065. $post['in_flood_table'] = true;
  2066. }
  2067. }
  2068. mod_page(_('Debug: Recent posts'), 'mod/debug/recent_posts.html', array('posts' => $posts, 'flood_posts' => $flood_posts));
  2069. }
  2070. function mod_debug_sql() {
  2071. global $config;
  2072. if (!hasPermission($config['mod']['debug_sql']))
  2073. error($config['error']['noaccess']);
  2074. $args['security_token'] = make_secure_link_token('debug/sql');
  2075. if (isset($_POST['query'])) {
  2076. $args['query'] = $_POST['query'];
  2077. if ($query = query($_POST['query'])) {
  2078. $args['result'] = $query->fetchAll(PDO::FETCH_ASSOC);
  2079. if (!empty($args['result']))
  2080. $args['keys'] = array_keys($args['result'][0]);
  2081. else
  2082. $args['result'] = 'empty';
  2083. } else {
  2084. $args['error'] = db_error();
  2085. }
  2086. }
  2087. mod_page(_('Debug: SQL'), 'mod/debug/sql.html', $args);
  2088. }
  2089. function mod_debug_apc() {
  2090. global $config;
  2091. if (!hasPermission($config['mod']['debug_apc']))
  2092. error($config['error']['noaccess']);
  2093. if ($config['cache']['enabled'] != 'apc')
  2094. error('APC is not enabled.');
  2095. $cache_info = apc_cache_info('user');
  2096. // $cached_vars = new APCIterator('user', '/^' . $config['cache']['prefix'] . '/');
  2097. $cached_vars = array();
  2098. foreach ($cache_info['cache_list'] as $var) {
  2099. if ($config['cache']['prefix'] != '' && strpos(isset($var['key']) ? $var['key'] : $var['info'], $config['cache']['prefix']) !== 0)
  2100. continue;
  2101. $cached_vars[] = $var;
  2102. }
  2103. mod_page(_('Debug: APC'), 'mod/debug/apc.html', array('cached_vars' => $cached_vars));
  2104. }