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.

2785 lines
80KB

  1. <?php
  2. /*
  3. * Copyright (c) 2010-2014 Tinyboard Development Group
  4. */
  5. if (realpath($_SERVER['SCRIPT_FILENAME']) == str_replace('\\', '/', __FILE__)) {
  6. // You cannot request this file directly.
  7. exit;
  8. }
  9. define('TINYBOARD', null);
  10. $microtime_start = microtime(true);
  11. require_once 'inc/display.php';
  12. require_once 'inc/template.php';
  13. require_once 'inc/database.php';
  14. require_once 'inc/events.php';
  15. require_once 'inc/api.php';
  16. require_once 'inc/mod/auth.php';
  17. require_once 'inc/polyfill.php';
  18. //require_once 'inc/lib/parsedown/Parsedown.php'; // we don't need that right now, do we?
  19. if (!extension_loaded('gettext')) {
  20. require_once 'inc/lib/gettext/gettext.inc';
  21. }
  22. // the user is not currently logged in as a moderator
  23. $mod = false;
  24. register_shutdown_function('fatal_error_handler');
  25. mb_internal_encoding('UTF-8');
  26. loadConfig();
  27. function init_locale($locale, $error='error') {
  28. if (extension_loaded('gettext')) {
  29. if (setlocale(LC_ALL, $locale) === false) {
  30. //$error('The specified locale (' . $locale . ') does not exist on your platform!');
  31. }
  32. bindtextdomain('tinyboard', './inc/locale');
  33. bind_textdomain_codeset('tinyboard', 'UTF-8');
  34. textdomain('tinyboard');
  35. } else {
  36. if (_setlocale(LC_ALL, $locale) === false) {
  37. $error('The specified locale (' . $locale . ') does not exist on your platform!');
  38. }
  39. _bindtextdomain('tinyboard', './inc/locale');
  40. _bind_textdomain_codeset('tinyboard', 'UTF-8');
  41. _textdomain('tinyboard');
  42. }
  43. }
  44. $current_locale = 'en';
  45. function loadConfig() {
  46. global $board, $config, $__ip, $debug, $__version, $microtime_start, $current_locale, $events;
  47. $error = function_exists('error') ? 'error' : 'basic_error_function_because_the_other_isnt_loaded_yet';
  48. $boardsuffix = isset($board['uri']) ? $board['uri'] : '';
  49. if (!isset($_SERVER['REMOTE_ADDR']))
  50. $_SERVER['REMOTE_ADDR'] = '0.0.0.0';
  51. if (file_exists('tmp/cache/cache_config.php')) {
  52. require_once('tmp/cache/cache_config.php');
  53. }
  54. if (isset($config['cache_config']) &&
  55. $config['cache_config'] &&
  56. $config = Cache::get('config_' . $boardsuffix ) ) {
  57. $events = Cache::get('events_' . $boardsuffix );
  58. define_groups();
  59. if (file_exists('inc/instance-functions.php')) {
  60. require_once('inc/instance-functions.php');
  61. }
  62. if ($config['locale'] != $current_locale) {
  63. $current_locale = $config['locale'];
  64. init_locale($config['locale'], $error);
  65. }
  66. }
  67. else {
  68. $config = array();
  69. reset_events();
  70. $arrays = array(
  71. 'db',
  72. 'api',
  73. 'cache',
  74. 'cookies',
  75. 'error',
  76. 'dir',
  77. 'mod',
  78. 'spam',
  79. 'filters',
  80. 'wordfilters',
  81. 'custom_capcode',
  82. 'custom_tripcode',
  83. 'dnsbl',
  84. 'dnsbl_exceptions',
  85. 'remote',
  86. 'allowed_ext',
  87. 'allowed_ext_files',
  88. 'file_icons',
  89. 'footer',
  90. 'stylesheets',
  91. 'additional_javascript',
  92. 'markup',
  93. 'custom_pages',
  94. 'dashboard_links'
  95. );
  96. foreach ($arrays as $key) {
  97. $config[$key] = array();
  98. }
  99. if (!file_exists('inc/instance-config.php'))
  100. $error('Tinyboard is not configured! Create inc/instance-config.php.');
  101. // Initialize locale as early as possible
  102. // Those calls are expensive. Unfortunately, our cache system is not initialized at this point.
  103. // So, we may store the locale in a tmp/ filesystem.
  104. if (file_exists($fn = 'tmp/cache/locale_' . $boardsuffix ) ) {
  105. $config['locale'] = @file_get_contents($fn);
  106. }
  107. else {
  108. $config['locale'] = 'en';
  109. $configstr = file_get_contents('inc/instance-config.php');
  110. if (isset($board['dir']) && file_exists($board['dir'] . '/config.php')) {
  111. $configstr .= file_get_contents($board['dir'] . '/config.php');
  112. }
  113. $matches = array();
  114. preg_match_all('/[^\/#*]\$config\s*\[\s*[\'"]locale[\'"]\s*\]\s*=\s*([\'"])(.*?)\1/', $configstr, $matches);
  115. if ($matches && isset ($matches[2]) && $matches[2]) {
  116. $matches = $matches[2];
  117. $config['locale'] = $matches[count($matches)-1];
  118. }
  119. @file_put_contents($fn, $config['locale']);
  120. }
  121. if ($config['locale'] != $current_locale) {
  122. $current_locale = $config['locale'];
  123. init_locale($config['locale'], $error);
  124. }
  125. require 'inc/config.php';
  126. require 'inc/instance-config.php';
  127. if (isset($board['dir']) && file_exists($board['dir'] . '/config.php')) {
  128. require $board['dir'] . '/config.php';
  129. }
  130. if ($config['locale'] != $current_locale) {
  131. $current_locale = $config['locale'];
  132. init_locale($config['locale'], $error);
  133. }
  134. if (!isset($config['global_message']))
  135. $config['global_message'] = false;
  136. if (!isset($config['post_url']))
  137. $config['post_url'] = $config['root'] . $config['file_post'];
  138. if (!isset($config['referer_match']))
  139. if (isset($_SERVER['HTTP_HOST'])) {
  140. $config['referer_match'] = '/^' .
  141. (preg_match('@^https?://@', $config['root']) ? '' :
  142. 'https?:\/\/' . $_SERVER['HTTP_HOST']) .
  143. preg_quote($config['root'], '/') .
  144. '(' .
  145. str_replace('%s', $config['board_regex'], preg_quote($config['board_path'], '/')) .
  146. '(' .
  147. preg_quote($config['file_index'], '/') . '|' .
  148. str_replace('%d', '\d+', preg_quote($config['file_page'])) .
  149. ')?' .
  150. '|' .
  151. str_replace('%s', $config['board_regex'], preg_quote($config['board_path'], '/')) .
  152. preg_quote($config['dir']['res'], '/') .
  153. '(' .
  154. str_replace('%d', '\d+', preg_quote($config['file_page'], '/')) . '|' .
  155. str_replace('%d', '\d+', preg_quote($config['file_page50'], '/')) . '|' .
  156. str_replace(array('%d', '%s'), array('\d+', '[a-z0-9-]+'), preg_quote($config['file_page_slug'], '/')) . '|' .
  157. str_replace(array('%d', '%s'), array('\d+', '[a-z0-9-]+'), preg_quote($config['file_page50_slug'], '/')) .
  158. ')' .
  159. '|' .
  160. preg_quote($config['file_mod'], '/') . '\?\/.+' .
  161. ')([#?](.+)?)?$/ui';
  162. } else {
  163. // CLI mode
  164. $config['referer_match'] = '//';
  165. }
  166. if (!isset($config['cookies']['path']))
  167. $config['cookies']['path'] = &$config['root'];
  168. if (!isset($config['dir']['static']))
  169. $config['dir']['static'] = $config['root'] . 'static/';
  170. if (!isset($config['image_blank']))
  171. $config['image_blank'] = $config['dir']['static'] . 'blank.gif';
  172. if (!isset($config['image_sticky']))
  173. $config['image_sticky'] = $config['dir']['static'] . 'sticky.gif';
  174. if (!isset($config['image_locked']))
  175. $config['image_locked'] = $config['dir']['static'] . 'locked.gif';
  176. if (!isset($config['image_bumplocked']))
  177. $config['image_bumplocked'] = $config['dir']['static'] . 'sage.gif';
  178. if (!isset($config['image_deleted']))
  179. $config['image_deleted'] = $config['dir']['static'] . 'deleted.png';
  180. if (!isset($config['uri_thumb']))
  181. $config['uri_thumb'] = $config['root'] . $board['dir'] . $config['dir']['thumb'];
  182. elseif (isset($board['dir']))
  183. $config['uri_thumb'] = sprintf($config['uri_thumb'], $board['dir']);
  184. if (!isset($config['uri_img']))
  185. $config['uri_img'] = $config['root'] . $board['dir'] . $config['dir']['img'];
  186. elseif (isset($board['dir']))
  187. $config['uri_img'] = sprintf($config['uri_img'], $board['dir']);
  188. if (!isset($config['uri_stylesheets']))
  189. $config['uri_stylesheets'] = $config['root'] . 'stylesheets/';
  190. if (!isset($config['url_stylesheet']))
  191. $config['url_stylesheet'] = $config['uri_stylesheets'] . 'style.css';
  192. if (!isset($config['url_javascript']))
  193. $config['url_javascript'] = $config['root'] . $config['file_script'];
  194. if (!isset($config['additional_javascript_url']))
  195. $config['additional_javascript_url'] = $config['root'];
  196. if (!isset($config['uri_flags']))
  197. $config['uri_flags'] = $config['root'] . 'static/flags/%s.png';
  198. if (!isset($config['user_flag']))
  199. $config['user_flag'] = false;
  200. if (!isset($config['user_flags']))
  201. $config['user_flags'] = array();
  202. if (!isset($__version))
  203. $__version = file_exists('.installed') ? trim(file_get_contents('.installed')) : false;
  204. $config['version'] = $__version;
  205. if ($config['allow_roll'])
  206. event_handler('post', 'diceRoller');
  207. if (in_array('webm', $config['allowed_ext_files']) ||
  208. in_array('mp4', $config['allowed_ext_files']))
  209. event_handler('post', 'postHandler');
  210. }
  211. // Effectful config processing below:
  212. date_default_timezone_set($config['timezone']);
  213. if ($config['root_file']) {
  214. chdir($config['root_file']);
  215. }
  216. // Keep the original address to properly comply with other board configurations
  217. if (!isset($__ip))
  218. $__ip = $_SERVER['REMOTE_ADDR'];
  219. // ::ffff:0.0.0.0
  220. if (preg_match('/^\:\:(ffff\:)?(\d+\.\d+\.\d+\.\d+)$/', $__ip, $m))
  221. $_SERVER['REMOTE_ADDR'] = $m[2];
  222. if ($config['verbose_errors']) {
  223. set_error_handler('verbose_error_handler');
  224. error_reporting(E_ALL);
  225. ini_set('display_errors', true);
  226. ini_set('html_errors', false);
  227. } else {
  228. ini_set('display_errors', false);
  229. }
  230. if ($config['syslog'])
  231. openlog('tinyboard', LOG_ODELAY, LOG_SYSLOG); // open a connection to sysem logger
  232. if ($config['recaptcha'])
  233. require_once 'inc/lib/recaptcha/recaptchalib.php';
  234. if ($config['cache']['enabled'])
  235. require_once 'inc/cache.php';
  236. if (in_array('webm', $config['allowed_ext_files']) ||
  237. in_array('mp4', $config['allowed_ext_files']))
  238. require_once 'inc/lib/webm/posthandler.php';
  239. event('load-config');
  240. if ($config['cache_config'] && !isset ($config['cache_config_loaded'])) {
  241. file_put_contents('tmp/cache/cache_config.php', '<?php '.
  242. '$config = array();'.
  243. '$config[\'cache\'] = '.var_export($config['cache'], true).';'.
  244. '$config[\'cache_config\'] = true;'.
  245. '$config[\'debug\'] = '.var_export($config['debug'], true).';'.
  246. 'require_once(\'inc/cache.php\');'
  247. );
  248. $config['cache_config_loaded'] = true;
  249. Cache::set('config_'.$boardsuffix, $config);
  250. Cache::set('events_'.$boardsuffix, $events);
  251. }
  252. if (is_array($config['anonymous']))
  253. $config['anonymous'] = $config['anonymous'][array_rand($config['anonymous'])];
  254. if ($config['debug']) {
  255. if (!isset($debug)) {
  256. $debug = array(
  257. 'sql' => array(),
  258. 'exec' => array(),
  259. 'purge' => array(),
  260. 'cached' => array(),
  261. 'write' => array(),
  262. 'time' => array(
  263. 'db_queries' => 0,
  264. 'exec' => 0,
  265. ),
  266. 'start' => $microtime_start,
  267. 'start_debug' => microtime(true)
  268. );
  269. $debug['start'] = $microtime_start;
  270. }
  271. }
  272. }
  273. function basic_error_function_because_the_other_isnt_loaded_yet($message, $priority = true) {
  274. global $config;
  275. if ($config['syslog'] && $priority !== false) {
  276. // Use LOG_NOTICE instead of LOG_ERR or LOG_WARNING because most error message are not significant.
  277. _syslog($priority !== true ? $priority : LOG_NOTICE, $message);
  278. }
  279. // Yes, this is horrible.
  280. die('<!DOCTYPE html><html><head><title>Error</title>' .
  281. '<style type="text/css">' .
  282. 'body{text-align:center;font-family:arial, helvetica, sans-serif;font-size:10pt;}' .
  283. 'p{padding:0;margin:20px 0;}' .
  284. 'p.c{font-size:11px;}' .
  285. '</style></head>' .
  286. '<body><h2>Error</h2>' . $message . '<hr/>' .
  287. '<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>');
  288. }
  289. function fatal_error_handler() {
  290. if ($error = error_get_last()) {
  291. if ($error['type'] == E_ERROR) {
  292. if (function_exists('error')) {
  293. error('Caught fatal error: ' . $error['message'] . ' in <strong>' . $error['file'] . '</strong> on line ' . $error['line'], LOG_ERR);
  294. } else {
  295. basic_error_function_because_the_other_isnt_loaded_yet('Caught fatal error: ' . $error['message'] . ' in ' . $error['file'] . ' on line ' . $error['line'], LOG_ERR);
  296. }
  297. }
  298. }
  299. }
  300. function _syslog($priority, $message) {
  301. if (isset($_SERVER['REMOTE_ADDR'], $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'])) {
  302. // CGI
  303. syslog($priority, $message . ' - client: ' . $_SERVER['REMOTE_ADDR'] . ', request: "' . $_SERVER['REQUEST_METHOD'] . ' ' . $_SERVER['REQUEST_URI'] . '"');
  304. } else {
  305. syslog($priority, $message);
  306. }
  307. }
  308. function verbose_error_handler($errno, $errstr, $errfile, $errline) {
  309. if (error_reporting() == 0)
  310. return false; // Looks like this warning was suppressed by the @ operator.
  311. error(utf8tohtml($errstr), true, array(
  312. 'file' => $errfile . ':' . $errline,
  313. 'errno' => $errno,
  314. 'error' => $errstr,
  315. 'backtrace' => array_slice(debug_backtrace(), 1)
  316. ));
  317. }
  318. function define_groups() {
  319. global $config;
  320. foreach ($config['mod']['groups'] as $group_value => $group_name) {
  321. $group_name = strtoupper($group_name);
  322. if(!defined($group_name)) {
  323. define($group_name, $group_value, true);
  324. }
  325. }
  326. ksort($config['mod']['groups']);
  327. }
  328. function create_antibot($board, $thread = null) {
  329. require_once dirname(__FILE__) . '/anti-bot.php';
  330. return _create_antibot($board, $thread);
  331. }
  332. function rebuildThemes($action, $boardname = false) {
  333. global $config, $board, $current_locale;
  334. // Save the global variables
  335. $_config = $config;
  336. $_board = $board;
  337. // List themes
  338. if ($themes = Cache::get("themes")) {
  339. // OK, we already have themes loaded
  340. }
  341. else {
  342. $query = query("SELECT `theme` FROM ``theme_settings`` WHERE `name` IS NULL AND `value` IS NULL") or error(db_error());
  343. $themes = array();
  344. while ($theme = $query->fetch(PDO::FETCH_ASSOC)) {
  345. $themes[] = $theme;
  346. }
  347. Cache::set("themes", $themes);
  348. }
  349. foreach ($themes as $theme) {
  350. // Restore them
  351. $config = $_config;
  352. $board = $_board;
  353. // Reload the locale
  354. if ($config['locale'] != $current_locale) {
  355. $current_locale = $config['locale'];
  356. init_locale($config['locale']);
  357. }
  358. if (PHP_SAPI === 'cli') {
  359. echo "Rebuilding theme ".$theme['theme']."... ";
  360. }
  361. rebuildTheme($theme['theme'], $action, $boardname);
  362. if (PHP_SAPI === 'cli') {
  363. echo "done\n";
  364. }
  365. }
  366. // Restore them again
  367. $config = $_config;
  368. $board = $_board;
  369. // Reload the locale
  370. if ($config['locale'] != $current_locale) {
  371. $current_locale = $config['locale'];
  372. init_locale($config['locale']);
  373. }
  374. }
  375. function loadThemeConfig($_theme) {
  376. global $config;
  377. if (!file_exists($config['dir']['themes'] . '/' . $_theme . '/info.php'))
  378. return false;
  379. // Load theme information into $theme
  380. include $config['dir']['themes'] . '/' . $_theme . '/info.php';
  381. return $theme;
  382. }
  383. function rebuildTheme($theme, $action, $board = false) {
  384. global $config, $_theme;
  385. $_theme = $theme;
  386. $theme = loadThemeConfig($_theme);
  387. if (file_exists($config['dir']['themes'] . '/' . $_theme . '/theme.php')) {
  388. require_once $config['dir']['themes'] . '/' . $_theme . '/theme.php';
  389. $theme['build_function']($action, themeSettings($_theme), $board);
  390. }
  391. }
  392. function themeSettings($theme) {
  393. if ($settings = Cache::get("theme_settings_".$theme)) {
  394. return $settings;
  395. }
  396. $query = prepare("SELECT `name`, `value` FROM ``theme_settings`` WHERE `theme` = :theme AND `name` IS NOT NULL");
  397. $query->bindValue(':theme', $theme);
  398. $query->execute() or error(db_error($query));
  399. $settings = array();
  400. while ($s = $query->fetch(PDO::FETCH_ASSOC)) {
  401. $settings[$s['name']] = $s['value'];
  402. }
  403. Cache::set("theme_settings_".$theme, $settings);
  404. return $settings;
  405. }
  406. function sprintf3($str, $vars, $delim = '%') {
  407. $replaces = array();
  408. foreach ($vars as $k => $v) {
  409. $replaces[$delim . $k . $delim] = $v;
  410. }
  411. return str_replace(array_keys($replaces),
  412. array_values($replaces), $str);
  413. }
  414. function mb_substr_replace($string, $replacement, $start, $length) {
  415. return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start + $length);
  416. }
  417. function setupBoard($array) {
  418. global $board, $config;
  419. $board = array(
  420. 'uri' => $array['uri'],
  421. 'title' => $array['title'],
  422. 'subtitle' => $array['subtitle'],
  423. #'indexed' => $array['indexed'],
  424. );
  425. // older versions
  426. $board['name'] = &$board['title'];
  427. $board['dir'] = sprintf($config['board_path'], $board['uri']);
  428. $board['url'] = sprintf($config['board_abbreviation'], $board['uri']);
  429. loadConfig();
  430. if (!file_exists($board['dir']))
  431. @mkdir($board['dir'], 0777) or error("Couldn't create " . $board['dir'] . ". Check permissions.", true);
  432. if (!file_exists($board['dir'] . $config['dir']['img']))
  433. @mkdir($board['dir'] . $config['dir']['img'], 0777)
  434. or error("Couldn't create " . $board['dir'] . $config['dir']['img'] . ". Check permissions.", true);
  435. if (!file_exists($board['dir'] . $config['dir']['thumb']))
  436. @mkdir($board['dir'] . $config['dir']['thumb'], 0777)
  437. or error("Couldn't create " . $board['dir'] . $config['dir']['img'] . ". Check permissions.", true);
  438. if (!file_exists($board['dir'] . $config['dir']['res']))
  439. @mkdir($board['dir'] . $config['dir']['res'], 0777)
  440. or error("Couldn't create " . $board['dir'] . $config['dir']['img'] . ". Check permissions.", true);
  441. }
  442. function openBoard($uri) {
  443. global $config, $build_pages;
  444. if ($config['try_smarter'])
  445. $build_pages = array();
  446. $board = getBoardInfo($uri);
  447. if ($board) {
  448. setupBoard($board);
  449. if (function_exists('after_open_board')) {
  450. after_open_board();
  451. }
  452. return true;
  453. }
  454. return false;
  455. }
  456. function getBoardInfo($uri) {
  457. global $config;
  458. if ($config['cache']['enabled'] && ($board = cache::get('board_' . $uri))) {
  459. return $board;
  460. }
  461. $query = prepare("SELECT * FROM ``boards`` WHERE `uri` = :uri LIMIT 1");
  462. $query->bindValue(':uri', $uri);
  463. $query->execute() or error(db_error($query));
  464. if ($board = $query->fetch(PDO::FETCH_ASSOC)) {
  465. if ($config['cache']['enabled'])
  466. cache::set('board_' . $uri, $board);
  467. return $board;
  468. }
  469. return false;
  470. }
  471. function boardTitle($uri) {
  472. $board = getBoardInfo($uri);
  473. if ($board)
  474. return $board['title'];
  475. return false;
  476. }
  477. function purge($uri) {
  478. global $config, $debug;
  479. // Fix for Unicode
  480. $uri = rawurlencode($uri);
  481. $noescape = "/!~*()+:";
  482. $noescape = preg_split('//', $noescape);
  483. $noescape_url = array_map("rawurlencode", $noescape);
  484. $uri = str_replace($noescape_url, $noescape, $uri);
  485. if (preg_match($config['referer_match'], $config['root']) && isset($_SERVER['REQUEST_URI'])) {
  486. $uri = (str_replace('\\', '/', dirname($_SERVER['REQUEST_URI'])) == '/' ? '/' : str_replace('\\', '/', dirname($_SERVER['REQUEST_URI'])) . '/') . $uri;
  487. } else {
  488. $uri = $config['root'] . $uri;
  489. }
  490. if ($config['debug']) {
  491. $debug['purge'][] = $uri;
  492. }
  493. foreach ($config['purge'] as &$purge) {
  494. $host = &$purge[0];
  495. $port = &$purge[1];
  496. $http_host = isset($purge[2]) ? $purge[2] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost');
  497. $request = "PURGE {$uri} HTTP/1.1\r\nHost: {$http_host}\r\nUser-Agent: Tinyboard\r\nConnection: Close\r\n\r\n";
  498. if ($fp = fsockopen($host, $port, $errno, $errstr, $config['purge_timeout'])) {
  499. fwrite($fp, $request);
  500. fclose($fp);
  501. } else {
  502. // Cannot connect?
  503. error('Could not PURGE for ' . $host);
  504. }
  505. }
  506. }
  507. function file_write($path, $data, $simple = false, $skip_purge = false) {
  508. global $config, $debug;
  509. if (preg_match('/^remote:\/\/(.+)\:(.+)$/', $path, $m)) {
  510. if (isset($config['remote'][$m[1]])) {
  511. require_once 'inc/remote.php';
  512. $remote = new Remote($config['remote'][$m[1]]);
  513. $remote->write($data, $m[2]);
  514. return;
  515. } else {
  516. error('Invalid remote server: ' . $m[1]);
  517. }
  518. }
  519. if (!$fp = fopen($path, $simple ? 'w' : 'c'))
  520. error('Unable to open file for writing: ' . $path);
  521. // File locking
  522. if (!$simple && !flock($fp, LOCK_EX)) {
  523. error('Unable to lock file: ' . $path);
  524. }
  525. // Truncate file
  526. if (!$simple && !ftruncate($fp, 0))
  527. error('Unable to truncate file: ' . $path);
  528. // Write data
  529. if (($bytes = fwrite($fp, $data)) === false)
  530. error('Unable to write to file: ' . $path);
  531. // Unlock
  532. if (!$simple)
  533. flock($fp, LOCK_UN);
  534. // Close
  535. if (!fclose($fp))
  536. error('Unable to close file: ' . $path);
  537. /**
  538. * Create gzipped file.
  539. *
  540. * When writing into a file foo.bar and the size is larger or equal to 1
  541. * KiB, this also produces the gzipped version foo.bar.gz
  542. *
  543. * This is useful with nginx with gzip_static on.
  544. */
  545. if ($config['gzip_static']) {
  546. $gzpath = "$path.gz";
  547. if ($bytes & ~0x3ff) { // if ($bytes >= 1024)
  548. if (file_put_contents($gzpath, gzencode($data), $simple ? 0 : LOCK_EX) === false)
  549. error("Unable to write to file: $gzpath");
  550. //if (!touch($gzpath, filemtime($path), fileatime($path)))
  551. // error("Unable to touch file: $gzpath");
  552. }
  553. else {
  554. @unlink($gzpath);
  555. }
  556. }
  557. if (!$skip_purge && isset($config['purge'])) {
  558. // Purge cache
  559. if (basename($path) == $config['file_index']) {
  560. // Index file (/index.html); purge "/" as well
  561. $uri = dirname($path);
  562. // root
  563. if ($uri == '.')
  564. $uri = '';
  565. else
  566. $uri .= '/';
  567. purge($uri);
  568. }
  569. purge($path);
  570. }
  571. if ($config['debug']) {
  572. $debug['write'][] = $path . ': ' . $bytes . ' bytes';
  573. }
  574. event('write', $path);
  575. }
  576. function file_unlink($path) {
  577. global $config, $debug;
  578. if ($config['debug']) {
  579. if (!isset($debug['unlink']))
  580. $debug['unlink'] = array();
  581. $debug['unlink'][] = $path;
  582. }
  583. $ret = @unlink($path);
  584. if ($config['gzip_static']) {
  585. $gzpath = "$path.gz";
  586. @unlink($gzpath);
  587. }
  588. if (isset($config['purge']) && $path[0] != '/' && isset($_SERVER['HTTP_HOST'])) {
  589. // Purge cache
  590. if (basename($path) == $config['file_index']) {
  591. // Index file (/index.html); purge "/" as well
  592. $uri = dirname($path);
  593. // root
  594. if ($uri == '.')
  595. $uri = '';
  596. else
  597. $uri .= '/';
  598. purge($uri);
  599. }
  600. purge($path);
  601. }
  602. event('unlink', $path);
  603. return $ret;
  604. }
  605. function hasPermission($action = null, $board = null, $_mod = null) {
  606. global $config;
  607. if (isset($_mod))
  608. $mod = &$_mod;
  609. else
  610. global $mod;
  611. if (!is_array($mod))
  612. return false;
  613. if (isset($action) && $mod['type'] < $action)
  614. return false;
  615. if (!isset($board) || $config['mod']['skip_per_board'])
  616. return true;
  617. if (!isset($mod['boards']))
  618. return false;
  619. if (!in_array('*', $mod['boards']) && !in_array($board, $mod['boards']))
  620. return false;
  621. return true;
  622. }
  623. function listBoards($just_uri = false) {
  624. global $config;
  625. $just_uri ? $cache_name = 'all_boards_uri' : $cache_name = 'all_boards';
  626. if ($config['cache']['enabled'] && ($boards = cache::get($cache_name)))
  627. return $boards;
  628. if (!$just_uri) {
  629. $query = query("SELECT * FROM ``boards`` ORDER BY `uri`") or error(db_error());
  630. $boards = $query->fetchAll();
  631. } else {
  632. $boards = array();
  633. $query = query("SELECT `uri` FROM ``boards``") or error(db_error());
  634. while ($board = $query->fetchColumn()) {
  635. $boards[] = $board;
  636. }
  637. }
  638. if ($config['cache']['enabled'])
  639. cache::set($cache_name, $boards);
  640. return $boards;
  641. }
  642. function until($timestamp) {
  643. $difference = $timestamp - time();
  644. switch(TRUE){
  645. case ($difference < 60):
  646. return $difference . ' ' . ngettext('second', 'seconds', $difference);
  647. case ($difference < 3600): //60*60 = 3600
  648. return ($num = round($difference/(60))) . ' ' . ngettext('minute', 'minutes', $num);
  649. case ($difference < 86400): //60*60*24 = 86400
  650. return ($num = round($difference/(3600))) . ' ' . ngettext('hour', 'hours', $num);
  651. case ($difference < 604800): //60*60*24*7 = 604800
  652. return ($num = round($difference/(86400))) . ' ' . ngettext('day', 'days', $num);
  653. case ($difference < 31536000): //60*60*24*365 = 31536000
  654. return ($num = round($difference/(604800))) . ' ' . ngettext('week', 'weeks', $num);
  655. default:
  656. return ($num = round($difference/(31536000))) . ' ' . ngettext('year', 'years', $num);
  657. }
  658. }
  659. function ago($timestamp) {
  660. $difference = time() - $timestamp;
  661. switch(TRUE){
  662. case ($difference < 60) :
  663. return $difference . ' ' . ngettext('second', 'seconds', $difference);
  664. case ($difference < 3600): //60*60 = 3600
  665. return ($num = round($difference/(60))) . ' ' . ngettext('minute', 'minutes', $num);
  666. case ($difference < 86400): //60*60*24 = 86400
  667. return ($num = round($difference/(3600))) . ' ' . ngettext('hour', 'hours', $num);
  668. case ($difference < 604800): //60*60*24*7 = 604800
  669. return ($num = round($difference/(86400))) . ' ' . ngettext('day', 'days', $num);
  670. case ($difference < 31536000): //60*60*24*365 = 31536000
  671. return ($num = round($difference/(604800))) . ' ' . ngettext('week', 'weeks', $num);
  672. default:
  673. return ($num = round($difference/(31536000))) . ' ' . ngettext('year', 'years', $num);
  674. }
  675. }
  676. function displayBan($ban) {
  677. global $config, $board;
  678. if (!$ban['seen']) {
  679. Bans::seen($ban['id']);
  680. }
  681. $ban['ip'] = $_SERVER['REMOTE_ADDR'];
  682. if ($ban['post'] && isset($ban['post']['board'], $ban['post']['id'])) {
  683. if (openBoard($ban['post']['board'])) {
  684. $query = query(sprintf("SELECT `files` FROM ``posts_%s`` WHERE `id` = " .
  685. (int)$ban['post']['id'], $board['uri']));
  686. if ($_post = $query->fetch(PDO::FETCH_ASSOC)) {
  687. $ban['post'] = array_merge($ban['post'], $_post);
  688. }
  689. }
  690. if ($ban['post']['thread']) {
  691. $post = new Post($ban['post']);
  692. } else {
  693. $post = new Thread($ban['post'], null, false, false);
  694. }
  695. }
  696. $denied_appeals = array();
  697. $pending_appeal = false;
  698. if ($config['ban_appeals']) {
  699. $query = query("SELECT `time`, `denied` FROM ``ban_appeals`` WHERE `ban_id` = " . (int)$ban['id']) or error(db_error());
  700. while ($ban_appeal = $query->fetch(PDO::FETCH_ASSOC)) {
  701. if ($ban_appeal['denied']) {
  702. $denied_appeals[] = $ban_appeal['time'];
  703. } else {
  704. $pending_appeal = $ban_appeal['time'];
  705. }
  706. }
  707. }
  708. // Show banned page and exit
  709. die(
  710. Element('page.html', array(
  711. 'title' => _('Banned!'),
  712. 'config' => $config,
  713. 'boardlist' => createBoardlist($mod),
  714. 'body' => Element('banned.html', array(
  715. 'config' => $config,
  716. 'ban' => $ban,
  717. 'board' => $board,
  718. 'post' => isset($post) ? $post->build(true) : false,
  719. 'denied_appeals' => $denied_appeals,
  720. 'pending_appeal' => $pending_appeal
  721. )
  722. ))
  723. ));
  724. }
  725. function checkBan($board = false) {
  726. global $config;
  727. if (!isset($_SERVER['REMOTE_ADDR'])) {
  728. // Server misconfiguration
  729. return;
  730. }
  731. if (event('check-ban', $board))
  732. return true;
  733. $ips = array();
  734. $ips[] = $_SERVER['REMOTE_ADDR'];
  735. if ($config['proxy_check'] && isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  736. $ips = array_merge($ips, explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']));
  737. }
  738. foreach ($ips as $ip) {
  739. $bans = Bans::find($_SERVER['REMOTE_ADDR'], $board, $config['show_modname']);
  740. foreach ($bans as &$ban) {
  741. if ($ban['expires'] && $ban['expires'] < time()) {
  742. Bans::delete($ban['id']);
  743. if ($config['require_ban_view'] && !$ban['seen']) {
  744. if (!isset($_POST['json_response'])) {
  745. displayBan($ban);
  746. } else {
  747. header('Content-Type: text/json');
  748. die(json_encode(array('error' => true, 'banned' => true)));
  749. }
  750. }
  751. } else {
  752. if (!isset($_POST['json_response'])) {
  753. displayBan($ban);
  754. } else {
  755. header('Content-Type: text/json');
  756. die(json_encode(array('error' => true, 'banned' => true)));
  757. }
  758. }
  759. }
  760. }
  761. // I'm not sure where else to put this. It doesn't really matter where; it just needs to be called every
  762. // now and then to keep the ban list tidy.
  763. if ($config['cache']['enabled'] && $last_time_purged = cache::get('purged_bans_last')) {
  764. if (time() - $last_time_purged < $config['purge_bans'] )
  765. return;
  766. }
  767. Bans::purge();
  768. if ($config['cache']['enabled'])
  769. cache::set('purged_bans_last', time());
  770. }
  771. function threadLocked($id) {
  772. global $board;
  773. if (event('check-locked', $id))
  774. return true;
  775. $query = prepare(sprintf("SELECT `locked` FROM ``posts_%s`` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri']));
  776. $query->bindValue(':id', $id, PDO::PARAM_INT);
  777. $query->execute() or error(db_error());
  778. if (($locked = $query->fetchColumn()) === false) {
  779. // Non-existant, so it can't be locked...
  780. return false;
  781. }
  782. return (bool)$locked;
  783. }
  784. function threadSageLocked($id) {
  785. global $board;
  786. if (event('check-sage-locked', $id))
  787. return true;
  788. $query = prepare(sprintf("SELECT `sage` FROM ``posts_%s`` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri']));
  789. $query->bindValue(':id', $id, PDO::PARAM_INT);
  790. $query->execute() or error(db_error());
  791. if (($sagelocked = $query->fetchColumn()) === false) {
  792. // Non-existant, so it can't be locked...
  793. return false;
  794. }
  795. return (bool)$sagelocked;
  796. }
  797. function threadExists($id) {
  798. global $board;
  799. $query = prepare(sprintf("SELECT 1 FROM ``posts_%s`` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri']));
  800. $query->bindValue(':id', $id, PDO::PARAM_INT);
  801. $query->execute() or error(db_error());
  802. if ($query->rowCount()) {
  803. return true;
  804. }
  805. return false;
  806. }
  807. function insertFloodPost(array $post) {
  808. global $board;
  809. $query = prepare("INSERT INTO ``flood`` VALUES (NULL, :ip, :board, :time, :posthash, :filehash, :isreply)");
  810. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
  811. $query->bindValue(':board', $board['uri']);
  812. $query->bindValue(':time', time());
  813. $query->bindValue(':posthash', make_comment_hex($post['body_nomarkup']));
  814. if ($post['has_file'])
  815. $query->bindValue(':filehash', $post['filehash']);
  816. else
  817. $query->bindValue(':filehash', null, PDO::PARAM_NULL);
  818. $query->bindValue(':isreply', !$post['op'], PDO::PARAM_INT);
  819. $query->execute() or error(db_error($query));
  820. }
  821. function post(array $post) {
  822. global $pdo, $board;
  823. $query = prepare(sprintf("INSERT INTO ``posts_%s`` VALUES ( NULL, :thread, :subject, :email, :name, :trip, :capcode, :body, :body_nomarkup, :time, :time, :files, :num_files, :filehash, :password, :ip, :sticky, :locked, 0, :embed, :slug)", $board['uri']));
  824. // Basic stuff
  825. if (!empty($post['subject'])) {
  826. $query->bindValue(':subject', $post['subject']);
  827. } else {
  828. $query->bindValue(':subject', null, PDO::PARAM_NULL);
  829. }
  830. if (!empty($post['email'])) {
  831. $query->bindValue(':email', $post['email']);
  832. } else {
  833. $query->bindValue(':email', null, PDO::PARAM_NULL);
  834. }
  835. if (!empty($post['trip'])) {
  836. $query->bindValue(':trip', $post['trip']);
  837. } else {
  838. $query->bindValue(':trip', null, PDO::PARAM_NULL);
  839. }
  840. $query->bindValue(':name', $post['name']);
  841. $query->bindValue(':body', $post['body']);
  842. $query->bindValue(':body_nomarkup', $post['body_nomarkup']);
  843. $query->bindValue(':time', isset($post['time']) ? $post['time'] : time(), PDO::PARAM_INT);
  844. $query->bindValue(':password', $post['password']);
  845. $query->bindValue(':ip', isset($post['ip']) ? $post['ip'] : $_SERVER['REMOTE_ADDR']);
  846. if ($post['op'] && $post['mod'] && isset($post['sticky']) && $post['sticky']) {
  847. $query->bindValue(':sticky', true, PDO::PARAM_INT);
  848. } else {
  849. $query->bindValue(':sticky', false, PDO::PARAM_INT);
  850. }
  851. if ($post['op'] && $post['mod'] && isset($post['locked']) && $post['locked']) {
  852. $query->bindValue(':locked', true, PDO::PARAM_INT);
  853. } else {
  854. $query->bindValue(':locked', false, PDO::PARAM_INT);
  855. }
  856. if ($post['mod'] && isset($post['capcode']) && $post['capcode']) {
  857. $query->bindValue(':capcode', $post['capcode'], PDO::PARAM_INT);
  858. } else {
  859. $query->bindValue(':capcode', null, PDO::PARAM_NULL);
  860. }
  861. if (!empty($post['embed'])) {
  862. $query->bindValue(':embed', $post['embed']);
  863. } else {
  864. $query->bindValue(':embed', null, PDO::PARAM_NULL);
  865. }
  866. if ($post['op']) {
  867. // No parent thread, image
  868. $query->bindValue(':thread', null, PDO::PARAM_NULL);
  869. } else {
  870. $query->bindValue(':thread', $post['thread'], PDO::PARAM_INT);
  871. }
  872. if ($post['has_file']) {
  873. $query->bindValue(':files', json_encode($post['files']));
  874. $query->bindValue(':num_files', $post['num_files']);
  875. $query->bindValue(':filehash', $post['filehash']);
  876. } else {
  877. $query->bindValue(':files', null, PDO::PARAM_NULL);
  878. $query->bindValue(':num_files', 0);
  879. $query->bindValue(':filehash', null, PDO::PARAM_NULL);
  880. }
  881. if ($post['op']) {
  882. $query->bindValue(':slug', slugify($post));
  883. }
  884. else {
  885. $query->bindValue(':slug', NULL);
  886. }
  887. if (!$query->execute()) {
  888. undoImage($post);
  889. error(db_error($query));
  890. }
  891. return $pdo->lastInsertId();
  892. }
  893. function bumpThread($id) {
  894. global $config, $board, $build_pages;
  895. if (event('bump', $id))
  896. return true;
  897. if ($config['try_smarter']) {
  898. $build_pages = array_merge(range(1, thread_find_page($id)), $build_pages);
  899. }
  900. $query = prepare(sprintf("UPDATE ``posts_%s`` SET `bump` = :time WHERE `id` = :id AND `thread` IS NULL", $board['uri']));
  901. $query->bindValue(':time', time(), PDO::PARAM_INT);
  902. $query->bindValue(':id', $id, PDO::PARAM_INT);
  903. $query->execute() or error(db_error($query));
  904. }
  905. // Remove file from post
  906. function deleteFile($id, $remove_entirely_if_already=true, $file=null) {
  907. global $board, $config;
  908. $query = prepare(sprintf("SELECT `thread`, `files`, `num_files` FROM ``posts_%s`` WHERE `id` = :id LIMIT 1", $board['uri']));
  909. $query->bindValue(':id', $id, PDO::PARAM_INT);
  910. $query->execute() or error(db_error($query));
  911. if (!$post = $query->fetch(PDO::FETCH_ASSOC))
  912. error($config['error']['invalidpost']);
  913. $files = json_decode($post['files']);
  914. $file_to_delete = $file !== false ? $files[(int)$file] : (object)array('file' => false);
  915. if (!$files[0]) error(_('That post has no files.'));
  916. if ($files[0]->file == 'deleted' && $post['num_files'] == 1 && !$post['thread'])
  917. return; // Can't delete OP's image completely.
  918. $query = prepare(sprintf("UPDATE ``posts_%s`` SET `files` = :file WHERE `id` = :id", $board['uri']));
  919. if (($file && $file_to_delete->file == 'deleted') && $remove_entirely_if_already) {
  920. // Already deleted; remove file fully
  921. $files[$file] = null;
  922. } else {
  923. foreach ($files as $i => $f) {
  924. if (($file !== false && $i == $file) || $file === null) {
  925. // Delete thumbnail
  926. file_unlink($board['dir'] . $config['dir']['thumb'] . $f->thumb);
  927. unset($files[$i]->thumb);
  928. // Delete file
  929. file_unlink($board['dir'] . $config['dir']['img'] . $f->file);
  930. $files[$i]->file = 'deleted';
  931. }
  932. }
  933. }
  934. $query->bindValue(':file', json_encode($files), PDO::PARAM_STR);
  935. $query->bindValue(':id', $id, PDO::PARAM_INT);
  936. $query->execute() or error(db_error($query));
  937. if ($post['thread'])
  938. buildThread($post['thread']);
  939. else
  940. buildThread($id);
  941. }
  942. // rebuild post (markup)
  943. function rebuildPost($id) {
  944. global $board, $mod;
  945. $query = prepare(sprintf("SELECT * FROM ``posts_%s`` WHERE `id` = :id", $board['uri']));
  946. $query->bindValue(':id', $id, PDO::PARAM_INT);
  947. $query->execute() or error(db_error($query));
  948. if ((!$post = $query->fetch(PDO::FETCH_ASSOC)) || !$post['body_nomarkup'])
  949. return false;
  950. markup($post['body'] = &$post['body_nomarkup']);
  951. $post = (object)$post;
  952. event('rebuildpost', $post);
  953. $post = (array)$post;
  954. $query = prepare(sprintf("UPDATE ``posts_%s`` SET `body` = :body WHERE `id` = :id", $board['uri']));
  955. $query->bindValue(':body', $post['body']);
  956. $query->bindValue(':id', $id, PDO::PARAM_INT);
  957. $query->execute() or error(db_error($query));
  958. buildThread($post['thread'] ? $post['thread'] : $id);
  959. return true;
  960. }
  961. // Delete a post (reply or thread)
  962. function deletePost($id, $error_if_doesnt_exist=true, $rebuild_after=true) {
  963. global $board, $config;
  964. // Select post and replies (if thread) in one query
  965. $query = prepare(sprintf("SELECT `id`,`thread`,`files`,`slug` FROM ``posts_%s`` WHERE `id` = :id OR `thread` = :id", $board['uri']));
  966. $query->bindValue(':id', $id, PDO::PARAM_INT);
  967. $query->execute() or error(db_error($query));
  968. if ($query->rowCount() < 1) {
  969. if ($error_if_doesnt_exist)
  970. error($config['error']['invalidpost']);
  971. else return false;
  972. }
  973. $ids = array();
  974. // Delete posts and maybe replies
  975. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  976. event('delete', $post);
  977. if (!$post['thread']) {
  978. // Delete thread HTML page
  979. file_unlink($board['dir'] . $config['dir']['res'] . link_for($post) );
  980. file_unlink($board['dir'] . $config['dir']['res'] . link_for($post, true) ); // noko50
  981. file_unlink($board['dir'] . $config['dir']['res'] . sprintf('%d.json', $post['id']));
  982. $antispam_query = prepare('DELETE FROM ``antispam`` WHERE `board` = :board AND `thread` = :thread');
  983. $antispam_query->bindValue(':board', $board['uri']);
  984. $antispam_query->bindValue(':thread', $post['id']);
  985. $antispam_query->execute() or error(db_error($antispam_query));
  986. } elseif ($query->rowCount() == 1) {
  987. // Rebuild thread
  988. $rebuild = &$post['thread'];
  989. }
  990. if ($post['files']) {
  991. // Delete file
  992. foreach (json_decode($post['files']) as $i => $f) {
  993. if ($f->file !== 'deleted') {
  994. file_unlink($board['dir'] . $config['dir']['img'] . $f->file);
  995. file_unlink($board['dir'] . $config['dir']['thumb'] . $f->thumb);
  996. }
  997. }
  998. }
  999. $ids[] = (int)$post['id'];
  1000. }
  1001. $query = prepare(sprintf("DELETE FROM ``posts_%s`` WHERE `id` = :id OR `thread` = :id", $board['uri']));
  1002. $query->bindValue(':id', $id, PDO::PARAM_INT);
  1003. $query->execute() or error(db_error($query));
  1004. $query = prepare("SELECT `board`, `post` FROM ``cites`` WHERE `target_board` = :board AND (`target` = " . implode(' OR `target` = ', $ids) . ") ORDER BY `board`");
  1005. $query->bindValue(':board', $board['uri']);
  1006. $query->execute() or error(db_error($query));
  1007. while ($cite = $query->fetch(PDO::FETCH_ASSOC)) {
  1008. if ($board['uri'] != $cite['board']) {
  1009. if (!isset($tmp_board))
  1010. $tmp_board = $board['uri'];
  1011. openBoard($cite['board']);
  1012. }
  1013. rebuildPost($cite['post']);
  1014. }
  1015. if (isset($tmp_board))
  1016. openBoard($tmp_board);
  1017. $query = prepare("DELETE FROM ``cites`` WHERE (`target_board` = :board AND (`target` = " . implode(' OR `target` = ', $ids) . ")) OR (`board` = :board AND (`post` = " . implode(' OR `post` = ', $ids) . "))");
  1018. $query->bindValue(':board', $board['uri']);
  1019. $query->execute() or error(db_error($query));
  1020. if (isset($rebuild) && $rebuild_after) {
  1021. buildThread($rebuild);
  1022. buildIndex();
  1023. }
  1024. return true;
  1025. }
  1026. function clean($pid = false) {
  1027. global $board, $config;
  1028. $offset = round($config['max_pages']*$config['threads_per_page']);
  1029. // I too wish there was an easier way of doing this...
  1030. $query = prepare(sprintf("SELECT `id` FROM ``posts_%s`` WHERE `thread` IS NULL ORDER BY `sticky` DESC, `bump` DESC LIMIT :offset, 9001", $board['uri']));
  1031. $query->bindValue(':offset', $offset, PDO::PARAM_INT);
  1032. $query->execute() or error(db_error($query));
  1033. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1034. deletePost($post['id'], false, false);
  1035. if ($pid) modLog("Automatically deleting thread #{$post['id']} due to new thread #{$pid}");
  1036. }
  1037. // Bump off threads with X replies earlier, spam prevention method
  1038. if ($config['early_404']) {
  1039. $offset = round($config['early_404_page']*$config['threads_per_page']);
  1040. $query = prepare(sprintf("SELECT `id` AS `thread_id`, (SELECT COUNT(`id`) FROM ``posts_%s`` WHERE `thread` = `thread_id`) AS `reply_count` FROM ``posts_%s`` WHERE `thread` IS NULL ORDER BY `sticky` DESC, `bump` DESC LIMIT :offset, 9001", $board['uri'], $board['uri']));
  1041. $query->bindValue(':offset', $offset, PDO::PARAM_INT);
  1042. $query->execute() or error(db_error($query));
  1043. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1044. if ($post['reply_count'] < $config['early_404_replies']) {
  1045. deletePost($post['thread_id'], false, false);
  1046. if ($pid) modLog("Automatically deleting thread #{$post['thread_id']} due to new thread #{$pid} (early 404 is set, #{$post['thread_id']} had {$post['reply_count']} replies)");
  1047. }
  1048. }
  1049. }
  1050. }
  1051. function thread_find_page($thread) {
  1052. global $config, $board;
  1053. $query = query(sprintf("SELECT `id` FROM ``posts_%s`` WHERE `thread` IS NULL ORDER BY `sticky` DESC, `bump` DESC", $board['uri'])) or error(db_error($query));
  1054. $threads = $query->fetchAll(PDO::FETCH_COLUMN);
  1055. if (($index = array_search($thread, $threads)) === false)
  1056. return false;
  1057. return floor(($config['threads_per_page'] + $index) / $config['threads_per_page']);
  1058. }
  1059. function index($page, $mod=false) {
  1060. global $board, $config, $debug;
  1061. $body = '';
  1062. $offset = round($page*$config['threads_per_page']-$config['threads_per_page']);
  1063. $query = prepare(sprintf("SELECT * FROM ``posts_%s`` WHERE `thread` IS NULL ORDER BY `sticky` DESC, `bump` DESC LIMIT :offset,:threads_per_page", $board['uri']));
  1064. $query->bindValue(':offset', $offset, PDO::PARAM_INT);
  1065. $query->bindValue(':threads_per_page', $config['threads_per_page'], PDO::PARAM_INT);
  1066. $query->execute() or error(db_error($query));
  1067. if ($page == 1 && $query->rowCount() < $config['threads_per_page'])
  1068. $board['thread_count'] = $query->rowCount();
  1069. if ($query->rowCount() < 1 && $page > 1)
  1070. return false;
  1071. $threads = array();
  1072. while ($th = $query->fetch(PDO::FETCH_ASSOC)) {
  1073. $thread = new Thread($th, $mod ? '?/' : $config['root'], $mod);
  1074. if ($config['cache']['enabled']) {
  1075. $cached = cache::get("thread_index_{$board['uri']}_{$th['id']}");
  1076. if (isset($cached['replies'], $cached['omitted'])) {
  1077. $replies = $cached['replies'];
  1078. $omitted = $cached['omitted'];
  1079. } else {
  1080. unset($cached);
  1081. }
  1082. }
  1083. if (!isset($cached)) {
  1084. $posts = prepare(sprintf("SELECT * FROM ``posts_%s`` WHERE `thread` = :id ORDER BY `id` DESC LIMIT :limit", $board['uri']));
  1085. $posts->bindValue(':id', $th['id']);
  1086. $posts->bindValue(':limit', ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview']), PDO::PARAM_INT);
  1087. $posts->execute() or error(db_error($posts));
  1088. $replies = array_reverse($posts->fetchAll(PDO::FETCH_ASSOC));
  1089. if (count($replies) == ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview'])) {
  1090. $count = numPosts($th['id']);
  1091. $omitted = array('post_count' => $count['replies'], 'image_count' => $count['images']);
  1092. } else {
  1093. $omitted = false;
  1094. }
  1095. if ($config['cache']['enabled'])
  1096. cache::set("thread_index_{$board['uri']}_{$th['id']}", array(
  1097. 'replies' => $replies,
  1098. 'omitted' => $omitted,
  1099. ));
  1100. }
  1101. $num_images = 0;
  1102. foreach ($replies as $po) {
  1103. if ($po['num_files'])
  1104. $num_images+=$po['num_files'];
  1105. $thread->add(new Post($po, $mod ? '?/' : $config['root'], $mod));
  1106. }
  1107. $thread->images = $num_images;
  1108. $thread->replies = isset($omitted['post_count']) ? $omitted['post_count'] : count($replies);
  1109. if ($omitted) {
  1110. $thread->omitted = $omitted['post_count'] - ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview']);
  1111. $thread->omitted_images = $omitted['image_count'] - $num_images;
  1112. }
  1113. $threads[] = $thread;
  1114. $body .= $thread->build(true);
  1115. }
  1116. if ($config['file_board']) {
  1117. $body = Element('fileboard.html', array('body' => $body, 'mod' => $mod));
  1118. }
  1119. return array(
  1120. 'board' => $board,
  1121. 'body' => $body,
  1122. 'post_url' => $config['post_url'],
  1123. 'config' => $config,
  1124. 'boardlist' => createBoardlist($mod),
  1125. 'threads' => $threads,
  1126. );
  1127. }
  1128. function getPageButtons($pages, $mod=false) {
  1129. global $config, $board;
  1130. $btn = array();
  1131. $root = ($mod ? '?/' : $config['root']) . $board['dir'];
  1132. foreach ($pages as $num => $page) {
  1133. if (isset($page['selected'])) {
  1134. // Previous button
  1135. if ($num == 0) {
  1136. // There is no previous page.
  1137. $btn['prev'] = _('Previous');
  1138. } else {
  1139. $loc = ($mod ? '?/' . $board['uri'] . '/' : '') .
  1140. ($num == 1 ?
  1141. $config['file_index']
  1142. :
  1143. sprintf($config['file_page'], $num)
  1144. );
  1145. $btn['prev'] = '<form action="' . ($mod ? '' : $root . $loc) . '" method="get">' .
  1146. ($mod ?
  1147. '<input type="hidden" name="status" value="301" />' .
  1148. '<input type="hidden" name="r" value="' . htmlentities($loc) . '" />'
  1149. :'') .
  1150. '<input type="submit" value="' . _('Previous') . '" /></form>';
  1151. }
  1152. if ($num == count($pages) - 1) {
  1153. // There is no next page.
  1154. $btn['next'] = _('Next');
  1155. } else {
  1156. $loc = ($mod ? '?/' . $board['uri'] . '/' : '') . sprintf($config['file_page'], $num + 2);
  1157. $btn['next'] = '<form action="' . ($mod ? '' : $root . $loc) . '" method="get">' .
  1158. ($mod ?
  1159. '<input type="hidden" name="status" value="301" />' .
  1160. '<input type="hidden" name="r" value="' . htmlentities($loc) . '" />'
  1161. :'') .
  1162. '<input type="submit" value="' . _('Next') . '" /></form>';
  1163. }
  1164. }
  1165. }
  1166. return $btn;
  1167. }
  1168. function getPages($mod=false) {
  1169. global $board, $config;
  1170. if (isset($board['thread_count'])) {
  1171. $count = $board['thread_count'];
  1172. } else {
  1173. // Count threads
  1174. $query = query(sprintf("SELECT COUNT(*) FROM ``posts_%s`` WHERE `thread` IS NULL", $board['uri'])) or error(db_error());
  1175. $count = $query->fetchColumn();
  1176. }
  1177. $count = floor(($config['threads_per_page'] + $count - 1) / $config['threads_per_page']);
  1178. if ($count < 1) $count = 1;
  1179. $pages = array();
  1180. for ($x=0;$x<$count && $x<$config['max_pages'];$x++) {
  1181. $pages[] = array(
  1182. 'num' => $x+1,
  1183. 'link' => $x==0 ? ($mod ? '?/' : $config['root']) . $board['dir'] . $config['file_index'] : ($mod ? '?/' : $config['root']) . $board['dir'] . sprintf($config['file_page'], $x+1)
  1184. );
  1185. }
  1186. return $pages;
  1187. }
  1188. // Stolen with permission from PlainIB (by Frank Usrs)
  1189. function make_comment_hex($str) {
  1190. // remove cross-board citations
  1191. // the numbers don't matter
  1192. $str = preg_replace('!>>>/[A-Za-z0-9]+/!', '', $str);
  1193. if (function_exists('iconv')) {
  1194. // remove diacritics and other noise
  1195. // FIXME: this removes cyrillic entirely
  1196. $oldstr = $str;
  1197. $str = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $str);
  1198. if (!$str) $str = $oldstr;
  1199. }
  1200. $str = strtolower($str);
  1201. // strip all non-alphabet characters
  1202. $str = preg_replace('/[^a-z]/', '', $str);
  1203. return md5($str);
  1204. }
  1205. function makerobot($body) {
  1206. global $config;
  1207. $body = strtolower($body);
  1208. // Leave only letters
  1209. $body = preg_replace('/[^a-z]/i', '', $body);
  1210. // Remove repeating characters
  1211. if ($config['robot_strip_repeating'])
  1212. $body = preg_replace('/(.)\\1+/', '$1', $body);
  1213. return sha1($body);
  1214. }
  1215. function checkRobot($body) {
  1216. if (empty($body) || event('check-robot', $body))
  1217. return true;
  1218. $body = makerobot($body);
  1219. $query = prepare("SELECT 1 FROM ``robot`` WHERE `hash` = :hash LIMIT 1");
  1220. $query->bindValue(':hash', $body);
  1221. $query->execute() or error(db_error($query));
  1222. if ($query->fetchColumn()) {
  1223. return true;
  1224. }
  1225. // Insert new hash
  1226. $query = prepare("INSERT INTO ``robot`` VALUES (:hash)");
  1227. $query->bindValue(':hash', $body);
  1228. $query->execute() or error(db_error($query));
  1229. return false;
  1230. }
  1231. // Returns an associative array with 'replies' and 'images' keys
  1232. function numPosts($id) {
  1233. global $board;
  1234. $query = prepare(sprintf("SELECT COUNT(*) AS `replies`, SUM(`num_files`) AS `images` FROM ``posts_%s`` WHERE `thread` = :thread", $board['uri'], $board['uri']));
  1235. $query->bindValue(':thread', $id, PDO::PARAM_INT);
  1236. $query->execute() or error(db_error($query));
  1237. return $query->fetch(PDO::FETCH_ASSOC);
  1238. }
  1239. function muteTime() {
  1240. global $config;
  1241. if ($time = event('mute-time'))
  1242. return $time;
  1243. // Find number of mutes in the past X hours
  1244. $query = prepare("SELECT COUNT(*) FROM ``mutes`` WHERE `time` >= :time AND `ip` = :ip");
  1245. $query->bindValue(':time', time()-($config['robot_mute_hour']*3600), PDO::PARAM_INT);
  1246. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
  1247. $query->execute() or error(db_error($query));
  1248. if (!$result = $query->fetchColumn())
  1249. return 0;
  1250. return pow($config['robot_mute_multiplier'], $result);
  1251. }
  1252. function mute() {
  1253. // Insert mute
  1254. $query = prepare("INSERT INTO ``mutes`` VALUES (:ip, :time)");
  1255. $query->bindValue(':time', time(), PDO::PARAM_INT);
  1256. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
  1257. $query->execute() or error(db_error($query));
  1258. return muteTime();
  1259. }
  1260. function checkMute() {
  1261. global $config, $debug;
  1262. if ($config['cache']['enabled']) {
  1263. // Cached mute?
  1264. if (($mute = cache::get("mute_${_SERVER['REMOTE_ADDR']}")) && ($mutetime = cache::get("mutetime_${_SERVER['REMOTE_ADDR']}"))) {
  1265. error(sprintf($config['error']['youaremuted'], $mute['time'] + $mutetime - time()));
  1266. }
  1267. }
  1268. $mutetime = muteTime();
  1269. if ($mutetime > 0) {
  1270. // Find last mute time
  1271. $query = prepare("SELECT `time` FROM ``mutes`` WHERE `ip` = :ip ORDER BY `time` DESC LIMIT 1");
  1272. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
  1273. $query->execute() or error(db_error($query));
  1274. if (!$mute = $query->fetch(PDO::FETCH_ASSOC)) {
  1275. // What!? He's muted but he's not muted...
  1276. return;
  1277. }
  1278. if ($mute['time'] + $mutetime > time()) {
  1279. if ($config['cache']['enabled']) {
  1280. cache::set("mute_${_SERVER['REMOTE_ADDR']}", $mute, $mute['time'] + $mutetime - time());
  1281. cache::set("mutetime_${_SERVER['REMOTE_ADDR']}", $mutetime, $mute['time'] + $mutetime - time());
  1282. }
  1283. // Not expired yet
  1284. error(sprintf($config['error']['youaremuted'], $mute['time'] + $mutetime - time()));
  1285. } else {
  1286. // Already expired
  1287. return;
  1288. }
  1289. }
  1290. }
  1291. function buildIndex($global_api = "yes") {
  1292. global $board, $config, $build_pages;
  1293. if (!$config['smart_build']) {
  1294. $pages = getPages();
  1295. if (!$config['try_smarter'])
  1296. $antibot = create_antibot($board['uri']);
  1297. if ($config['api']['enabled']) {
  1298. $api = new Api();
  1299. $catalog = array();
  1300. }
  1301. }
  1302. for ($page = 1; $page <= $config['max_pages']; $page++) {
  1303. $filename = $board['dir'] . ($page == 1 ? $config['file_index'] : sprintf($config['file_page'], $page));
  1304. $jsonFilename = $board['dir'] . ($page - 1) . '.json'; // pages should start from 0
  1305. if ((!$config['api']['enabled'] || $global_api == "skip" || $config['smart_build']) && $config['try_smarter']
  1306. && isset($build_pages) && !empty($build_pages) && !in_array($page, $build_pages) )
  1307. continue;
  1308. if (!$config['smart_build']) {
  1309. $content = index($page);
  1310. if (!$content)
  1311. break;
  1312. // json api
  1313. if ($config['api']['enabled']) {
  1314. $threads = $content['threads'];
  1315. $json = json_encode($api->translatePage($threads));
  1316. file_write($jsonFilename, $json);
  1317. $catalog[$page-1] = $threads;
  1318. }
  1319. if ($config['api']['enabled'] && $global_api != "skip" && $config['try_smarter'] && isset($build_pages)
  1320. && !empty($build_pages) && !in_array($page, $build_pages) )
  1321. continue;
  1322. if ($config['try_smarter']) {
  1323. $antibot = create_antibot($board['uri'], 0 - $page);
  1324. $content['current_page'] = $page;
  1325. }
  1326. $antibot->reset();
  1327. $content['pages'] = $pages;
  1328. $content['pages'][$page-1]['selected'] = true;
  1329. $content['btn'] = getPageButtons($content['pages']);
  1330. $content['antibot'] = $antibot;
  1331. file_write($filename, Element('index.html', $content));
  1332. }
  1333. else {
  1334. file_unlink($filename);
  1335. file_unlink($jsonFilename);
  1336. }
  1337. }
  1338. if (!$config['smart_build'] && $page < $config['max_pages']) {
  1339. for (;$page<=$config['max_pages'];$page++) {
  1340. $filename = $board['dir'] . ($page==1 ? $config['file_index'] : sprintf($config['file_page'], $page));
  1341. file_unlink($filename);
  1342. if ($config['api']['enabled']) {
  1343. $jsonFilename = $board['dir'] . ($page - 1) . '.json';
  1344. file_unlink($jsonFilename);
  1345. }
  1346. }
  1347. }
  1348. // json api catalog
  1349. if ($config['api']['enabled'] && $global_api != "skip") {
  1350. if ($config['smart_build']) {
  1351. $jsonFilename = $board['dir'] . 'catalog.json';
  1352. file_unlink($jsonFilename);
  1353. $jsonFilename = $board['dir'] . 'threads.json';
  1354. file_unlink($jsonFilename);
  1355. }
  1356. else {
  1357. $json = json_encode($api->translateCatalog($catalog));
  1358. $jsonFilename = $board['dir'] . 'catalog.json';
  1359. file_write($jsonFilename, $json);
  1360. $json = json_encode($api->translateCatalog($catalog, true));
  1361. $jsonFilename = $board['dir'] . 'threads.json';
  1362. file_write($jsonFilename, $json);
  1363. }
  1364. }
  1365. if ($config['try_smarter'])
  1366. $build_pages = array();
  1367. }
  1368. function buildJavascript() {
  1369. global $config;
  1370. $stylesheets = array();
  1371. foreach ($config['stylesheets'] as $name => $uri) {
  1372. $stylesheets[] = array(
  1373. 'name' => addslashes($name),
  1374. 'uri' => addslashes((!empty($uri) ? $config['uri_stylesheets'] : '') . $uri));
  1375. }
  1376. $script = Element('main.js', array(
  1377. 'config' => $config,
  1378. 'stylesheets' => $stylesheets
  1379. ));
  1380. // Check if we have translation for the javascripts; if yes, we add it to additional javascripts
  1381. list($pure_locale) = explode(".", $config['locale']);
  1382. if (file_exists ($jsloc = "inc/locale/$pure_locale/LC_MESSAGES/javascript.js")) {
  1383. $script = file_get_contents($jsloc) . "\n\n" . $script;
  1384. }
  1385. if ($config['additional_javascript_compile']) {
  1386. foreach ($config['additional_javascript'] as $file) {
  1387. $script .= file_get_contents($file);
  1388. }
  1389. }
  1390. if ($config['minify_js']) {
  1391. require_once 'inc/lib/minify/JSMin.php';
  1392. $script = JSMin::minify($script);
  1393. }
  1394. file_write($config['file_script'], $script);
  1395. }
  1396. function checkDNSBL() {
  1397. global $config;
  1398. if (isIPv6())
  1399. return; // No IPv6 support yet.
  1400. if (!isset($_SERVER['REMOTE_ADDR']))
  1401. return; // Fix your web server configuration
  1402. if (in_array($_SERVER['REMOTE_ADDR'], $config['dnsbl_exceptions']))
  1403. return;
  1404. $ipaddr = ReverseIPOctets($_SERVER['REMOTE_ADDR']);
  1405. foreach ($config['dnsbl'] as $blacklist) {
  1406. if (!is_array($blacklist))
  1407. $blacklist = array($blacklist);
  1408. if (($lookup = str_replace('%', $ipaddr, $blacklist[0])) == $blacklist[0])
  1409. $lookup = $ipaddr . '.' . $blacklist[0];
  1410. if (!$ip = DNS($lookup))
  1411. continue; // not in list
  1412. $blacklist_name = isset($blacklist[2]) ? $blacklist[2] : $blacklist[0];
  1413. if (!isset($blacklist[1])) {
  1414. // If you're listed at all, you're blocked.
  1415. error(sprintf($config['error']['dnsbl'], $blacklist_name));
  1416. } elseif (is_array($blacklist[1])) {
  1417. foreach ($blacklist[1] as $octet) {
  1418. if ($ip == $octet || $ip == '127.0.0.' . $octet)
  1419. error(sprintf($config['error']['dnsbl'], $blacklist_name));
  1420. }
  1421. } elseif (is_callable($blacklist[1])) {
  1422. if ($blacklist[1]($ip))
  1423. error(sprintf($config['error']['dnsbl'], $blacklist_name));
  1424. } else {
  1425. if ($ip == $blacklist[1] || $ip == '127.0.0.' . $blacklist[1])
  1426. error(sprintf($config['error']['dnsbl'], $blacklist_name));
  1427. }
  1428. }
  1429. }
  1430. function isIPv6() {
  1431. return strstr($_SERVER['REMOTE_ADDR'], ':') !== false;
  1432. }
  1433. function ReverseIPOctets($ip) {
  1434. return implode('.', array_reverse(explode('.', $ip)));
  1435. }
  1436. function wordfilters(&$body) {
  1437. global $config;
  1438. foreach ($config['wordfilters'] as $filter) {
  1439. if (isset($filter[2]) && $filter[2]) {
  1440. if (is_callable($filter[1]))
  1441. $body = preg_replace_callback($filter[0], $filter[1], $body);
  1442. else
  1443. $body = preg_replace($filter[0], $filter[1], $body);
  1444. } else {
  1445. $body = str_ireplace($filter[0], $filter[1], $body);
  1446. }
  1447. }
  1448. }
  1449. function quote($body, $quote=true) {
  1450. global $config;
  1451. $body = str_replace('<br/>', "\n", $body);
  1452. $body = strip_tags($body);
  1453. $body = preg_replace("/(^|\n)/", '$1&gt;', $body);
  1454. $body .= "\n";
  1455. if ($config['minify_html'])
  1456. $body = str_replace("\n", '&#010;', $body);
  1457. return $body;
  1458. }
  1459. function markup_url($matches) {
  1460. global $config, $markup_urls;
  1461. $url = $matches[1];
  1462. $after = $matches[2];
  1463. $markup_urls[] = $url;
  1464. $link = (object) array(
  1465. 'href' => $config['link_prefix'] . $url,
  1466. 'text' => $url,
  1467. 'rel' => 'nofollow',
  1468. 'target' => '_blank',
  1469. );
  1470. event('markup-url', $link);
  1471. $link = (array)$link;
  1472. $parts = array();
  1473. foreach ($link as $attr => $value) {
  1474. if ($attr == 'text' || $attr == 'after')
  1475. continue;
  1476. $parts[] = $attr . '="' . $value . '"';
  1477. }
  1478. if (isset($link['after']))
  1479. $after = $link['after'] . $after;
  1480. return '<a ' . implode(' ', $parts) . '>' . $link['text'] . '</a>' . $after;
  1481. }
  1482. function unicodify($body) {
  1483. $body = str_replace('...', '&hellip;', $body);
  1484. $body = str_replace('&lt;--', '&larr;', $body);
  1485. $body = str_replace('--&gt;', '&rarr;', $body);
  1486. // En and em- dashes are rendered exactly the same in
  1487. // most monospace fonts (they look the same in code
  1488. // editors).
  1489. $body = str_replace('---', '&mdash;', $body); // em dash
  1490. $body = str_replace('--', '&ndash;', $body); // en dash
  1491. return $body;
  1492. }
  1493. function extract_modifiers($body) {
  1494. $modifiers = array();
  1495. if (preg_match_all('@<tinyboard ([\w\s]+)>(.*?)</tinyboard>@us', $body, $matches, PREG_SET_ORDER)) {
  1496. foreach ($matches as $match) {
  1497. if (preg_match('/^escape /', $match[1]))
  1498. continue;
  1499. $modifiers[$match[1]] = html_entity_decode($match[2]);
  1500. }
  1501. }
  1502. return $modifiers;
  1503. }
  1504. function remove_modifiers($body) {
  1505. return preg_replace('@<tinyboard ([\w\s]+)>(.+?)</tinyboard>@usm', '', $body);
  1506. }
  1507. function markup(&$body, $track_cites = false, $op = false) {
  1508. global $board, $config, $markup_urls;
  1509. $modifiers = extract_modifiers($body);
  1510. $body = preg_replace('@<tinyboard (?!escape )([\w\s]+)>(.+?)</tinyboard>@us', '', $body);
  1511. $body = preg_replace('@<(tinyboard) escape ([\w\s]+)>@i', '<$1 $2>', $body);
  1512. if (isset($modifiers['raw html']) && $modifiers['raw html'] == '1') {
  1513. return array();
  1514. }
  1515. $body = str_replace("\r", '', $body);
  1516. $body = utf8tohtml($body);
  1517. if (mysql_version() < 50503)
  1518. $body = mb_encode_numericentity($body, array(0x010000, 0xffffff, 0, 0xffffff), 'UTF-8');
  1519. if ($config['markup_code']) {
  1520. $code_markup = array();
  1521. $body = preg_replace_callback($config['markup_code'], function($matches) use (&$code_markup) {
  1522. $d = count($code_markup);
  1523. $code_markup[] = $matches;
  1524. return "<code $d>";
  1525. }, $body);
  1526. }
  1527. foreach ($config['markup'] as $markup) {
  1528. if (is_string($markup[1])) {
  1529. $body = preg_replace($markup[0], $markup[1], $body);
  1530. } elseif (is_callable($markup[1])) {
  1531. $body = preg_replace_callback($markup[0], $markup[1], $body);
  1532. }
  1533. }
  1534. if ($config['markup_urls']) {
  1535. $markup_urls = array();
  1536. $body = preg_replace_callback(
  1537. '/((?:https?:\/\/|ftp:\/\/|irc:\/\/)[^\s<>()"]+?(?:\([^\s<>()"]*?\)[^\s<>()"]*?)*)((?:\s|<|>|"|\.||\]|!|\?|,|&#44;|&quot;)*(?:[\s<>()"]|$))/',
  1538. 'markup_url',
  1539. $body,
  1540. -1,
  1541. $num_links);
  1542. if ($num_links > $config['max_links'])
  1543. error($config['error']['toomanylinks']);
  1544. }
  1545. if ($config['markup_repair_tidy'])
  1546. $body = str_replace(' ', ' &nbsp;', $body);
  1547. if ($config['auto_unicode']) {
  1548. $body = unicodify($body);
  1549. if ($config['markup_urls']) {
  1550. foreach ($markup_urls as &$url) {
  1551. $body = str_replace(unicodify($url), $url, $body);
  1552. }
  1553. }
  1554. }
  1555. $tracked_cites = array();
  1556. // Cites
  1557. if (isset($board) && preg_match_all('/(^|\s)&gt;&gt;(\d+?)([\s,.)?]|$)/m', $body, $cites, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) {
  1558. if (count($cites[0]) > $config['max_cites']) {
  1559. error($config['error']['toomanycites']);
  1560. }
  1561. $skip_chars = 0;
  1562. $body_tmp = $body;
  1563. $search_cites = array();
  1564. foreach ($cites as $matches) {
  1565. $search_cites[] = '`id` = ' . $matches[2][0];
  1566. }
  1567. $search_cites = array_unique($search_cites);
  1568. $query = query(sprintf('SELECT `thread`, `id` FROM ``posts_%s`` WHERE ' .
  1569. implode(' OR ', $search_cites), $board['uri'])) or error(db_error());
  1570. $cited_posts = array();
  1571. while ($cited = $query->fetch(PDO::FETCH_ASSOC)) {
  1572. $cited_posts[$cited['id']] = $cited['thread'] ? $cited['thread'] : false;
  1573. }
  1574. foreach ($cites as $matches) {
  1575. $cite = $matches[2][0];
  1576. // preg_match_all is not multibyte-safe
  1577. foreach ($matches as &$match) {
  1578. $match[1] = mb_strlen(substr($body_tmp, 0, $match[1]));
  1579. }
  1580. if (isset($cited_posts[$cite])) {
  1581. $replacement = '<a onclick="highlightReply(\''.$cite.'\', event);" href="' .
  1582. $config['root'] . $board['dir'] . $config['dir']['res'] .
  1583. link_for(array('id' => $cite, 'thread' => $cited_posts[$cite])) . '#' . $cite . '">' .
  1584. '&gt;&gt;' . $cite .
  1585. '</a>';
  1586. $body = mb_substr_replace($body, $matches[1][0] . $replacement . $matches[3][0], $matches[0][1] + $skip_chars, mb_strlen($matches[0][0]));
  1587. $skip_chars += mb_strlen($matches[1][0] . $replacement . $matches[3][0]) - mb_strlen($matches[0][0]);
  1588. if ($track_cites && $config['track_cites'])
  1589. $tracked_cites[] = array($board['uri'], $cite);
  1590. }
  1591. }
  1592. }
  1593. // Cross-board linking
  1594. if (preg_match_all('/(^|\s)&gt;&gt;&gt;\/(' . $config['board_regex'] . 'f?)\/(\d+)?([\s,.)?]|$)/um', $body, $cites, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) {
  1595. if (count($cites[0]) > $config['max_cites']) {
  1596. error($config['error']['toomanycross']);
  1597. }
  1598. $skip_chars = 0;
  1599. $body_tmp = $body;
  1600. if (isset($cited_posts)) {
  1601. // Carry found posts from local board >>X links
  1602. foreach ($cited_posts as $cite => $thread) {
  1603. $cited_posts[$cite] = $config['root'] . $board['dir'] . $config['dir']['res'] .
  1604. ($thread ? $thread : $cite) . '.html#' . $cite;
  1605. }
  1606. $cited_posts = array(
  1607. $board['uri'] => $cited_posts
  1608. );
  1609. } else
  1610. $cited_posts = array();
  1611. $crossboard_indexes = array();
  1612. $search_cites_boards = array();
  1613. foreach ($cites as $matches) {
  1614. $_board = $matches[2][0];
  1615. $cite = @$matches[3][0];
  1616. if (!isset($search_cites_boards[$_board]))
  1617. $search_cites_boards[$_board] = array();
  1618. $search_cites_boards[$_board][] = $cite;
  1619. }
  1620. $tmp_board = $board['uri'];
  1621. foreach ($search_cites_boards as $_board => $search_cites) {
  1622. $clauses = array();
  1623. foreach ($search_cites as $cite) {
  1624. if (!$cite || isset($cited_posts[$_board][$cite]))
  1625. continue;
  1626. $clauses[] = '`id` = ' . $cite;
  1627. }
  1628. $clauses = array_unique($clauses);
  1629. if ($board['uri'] != $_board) {
  1630. if (!openBoard($_board))
  1631. continue; // Unknown board
  1632. }
  1633. if (!empty($clauses)) {
  1634. $cited_posts[$_board] = array();
  1635. $query = query(sprintf('SELECT `thread`, `id`, `slug` FROM ``posts_%s`` WHERE ' .
  1636. implode(' OR ', $clauses), $board['uri'])) or error(db_error());
  1637. while ($cite = $query->fetch(PDO::FETCH_ASSOC)) {
  1638. $cited_posts[$_board][$cite['id']] = $config['root'] . $board['dir'] . $config['dir']['res'] .
  1639. link_for($cite) . '#' . $cite['id'];
  1640. }
  1641. }
  1642. $crossboard_indexes[$_board] = $config['root'] . $board['dir'] . $config['file_index'];
  1643. }
  1644. // Restore old board
  1645. if ($board['uri'] != $tmp_board)
  1646. openBoard($tmp_board);
  1647. foreach ($cites as $matches) {
  1648. $_board = $matches[2][0];
  1649. $cite = @$matches[3][0];
  1650. // preg_match_all is not multibyte-safe
  1651. foreach ($matches as &$match) {
  1652. $match[1] = mb_strlen(substr($body_tmp, 0, $match[1]));
  1653. }
  1654. if ($cite) {
  1655. if (isset($cited_posts[$_board][$cite])) {
  1656. $link = $cited_posts[$_board][$cite];
  1657. $replacement = '<a ' .
  1658. ($_board == $board['uri'] ?
  1659. 'onclick="highlightReply(\''.$cite.'\', event);" '
  1660. : '') . 'href="' . $link . '">' .
  1661. '&gt;&gt;&gt;/' . $_board . '/' . $cite .
  1662. '</a>';
  1663. $body = mb_substr_replace($body, $matches[1][0] . $replacement . $matches[4][0], $matches[0][1] + $skip_chars, mb_strlen($matches[0][0]));
  1664. $skip_chars += mb_strlen($matches[1][0] . $replacement . $matches[4][0]) - mb_strlen($matches[0][0]);
  1665. if ($track_cites && $config['track_cites'])
  1666. $tracked_cites[] = array($_board, $cite);
  1667. }
  1668. } elseif(isset($crossboard_indexes[$_board])) {
  1669. $replacement = '<a href="' . $crossboard_indexes[$_board] . '">' .
  1670. '&gt;&gt;&gt;/' . $_board . '/' .
  1671. '</a>';
  1672. $body = mb_substr_replace($body, $matches[1][0] . $replacement . $matches[4][0], $matches[0][1] + $skip_chars, mb_strlen($matches[0][0]));
  1673. $skip_chars += mb_strlen($matches[1][0] . $replacement . $matches[4][0]) - mb_strlen($matches[0][0]);
  1674. }
  1675. }
  1676. }
  1677. $tracked_cites = array_unique($tracked_cites, SORT_REGULAR);
  1678. $body = preg_replace("/^\s*&gt;.*$/m", '<span class="quote">$0</span>', $body);
  1679. if ($config['strip_superfluous_returns'])
  1680. $body = preg_replace('/\s+$/', '', $body);
  1681. $body = preg_replace("/\n/", '<br/>', $body);
  1682. // Fix code markup
  1683. if ($config['markup_code']) {
  1684. foreach ($code_markup as $id => $val) {
  1685. $code = isset($val[2]) ? $val[2] : $val[1];
  1686. $code_lang = isset($val[2]) ? $val[1] : "";
  1687. $code = "<pre class='code lang-$code_lang'>".str_replace(array("\n","\t"), array("&#10;","&#9;"), htmlspecialchars($code))."</pre>";
  1688. $body = str_replace("<code $id>", $code, $body);
  1689. }
  1690. }
  1691. if ($config['markup_repair_tidy']) {
  1692. $tidy = new tidy();
  1693. $body = str_replace("\t", '&#09;', $body);
  1694. $body = $tidy->repairString($body, array(
  1695. 'doctype' => 'omit',
  1696. 'bare' => true,
  1697. 'literal-attributes' => true,
  1698. 'indent' => false,
  1699. 'show-body-only' => true,
  1700. 'wrap' => 0,
  1701. 'output-bom' => false,
  1702. 'output-html' => true,
  1703. 'newline' => 'LF',
  1704. 'quiet' => true,
  1705. ), 'utf8');
  1706. $body = str_replace("\n", '', $body);
  1707. }
  1708. // replace tabs with 8 spaces
  1709. $body = str_replace("\t", ' ', $body);
  1710. return $tracked_cites;
  1711. }
  1712. function escape_markup_modifiers($string) {
  1713. return preg_replace('@<(tinyboard) ([\w\s]+)>@mi', '<$1 escape $2>', $string);
  1714. }
  1715. function utf8tohtml($utf8) {
  1716. return htmlspecialchars($utf8, ENT_NOQUOTES, 'UTF-8');
  1717. }
  1718. function ordutf8($string, &$offset) {
  1719. $code = ord(substr($string, $offset,1));
  1720. if ($code >= 128) { // otherwise 0xxxxxxx
  1721. if ($code < 224)
  1722. $bytesnumber = 2; // 110xxxxx
  1723. else if ($code < 240)
  1724. $bytesnumber = 3; // 1110xxxx
  1725. else if ($code < 248)
  1726. $bytesnumber = 4; // 11110xxx
  1727. $codetemp = $code - 192 - ($bytesnumber > 2 ? 32 : 0) - ($bytesnumber > 3 ? 16 : 0);
  1728. for ($i = 2; $i <= $bytesnumber; $i++) {
  1729. $offset ++;
  1730. $code2 = ord(substr($string, $offset, 1)) - 128; //10xxxxxx
  1731. $codetemp = $codetemp*64 + $code2;
  1732. }
  1733. $code = $codetemp;
  1734. }
  1735. $offset += 1;
  1736. if ($offset >= strlen($string))
  1737. $offset = -1;
  1738. return $code;
  1739. }
  1740. function strip_combining_chars($str) {
  1741. $chars = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
  1742. $str = '';
  1743. foreach ($chars as $char) {
  1744. $o = 0;
  1745. $ord = ordutf8($char, $o);
  1746. if ( ($ord >= 768 && $ord <= 879) || ($ord >= 1536 && $ord <= 1791) || ($ord >= 3655 && $ord <= 3659) || ($ord >= 7616 && $ord <= 7679) || ($ord >= 8400 && $ord <= 8447) || ($ord >= 65056 && $ord <= 65071))
  1747. continue;
  1748. $str .= $char;
  1749. }
  1750. return $str;
  1751. }
  1752. function buildThread($id, $return = false, $mod = false) {
  1753. global $board, $config, $build_pages;
  1754. $id = round($id);
  1755. if (event('build-thread', $id))
  1756. return;
  1757. if ($config['cache']['enabled'] && !$mod) {
  1758. // Clear cache
  1759. cache::delete("thread_index_{$board['uri']}_{$id}");
  1760. cache::delete("thread_{$board['uri']}_{$id}");
  1761. }
  1762. if ($config['try_smarter'] && !$mod)
  1763. $build_pages[] = thread_find_page($id);
  1764. if (!$config['smart_build'] || $return || $mod) {
  1765. $query = prepare(sprintf("SELECT * FROM ``posts_%s`` WHERE (`thread` IS NULL AND `id` = :id) OR `thread` = :id ORDER BY `thread`,`id`", $board['uri']));
  1766. $query->bindValue(':id', $id, PDO::PARAM_INT);
  1767. $query->execute() or error(db_error($query));
  1768. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1769. if (!isset($thread)) {
  1770. $thread = new Thread($post, $mod ? '?/' : $config['root'], $mod);
  1771. } else {
  1772. $thread->add(new Post($post, $mod ? '?/' : $config['root'], $mod));
  1773. }
  1774. }
  1775. // Check if any posts were found
  1776. if (!isset($thread))
  1777. error($config['error']['nonexistant']);
  1778. $hasnoko50 = $thread->postCount() >= $config['noko50_min'];
  1779. $antibot = $mod || $return ? false : create_antibot($board['uri'], $id);
  1780. $body = Element('thread.html', array(
  1781. 'board' => $board,
  1782. 'thread' => $thread,
  1783. 'body' => $thread->build(),
  1784. 'config' => $config,
  1785. 'id' => $id,
  1786. 'mod' => $mod,
  1787. 'hasnoko50' => $hasnoko50,
  1788. 'isnoko50' => false,
  1789. 'antibot' => $antibot,
  1790. 'boardlist' => createBoardlist($mod),
  1791. 'return' => ($mod ? '?' . $board['url'] . $config['file_index'] : $config['root'] . $board['dir'] . $config['file_index'])
  1792. ));
  1793. // json api
  1794. if ($config['api']['enabled']) {
  1795. $api = new Api();
  1796. $json = json_encode($api->translateThread($thread));
  1797. $jsonFilename = $board['dir'] . $config['dir']['res'] . $id . '.json';
  1798. file_write($jsonFilename, $json);
  1799. }
  1800. }
  1801. else {
  1802. $jsonFilename = $board['dir'] . $config['dir']['res'] . $id . '.json';
  1803. file_unlink($jsonFilename);
  1804. }
  1805. if ($config['smart_build'] && !$return && !$mod) {
  1806. $noko50fn = $board['dir'] . $config['dir']['res'] . link_for(array('id' => $id), true);
  1807. file_unlink($noko50fn);
  1808. file_unlink($board['dir'] . $config['dir']['res'] . link_for(array('id' => $id)));
  1809. } else if ($return) {
  1810. return $body;
  1811. } else {
  1812. $noko50fn = $board['dir'] . $config['dir']['res'] . link_for($thread, true);
  1813. if ($hasnoko50 || file_exists($noko50fn)) {
  1814. buildThread50($id, $return, $mod, $thread, $antibot);
  1815. }
  1816. file_write($board['dir'] . $config['dir']['res'] . link_for($thread), $body);
  1817. }
  1818. }
  1819. function buildThread50($id, $return = false, $mod = false, $thread = null, $antibot = false) {
  1820. global $board, $config, $build_pages;
  1821. $id = round($id);
  1822. if ($antibot)
  1823. $antibot->reset();
  1824. if (!$thread) {
  1825. $query = prepare(sprintf("SELECT * FROM ``posts_%s`` WHERE (`thread` IS NULL AND `id` = :id) OR `thread` = :id ORDER BY `thread`,`id` DESC LIMIT :limit", $board['uri']));
  1826. $query->bindValue(':id', $id, PDO::PARAM_INT);
  1827. $query->bindValue(':limit', $config['noko50_count']+1, PDO::PARAM_INT);
  1828. $query->execute() or error(db_error($query));
  1829. $num_images = 0;
  1830. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1831. if (!isset($thread)) {
  1832. $thread = new Thread($post, $mod ? '?/' : $config['root'], $mod);
  1833. } else {
  1834. if ($post['files'])
  1835. $num_images += $post['num_files'];
  1836. $thread->add(new Post($post, $mod ? '?/' : $config['root'], $mod));
  1837. }
  1838. }
  1839. // Check if any posts were found
  1840. if (!isset($thread))
  1841. error($config['error']['nonexistant']);
  1842. if ($query->rowCount() == $config['noko50_count']+1) {
  1843. $count = prepare(sprintf("SELECT COUNT(`id`) as `num` FROM ``posts_%s`` WHERE `thread` = :thread UNION ALL
  1844. SELECT SUM(`num_files`) FROM ``posts_%s`` WHERE `files` IS NOT NULL AND `thread` = :thread", $board['uri'], $board['uri']));
  1845. $count->bindValue(':thread', $id, PDO::PARAM_INT);
  1846. $count->execute() or error(db_error($count));
  1847. $c = $count->fetch();
  1848. $thread->omitted = $c['num'] - $config['noko50_count'];
  1849. $c = $count->fetch();
  1850. $thread->omitted_images = $c['num'] - $num_images;
  1851. }
  1852. $thread->posts = array_reverse($thread->posts);
  1853. } else {
  1854. $allPosts = $thread->posts;
  1855. $thread->posts = array_slice($allPosts, -$config['noko50_count']);
  1856. $thread->omitted += count($allPosts) - count($thread->posts);
  1857. foreach ($allPosts as $index => $post) {
  1858. if ($index == count($allPosts)-count($thread->posts))
  1859. break;
  1860. if ($post->files)
  1861. $thread->omitted_images += $post->num_files;
  1862. }
  1863. }
  1864. $hasnoko50 = $thread->postCount() >= $config['noko50_min'];
  1865. $body = Element('thread.html', array(
  1866. 'board' => $board,
  1867. 'thread' => $thread,
  1868. 'body' => $thread->build(false, true),
  1869. 'config' => $config,
  1870. 'id' => $id,
  1871. 'mod' => $mod,
  1872. 'hasnoko50' => $hasnoko50,
  1873. 'isnoko50' => true,
  1874. 'antibot' => $mod ? false : ($antibot ? $antibot : create_antibot($board['uri'], $id)),
  1875. 'boardlist' => createBoardlist($mod),
  1876. 'return' => ($mod ? '?' . $board['url'] . $config['file_index'] : $config['root'] . $board['dir'] . $config['file_index'])
  1877. ));
  1878. if ($return) {
  1879. return $body;
  1880. } else {
  1881. file_write($board['dir'] . $config['dir']['res'] . link_for($thread, true), $body);
  1882. }
  1883. }
  1884. function rrmdir($dir) {
  1885. if (is_dir($dir)) {
  1886. $objects = scandir($dir);
  1887. foreach ($objects as $object) {
  1888. if ($object != "." && $object != "..") {
  1889. if (filetype($dir."/".$object) == "dir")
  1890. rrmdir($dir."/".$object);
  1891. else
  1892. file_unlink($dir."/".$object);
  1893. }
  1894. }
  1895. reset($objects);
  1896. rmdir($dir);
  1897. }
  1898. }
  1899. function poster_id($ip, $thread) {
  1900. global $config;
  1901. if ($id = event('poster-id', $ip, $thread))
  1902. return $id;
  1903. // Confusing, hard to brute-force, but simple algorithm
  1904. return substr(sha1(sha1($ip . $config['secure_trip_salt'] . $thread) . $config['secure_trip_salt']), 0, $config['poster_id_length']);
  1905. }
  1906. function generate_tripcode($name) {
  1907. global $config;
  1908. if ($trip = event('tripcode', $name))
  1909. return $trip;
  1910. if (!preg_match('/^([^#]+)?(##|#)(.+)$/', $name, $match))
  1911. return array($name);
  1912. $name = $match[1];
  1913. $secure = $match[2] == '##';
  1914. $trip = $match[3];
  1915. // convert to SHIT_JIS encoding
  1916. $trip = mb_convert_encoding($trip, 'Shift_JIS', 'UTF-8');
  1917. // generate salt
  1918. $salt = substr($trip . 'H..', 1, 2);
  1919. $salt = preg_replace('/[^.-z]/', '.', $salt);
  1920. $salt = strtr($salt, ':;<=>?@[\]^_`', 'ABCDEFGabcdef');
  1921. if ($secure) {
  1922. if (isset($config['custom_tripcode']["##{$trip}"]))
  1923. $trip = $config['custom_tripcode']["##{$trip}"];
  1924. else
  1925. $trip = '!!' . substr(crypt($trip, str_replace('+', '.', '_..A.' . substr(base64_encode(sha1($trip . $config['secure_trip_salt'], true)), 0, 4))), -10);
  1926. } else {
  1927. if (isset($config['custom_tripcode']["#{$trip}"]))
  1928. $trip = $config['custom_tripcode']["#{$trip}"];
  1929. else
  1930. $trip = '!' . substr(crypt($trip, $salt), -10);
  1931. }
  1932. return array($name, $trip);
  1933. }
  1934. // Highest common factor
  1935. function hcf($a, $b){
  1936. $gcd = 1;
  1937. if ($a>$b) {
  1938. $a = $a+$b;
  1939. $b = $a-$b;
  1940. $a = $a-$b;
  1941. }
  1942. if ($b==(round($b/$a))*$a)
  1943. $gcd=$a;
  1944. else {
  1945. for ($i=round($a/2);$i;$i--) {
  1946. if ($a == round($a/$i)*$i && $b == round($b/$i)*$i) {
  1947. $gcd = $i;
  1948. $i = false;
  1949. }
  1950. }
  1951. }
  1952. return $gcd;
  1953. }
  1954. function fraction($numerator, $denominator, $sep) {
  1955. $gcf = hcf($numerator, $denominator);
  1956. $numerator = $numerator / $gcf;
  1957. $denominator = $denominator / $gcf;
  1958. return "{$numerator}{$sep}{$denominator}";
  1959. }
  1960. function getPostByHash($hash) {
  1961. global $board;
  1962. $query = prepare(sprintf("SELECT `id`,`thread` FROM ``posts_%s`` WHERE `filehash` = :hash", $board['uri']));
  1963. $query->bindValue(':hash', $hash, PDO::PARAM_STR);
  1964. $query->execute() or error(db_error($query));
  1965. if ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1966. return $post;
  1967. }
  1968. return false;
  1969. }
  1970. function getPostByHashInThread($hash, $thread) {
  1971. global $board;
  1972. $query = prepare(sprintf("SELECT `id`,`thread` FROM ``posts_%s`` WHERE `filehash` = :hash AND ( `thread` = :thread OR `id` = :thread )", $board['uri']));
  1973. $query->bindValue(':hash', $hash, PDO::PARAM_STR);
  1974. $query->bindValue(':thread', $thread, PDO::PARAM_INT);
  1975. $query->execute() or error(db_error($query));
  1976. if ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1977. return $post;
  1978. }
  1979. return false;
  1980. }
  1981. function getPostByEmbed($embed) {
  1982. global $board, $config;
  1983. $matches = array();
  1984. foreach ($config['embedding'] as &$e) {
  1985. if (preg_match($e[0], $embed, $matches) && isset($matches[1]) && !empty($matches[1])) {
  1986. $embed = '%'.$matches[1].'%';
  1987. break;
  1988. }
  1989. }
  1990. if (!isset($embed)) return false;
  1991. $query = prepare(sprintf("SELECT `id`,`thread` FROM ``posts_%s`` WHERE `embed` LIKE :embed", $board['uri']));
  1992. $query->bindValue(':embed', $embed, PDO::PARAM_STR);
  1993. $query->execute() or error(db_error($query));
  1994. if ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1995. return $post;
  1996. }
  1997. return false;
  1998. }
  1999. function getPostByEmbedInThread($embed, $thread) {
  2000. global $board, $config;
  2001. $matches = array();
  2002. foreach ($config['embedding'] as &$e) {
  2003. if (preg_match($e[0], $embed, $matches) && isset($matches[1]) && !empty($matches[1])) {
  2004. $embed = '%'.$matches[1].'%';
  2005. break;
  2006. }
  2007. }
  2008. if (!isset($embed)) return false;
  2009. $query = prepare(sprintf("SELECT `id`,`thread` FROM ``posts_%s`` WHERE `embed` = :embed AND ( `thread` = :thread OR `id` = :thread )", $board['uri']));
  2010. $query->bindValue(':embed', $embed, PDO::PARAM_STR);
  2011. $query->bindValue(':thread', $thread, PDO::PARAM_INT);
  2012. $query->execute() or error(db_error($query));
  2013. if ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  2014. return $post;
  2015. }
  2016. return false;
  2017. }
  2018. function undoImage(array $post) {
  2019. if (!$post['has_file'] || !isset($post['files']))
  2020. return;
  2021. foreach ($post['files'] as $key => $file) {
  2022. if (isset($file['file_path']))
  2023. file_unlink($file['file_path']);
  2024. if (isset($file['thumb_path']))
  2025. file_unlink($file['thumb_path']);
  2026. }
  2027. }
  2028. function rDNS($ip_addr) {
  2029. global $config;
  2030. if ($config['cache']['enabled'] && ($host = cache::get('rdns_' . $ip_addr))) {
  2031. return $host;
  2032. }
  2033. if (!$config['dns_system']) {
  2034. $host = gethostbyaddr($ip_addr);
  2035. } else {
  2036. $resp = shell_exec_error('host -W 1 ' . $ip_addr);
  2037. if (preg_match('/domain name pointer ([^\s]+)$/', $resp, $m))
  2038. $host = $m[1];
  2039. else
  2040. $host = $ip_addr;
  2041. }
  2042. $isip = filter_var($host, FILTER_VALIDATE_IP);
  2043. if ($config['fcrdns'] && !$isip && DNS($host) != $ip_addr) {
  2044. $host = $ip_addr;
  2045. }
  2046. if ($config['cache']['enabled'])
  2047. cache::set('rdns_' . $ip_addr, $host);
  2048. return $host;
  2049. }
  2050. function DNS($host) {
  2051. global $config;
  2052. if ($config['cache']['enabled'] && ($ip_addr = cache::get('dns_' . $host))) {
  2053. return $ip_addr != '?' ? $ip_addr : false;
  2054. }
  2055. if (!$config['dns_system']) {
  2056. $ip_addr = gethostbyname($host);
  2057. if ($ip_addr == $host)
  2058. $ip_addr = false;
  2059. } else {
  2060. $resp = shell_exec_error('host -W 1 ' . $host);
  2061. if (preg_match('/has address ([^\s]+)$/', $resp, $m))
  2062. $ip_addr = $m[1];
  2063. else
  2064. $ip_addr = false;
  2065. }
  2066. if ($config['cache']['enabled'])
  2067. cache::set('dns_' . $host, $ip_addr !== false ? $ip_addr : '?');
  2068. return $ip_addr;
  2069. }
  2070. function shell_exec_error($command, $suppress_stdout = false) {
  2071. global $config, $debug;
  2072. if ($config['debug'])
  2073. $start = microtime(true);
  2074. $return = trim(shell_exec('PATH="' . escapeshellcmd($config['shell_path']) . ':$PATH";' .
  2075. $command . ' 2>&1 ' . ($suppress_stdout ? '> /dev/null ' : '') . '&& echo "TB_SUCCESS"'));
  2076. $return = preg_replace('/TB_SUCCESS$/', '', $return);
  2077. if ($config['debug']) {
  2078. $time = microtime(true) - $start;
  2079. $debug['exec'][] = array(
  2080. 'command' => $command,
  2081. 'time' => '~' . round($time * 1000, 2) . 'ms',
  2082. 'response' => $return ? $return : null
  2083. );
  2084. $debug['time']['exec'] += $time;
  2085. }
  2086. return $return === 'TB_SUCCESS' ? false : $return;
  2087. }
  2088. /* Die rolling:
  2089. * If "dice XdY+/-Z" is in the email field (where X or +/-Z may be
  2090. * missing), X Y-sided dice are rolled and summed, with the modifier Z
  2091. * added on. The result is displayed at the top of the post.
  2092. */
  2093. function diceRoller($post) {
  2094. global $config;
  2095. if(strpos(strtolower($post->email), 'dice%20') === 0) {
  2096. $dicestr = str_split(substr($post->email, strlen('dice%20')));
  2097. // Get params
  2098. $diceX = '';
  2099. $diceY = '';
  2100. $diceZ = '';
  2101. $curd = 'diceX';
  2102. for($i = 0; $i < count($dicestr); $i ++) {
  2103. if(is_numeric($dicestr[$i])) {
  2104. $$curd .= $dicestr[$i];
  2105. } else if($dicestr[$i] == 'd') {
  2106. $curd = 'diceY';
  2107. } else if($dicestr[$i] == '-' || $dicestr[$i] == '+') {
  2108. $curd = 'diceZ';
  2109. $$curd = $dicestr[$i];
  2110. }
  2111. }
  2112. // Default values for X and Z
  2113. if($diceX == '') {
  2114. $diceX = '1';
  2115. }
  2116. if($diceZ == '') {
  2117. $diceZ = '+0';
  2118. }
  2119. // Intify them
  2120. $diceX = intval($diceX);
  2121. $diceY = intval($diceY);
  2122. $diceZ = intval($diceZ);
  2123. // Continue only if we have valid values
  2124. if($diceX > 0 && $diceY > 0) {
  2125. $dicerolls = array();
  2126. $dicesum = $diceZ;
  2127. for($i = 0; $i < $diceX; $i++) {
  2128. $roll = rand(1, $diceY);
  2129. $dicerolls[] = $roll;
  2130. $dicesum += $roll;
  2131. }
  2132. // Prepend the result to the post body
  2133. $modifier = ($diceZ != 0) ? ((($diceZ < 0) ? ' - ' : ' + ') . abs($diceZ)) : '';
  2134. $dicesum = ($diceX > 1) ? ' = ' . $dicesum : '';
  2135. $post->body = '<table class="diceroll"><tr><td><img src="'.$config['dir']['static'].'d10.svg" alt="Dice roll" width="24"></td><td>Rolled ' . implode(', ', $dicerolls) . $modifier . $dicesum . '</td></tr></table><br/>' . $post->body;
  2136. }
  2137. }
  2138. }
  2139. function slugify($post) {
  2140. global $config;
  2141. $slug = "";
  2142. if (isset($post['subject']) && $post['subject'])
  2143. $slug = $post['subject'];
  2144. elseif (isset ($post['body_nomarkup']) && $post['body_nomarkup'])
  2145. $slug = $post['body_nomarkup'];
  2146. elseif (isset ($post['body']) && $post['body'])
  2147. $slug = strip_html($post['body']);
  2148. // Fix UTF-8 first
  2149. $slug = mb_convert_encoding($slug, "UTF-8", "UTF-8");
  2150. // Transliterate local characters like ü, I wonder how would it work for weird alphabets :^)
  2151. $slug = iconv("UTF-8", "ASCII//TRANSLIT//IGNORE", $slug);
  2152. // Remove Tinyboard custom markup
  2153. $slug = preg_replace("/<tinyboard [^>]+>.*?<\/tinyboard>/s", '', $slug);
  2154. // Downcase everything
  2155. $slug = strtolower($slug);
  2156. // Strip bad characters, alphanumerics should suffice
  2157. $slug = preg_replace('/[^a-zA-Z0-9]/', '-', $slug);
  2158. // Replace multiple dashes with single ones
  2159. $slug = preg_replace('/-+/', '-', $slug);
  2160. // Strip dashes at the beginning and at the end
  2161. $slug = preg_replace('/^-|-$/', '', $slug);
  2162. // Slug should be X characters long, at max (80?)
  2163. $slug = substr($slug, 0, $config['slug_max_size']);
  2164. // Slug is now ready
  2165. return $slug;
  2166. }
  2167. function link_for($post, $page50 = false, $foreignlink = false, $thread = false) {
  2168. global $config, $board;
  2169. $post = (array)$post;
  2170. // Where do we need to look for OP?
  2171. $b = $foreignlink ? $foreignlink : (isset($post['board']) ? array('uri' => $post['board']) : $board);
  2172. $id = (isset($post['thread']) && $post['thread']) ? $post['thread'] : $post['id'];
  2173. $slug = false;
  2174. if ($config['slugify'] && ( (isset($post['thread']) && $post['thread']) || !isset ($post['slug']) ) ) {
  2175. $cvar = "slug_".$b['uri']."_".$id;
  2176. if (!$thread) {
  2177. $slug = Cache::get($cvar);
  2178. if ($slug === false) {
  2179. $query = prepare(sprintf("SELECT `slug` FROM ``posts_%s`` WHERE `id` = :id", $b['uri']));
  2180. $query->bindValue(':id', $id, PDO::PARAM_INT);
  2181. $query->execute() or error(db_error($query));
  2182. $thread = $query->fetch(PDO::FETCH_ASSOC);
  2183. $slug = $thread['slug'];
  2184. Cache::set($cvar, $slug);
  2185. }
  2186. }
  2187. else {
  2188. $slug = $thread['slug'];
  2189. }
  2190. }
  2191. elseif ($config['slugify']) {
  2192. $slug = $post['slug'];
  2193. }
  2194. if ( $page50 && $slug) $tpl = $config['file_page50_slug'];
  2195. else if (!$page50 && $slug) $tpl = $config['file_page_slug'];
  2196. else if ( $page50 && !$slug) $tpl = $config['file_page50'];
  2197. else if (!$page50 && !$slug) $tpl = $config['file_page'];
  2198. return sprintf($tpl, $id, $slug);
  2199. }
  2200. function prettify_textarea($s){
  2201. return str_replace("\t", '&#09;', str_replace("\n", '&#13;&#10;', htmlentities($s)));
  2202. }
  2203. class HTMLPurifier_URIFilter_NoExternalImages extends HTMLPurifier_URIFilter {
  2204. public $name = 'NoExternalImages';
  2205. public function filter(&$uri, $c, $context) {
  2206. global $config;
  2207. $ct = $context->get('CurrentToken');
  2208. if (!$ct || $ct->name !== 'img') return true;
  2209. if (!isset($uri->host) && !isset($uri->scheme)) return true;
  2210. if (!in_array($uri->scheme . '://' . $uri->host . '/', $config['allowed_offsite_urls'])) {
  2211. error('No off-site links in board announcement images.');
  2212. }
  2213. return true;
  2214. }
  2215. }
  2216. function purify_html($s) {
  2217. global $config;
  2218. $c = HTMLPurifier_Config::createDefault();
  2219. $c->set('HTML.Allowed', $config['allowed_html']);
  2220. $uri = $c->getDefinition('URI');
  2221. $uri->addFilter(new HTMLPurifier_URIFilter_NoExternalImages(), $c);
  2222. $purifier = new HTMLPurifier($c);
  2223. $clean_html = $purifier->purify($s);
  2224. return $clean_html;
  2225. }
  2226. function markdown($s) {
  2227. $pd = new Parsedown();
  2228. $pd->setMarkupEscaped(true);
  2229. $pd->setimagesEnabled(false);
  2230. return $pd->text($s);
  2231. }