Advertisement
Guest User

Untitled

a guest
May 9th, 2012
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 51.15 KB | None | 0 0
  1. <?php
  2. if($_SERVER['SCRIPT_FILENAME'] == str_replace('\\', '/', __FILE__)) {
  3. // You cannot request this file directly.
  4. header('Location: ../', true, 302);
  5. exit;
  6. }
  7.  
  8. register_shutdown_function('fatal_error_handler');
  9. loadConfig();
  10.  
  11. function loadConfig() {
  12. global $board, $config, $__ip, $debug;
  13.  
  14. require 'config.php';
  15. if (file_exists('inc/instance-config.php')) {
  16. require 'inc/instance-config.php';
  17. }
  18. if(isset($board['dir']) && file_exists($board['dir'] . '/config.php')) {
  19. require $board['dir'] . '/config.php';
  20. }
  21.  
  22. if($config['debug']) {
  23. if(!isset($debug)) {
  24. $debug = Array('sql' => Array(), 'purge' => Array(), 'memcached' => Array());
  25. $debug['start'] = microtime(true);
  26. }
  27. }
  28.  
  29. date_default_timezone_set($config['timezone']);
  30.  
  31. if(!isset($config['post_url']))
  32. $config['post_url'] = $config['root'] . $config['file_post'];
  33.  
  34. if(!isset($config['referer_match']))
  35. $config['referer_match'] = '/^' .
  36. (preg_match($config['url_regex'], $config['root']) ? '' :
  37. (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http') .
  38. ':\/\/'.$_SERVER['HTTP_HOST']) .
  39. preg_quote($config['root'], '/') .
  40. '(' .
  41. str_replace('%s', '\w+', preg_quote($config['board_path'], '/')) .
  42. '(' . preg_quote($config['file_index'], '/') . ')?' .
  43. '|' .
  44. str_replace('%s', '\w+', preg_quote($config['board_path'], '/')) .
  45. preg_quote($config['dir']['res'], '/') .
  46. str_replace('%d', '\d+', preg_quote($config['file_page'], '/')) .
  47. '|' .
  48. preg_quote($config['file_mod'], '/') . '\?\/.+' .
  49. ')$/i';
  50.  
  51. if(!isset($config['cookies']['path']))
  52. $config['cookies']['path'] = &$config['root'];
  53.  
  54. if(!isset($config['dir']['static']))
  55. $config['dir']['static'] = $config['root'] . 'static/';
  56.  
  57. if(!isset($config['image_sticky']))
  58. $config['image_sticky'] = $config['dir']['static'] . 'sticky.gif';
  59. if(!isset($config['image_locked']))
  60. $config['image_locked'] = $config['dir']['static'] . 'locked.gif';
  61. if(!isset($config['image_deleted']))
  62. $config['image_deleted'] = $config['dir']['static'] . 'deleted.png';
  63. if(!isset($config['image_zip']))
  64. $config['image_zip'] = $config['dir']['static'] . 'zip.png';
  65.  
  66. if(!isset($config['uri_thumb']))
  67. $config['uri_thumb'] = $config['root'] . $board['dir'] . $config['dir']['thumb'];
  68. else
  69. $config['uri_thumb'] = sprintf($config['uri_thumb'], $board['dir']);
  70.  
  71. if(!isset($config['uri_img']))
  72. $config['uri_img'] = $config['root'] . $board['dir'] . $config['dir']['img'];
  73. else
  74. $config['uri_img'] = sprintf($config['uri_img'], $board['dir']);
  75.  
  76. if(!isset($config['uri_stylesheets']))
  77. $config['uri_stylesheets'] = $config['root'] . 'stylesheets/';
  78.  
  79. if(!isset($config['url_stylesheet']))
  80. $config['url_stylesheet'] = $config['uri_stylesheets'] . 'style.css';
  81. if(!isset($config['url_javascript']))
  82. $config['url_javascript'] = $config['root'] . 'main.js';
  83.  
  84. if($config['root_file']) {
  85. chdir($config['root_file']);
  86. }
  87.  
  88. if($config['verbose_errors']) {
  89. error_reporting(E_ALL);
  90. ini_set('display_errors', 1);
  91. }
  92.  
  93. if($config['ipv6_ipv4'] && isset($_SERVER['REMOTE_ADDR'])) {
  94. // Keep the original address to properly comply with other board configurations
  95. if(!isset($__ip))
  96. $__ip = &$_SERVER['REMOTE_ADDR'];
  97.  
  98. // ::ffff:0.0.0.0
  99. if(preg_match('/^\:\:(ffff\:)?(\d+\.\d+\.\d+\.\d+)$/', $__ip, $m))
  100. $_SERVER['REMOTE_ADDR'] = $m[2];
  101. }
  102.  
  103. if($config['recaptcha'])
  104. require_once 'inc/contrib/recaptcha/recaptchalib.php';
  105. if($config['memcached']['enabled'])
  106. memcached_open();
  107. }
  108.  
  109. function basic_error_function_because_the_other_isnt_loaded_yet($message) {
  110. if(function_exists('sql_close')) sql_close();
  111. // Yes, this is horrible.
  112. die('<!DOCTYPE html><html><head><title>Error</title>' .
  113. '<style type="text/css">' .
  114. 'body{text-align:center;font-family:arial, helvetica, sans-serif;font-size:10pt;}' .
  115. 'p{padding:0;margin:20px 0;}' .
  116. 'p.c{font-size:11px;}' .
  117. '</style></head>' .
  118. '<body><h2>Error</h2>' . $message . '<hr/>' .
  119. '<p class="c">This alternative error page is being displayed because the other couldn\'t be found or hasn\'t loaded yet.</p></body></html>');
  120. }
  121.  
  122. function fatal_error_handler() {
  123. if($error = error_get_last()) {
  124. if($error['type'] == E_ERROR) {
  125. if(function_exists('error')) {
  126. error('Caught fatal error: ' . $error['message'] . ' in <strong>' . $error['file'] . '</strong> on line ' . $error['line']);
  127. } else {
  128. basic_error_function_because_the_other_isnt_loaded_yet('Caught fatal error: ' . $error['message'] . ' in ' . $error['file'] . ' on line ' . $error['line']);
  129. }
  130. }
  131. }
  132. }
  133.  
  134. // Memcached
  135. function memcached_open() {
  136. global $memcached, $config;
  137. if($memcached) return;
  138.  
  139. $memcached = new Memcached();
  140. $memcached->addServers($config['memcached']['servers']);
  141. }
  142.  
  143. function loadThemeConfig($_theme) {
  144. global $config;
  145.  
  146. if(!file_exists($config['dir']['themes'] . '/' . $_theme . '/info.php'))
  147. return false;
  148.  
  149. // Load theme information into $theme
  150. include $config['dir']['themes'] . '/' . $_theme . '/info.php';
  151. return $theme;
  152. }
  153.  
  154. function rebuildTheme($theme, $action) {
  155. global $config, $_theme;
  156. $_theme = $theme;
  157.  
  158. $theme = loadThemeConfig($_theme);
  159.  
  160. if(file_exists($config['dir']['themes'] . '/' . $_theme . '/theme.php')) {
  161. require_once $config['dir']['themes'] . '/' . $_theme . '/theme.php';
  162. $theme['build_function']($action, themeSettings($_theme));
  163. }
  164. }
  165.  
  166. function rebuildThemes($action) {
  167. global $config, $_theme;
  168.  
  169. // List themes
  170. $query = query("SELECT `theme` FROM `theme_settings` WHERE `name` IS NULL AND `value` IS NULL") or error(db_error());
  171. while($theme = $query->fetch()) {
  172. rebuildTheme($theme['theme'], $action);
  173. }
  174. }
  175.  
  176. function themeSettings($theme) {
  177. $query = prepare("SELECT `name`, `value` FROM `theme_settings` WHERE `theme` = :theme AND `name` IS NOT NULL");
  178. $query->bindValue(':theme', $theme);
  179. $query->execute() or error(db_error($query));
  180.  
  181. $settings = Array();
  182. while($s = $query->fetch()) {
  183. $settings[$s['name']] = $s['value'];
  184. }
  185.  
  186. return $settings;
  187. }
  188.  
  189. function sprintf3($str, $vars, $delim = '%') {
  190. $replaces = array();
  191. foreach($vars as $k => $v) {
  192. $replaces[$delim . $k . $delim] = $v;
  193. }
  194. return str_replace(array_keys($replaces),
  195. array_values($replaces), $str);
  196. }
  197.  
  198. function setupBoard($array) {
  199. global $board, $config;
  200.  
  201. $board = Array(
  202. 'id' => $array['id'],
  203. 'uri' => $array['uri'],
  204. 'name' => $array['title'],
  205. 'title' => $array['subtitle']);
  206.  
  207. $board['dir'] = sprintf($config['board_path'], $board['uri']);
  208. $board['url'] = sprintf($config['board_abbreviation'], $board['uri']);
  209.  
  210. loadConfig();
  211.  
  212. if(!file_exists($board['dir'])) mkdir($board['dir'], 0777);
  213. if(!file_exists($board['dir'] . $config['dir']['img'])) @mkdir($board['dir'] . $config['dir']['img'], 0777) or error("Couldn't create " . $config['dir']['img'] . ". Check permissions.", true);
  214. if(!file_exists($board['dir'] . $config['dir']['thumb'])) @mkdir($board['dir'] . $config['dir']['thumb'], 0777) or error("Couldn't create " . $config['dir']['thumb'] . ". Check permissions.", true);
  215. if(!file_exists($board['dir'] . $config['dir']['res'])) @mkdir($board['dir'] . $config['dir']['res'], 0777) or error("Couldn't create " . $config['dir']['res'] . ". Check permissions.", true);
  216. }
  217.  
  218. function openBoard($uri) {
  219. $query = prepare("SELECT * FROM `boards` WHERE `uri` = :uri LIMIT 1");
  220. $query->bindValue(':uri', $uri);
  221. $query->execute() or error(db_error($query));
  222.  
  223. if($board = $query->fetch()) {
  224. setupBoard($board);
  225. return true;
  226. } else return false;
  227. }
  228.  
  229. function boardTitle($uri) {
  230. $query = prepare("SELECT `title` FROM `boards` WHERE `uri` = :uri LIMIT 1");
  231. $query->bindValue(':uri', $uri);
  232. $query->execute() or error(db_error($query));
  233.  
  234. if($title = $query->fetch()) {
  235. return $title['title'];
  236. } else return false;
  237. }
  238.  
  239. function purge($uri) {
  240. global $config, $debug;
  241. if(preg_match($config['referer_match'], $config['root'])) {
  242. $uri = (str_replace('\\', '/', dirname($_SERVER['REQUEST_URI'])) == '/' ? '/' : str_replace('\\', '/', dirname($_SERVER['REQUEST_URI'])) . '/') . $uri;
  243. } else {
  244. $uri = $config['root'] . $uri;
  245. }
  246.  
  247. if($config['debug']) {
  248. $debug['purge'][] = $uri;
  249. }
  250.  
  251. foreach($config['purge'] as &$purge) {
  252. $host = &$purge[0];
  253. $port = &$purge[1];
  254. $http_host = isset($purge[2]) ? $purge[2] : $_SERVER['HTTP_HOST'];
  255. $request = "PURGE {$uri} HTTP/1.0\r\nHost: {$http_host}\r\nUser-Agent: Tinyboard\r\nConnection: Close\r\n\r\n";
  256. if($fp = fsockopen($host, $port, $errno, $errstr, $config['purge_timeout'])) {
  257. fwrite($fp, $request);
  258. fclose($fp);
  259. } else {
  260. // Cannot connect?
  261. error('Could not PURGE for ' . $host);
  262. }
  263. }
  264. }
  265.  
  266. function file_write($path, $data, $simple = false, $skip_purge = false) {
  267. global $config;
  268.  
  269. if(preg_match('/^remote:\/\/(.+)\:(.+)$/', $path, $m)) {
  270. if(isset($config['remote'][$m[1]])) {
  271. require_once 'inc/remote.php';
  272.  
  273. $remote = new Remote($config['remote'][$m[1]]);
  274. $remote->write($data, $m[2]);
  275. return;
  276. } else {
  277. error('Invalid remote server: ' . $m[1]);
  278. }
  279. }
  280.  
  281. if(!$fp = fopen($path, $simple ? 'w' : 'c'))
  282. error('Unable to open file for writing: ' . $path);
  283.  
  284. // File locking
  285. if(!$simple && !flock($fp, LOCK_EX)) {
  286. error('Unable to lock file: ' . $path);
  287. }
  288.  
  289. // Truncate file
  290. if(!$simple && !ftruncate($fp, 0))
  291. error('Unable to truncate file: ' . $path);
  292.  
  293. // Write data
  294. if(fwrite($fp, $data) === false)
  295. error('Unable to write to file: ' . $path);
  296.  
  297. // Unlock
  298. if(!$simple)
  299. flock($fp, LOCK_UN);
  300.  
  301. // Close
  302. if(!fclose($fp))
  303. error('Unable to close file: ' . $path);
  304.  
  305. if(!$skip_purge && isset($config['purge']) && isset($_SERVER['HTTP_HOST'])) {
  306. // Purge cache
  307. if(basename($path) == $config['file_index']) {
  308. // Index file (/index.html); purge "/" as well
  309. $uri = dirname($path);
  310. // root
  311. if($uri == '.')
  312. $uri = '';
  313. else
  314. $uri .= '/';
  315. purge($uri);
  316. }
  317. purge($path);
  318. }
  319. }
  320.  
  321. function file_unlink($path) {
  322. global $config, $debug;
  323.  
  324. if($config['debug']) {
  325. if(!isset($debug['unlink']))
  326. $debug['unlink'] = Array();
  327. $debug['unlink'][] = $path;
  328. }
  329.  
  330. $ret = @unlink($path);
  331. if(isset($config['purge']) && isset($_SERVER['HTTP_HOST'])) {
  332. // Purge cache
  333. if(basename($path) == $config['file_index']) {
  334. // Index file (/index.html); purge "/" as well
  335. $uri = dirname($path);
  336. // root
  337. if($uri == '.')
  338. $uri = '';
  339. else
  340. $uri .= '/';
  341. purge($uri);
  342. }
  343. purge($path);
  344. }
  345. return $ret;
  346. }
  347.  
  348. function listBoards() {
  349. $query = query("SELECT * FROM `boards` ORDER BY `uri`") or error(db_error());
  350. $boards = $query->fetchAll();
  351. return $boards;
  352. }
  353.  
  354. function checkFlood($post) {
  355. global $board, $config;
  356.  
  357. $query = prepare(sprintf("SELECT * FROM `posts_%s` WHERE (`ip` = :ip AND `time` >= :floodtime) OR (`ip` = :ip AND `body` = :body AND `time` >= :floodsameiptime) OR (`body` = :body AND `time` >= :floodsametime) LIMIT 1", $board['uri']));
  358. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
  359. $query->bindValue(':body', $post['body'], PDO::PARAM_INT);
  360. $query->bindValue(':floodtime', time()-$config['flood_time'], PDO::PARAM_INT);
  361. $query->bindValue(':floodsameiptime', time()-$config['flood_time_ip'], PDO::PARAM_INT);
  362. $query->bindValue(':floodsametime', time()-$config['flood_time_same'], PDO::PARAM_INT);
  363. $query->execute() or error(db_error($query));
  364.  
  365. return (bool)$query->fetch();
  366. }
  367.  
  368. function until($timestamp) {
  369. $difference = $timestamp - time();
  370. if($difference < 60) {
  371. return $difference . ' second' . ($difference != 1 ? 's' : '');
  372. } elseif($difference < 60*60) {
  373. return ($num = round($difference/(60))) . ' minute' . ($num != 1 ? 's' : '');
  374. } elseif($difference < 60*60*24) {
  375. return ($num = round($difference/(60*60))) . ' hour' . ($num != 1 ? 's' : '');
  376. } elseif($difference < 60*60*24*7) {
  377. return ($num = round($difference/(60*60*24))) . ' day' . ($num != 1 ? 's' : '');
  378. } elseif($difference < 60*60*24*365) {
  379. return ($num = round($difference/(60*60*24*7))) . ' week' . ($num != 1 ? 's' : '');
  380. } else {
  381. return ($num = round($difference/(60*60*24*365))) . ' year' . ($num != 1 ? 's' : '');
  382. }
  383. }
  384.  
  385. function ago($timestamp) {
  386. $difference = time() - $timestamp;
  387. if($difference < 60) {
  388. return $difference . ' second' . ($difference != 1 ? 's' : '');
  389. } elseif($difference < 60*60) {
  390. return ($num = round($difference/(60))) . ' minute' . ($num != 1 ? 's' : '');
  391. } elseif($difference < 60*60*24) {
  392. return ($num = round($difference/(60*60))) . ' hour' . ($num != 1 ? 's' : '');
  393. } elseif($difference < 60*60*24*7) {
  394. return ($num = round($difference/(60*60*24))) . ' day' . ($num != 1 ? 's' : '');
  395. } elseif($difference < 60*60*24*365) {
  396. return ($num = round($difference/(60*60*24*7))) . ' week' . ($num != 1 ? 's' : '');
  397. } else {
  398. return ($num = round($difference/(60*60*24*365))) . ' year' . ($num != 1 ? 's' : '');
  399. }
  400. }
  401.  
  402. function formatDate($timestamp) {
  403. return date('jS F, Y', $timestamp);
  404. }
  405.  
  406. function displayBan($ban) {
  407. global $config;
  408.  
  409. $body = '<div class="ban">
  410. <h2>You are banned! ;_;</h2>
  411. <p>You have been banned from ' .
  412. (!isset($ban['uri']) ?
  413. 'all boards':
  414. '<strong>' . sprintf($config['board_abbreviation'], $ban['uri']) . '</strong>'
  415. ) .
  416. ' ' .
  417. ($ban['reason'] ? 'for the following reason:' : 'for an unspecified reason.') .
  418. '</p>' .
  419. ($ban['reason'] ?
  420. '<p class="reason">' .
  421. $ban['reason'] .
  422. '</p>'
  423. : '') .
  424. '<p>Your ban was filed on <strong>' .
  425. formatDate($ban['set']) .
  426. '</strong>, and <span id="expires">' .
  427. ($ban['expires'] ?
  428. 'expires <span id="countdown">' . until($ban['expires']) . '</span> from now, which is on <strong>' .
  429. formatDate($ban['expires']) .
  430. '</strong>
  431. <script>
  432. // return date("jS F, Y", $timestamp);
  433. var secondsLeft = ' . ($ban['expires'] - time()) . '
  434. var end = new Date().getTime() + secondsLeft*1000;
  435. function updateExpiresTime() {
  436. countdown.firstChild.nodeValue = until(end);
  437. }
  438. function until(end) {
  439. var now = new Date().getTime();
  440. var diff = Math.round((end - now) / 1000); // in seconds
  441. if (diff < 0) {
  442. document.getElementById("expires").innerHTML = "has since expired. Refresh the page to continue.";
  443. //location.reload(true);
  444. clearInterval(int);
  445. return "";
  446. } else if (diff < 60) {
  447. return diff + " second" + (diff == 1 ? "" : "s");
  448. } else if (diff < 60*60) {
  449. return (num = Math.round(diff/(60))) + " minute" + (num == 1 ? "" : "s");
  450. } else if (diff < 60*60*24) {
  451. return (num = Math.round(diff/(60*60))) + " hour" + (num == 1 ? "" : "s");
  452. } else if (diff < 60*60*24*7) {
  453. return (num = Math.round(diff/(60*60*24))) + " day" + (num == 1 ? "" : "s");
  454. } else if (diff < 60*60*24*365) {
  455. return (num = Math.round(diff/(60*60*24*7))) + " week" + (num == 1 ? "" : "s");
  456. } else {
  457. return (num = Math.round(diff/(60*60*24*365))) + " year" + (num == 1 ? "" : "s");
  458. }
  459. }
  460. var countdown = document.getElementById("countdown");
  461.  
  462. updateExpiresTime();
  463. var int = setInterval(updateExpiresTime, 1000);
  464. </script>'
  465. : '<em>will not expire</em>.' ) .
  466. '</span></p>
  467. <p>Your IP address is <strong>' . $_SERVER['REMOTE_ADDR'] . '</strong>.</p>
  468. </div>';
  469.  
  470. // Show banned page and exit
  471. die(Element('page.html', Array(
  472. 'config' => $config,
  473. 'title' => 'Banned',
  474. 'subtitle' => 'You are banned!',
  475. 'body' => $body
  476. )
  477. ));
  478. }
  479.  
  480. function checkBan($board = 0) {
  481. global $config, $memcached;
  482.  
  483. if(!isset($_SERVER['REMOTE_ADDR'])) {
  484. // Server misconfiguration
  485. return;
  486. }
  487.  
  488.  
  489. $query = prepare("SELECT `set`, `expires`, `reason`, `board`, `uri`, `bans`.`id` FROM `bans` LEFT JOIN `boards` ON `boards`.`id` = `board` WHERE (`board` IS NULL OR `uri` = :board) AND `ip` = :ip ORDER BY `expires` IS NULL DESC, `expires` DESC, `expires` DESC LIMIT 1");
  490. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
  491. $query->bindValue(':board', $board);
  492. $query->execute() or error(db_error($query));
  493. if($query->rowCount() < 1 && $config['ban_range']) {
  494. $query = prepare("SELECT `set`, `expires`, `reason`, `board`, `uri` FROM `bans` LEFT JOIN `boards` ON `boards`.`id` = `board` WHERE (`board` IS NULL OR `uri` = :board) AND :ip REGEXP CONCAT('^', REPLACE(REPLACE(`ip`, '.', '\\.'), '*', '[0-9]*'), '$') ORDER BY `expires` IS NULL DESC, `expires` DESC LIMIT 1");
  495. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
  496. $query->bindValue(':board', $board);
  497. $query->execute() or error(db_error($query));
  498. }
  499.  
  500. if($ban = $query->fetch()) {
  501. if($ban['expires'] && $ban['expires'] < time()) {
  502. // Ban expired
  503. $query = prepare("DELETE FROM `bans` WHERE `id` = :id LIMIT 1");
  504. $query->bindValue(':id', $ban['id'], PDO::PARAM_INT);
  505. $query->execute() or error(db_error($query));
  506.  
  507. return;
  508. }
  509.  
  510. displayBan($ban);
  511. }
  512. }
  513.  
  514. function threadLocked($id) {
  515. global $board;
  516.  
  517. $query = prepare(sprintf("SELECT `locked` FROM `posts_%s` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri']));
  518. $query->bindValue(':id', $id, PDO::PARAM_INT);
  519. $query->execute() or error(db_error());
  520.  
  521. if(!$post = $query->fetch()) {
  522. // Non-existant, so it can't be locked...
  523. return false;
  524. }
  525.  
  526. return (bool) $post['locked'];
  527. }
  528.  
  529. function threadExists($id) {
  530. global $board;
  531.  
  532. $query = prepare(sprintf("SELECT 1 FROM `posts_%s` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri']));
  533. $query->bindValue(':id', $id, PDO::PARAM_INT);
  534. $query->execute() or error(db_error());
  535.  
  536. if($query->rowCount()) {
  537. return true;
  538. } else return false;
  539. }
  540.  
  541. function post($post, $OP) {
  542. global $pdo, $board;
  543. $query = prepare(sprintf("INSERT INTO `posts_%s` VALUES ( NULL, :thread, :subject, :email, :name, :trip, :capcode, :body, :time, :time, :thumb, :thumbwidth, :thumbheight, :file, :width, :height, :filesize, :filename, :filehash, :password, :ip, :sticky, :locked, :embed)", $board['uri']));
  544.  
  545. // Basic stuff
  546. $query->bindValue(':subject', $post['subject']);
  547. $query->bindValue(':email', $post['email']);
  548. $query->bindValue(':name', $post['name']);
  549. $query->bindValue(':trip', $post['trip']);
  550. $query->bindValue(':body', $post['body']);
  551. $query->bindValue(':time', time(), PDO::PARAM_INT);
  552. $query->bindValue(':password', $post['password']);
  553. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
  554.  
  555. if($post['mod'] && $post['sticky']) {
  556. $query->bindValue(':sticky', 1, PDO::PARAM_INT);
  557. } else {
  558. $query->bindValue(':sticky', 0, PDO::PARAM_INT);
  559. }
  560.  
  561. if($post['mod'] && $post['locked']) {
  562. $query->bindValue(':locked', 1, PDO::PARAM_INT);
  563. } else {
  564. $query->bindValue(':locked', 0, PDO::PARAM_INT);
  565. }
  566.  
  567. if($post['mod'] && isset($post['capcode']) && $post['capcode']) {
  568. $query->bindValue(':capcode', $post['capcode'], PDO::PARAM_INT);
  569. } else {
  570. $query->bindValue(':capcode', NULL, PDO::PARAM_NULL);
  571. }
  572.  
  573. if(!empty($post['embed'])) {
  574. $query->bindValue(':embed', $post['embed']);
  575. } else {
  576. $query->bindValue(':embed', NULL, PDO::PARAM_NULL);
  577. }
  578.  
  579. if($OP) {
  580. // No parent thread, image
  581. $query->bindValue(':thread', null, PDO::PARAM_NULL);
  582. } else {
  583. $query->bindValue(':thread', $post['thread'], PDO::PARAM_INT);
  584. }
  585.  
  586. if($post['has_file']) {
  587. $query->bindValue(':thumb', $post['thumb']);
  588. $query->bindValue(':thumbwidth', $post['thumbwidth'], PDO::PARAM_INT);
  589. $query->bindValue(':thumbheight', $post['thumbheight'], PDO::PARAM_INT);
  590. $query->bindValue(':file', $post['file']);
  591. $query->bindValue(':width', $post['width'], PDO::PARAM_INT);
  592. $query->bindValue(':height', $post['height'], PDO::PARAM_INT);
  593. $query->bindValue(':filesize', $post['filesize'], PDO::PARAM_INT);
  594. $query->bindValue(':filename', $post['filename']);
  595. $query->bindValue(':filehash', $post['filehash']);
  596. } else {
  597. $query->bindValue(':thumb', null, PDO::PARAM_NULL);
  598. $query->bindValue(':thumbwidth', null, PDO::PARAM_NULL);
  599. $query->bindValue(':thumbheight', null, PDO::PARAM_NULL);
  600. $query->bindValue(':file', null, PDO::PARAM_NULL);
  601. $query->bindValue(':width', null, PDO::PARAM_NULL);
  602. $query->bindValue(':height', null, PDO::PARAM_NULL);
  603. $query->bindValue(':filesize', null, PDO::PARAM_NULL);
  604. $query->bindValue(':filename', null, PDO::PARAM_NULL);
  605. $query->bindValue(':filehash', null, PDO::PARAM_NULL);
  606. }
  607.  
  608. $query->execute() or error(db_error($query));
  609.  
  610. return $pdo->lastInsertId();
  611. }
  612.  
  613. function bumpThread($id) {
  614. global $board;
  615. $query = prepare(sprintf("UPDATE `posts_%s` SET `bump` = :time WHERE `id` = :id AND `thread` IS NULL", $board['uri']));
  616. $query->bindValue(':time', time(), PDO::PARAM_INT);
  617. $query->bindValue(':id', $id, PDO::PARAM_INT);
  618. $query->execute() or error(db_error($query));
  619. }
  620.  
  621. // Remove file from post
  622. function deleteFile($id, $remove_entirely_if_already=true) {
  623. global $board, $config;
  624.  
  625. $query = prepare(sprintf("SELECT `thread`,`thumb`,`file` FROM `posts_%s` WHERE `id` = :id LIMIT 1", $board['uri']));
  626. $query->bindValue(':id', $id, PDO::PARAM_INT);
  627. $query->execute() or error(db_error($query));
  628.  
  629. if($query->rowCount() < 1) {
  630. error($config['error']['invalidpost']);
  631. }
  632.  
  633. $post = $query->fetch();
  634.  
  635. if($post['file'] == 'deleted' && !$post['thread'])
  636. return; // Can't delete OP's image completely.
  637.  
  638. $query = prepare(sprintf("UPDATE `posts_%s` SET `thumb` = NULL, `thumbwidth` = NULL, `thumbheight` = NULL, `filewidth` = NULL, `fileheight` = NULL, `filesize` = NULL, `filename` = NULL, `filehash` = NULL, `file` = :file WHERE `id` = :id", $board['uri']));
  639. if($post['file'] == 'deleted' && $remove_entirely_if_already) {
  640. // Already deleted; remove file fully
  641. $query->bindValue(':file', null, PDO::PARAM_NULL);
  642. } else {
  643. // Delete thumbnail
  644. file_unlink($board['dir'] . $config['dir']['thumb'] . $post['thumb']);
  645.  
  646. // Delete file
  647. file_unlink($board['dir'] . $config['dir']['img'] . $post['file']);
  648.  
  649. // Set file to 'deleted'
  650. $query->bindValue(':file', 'deleted', PDO::PARAM_INT);
  651. }
  652. // Update database
  653.  
  654. $query->bindValue(':id', $id, PDO::PARAM_INT);
  655. $query->execute() or error(db_error($query));
  656.  
  657. if($post['thread'])
  658. buildThread($post['thread']);
  659. }
  660.  
  661. // Delete a post (reply or thread)
  662. function deletePost($id, $error_if_doesnt_exist=true) {
  663. global $board, $config;
  664.  
  665. // Select post and replies (if thread) in one query
  666. $query = prepare(sprintf("SELECT `id`,`thread`,`thumb`,`file` FROM `posts_%s` WHERE `id` = :id OR `thread` = :id", $board['uri']));
  667. $query->bindValue(':id', $id, PDO::PARAM_INT);
  668. $query->execute() or error(db_error($query));
  669.  
  670. if($query->rowCount() < 1) {
  671. if($error_if_doesnt_exist)
  672. error($config['error']['invalidpost']);
  673. else return false;
  674. }
  675.  
  676. // Delete posts and maybe replies
  677. while($post = $query->fetch()) {
  678. if(!$post['thread']) {
  679. // Delete thread HTML page
  680. file_unlink($board['dir'] . $config['dir']['res'] . sprintf($config['file_page'], $post['id']));
  681. } elseif($query->rowCount() == 1) {
  682. // Rebuild thread
  683. $rebuild = &$post['thread'];
  684. }
  685. if($post['thumb']) {
  686. // Delete thumbnail
  687. file_unlink($board['dir'] . $config['dir']['thumb'] . $post['thumb']);
  688. }
  689. if($post['file']) {
  690. // Delete file
  691. file_unlink($board['dir'] . $config['dir']['img'] . $post['file']);
  692. }
  693. }
  694.  
  695. $query = prepare(sprintf("DELETE FROM `posts_%s` WHERE `id` = :id OR `thread` = :id", $board['uri']));
  696. $query->bindValue(':id', $id, PDO::PARAM_INT);
  697. $query->execute() or error(db_error($query));
  698.  
  699. if(isset($rebuild)) {
  700. buildThread($rebuild);
  701. }
  702.  
  703. return true;
  704. }
  705.  
  706. function clean() {
  707. global $board, $config;
  708. $offset = round($config['max_pages']*$config['threads_per_page']);
  709.  
  710. // I too wish there was an easier way of doing this...
  711. $query = prepare(sprintf("SELECT `id` FROM `posts_%s` WHERE `thread` IS NULL ORDER BY `sticky` DESC, `bump` DESC LIMIT :offset, 9001", $board['uri']));
  712. $query->bindValue(':offset', $offset, PDO::PARAM_INT);
  713.  
  714. $query->execute() or error(db_error($query));
  715. while($post = $query->fetch()) {
  716. deletePost($post['id']);
  717. }
  718. }
  719.  
  720. function index($page, $mod=false) {
  721. global $board, $config, $memcached, $debug;
  722.  
  723. $body = '';
  724. $offset = round($page*$config['threads_per_page']-$config['threads_per_page']);
  725.  
  726. $query = prepare(sprintf("SELECT * FROM `posts_%s` WHERE `thread` IS NULL ORDER BY `sticky` DESC, `bump` DESC LIMIT :offset,:threads_per_page", $board['uri']));
  727. $query->bindValue(':offset', $offset, PDO::PARAM_INT);
  728. $query->bindValue(':threads_per_page', $config['threads_per_page'], PDO::PARAM_INT);
  729. $query->execute() or error(db_error($query));
  730.  
  731. if($query->rowcount() < 1 && $page > 1) return false;
  732. while($th = $query->fetch()) {
  733. $thread = new Thread($th['id'], $th['subject'], $th['email'], $th['name'], $th['trip'], $th['capcode'], $th['body'], $th['time'], $th['thumb'], $th['thumbwidth'], $th['thumbheight'], $th['file'], $th['filewidth'], $th['fileheight'], $th['filesize'], $th['filename'], $th['ip'], $th['sticky'], $th['locked'], $th['embed'], $mod ? '?/' : $config['root'], $mod);
  734.  
  735. if($config['memcached']['enabled'] && !$mod) {
  736. if($built = $memcached->get("threadindex_{$board['uri']}_{$th['id']}")) {
  737. $body .= $built;
  738. if($config['debug']) {
  739. $debug['memcached'][] = "threadindex_{$board['uri']}_{$th['id']}";
  740. }
  741. continue;
  742. }
  743. }
  744.  
  745. $posts = prepare(sprintf("SELECT * FROM `posts_%s` WHERE `thread` = :id ORDER BY `id` DESC LIMIT :limit", $board['uri']));
  746. $posts->bindValue(':id', $th['id']);
  747. $posts->bindValue(':limit', ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview']), PDO::PARAM_INT);
  748. $posts->execute() or error(db_error($posts));
  749.  
  750. $num_images = 0;
  751. while($po = $posts->fetch()) {
  752. if($po['file'])
  753. $num_images++;
  754.  
  755. $thread->add(new Post($po['id'], $th['id'], $po['subject'], $po['email'], $po['name'], $po['trip'], $po['capcode'], $po['body'], $po['time'], $po['thumb'], $po['thumbwidth'], $po['thumbheight'], $po['file'], $po['filewidth'], $po['fileheight'], $po['filesize'], $po['filename'], $po['ip'], $po['embed'], $mod ? '?/' : $config['root'], $mod));
  756. }
  757.  
  758. if($posts->rowCount() == ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview'])) {
  759. $count = prepare(sprintf("SELECT COUNT(`id`) as `num` FROM `posts_%s` WHERE `thread` = :thread UNION ALL SELECT COUNT(`id`) FROM `posts_%s` WHERE `file` IS NOT NULL AND `thread` = :thread", $board['uri'], $board['uri']));
  760. $count->bindValue(':thread', $th['id'], PDO::PARAM_INT);
  761. $count->execute() or error(db_error($count));
  762.  
  763. $c = $count->fetch();
  764. $thread->omitted = $c['num'] - ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview']);
  765.  
  766. $c = $count->fetch();
  767. $thread->omitted_images = $c['num'] - $num_images;
  768. }
  769.  
  770. $thread->posts = array_reverse($thread->posts);
  771.  
  772. $built = '<div id="thread_' . $thread->id . '">' . $thread->build(true) . '</div>';
  773.  
  774. if($config['memcached']['enabled'] && !$mod) {
  775. $memcached->set("threadindex_{$board['uri']}_{$th['id']}", $built, time() + $config['memcached']['timeout']);
  776. }
  777.  
  778. $body .= $built;
  779. }
  780.  
  781. return Array(
  782. 'board'=>$board,
  783. 'body'=>$body,
  784. 'post_url' => $config['post_url'],
  785. 'config' => $config,
  786. 'boardlist' => createBoardlist($mod)
  787. );
  788. }
  789.  
  790. function getPageButtons($pages, $mod=false) {
  791. global $config, $board;
  792.  
  793. $btn = Array();
  794. $root = ($mod ? '?/' : $config['root']) . $board['dir'];
  795.  
  796. foreach($pages as $num => $page) {
  797. if(isset($page['selected'])) {
  798. // Previous button
  799. if($num == 0) {
  800. // There is no previous page.
  801. $btn['prev'] = 'Previous';
  802. } else {
  803. $loc = ($mod ? '?/' . $board['uri'] . '/' : '') .
  804. ($num == 1 ?
  805. $config['file_index']
  806. :
  807. sprintf($config['file_page'], $num)
  808. );
  809.  
  810. $btn['prev'] = '<form action="' . ($mod ? '' : $root . $loc) . '" method="get">' .
  811. ($mod ?
  812. '<input type="hidden" name="status" value="301" />' .
  813. '<input type="hidden" name="r" value="' . htmlentities($loc) . '" />'
  814. :'') .
  815. '<input type="submit" value="Previous" /></form>';
  816. }
  817.  
  818. if($num == count($pages) - 1) {
  819. // There is no next page.
  820. $btn['next'] = 'Next';
  821. } else {
  822. $loc = ($mod ? '?/' . $board['uri'] . '/' : '') . sprintf($config['file_page'], $num + 2);
  823.  
  824. $btn['next'] = '<form action="' . ($mod ? '' : $root . $loc) . '" method="get">' .
  825. ($mod ?
  826. '<input type="hidden" name="status" value="301" />' .
  827. '<input type="hidden" name="r" value="' . htmlentities($loc) . '" />'
  828. :'') .
  829. '<input type="submit" value="Next" /></form>';
  830. }
  831. }
  832. }
  833.  
  834. return $btn;
  835. }
  836.  
  837. function getPages($mod=false) {
  838. global $board, $config;
  839.  
  840. // Count threads
  841. $query = query(sprintf("SELECT COUNT(`id`) as `num` FROM `posts_%s` WHERE `thread` IS NULL", $board['uri'])) or error(db_error());
  842.  
  843. $count = current($query->fetch());
  844. $count = floor(($config['threads_per_page'] + $count - 1) / $config['threads_per_page']);
  845.  
  846. if($count < 1) $count = 1;
  847.  
  848. $pages = Array();
  849. for($x=0;$x<$count && $x<$config['max_pages'];$x++) {
  850. $pages[] = Array(
  851. 'num' => $x+1,
  852. 'link' => $x==0 ? ($mod ? '?/' : $config['root']) . $board['dir'] . $config['file_index'] : ($mod ? '?/' : $config['root']) . $board['dir'] . sprintf($config['file_page'], $x+1)
  853. );
  854. }
  855.  
  856. return $pages;
  857. }
  858.  
  859. function makerobot($body) {
  860. global $config;
  861. $body = strtolower($body);
  862.  
  863. // Leave only letters
  864. $body = preg_replace('/[^a-z]/i', '', $body);
  865. // Remove repeating characters
  866. if($config['robot_strip_repeating'])
  867. $body = preg_replace('/(.)\\1+/', '$1', $body);
  868.  
  869. return sha1($body);
  870. }
  871.  
  872. function checkRobot($body) {
  873. $body = makerobot($body);
  874. $query = prepare("SELECT 1 FROM `robot` WHERE `hash` = :hash LIMIT 1");
  875. $query->bindValue(':hash', $body);
  876. $query->execute() or error(db_error($query));
  877.  
  878. if($query->fetch()) {
  879. return true;
  880. } else {
  881. // Insert new hash
  882.  
  883. $query = prepare("INSERT INTO `robot` VALUES (:hash)");
  884. $query->bindValue(':hash', $body);
  885. $query->execute() or error(db_error($query));
  886. return false;
  887. }
  888. }
  889.  
  890. function numPosts($id) {
  891. global $board;
  892. $query = prepare(sprintf("SELECT COUNT(*) as `count` FROM `posts_%s` WHERE `thread` = :thread", $board['uri']));
  893. $query->bindValue(':thread', $id, PDO::PARAM_INT);
  894. $query->execute() or error(db_error($query));
  895.  
  896. $result = $query->fetch();
  897. return $result['count'];
  898. }
  899.  
  900. function muteTime() {
  901. global $config;
  902. // Find number of mutes in the past X hours
  903. $query = prepare("SELECT COUNT(*) as `count` FROM `mutes` WHERE `time` >= :time AND `ip` = :ip");
  904. $query->bindValue(':time', time()-($config['robot_mute_hour']*3600), PDO::PARAM_INT);
  905. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
  906. $query->execute() or error(db_error($query));
  907.  
  908. $result = $query->fetch();
  909. if($result['count'] == 0) return 0;
  910. return pow($config['robot_mute_multiplier'], $result['count']);
  911. }
  912.  
  913. function mute() {
  914. // Insert mute
  915. $query = prepare("INSERT INTO `mutes` VALUES (:ip, :time)");
  916. $query->bindValue(':time', time(), PDO::PARAM_INT);
  917. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
  918. $query->execute() or error(db_error($query));
  919.  
  920. return muteTime();
  921. }
  922.  
  923. function checkMute() {
  924. global $config, $memcached;
  925.  
  926. if($config['memcached']['enabled']) {
  927. // Cached mute?
  928. if(($mute = $memcached->get("mute_${_SERVER['REMOTE_ADDR']}")) && ($mutetime = $memcached->get("mutetime_${_SERVER['REMOTE_ADDR']}"))) {
  929. error(sprintf($config['error']['youaremuted'], $mute['time'] + $mutetime - time()));
  930. }
  931. }
  932.  
  933. $mutetime = muteTime();
  934. if($mutetime > 0) {
  935. // Find last mute time
  936. $query = prepare("SELECT `time` FROM `mutes` WHERE `ip` = :ip ORDER BY `time` DESC LIMIT 1");
  937. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
  938. $query->execute() or error(db_error($query));
  939.  
  940. if(!$mute = $query->fetch()) {
  941. // What!? He's muted but he's not muted...
  942. return;
  943. }
  944.  
  945. if($mute['time'] + $mutetime > time()) {
  946. if($config['memcached']['enabled']) {
  947. $memcached->set("mute_${_SERVER['REMOTE_ADDR']}", $mute, $mute['time'] + $mutetime);
  948. $memcached->set("mutetime_${_SERVER['REMOTE_ADDR']}", $mutetime, $mute['time'] + $mutetime);
  949. }
  950. // Not expired yet
  951. error(sprintf($config['error']['youaremuted'], $mute['time'] + $mutetime - time()));
  952. } else {
  953. // Already expired
  954. return;
  955. }
  956. }
  957. }
  958.  
  959. function createHiddenInputs() {
  960. global $config;
  961.  
  962. $inputs = Array();
  963.  
  964. shuffle($config['spam']['hidden_input_names']);
  965. $hidden_input_names_x = 0;
  966.  
  967. $input_count = rand($config['spam']['hidden_inputs_min'], $config['spam']['hidden_inputs_max']);
  968. for($x=0;$x<$input_count;$x++) {
  969. if(rand(0, 2) == 0 || $hidden_input_names_x < 0) {
  970. // Use an obscure name
  971. $name = substr(base64_encode(sha1(rand())), 0, rand(2, 40));
  972. } else {
  973. // Use a pre-defined confusing name
  974. $name = $config['spam']['hidden_input_names'][$hidden_input_names_x++];
  975. if($hidden_input_names_x >= count($config['spam']['hidden_input_names']))
  976. $hidden_input_names_x = -1;
  977. }
  978.  
  979. if(rand(0, 2) == 0) {
  980. // Value must be null
  981. $inputs[$name] = '';
  982. } elseif(rand(0, 4) == 0) {
  983. // Numeric value
  984. $inputs[$name] = rand(0, 100);
  985. } else {
  986. // Obscure value
  987. $inputs[$name] = substr(base64_encode(sha1(rand())), 0, rand(2, 40));
  988. }
  989. }
  990.  
  991. $content = '';
  992. foreach($inputs as $name => $value) {
  993. $display_type = rand(0, 8);
  994.  
  995. switch($display_type) {
  996. case 0:
  997. $content .= '<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />';
  998. break;
  999. case 1:
  1000. $content .= '<input style="display:none" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />';
  1001. break;
  1002. case 2:
  1003. $content .= '<input type="hidden" value="' . htmlspecialchars($value) . '" name="' . htmlspecialchars($name) . '" />';
  1004. break;
  1005. case 3:
  1006. $content .= '<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />';
  1007. break;
  1008. case 4:
  1009. $content .= '<span style="display:none"><input type="text" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" /></span>';
  1010. break;
  1011. case 5:
  1012. $content .= '<div style="display:none"><input type="text" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" /></div>';
  1013. break;
  1014. case 6:
  1015. if(!empty($value))
  1016. $content .= '<textarea style="display:none" name="' . htmlspecialchars($name) . '">' . htmlspecialchars($value) . '</textarea>';
  1017. else
  1018. $content .= '<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />';
  1019. break;
  1020. case 7:
  1021. if(!empty($value))
  1022. $content .= '<textarea name="' . htmlspecialchars($name) . '" style="display:none">' . htmlspecialchars($value) . '</textarea>';
  1023. else
  1024. $content .= '<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />';
  1025. break;
  1026. case 8:
  1027. $content .= '<div style="display:none"><textarea name="' . htmlspecialchars($name) . '" style="display:none">' . htmlspecialchars($value) . '</textarea></div>';
  1028. break;
  1029. }
  1030. }
  1031.  
  1032. // Create a hash to validate it after
  1033. // This is the tricky part.
  1034.  
  1035. // First, sort the keys in alphabetical order (A-Z)
  1036. ksort($inputs);
  1037.  
  1038. $hash = '';
  1039.  
  1040. // Iterate through each input
  1041. foreach($inputs as $name => $value) {
  1042. $hash .= $name . '=' . $value;
  1043. }
  1044.  
  1045. // Add a salt to the hash
  1046. $hash .= $config['cookies']['salt'];
  1047.  
  1048. // Use SHA1 for the hash
  1049. $hash = sha1($hash);
  1050.  
  1051. // Append it to the HTML
  1052. $content .= '<input type="hidden" name="hash" value="' . $hash . '" />';
  1053.  
  1054. return $content;
  1055. }
  1056.  
  1057. function checkSpam() {
  1058. global $config;
  1059.  
  1060. if(!isset($_POST['hash']))
  1061. return true;
  1062.  
  1063. $hash = $_POST['hash'];
  1064.  
  1065. // Reconsturct the $inputs array
  1066. $inputs = Array();
  1067.  
  1068. foreach($_POST as $name => $value) {
  1069. if(in_array($name, $config['spam']['valid_inputs']))
  1070. continue;
  1071.  
  1072. $inputs[$name] = $value;
  1073. }
  1074.  
  1075. // Sort the inputs in alphabetical order (A-Z)
  1076. ksort($inputs);
  1077.  
  1078. $_hash = '';
  1079.  
  1080. // Iterate through each input
  1081. foreach($inputs as $name => $value) {
  1082. $_hash .= $name . '=' . $value;
  1083. }
  1084.  
  1085. // Add a salt to the hash
  1086. $_hash .= $config['cookies']['salt'];
  1087.  
  1088. // Use SHA1 for the hash
  1089. $_hash = sha1($_hash);
  1090.  
  1091. return $hash != $_hash;
  1092. }
  1093.  
  1094. function buildIndex() {
  1095. global $board, $config;
  1096.  
  1097. $pages = getPages();
  1098.  
  1099. $page = 1;
  1100. while($page <= $config['max_pages'] && $content = index($page)) {
  1101. $filename = $board['dir'] . ($page==1 ? $config['file_index'] : sprintf($config['file_page'], $page));
  1102. if(file_exists($filename)) $md5 = md5_file($filename);
  1103.  
  1104. $content['pages'] = $pages;
  1105. $content['pages'][$page-1]['selected'] = true;
  1106. $content['btn'] = getPageButtons($content['pages']);
  1107. $content['hidden_inputs'] = createHiddenInputs();
  1108. file_write($filename, Element('index.html', $content));
  1109.  
  1110. if(isset($md5) && $md5 == md5_file($filename)) {
  1111. break;
  1112. }
  1113. $page++;
  1114. }
  1115. if($page < $config['max_pages']) {
  1116. for(;$page<=$config['max_pages'];$page++) {
  1117. $filename = $page==1 ? $config['file_index'] : sprintf($config['file_page'], $page);
  1118. file_unlink($filename);
  1119. }
  1120. }
  1121. }
  1122.  
  1123. function buildJavascript() {
  1124. global $config;
  1125.  
  1126. $stylesheets = Array();
  1127. foreach($config['stylesheets'] as $name => $uri) {
  1128. $stylesheets[] = Array(
  1129. 'name' => addslashes($name),
  1130. 'uri' => addslashes((!empty($uri) ? $config['uri_stylesheets'] : '') . $uri));
  1131. }
  1132.  
  1133. file_write($config['file_script'], Element('main.js', Array(
  1134. 'config' => $config,
  1135. 'stylesheets' => $stylesheets
  1136. )));
  1137. }
  1138.  
  1139. function checkDNSBL() {
  1140. global $config;
  1141.  
  1142. if(isIPv6())
  1143. return; // No IPv6 support yet.
  1144.  
  1145. if(!isset($_SERVER['REMOTE_ADDR']))
  1146. return; // Fix your web server configuration
  1147.  
  1148. if(in_array($_SERVER['REMOTE_ADDR'], $config['dnsbl_exceptions']))
  1149. return;
  1150.  
  1151. $ip = ReverseIPOctets($_SERVER['REMOTE_ADDR']);
  1152.  
  1153. foreach($config['dnsbl'] as &$blacklist) {
  1154. $lookup = $ip . '.' . $blacklist;
  1155. $host = gethostbyname($lookup);
  1156. if($host != $lookup) {
  1157. // On NXDOMAIN (meaning it's not in the blacklist), gethostbyname() returns the host unchanged.
  1158. if(preg_match('/^127\.0\.0\./', $host) && $host != '127.0.0.10')
  1159. error(sprintf($config['error']['dnsbl'], $blacklist));
  1160. }
  1161. }
  1162. }
  1163.  
  1164. function isIPv6() {
  1165. return strstr($_SERVER['REMOTE_ADDR'], ':') !== false;
  1166. }
  1167.  
  1168. function ReverseIPOctets($ip) {
  1169. $ipoc = explode('.', $ip);
  1170. return $ipoc[3] . '.' . $ipoc[2] . '.' . $ipoc[1] . '.' . $ipoc[0];
  1171. }
  1172.  
  1173. function wordfilters(&$body) {
  1174. global $config;
  1175.  
  1176. foreach($config['wordfilters'] as $filter) {
  1177. if(isset($filter[2]) && $filter[2]) {
  1178. $body = preg_replace($filter[0], $filter[1], $body);
  1179. } else {
  1180. $body = str_replace($filter[0], $filter[1], $body);
  1181. }
  1182. }
  1183. }
  1184.  
  1185. function quote($body, $quote=true) {
  1186. $body = str_replace('<br/>', "\n", $body);
  1187.  
  1188. $body = strip_tags($body);
  1189.  
  1190. $body = preg_replace("/(^|\n)/", '$1&gt;', $body);
  1191.  
  1192. return $body . "\n";
  1193. }
  1194.  
  1195. function markup(&$body) {
  1196. global $board, $config;
  1197.  
  1198. $body = utf8tohtml($body, true);
  1199.  
  1200. if($config['wiki_markup']) {
  1201. $body = preg_replace("/(^|\n)==(.+?)==\n?/m", "<span class=\"heading\">$2</span>", $body);
  1202. $body = preg_replace("/'''(.+?)'''/m", "<strong>$1</strong>", $body);
  1203. $body = preg_replace("/''(.+?)''/m", "<em>$1</em>", $body);
  1204. $body = preg_replace("/\*\*(.+?)\*\*/m", "<span class=\"spoiler\">$1</span>", $body);
  1205. }
  1206.  
  1207. if($config['markup_urls']) {
  1208. $body = preg_replace($config['url_regex'], "<a target=\"_blank\" rel=\"nofollow\" href=\"$0\">$0</a>", $body, -1, $num_links);
  1209. if($num_links > $config['max_links'])
  1210. error($config['error']['toomanylinks']);
  1211. }
  1212.  
  1213. if($config['auto_unicode']) {
  1214. $body = str_replace('...', '&hellip;', $body);
  1215. $body = str_replace('&lt;--', '&larr;', $body);
  1216. $body = str_replace('--&gt;', '&rarr;', $body);
  1217.  
  1218. // En and em- dashes are rendered exactly the same in
  1219. // most monospace fonts (they look the same in code
  1220. // editors).
  1221. $body = str_replace('---', '&ndash;', $body); // em dash
  1222. $body = str_replace('--', '&mdash;', $body); // en dash
  1223. }
  1224.  
  1225. // Cites
  1226. if(isset($board) && preg_match_all('/(^|\s)&gt;&gt;(\d+?)([\s,.?]|$)/', $body, $cites)) {
  1227. if(count($cites[0]) > $config['max_cites']) {
  1228. error($config['error']['toomanycites']);
  1229. }
  1230.  
  1231. for($index=0;$index<count($cites[0]);$index++) {
  1232. $cite = $cites[2][$index];
  1233. $query = prepare(sprintf("SELECT `thread`,`id` FROM `posts_%s` WHERE `id` = :id LIMIT 1", $board['uri']));
  1234. $query->bindValue(':id', $cite);
  1235. $query->execute() or error(db_error($query));
  1236.  
  1237. if($post = $query->fetch()) {
  1238. $replacement = '<a onclick="highlightReply(\''.$cite.'\');" href="' .
  1239. $config['root'] . $board['dir'] . $config['dir']['res'] . ($post['thread']?$post['thread']:$post['id']) . '.html#' . $cite . '">' .
  1240. '&gt;&gt;' . $cite .
  1241. '</a>';
  1242. $body = str_replace($cites[0][$index], $cites[1][$index] . $replacement . $cites[3][$index], $body);
  1243. }
  1244. }
  1245. }
  1246.  
  1247. // Cross-board linking
  1248. if(preg_match_all('/(^|\s)&gt;&gt;&gt;\/(\w+?)\/(\d+)?([\s,.?]|$)/', $body, $cites)) {
  1249. if(count($cites[0]) > $config['max_cites']) {
  1250. error($config['error']['toomanycross']);
  1251. }
  1252.  
  1253. for($index=0;$index<count($cites[0]);$index++) {
  1254. $_board = $cites[2][$index];
  1255. $cite = @$cites[3][$index];
  1256.  
  1257. // Temporarily store board information because it will be overwritten
  1258. $tmp_board = $board['uri'];
  1259.  
  1260. // Check if the board exists, and load settings
  1261. if(openBoard($_board)) {
  1262. if($cite) {
  1263. $query = prepare(sprintf("SELECT `thread`,`id` FROM `posts_%s` WHERE `id` = :id LIMIT 1", $board['uri']));
  1264. $query->bindValue(':id', $cite);
  1265. $query->execute() or error(db_error($query));
  1266.  
  1267. if($post = $query->fetch()) {
  1268. $replacement = '<a onclick="highlightReply(\''.$cite.'\');" href="' .
  1269. $config['root'] . $board['dir'] . $config['dir']['res'] . ($post['thread']?$post['thread']:$post['id']) . '.html#' . $cite . '">' .
  1270. '&gt;&gt;&gt;/' . $_board . '/' . $cite .
  1271. '</a>';
  1272. $body = str_replace($cites[0][$index], $cites[1][$index] . $replacement . $cites[4][$index], $body);
  1273. }
  1274. } else {
  1275. $replacement = '<a href="' .
  1276. $config['root'] . $board['dir'] . $config['file_index'] . '">' .
  1277. '&gt;&gt;&gt;/' . $_board . '/' .
  1278. '</a>';
  1279. $body = str_replace($cites[0][$index], $cites[1][$index] . $replacement . $cites[4][$index], $body);
  1280. }
  1281. }
  1282.  
  1283. // Restore main board settings
  1284. openBoard($tmp_board);
  1285. }
  1286. }
  1287.  
  1288.  
  1289. $body = str_replace("\r", '', $body);
  1290.  
  1291. $body = preg_replace("/(^|\n)([\s]+)?(&gt;)([^\n]+)?($|\n)/m", '$1$2<span class="quote">$3$4</span>$5', $body);
  1292.  
  1293. if($config['strip_superfluous_returns'])
  1294. $body = preg_replace('/\s+$/', '', $body);
  1295.  
  1296. $body = preg_replace("/\n/", '<br/>', $body);
  1297. }
  1298.  
  1299. function html_entity_decode_utf8($string) {
  1300. static $trans_tbl;
  1301.  
  1302. // replace numeric entities
  1303. $string = preg_replace('~&#x([0-9a-f]+);~ei', 'code2utf(hexdec("\\1"))', $string);
  1304. $string = preg_replace('~&#([0-9]+);~e', 'code2utf(\\1)', $string);
  1305.  
  1306. // replace literal entities
  1307. if (!isset($trans_tbl)) {
  1308. $trans_tbl = array();
  1309.  
  1310. foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key)
  1311. $trans_tbl[$key] = utf8_encode($val);
  1312. }
  1313.  
  1314. return strtr($string, $trans_tbl);
  1315. }
  1316.  
  1317. // Returns the utf string corresponding to the unicode value (from php.net, courtesy - [email protected])
  1318. function code2utf($num) {
  1319. if ($num < 128)
  1320. return chr($num);
  1321. if ($num < 2048)
  1322. return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
  1323. if ($num < 65536)
  1324. return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
  1325. if ($num < 2097152)
  1326. return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
  1327. return '';
  1328. }
  1329.  
  1330. function utf8tohtml($utf8, $encodeTags=true) {
  1331. $result = '';
  1332. for ($i = 0; $i < strlen($utf8); $i++) {
  1333. $char = $utf8[$i];
  1334. $ascii = ord($char);
  1335. if ($ascii < 128) {
  1336. // one-byte character
  1337. $result .= ($encodeTags) ? htmlentities($char) : $char;
  1338. } else if ($ascii < 192) {
  1339. // non-utf8 character or not a start byte
  1340. } else if ($ascii < 224) {
  1341. // two-byte character
  1342. $result .= htmlentities(substr($utf8, $i, 2), ENT_QUOTES, 'UTF-8');
  1343. $i++;
  1344. } else if ($ascii < 240) {
  1345. // three-byte character
  1346. $ascii1 = ord($utf8[$i+1]);
  1347. $ascii2 = @ord($utf8[$i+2]);
  1348. $unicode = (15 & $ascii) * 4096 +
  1349. (63 & $ascii1) * 64 +
  1350. (63 & $ascii2);
  1351. $result .= "&#$unicode;";
  1352. $i += 2;
  1353. } else if ($ascii < 248) {
  1354. // four-byte character
  1355. $ascii1 = ord($utf8[$i+1]);
  1356. $ascii2 = ord($utf8[$i+2]);
  1357. $ascii3 = ord($utf8[$i+3]);
  1358. $unicode = (15 & $ascii) * 262144 +
  1359. (63 & $ascii1) * 4096 +
  1360. (63 & $ascii2) * 64 +
  1361. (63 & $ascii3);
  1362. $result .= "&#$unicode;";
  1363. $i += 3;
  1364. }
  1365. }
  1366. return $result;
  1367. }
  1368.  
  1369. function buildThread($id, $return=false, $mod=false) {
  1370. global $board, $config, $memcached;
  1371. $id = round($id);
  1372.  
  1373. if($config['memcached']['enabled'] && !$mod) {
  1374. // Clear cache for index pages
  1375. $memcached->delete("threadindex_{$board['uri']}_{$id}");
  1376. }
  1377.  
  1378. $query = prepare(sprintf("SELECT * FROM `posts_%s` WHERE (`thread` IS NULL AND `id` = :id) OR `thread` = :id ORDER BY `thread`,`id`", $board['uri']));
  1379. $query->bindValue(':id', $id, PDO::PARAM_INT);
  1380. $query->execute() or error(db_error($query));
  1381.  
  1382. while($post = $query->fetch()) {
  1383. if(!isset($thread)) {
  1384. $thread = new Thread($post['id'], $post['subject'], $post['email'], $post['name'], $post['trip'], $post['capcode'], $post['body'], $post['time'], $post['thumb'], $post['thumbwidth'], $post['thumbheight'], $post['file'], $post['filewidth'], $post['fileheight'], $post['filesize'], $post['filename'], $post['ip'], $post['sticky'], $post['locked'], $post['embed'], $mod ? '?/' : $config['root'], $mod);
  1385. } else {
  1386. $thread->add(new Post($post['id'], $thread->id, $post['subject'], $post['email'], $post['name'], $post['trip'], $post['capcode'], $post['body'], $post['time'], $post['thumb'], $post['thumbwidth'], $post['thumbheight'], $post['file'], $post['filewidth'], $post['fileheight'], $post['filesize'], $post['filename'], $post['ip'], $post['embed'], $mod ? '?/' : $config['root'], $mod));
  1387. }
  1388. }
  1389.  
  1390. // Check if any posts were found
  1391. if(!isset($thread)) error($config['error']['nonexistant']);
  1392.  
  1393. $body = Element('thread.html', Array(
  1394. 'board'=>$board,
  1395. 'body'=>$thread->build(),
  1396. 'config' => $config,
  1397. 'id' => $id,
  1398. 'mod' => $mod,
  1399. 'boardlist' => createBoardlist($mod),
  1400. 'hidden_inputs' => $content['hidden_inputs'] = createHiddenInputs(),
  1401. 'return' => ($mod ? '?' . $board['url'] . $config['file_index'] : $config['root'] . $board['uri'] . '/' . $config['file_index'])
  1402. ));
  1403.  
  1404. if($return)
  1405. return $body;
  1406. else
  1407. file_write($board['dir'] . $config['dir']['res'] . sprintf($config['file_page'], $id), $body);
  1408. }
  1409.  
  1410. function rrmdir($dir) {
  1411. if (is_dir($dir)) {
  1412. $objects = scandir($dir);
  1413. foreach ($objects as $object) {
  1414. if ($object != "." && $object != "..") {
  1415. if (filetype($dir."/".$object) == "dir")
  1416. rrmdir($dir."/".$object);
  1417. else
  1418. file_unlink($dir."/".$object);
  1419. }
  1420. }
  1421. reset($objects);
  1422. rmdir($dir);
  1423. }
  1424. }
  1425.  
  1426. function poster_id($ip, $thread) {
  1427. global $config;
  1428.  
  1429. // Confusing, hard to brute-force, but simple algorithm
  1430. return substr(sha1(sha1($ip . $config['secure_trip_salt'] . $thread) . $config['secure_trip_salt']), 0, $config['poster_id_length']);
  1431. }
  1432.  
  1433. function generate_tripcode($name, $length = 10){
  1434. global $config;
  1435. $t = explode('#', $name);
  1436. $nameo = $t[0];
  1437. if ( isset ( $t[1] ) || isset ( $t[2] ) ) {
  1438. $trip = ( ( strlen ( $t[1] ) > 0 ) ? $t[1] : $t[2] );
  1439. if ( ( function_exists ( 'mb_convert_encoding' ) ) ) {
  1440. // multi-byte encoding is necessary to produce standard tripcode output, but only use it if available
  1441. mb_substitute_character('none');
  1442. $recoded_cap = mb_convert_encoding ( $trip, 'Shift_JIS', 'UTF-8' );
  1443. }
  1444. $trip = ( ( ! empty ( $recoded_cap ) ) ? $recoded_cap : $trip );
  1445. $salt = substr ( $trip.'H.', 1, 2 );
  1446. $salt = preg_replace ( '/[^\.-z]/', '.', $salt );
  1447. $salt = strtr ( $salt, ':;<=>?@[\]^_`', 'ABCDEFGabcdef' );
  1448. if ( isset ( $t[2] ) ) {
  1449. // secure
  1450. if(isset($config['custom_tripcode']["##{$trip}"]))
  1451. $trip = $config['custom_tripcode']["##{$trip}"];
  1452. else
  1453. $trip = '!!' . substr ( crypt ( $trip, $config['secure_trip_salt'] ), ( -1 * $length ) );
  1454. } else {
  1455. // insecure
  1456. if(isset($config['custom_tripcode']["#{$trip}"]))
  1457. $trip = $config['custom_tripcode']["#{$trip}"];
  1458. else
  1459. $trip = '!' . substr ( crypt ( $trip, $salt ), ( -1 * $length ) );
  1460. }
  1461. }
  1462. if ( isset ( $trip ) ) {
  1463. return array ( $nameo, $trip );
  1464. } else {
  1465. return array ( $nameo );
  1466. }
  1467. }
  1468.  
  1469. // Highest common factor
  1470. function hcf($a, $b){
  1471. $gcd = 1;
  1472. if ($a>$b) {
  1473. $a = $a+$b;
  1474. $b = $a-$b;
  1475. $a = $a-$b;
  1476. }
  1477. if ($b==(round($b/$a))*$a)
  1478. $gcd=$a;
  1479. else {
  1480. for($i=round($a/2);$i;$i--) {
  1481. if ($a == round($a/$i)*$i && $b == round($b/$i)*$i) {
  1482. $gcd = $i;
  1483. $i = false;
  1484. }
  1485. }
  1486. }
  1487. return $gcd;
  1488. }
  1489.  
  1490. function fraction($numerator, $denominator, $sep) {
  1491. $gcf = hcf($numerator, $denominator);
  1492. $numerator = $numerator / $gcf;
  1493. $denominator = $denominator / $gcf;
  1494.  
  1495. return "{$numerator}{$sep}{$denominator}";
  1496. }
  1497.  
  1498.  
  1499.  
  1500. function getPostByHash($hash) {
  1501. global $board;
  1502. $query = prepare(sprintf("SELECT `id`,`thread` FROM `posts_%s` WHERE `filehash` = :hash", $board['uri']));
  1503. $query->bindValue(':hash', $hash, PDO::PARAM_STR);
  1504. $query->execute() or error(db_error($query));
  1505.  
  1506. if($post = $query->fetch()) {
  1507. return $post;
  1508. }
  1509.  
  1510. return false;
  1511. }
  1512.  
  1513. function undoImage($post) {
  1514. if($post['has_file']) {
  1515. if(isset($post['thumb']))
  1516. file_unlink($post['file']);
  1517. if(isset($post['thumb']))
  1518. file_unlink($post['thumb']);
  1519. }
  1520. }
  1521. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement