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.

2791 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. @include_once 'inc/lib/parsedown/Parsedown.php'; // fail silently, this isn't a critical piece of code
  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, :cycle, 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['op'] && $post['mod'] && isset($post['cycle']) && $post['cycle']) {
  857. $query->bindValue(':cycle', true, PDO::PARAM_INT);
  858. } else {
  859. $query->bindValue(':cycle', false, PDO::PARAM_INT);
  860. }
  861. if ($post['mod'] && isset($post['capcode']) && $post['capcode']) {
  862. $query->bindValue(':capcode', $post['capcode'], PDO::PARAM_INT);
  863. } else {
  864. $query->bindValue(':capcode', null, PDO::PARAM_NULL);
  865. }
  866. if (!empty($post['embed'])) {
  867. $query->bindValue(':embed', $post['embed']);
  868. } else {
  869. $query->bindValue(':embed', null, PDO::PARAM_NULL);
  870. }
  871. if ($post['op']) {
  872. // No parent thread, image
  873. $query->bindValue(':thread', null, PDO::PARAM_NULL);
  874. } else {
  875. $query->bindValue(':thread', $post['thread'], PDO::PARAM_INT);
  876. }
  877. if ($post['has_file']) {
  878. $query->bindValue(':files', json_encode($post['files']));
  879. $query->bindValue(':num_files', $post['num_files']);
  880. $query->bindValue(':filehash', $post['filehash']);
  881. } else {
  882. $query->bindValue(':files', null, PDO::PARAM_NULL);
  883. $query->bindValue(':num_files', 0);
  884. $query->bindValue(':filehash', null, PDO::PARAM_NULL);
  885. }
  886. if ($post['op']) {
  887. $query->bindValue(':slug', slugify($post));
  888. }
  889. else {
  890. $query->bindValue(':slug', NULL);
  891. }
  892. if (!$query->execute()) {
  893. undoImage($post);
  894. error(db_error($query));
  895. }
  896. return $pdo->lastInsertId();
  897. }
  898. function bumpThread($id) {
  899. global $config, $board, $build_pages;
  900. if (event('bump', $id))
  901. return true;
  902. if ($config['try_smarter']) {
  903. $build_pages = array_merge(range(1, thread_find_page($id)), $build_pages);
  904. }
  905. $query = prepare(sprintf("UPDATE ``posts_%s`` SET `bump` = :time WHERE `id` = :id AND `thread` IS NULL", $board['uri']));
  906. $query->bindValue(':time', time(), PDO::PARAM_INT);
  907. $query->bindValue(':id', $id, PDO::PARAM_INT);
  908. $query->execute() or error(db_error($query));
  909. }
  910. // Remove file from post
  911. function deleteFile($id, $remove_entirely_if_already=true, $file=null) {
  912. global $board, $config;
  913. $query = prepare(sprintf("SELECT `thread`, `files`, `num_files` FROM ``posts_%s`` WHERE `id` = :id LIMIT 1", $board['uri']));
  914. $query->bindValue(':id', $id, PDO::PARAM_INT);
  915. $query->execute() or error(db_error($query));
  916. if (!$post = $query->fetch(PDO::FETCH_ASSOC))
  917. error($config['error']['invalidpost']);
  918. $files = json_decode($post['files']);
  919. $file_to_delete = $file !== false ? $files[(int)$file] : (object)array('file' => false);
  920. if (!$files[0]) error(_('That post has no files.'));
  921. if ($files[0]->file == 'deleted' && $post['num_files'] == 1 && !$post['thread'])
  922. return; // Can't delete OP's image completely.
  923. $query = prepare(sprintf("UPDATE ``posts_%s`` SET `files` = :file WHERE `id` = :id", $board['uri']));
  924. if (($file && $file_to_delete->file == 'deleted') && $remove_entirely_if_already) {
  925. // Already deleted; remove file fully
  926. $files[$file] = null;
  927. } else {
  928. foreach ($files as $i => $f) {
  929. if (($file !== false && $i == $file) || $file === null) {
  930. // Delete thumbnail
  931. file_unlink($board['dir'] . $config['dir']['thumb'] . $f->thumb);
  932. unset($files[$i]->thumb);
  933. // Delete file
  934. file_unlink($board['dir'] . $config['dir']['img'] . $f->file);
  935. $files[$i]->file = 'deleted';
  936. }
  937. }
  938. }
  939. $query->bindValue(':file', json_encode($files), PDO::PARAM_STR);
  940. $query->bindValue(':id', $id, PDO::PARAM_INT);
  941. $query->execute() or error(db_error($query));
  942. if ($post['thread'])
  943. buildThread($post['thread']);
  944. else
  945. buildThread($id);
  946. }
  947. // rebuild post (markup)
  948. function rebuildPost($id) {
  949. global $board, $mod;
  950. $query = prepare(sprintf("SELECT * FROM ``posts_%s`` WHERE `id` = :id", $board['uri']));
  951. $query->bindValue(':id', $id, PDO::PARAM_INT);
  952. $query->execute() or error(db_error($query));
  953. if ((!$post = $query->fetch(PDO::FETCH_ASSOC)) || !$post['body_nomarkup'])
  954. return false;
  955. markup($post['body'] = &$post['body_nomarkup']);
  956. $post = (object)$post;
  957. event('rebuildpost', $post);
  958. $post = (array)$post;
  959. $query = prepare(sprintf("UPDATE ``posts_%s`` SET `body` = :body WHERE `id` = :id", $board['uri']));
  960. $query->bindValue(':body', $post['body']);
  961. $query->bindValue(':id', $id, PDO::PARAM_INT);
  962. $query->execute() or error(db_error($query));
  963. buildThread($post['thread'] ? $post['thread'] : $id);
  964. return true;
  965. }
  966. // Delete a post (reply or thread)
  967. function deletePost($id, $error_if_doesnt_exist=true, $rebuild_after=true) {
  968. global $board, $config;
  969. // Select post and replies (if thread) in one query
  970. $query = prepare(sprintf("SELECT `id`,`thread`,`files`,`slug` FROM ``posts_%s`` WHERE `id` = :id OR `thread` = :id", $board['uri']));
  971. $query->bindValue(':id', $id, PDO::PARAM_INT);
  972. $query->execute() or error(db_error($query));
  973. if ($query->rowCount() < 1) {
  974. if ($error_if_doesnt_exist)
  975. error($config['error']['invalidpost']);
  976. else return false;
  977. }
  978. $ids = array();
  979. // Delete posts and maybe replies
  980. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  981. event('delete', $post);
  982. if (!$post['thread']) {
  983. // Delete thread HTML page
  984. file_unlink($board['dir'] . $config['dir']['res'] . link_for($post) );
  985. file_unlink($board['dir'] . $config['dir']['res'] . link_for($post, true) ); // noko50
  986. file_unlink($board['dir'] . $config['dir']['res'] . sprintf('%d.json', $post['id']));
  987. $antispam_query = prepare('DELETE FROM ``antispam`` WHERE `board` = :board AND `thread` = :thread');
  988. $antispam_query->bindValue(':board', $board['uri']);
  989. $antispam_query->bindValue(':thread', $post['id']);
  990. $antispam_query->execute() or error(db_error($antispam_query));
  991. } elseif ($query->rowCount() == 1) {
  992. // Rebuild thread
  993. $rebuild = &$post['thread'];
  994. }
  995. if ($post['files']) {
  996. // Delete file
  997. foreach (json_decode($post['files']) as $i => $f) {
  998. if ($f->file !== 'deleted') {
  999. file_unlink($board['dir'] . $config['dir']['img'] . $f->file);
  1000. file_unlink($board['dir'] . $config['dir']['thumb'] . $f->thumb);
  1001. }
  1002. }
  1003. }
  1004. $ids[] = (int)$post['id'];
  1005. }
  1006. $query = prepare(sprintf("DELETE FROM ``posts_%s`` WHERE `id` = :id OR `thread` = :id", $board['uri']));
  1007. $query->bindValue(':id', $id, PDO::PARAM_INT);
  1008. $query->execute() or error(db_error($query));
  1009. $query = prepare("SELECT `board`, `post` FROM ``cites`` WHERE `target_board` = :board AND (`target` = " . implode(' OR `target` = ', $ids) . ") ORDER BY `board`");
  1010. $query->bindValue(':board', $board['uri']);
  1011. $query->execute() or error(db_error($query));
  1012. while ($cite = $query->fetch(PDO::FETCH_ASSOC)) {
  1013. if ($board['uri'] != $cite['board']) {
  1014. if (!isset($tmp_board))
  1015. $tmp_board = $board['uri'];
  1016. openBoard($cite['board']);
  1017. }
  1018. rebuildPost($cite['post']);
  1019. }
  1020. if (isset($tmp_board))
  1021. openBoard($tmp_board);
  1022. $query = prepare("DELETE FROM ``cites`` WHERE (`target_board` = :board AND (`target` = " . implode(' OR `target` = ', $ids) . ")) OR (`board` = :board AND (`post` = " . implode(' OR `post` = ', $ids) . "))");
  1023. $query->bindValue(':board', $board['uri']);
  1024. $query->execute() or error(db_error($query));
  1025. if (isset($rebuild) && $rebuild_after) {
  1026. buildThread($rebuild);
  1027. buildIndex();
  1028. }
  1029. return true;
  1030. }
  1031. function clean($pid = false) {
  1032. global $board, $config;
  1033. $offset = round($config['max_pages']*$config['threads_per_page']);
  1034. // I too wish there was an easier way of doing this...
  1035. $query = prepare(sprintf("SELECT `id` FROM ``posts_%s`` WHERE `thread` IS NULL ORDER BY `sticky` DESC, `bump` DESC LIMIT :offset, 9001", $board['uri']));
  1036. $query->bindValue(':offset', $offset, PDO::PARAM_INT);
  1037. $query->execute() or error(db_error($query));
  1038. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1039. deletePost($post['id'], false, false);
  1040. if ($pid) modLog("Automatically deleting thread #{$post['id']} due to new thread #{$pid}");
  1041. }
  1042. // Bump off threads with X replies earlier, spam prevention method
  1043. if ($config['early_404']) {
  1044. $offset = round($config['early_404_page']*$config['threads_per_page']);
  1045. $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']));
  1046. $query->bindValue(':offset', $offset, PDO::PARAM_INT);
  1047. $query->execute() or error(db_error($query));
  1048. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1049. if ($post['reply_count'] < $config['early_404_replies']) {
  1050. deletePost($post['thread_id'], false, false);
  1051. 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)");
  1052. }
  1053. }
  1054. }
  1055. }
  1056. function thread_find_page($thread) {
  1057. global $config, $board;
  1058. $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));
  1059. $threads = $query->fetchAll(PDO::FETCH_COLUMN);
  1060. if (($index = array_search($thread, $threads)) === false)
  1061. return false;
  1062. return floor(($config['threads_per_page'] + $index) / $config['threads_per_page']);
  1063. }
  1064. function index($page, $mod=false) {
  1065. global $board, $config, $debug;
  1066. $body = '';
  1067. $offset = round($page*$config['threads_per_page']-$config['threads_per_page']);
  1068. $query = prepare(sprintf("SELECT * FROM ``posts_%s`` WHERE `thread` IS NULL ORDER BY `sticky` DESC, `bump` DESC LIMIT :offset,:threads_per_page", $board['uri']));
  1069. $query->bindValue(':offset', $offset, PDO::PARAM_INT);
  1070. $query->bindValue(':threads_per_page', $config['threads_per_page'], PDO::PARAM_INT);
  1071. $query->execute() or error(db_error($query));
  1072. if ($page == 1 && $query->rowCount() < $config['threads_per_page'])
  1073. $board['thread_count'] = $query->rowCount();
  1074. if ($query->rowCount() < 1 && $page > 1)
  1075. return false;
  1076. $threads = array();
  1077. while ($th = $query->fetch(PDO::FETCH_ASSOC)) {
  1078. $thread = new Thread($th, $mod ? '?/' : $config['root'], $mod);
  1079. if ($config['cache']['enabled']) {
  1080. $cached = cache::get("thread_index_{$board['uri']}_{$th['id']}");
  1081. if (isset($cached['replies'], $cached['omitted'])) {
  1082. $replies = $cached['replies'];
  1083. $omitted = $cached['omitted'];
  1084. } else {
  1085. unset($cached);
  1086. }
  1087. }
  1088. if (!isset($cached)) {
  1089. $posts = prepare(sprintf("SELECT * FROM ``posts_%s`` WHERE `thread` = :id ORDER BY `id` DESC LIMIT :limit", $board['uri']));
  1090. $posts->bindValue(':id', $th['id']);
  1091. $posts->bindValue(':limit', ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview']), PDO::PARAM_INT);
  1092. $posts->execute() or error(db_error($posts));
  1093. $replies = array_reverse($posts->fetchAll(PDO::FETCH_ASSOC));
  1094. if (count($replies) == ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview'])) {
  1095. $count = numPosts($th['id']);
  1096. $omitted = array('post_count' => $count['replies'], 'image_count' => $count['images']);
  1097. } else {
  1098. $omitted = false;
  1099. }
  1100. if ($config['cache']['enabled'])
  1101. cache::set("thread_index_{$board['uri']}_{$th['id']}", array(
  1102. 'replies' => $replies,
  1103. 'omitted' => $omitted,
  1104. ));
  1105. }
  1106. $num_images = 0;
  1107. foreach ($replies as $po) {
  1108. if ($po['num_files'])
  1109. $num_images+=$po['num_files'];
  1110. $thread->add(new Post($po, $mod ? '?/' : $config['root'], $mod));
  1111. }
  1112. $thread->images = $num_images;
  1113. $thread->replies = isset($omitted['post_count']) ? $omitted['post_count'] : count($replies);
  1114. if ($omitted) {
  1115. $thread->omitted = $omitted['post_count'] - ($th['sticky'] ? $config['threads_preview_sticky'] : $config['threads_preview']);
  1116. $thread->omitted_images = $omitted['image_count'] - $num_images;
  1117. }
  1118. $threads[] = $thread;
  1119. $body .= $thread->build(true);
  1120. }
  1121. if ($config['file_board']) {
  1122. $body = Element('fileboard.html', array('body' => $body, 'mod' => $mod));
  1123. }
  1124. return array(
  1125. 'board' => $board,
  1126. 'body' => $body,
  1127. 'post_url' => $config['post_url'],
  1128. 'config' => $config,
  1129. 'boardlist' => createBoardlist($mod),
  1130. 'threads' => $threads,
  1131. );
  1132. }
  1133. function getPageButtons($pages, $mod=false) {
  1134. global $config, $board;
  1135. $btn = array();
  1136. $root = ($mod ? '?/' : $config['root']) . $board['dir'];
  1137. foreach ($pages as $num => $page) {
  1138. if (isset($page['selected'])) {
  1139. // Previous button
  1140. if ($num == 0) {
  1141. // There is no previous page.
  1142. $btn['prev'] = _('Previous');
  1143. } else {
  1144. $loc = ($mod ? '?/' . $board['uri'] . '/' : '') .
  1145. ($num == 1 ?
  1146. $config['file_index']
  1147. :
  1148. sprintf($config['file_page'], $num)
  1149. );
  1150. $btn['prev'] = '<form action="' . ($mod ? '' : $root . $loc) . '" method="get">' .
  1151. ($mod ?
  1152. '<input type="hidden" name="status" value="301" />' .
  1153. '<input type="hidden" name="r" value="' . htmlentities($loc) . '" />'
  1154. :'') .
  1155. '<input type="submit" value="' . _('Previous') . '" /></form>';
  1156. }
  1157. if ($num == count($pages) - 1) {
  1158. // There is no next page.
  1159. $btn['next'] = _('Next');
  1160. } else {
  1161. $loc = ($mod ? '?/' . $board['uri'] . '/' : '') . sprintf($config['file_page'], $num + 2);
  1162. $btn['next'] = '<form action="' . ($mod ? '' : $root . $loc) . '" method="get">' .
  1163. ($mod ?
  1164. '<input type="hidden" name="status" value="301" />' .
  1165. '<input type="hidden" name="r" value="' . htmlentities($loc) . '" />'
  1166. :'') .
  1167. '<input type="submit" value="' . _('Next') . '" /></form>';
  1168. }
  1169. }
  1170. }
  1171. return $btn;
  1172. }
  1173. function getPages($mod=false) {
  1174. global $board, $config;
  1175. if (isset($board['thread_count'])) {
  1176. $count = $board['thread_count'];
  1177. } else {
  1178. // Count threads
  1179. $query = query(sprintf("SELECT COUNT(*) FROM ``posts_%s`` WHERE `thread` IS NULL", $board['uri'])) or error(db_error());
  1180. $count = $query->fetchColumn();
  1181. }
  1182. $count = floor(($config['threads_per_page'] + $count - 1) / $config['threads_per_page']);
  1183. if ($count < 1) $count = 1;
  1184. $pages = array();
  1185. for ($x=0;$x<$count && $x<$config['max_pages'];$x++) {
  1186. $pages[] = array(
  1187. 'num' => $x+1,
  1188. 'link' => $x==0 ? ($mod ? '?/' : $config['root']) . $board['dir'] . $config['file_index'] : ($mod ? '?/' : $config['root']) . $board['dir'] . sprintf($config['file_page'], $x+1)
  1189. );
  1190. }
  1191. return $pages;
  1192. }
  1193. // Stolen with permission from PlainIB (by Frank Usrs)
  1194. function make_comment_hex($str) {
  1195. // remove cross-board citations
  1196. // the numbers don't matter
  1197. $str = preg_replace('!>>>/[A-Za-z0-9]+/!', '', $str);
  1198. if (function_exists('iconv')) {
  1199. // remove diacritics and other noise
  1200. // FIXME: this removes cyrillic entirely
  1201. $oldstr = $str;
  1202. $str = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $str);
  1203. if (!$str) $str = $oldstr;
  1204. }
  1205. $str = strtolower($str);
  1206. // strip all non-alphabet characters
  1207. $str = preg_replace('/[^a-z]/', '', $str);
  1208. return md5($str);
  1209. }
  1210. function makerobot($body) {
  1211. global $config;
  1212. $body = strtolower($body);
  1213. // Leave only letters
  1214. $body = preg_replace('/[^a-z]/i', '', $body);
  1215. // Remove repeating characters
  1216. if ($config['robot_strip_repeating'])
  1217. $body = preg_replace('/(.)\\1+/', '$1', $body);
  1218. return sha1($body);
  1219. }
  1220. function checkRobot($body) {
  1221. if (empty($body) || event('check-robot', $body))
  1222. return true;
  1223. $body = makerobot($body);
  1224. $query = prepare("SELECT 1 FROM ``robot`` WHERE `hash` = :hash LIMIT 1");
  1225. $query->bindValue(':hash', $body);
  1226. $query->execute() or error(db_error($query));
  1227. if ($query->fetchColumn()) {
  1228. return true;
  1229. }
  1230. // Insert new hash
  1231. $query = prepare("INSERT INTO ``robot`` VALUES (:hash)");
  1232. $query->bindValue(':hash', $body);
  1233. $query->execute() or error(db_error($query));
  1234. return false;
  1235. }
  1236. // Returns an associative array with 'replies' and 'images' keys
  1237. function numPosts($id) {
  1238. global $board;
  1239. $query = prepare(sprintf("SELECT COUNT(*) AS `replies`, SUM(`num_files`) AS `images` FROM ``posts_%s`` WHERE `thread` = :thread", $board['uri'], $board['uri']));
  1240. $query->bindValue(':thread', $id, PDO::PARAM_INT);
  1241. $query->execute() or error(db_error($query));
  1242. return $query->fetch(PDO::FETCH_ASSOC);
  1243. }
  1244. function muteTime() {
  1245. global $config;
  1246. if ($time = event('mute-time'))
  1247. return $time;
  1248. // Find number of mutes in the past X hours
  1249. $query = prepare("SELECT COUNT(*) FROM ``mutes`` WHERE `time` >= :time AND `ip` = :ip");
  1250. $query->bindValue(':time', time()-($config['robot_mute_hour']*3600), PDO::PARAM_INT);
  1251. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
  1252. $query->execute() or error(db_error($query));
  1253. if (!$result = $query->fetchColumn())
  1254. return 0;
  1255. return pow($config['robot_mute_multiplier'], $result);
  1256. }
  1257. function mute() {
  1258. // Insert mute
  1259. $query = prepare("INSERT INTO ``mutes`` VALUES (:ip, :time)");
  1260. $query->bindValue(':time', time(), PDO::PARAM_INT);
  1261. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
  1262. $query->execute() or error(db_error($query));
  1263. return muteTime();
  1264. }
  1265. function checkMute() {
  1266. global $config, $debug;
  1267. if ($config['cache']['enabled']) {
  1268. // Cached mute?
  1269. if (($mute = cache::get("mute_${_SERVER['REMOTE_ADDR']}")) && ($mutetime = cache::get("mutetime_${_SERVER['REMOTE_ADDR']}"))) {
  1270. error(sprintf($config['error']['youaremuted'], $mute['time'] + $mutetime - time()));
  1271. }
  1272. }
  1273. $mutetime = muteTime();
  1274. if ($mutetime > 0) {
  1275. // Find last mute time
  1276. $query = prepare("SELECT `time` FROM ``mutes`` WHERE `ip` = :ip ORDER BY `time` DESC LIMIT 1");
  1277. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR']);
  1278. $query->execute() or error(db_error($query));
  1279. if (!$mute = $query->fetch(PDO::FETCH_ASSOC)) {
  1280. // What!? He's muted but he's not muted...
  1281. return;
  1282. }
  1283. if ($mute['time'] + $mutetime > time()) {
  1284. if ($config['cache']['enabled']) {
  1285. cache::set("mute_${_SERVER['REMOTE_ADDR']}", $mute, $mute['time'] + $mutetime - time());
  1286. cache::set("mutetime_${_SERVER['REMOTE_ADDR']}", $mutetime, $mute['time'] + $mutetime - time());
  1287. }
  1288. // Not expired yet
  1289. error(sprintf($config['error']['youaremuted'], $mute['time'] + $mutetime - time()));
  1290. } else {
  1291. // Already expired
  1292. return;
  1293. }
  1294. }
  1295. }
  1296. function buildIndex($global_api = "yes") {
  1297. global $board, $config, $build_pages;
  1298. if (!$config['smart_build']) {
  1299. $pages = getPages();
  1300. if (!$config['try_smarter'])
  1301. $antibot = create_antibot($board['uri']);
  1302. if ($config['api']['enabled']) {
  1303. $api = new Api();
  1304. $catalog = array();
  1305. }
  1306. }
  1307. for ($page = 1; $page <= $config['max_pages']; $page++) {
  1308. $filename = $board['dir'] . ($page == 1 ? $config['file_index'] : sprintf($config['file_page'], $page));
  1309. $jsonFilename = $board['dir'] . ($page - 1) . '.json'; // pages should start from 0
  1310. if ((!$config['api']['enabled'] || $global_api == "skip" || $config['smart_build']) && $config['try_smarter']
  1311. && isset($build_pages) && !empty($build_pages) && !in_array($page, $build_pages) )
  1312. continue;
  1313. if (!$config['smart_build']) {
  1314. $content = index($page);
  1315. if (!$content)
  1316. break;
  1317. // json api
  1318. if ($config['api']['enabled']) {
  1319. $threads = $content['threads'];
  1320. $json = json_encode($api->translatePage($threads));
  1321. file_write($jsonFilename, $json);
  1322. $catalog[$page-1] = $threads;
  1323. }
  1324. if ($config['api']['enabled'] && $global_api != "skip" && $config['try_smarter'] && isset($build_pages)
  1325. && !empty($build_pages) && !in_array($page, $build_pages) )
  1326. continue;
  1327. if ($config['try_smarter']) {
  1328. $antibot = create_antibot($board['uri'], 0 - $page);
  1329. $content['current_page'] = $page;
  1330. }
  1331. $antibot->reset();
  1332. $content['pages'] = $pages;
  1333. $content['pages'][$page-1]['selected'] = true;
  1334. $content['btn'] = getPageButtons($content['pages']);
  1335. $content['antibot'] = $antibot;
  1336. file_write($filename, Element('index.html', $content));
  1337. }
  1338. else {
  1339. file_unlink($filename);
  1340. file_unlink($jsonFilename);
  1341. }
  1342. }
  1343. if (!$config['smart_build'] && $page < $config['max_pages']) {
  1344. for (;$page<=$config['max_pages'];$page++) {
  1345. $filename = $board['dir'] . ($page==1 ? $config['file_index'] : sprintf($config['file_page'], $page));
  1346. file_unlink($filename);
  1347. if ($config['api']['enabled']) {
  1348. $jsonFilename = $board['dir'] . ($page - 1) . '.json';
  1349. file_unlink($jsonFilename);
  1350. }
  1351. }
  1352. }
  1353. // json api catalog
  1354. if ($config['api']['enabled'] && $global_api != "skip") {
  1355. if ($config['smart_build']) {
  1356. $jsonFilename = $board['dir'] . 'catalog.json';
  1357. file_unlink($jsonFilename);
  1358. $jsonFilename = $board['dir'] . 'threads.json';
  1359. file_unlink($jsonFilename);
  1360. }
  1361. else {
  1362. $json = json_encode($api->translateCatalog($catalog));
  1363. $jsonFilename = $board['dir'] . 'catalog.json';
  1364. file_write($jsonFilename, $json);
  1365. $json = json_encode($api->translateCatalog($catalog, true));
  1366. $jsonFilename = $board['dir'] . 'threads.json';
  1367. file_write($jsonFilename, $json);
  1368. }
  1369. }
  1370. if ($config['try_smarter'])
  1371. $build_pages = array();
  1372. }
  1373. function buildJavascript() {
  1374. global $config;
  1375. $stylesheets = array();
  1376. foreach ($config['stylesheets'] as $name => $uri) {
  1377. $stylesheets[] = array(
  1378. 'name' => addslashes($name),
  1379. 'uri' => addslashes((!empty($uri) ? $config['uri_stylesheets'] : '') . $uri));
  1380. }
  1381. $script = Element('main.js', array(
  1382. 'config' => $config,
  1383. 'stylesheets' => $stylesheets
  1384. ));
  1385. // Check if we have translation for the javascripts; if yes, we add it to additional javascripts
  1386. list($pure_locale) = explode(".", $config['locale']);
  1387. if (file_exists ($jsloc = "inc/locale/$pure_locale/LC_MESSAGES/javascript.js")) {
  1388. $script = file_get_contents($jsloc) . "\n\n" . $script;
  1389. }
  1390. if ($config['additional_javascript_compile']) {
  1391. foreach ($config['additional_javascript'] as $file) {
  1392. $script .= file_get_contents($file);
  1393. }
  1394. }
  1395. if ($config['minify_js']) {
  1396. require_once 'inc/lib/minify/JSMin.php';
  1397. $script = JSMin::minify($script);
  1398. }
  1399. file_write($config['file_script'], $script);
  1400. }
  1401. function checkDNSBL() {
  1402. global $config;
  1403. if (isIPv6())
  1404. return; // No IPv6 support yet.
  1405. if (!isset($_SERVER['REMOTE_ADDR']))
  1406. return; // Fix your web server configuration
  1407. if (in_array($_SERVER['REMOTE_ADDR'], $config['dnsbl_exceptions']))
  1408. return;
  1409. $ipaddr = ReverseIPOctets($_SERVER['REMOTE_ADDR']);
  1410. foreach ($config['dnsbl'] as $blacklist) {
  1411. if (!is_array($blacklist))
  1412. $blacklist = array($blacklist);
  1413. if (($lookup = str_replace('%', $ipaddr, $blacklist[0])) == $blacklist[0])
  1414. $lookup = $ipaddr . '.' . $blacklist[0];
  1415. if (!$ip = DNS($lookup))
  1416. continue; // not in list
  1417. $blacklist_name = isset($blacklist[2]) ? $blacklist[2] : $blacklist[0];
  1418. if (!isset($blacklist[1])) {
  1419. // If you're listed at all, you're blocked.
  1420. error(sprintf($config['error']['dnsbl'], $blacklist_name));
  1421. } elseif (is_array($blacklist[1])) {
  1422. foreach ($blacklist[1] as $octet) {
  1423. if ($ip == $octet || $ip == '127.0.0.' . $octet)
  1424. error(sprintf($config['error']['dnsbl'], $blacklist_name));
  1425. }
  1426. } elseif (is_callable($blacklist[1])) {
  1427. if ($blacklist[1]($ip))
  1428. error(sprintf($config['error']['dnsbl'], $blacklist_name));
  1429. } else {
  1430. if ($ip == $blacklist[1] || $ip == '127.0.0.' . $blacklist[1])
  1431. error(sprintf($config['error']['dnsbl'], $blacklist_name));
  1432. }
  1433. }
  1434. }
  1435. function isIPv6() {
  1436. return strstr($_SERVER['REMOTE_ADDR'], ':') !== false;
  1437. }
  1438. function ReverseIPOctets($ip) {
  1439. return implode('.', array_reverse(explode('.', $ip)));
  1440. }
  1441. function wordfilters(&$body) {
  1442. global $config;
  1443. foreach ($config['wordfilters'] as $filter) {
  1444. if (isset($filter[2]) && $filter[2]) {
  1445. if (is_callable($filter[1]))
  1446. $body = preg_replace_callback($filter[0], $filter[1], $body);
  1447. else
  1448. $body = preg_replace($filter[0], $filter[1], $body);
  1449. } else {
  1450. $body = str_ireplace($filter[0], $filter[1], $body);
  1451. }
  1452. }
  1453. }
  1454. function quote($body, $quote=true) {
  1455. global $config;
  1456. $body = str_replace('<br/>', "\n", $body);
  1457. $body = strip_tags($body);
  1458. $body = preg_replace("/(^|\n)/", '$1&gt;', $body);
  1459. $body .= "\n";
  1460. if ($config['minify_html'])
  1461. $body = str_replace("\n", '&#010;', $body);
  1462. return $body;
  1463. }
  1464. function markup_url($matches) {
  1465. global $config, $markup_urls;
  1466. $url = $matches[1];
  1467. $after = $matches[2];
  1468. $markup_urls[] = $url;
  1469. $link = (object) array(
  1470. 'href' => $config['link_prefix'] . $url,
  1471. 'text' => $url,
  1472. 'rel' => 'nofollow',
  1473. 'target' => '_blank',
  1474. );
  1475. event('markup-url', $link);
  1476. $link = (array)$link;
  1477. $parts = array();
  1478. foreach ($link as $attr => $value) {
  1479. if ($attr == 'text' || $attr == 'after')
  1480. continue;
  1481. $parts[] = $attr . '="' . $value . '"';
  1482. }
  1483. if (isset($link['after']))
  1484. $after = $link['after'] . $after;
  1485. return '<a ' . implode(' ', $parts) . '>' . $link['text'] . '</a>' . $after;
  1486. }
  1487. function unicodify($body) {
  1488. $body = str_replace('...', '&hellip;', $body);
  1489. $body = str_replace('&lt;--', '&larr;', $body);
  1490. $body = str_replace('--&gt;', '&rarr;', $body);
  1491. // En and em- dashes are rendered exactly the same in
  1492. // most monospace fonts (they look the same in code
  1493. // editors).
  1494. $body = str_replace('---', '&mdash;', $body); // em dash
  1495. $body = str_replace('--', '&ndash;', $body); // en dash
  1496. return $body;
  1497. }
  1498. function extract_modifiers($body) {
  1499. $modifiers = array();
  1500. if (preg_match_all('@<tinyboard ([\w\s]+)>(.*?)</tinyboard>@us', $body, $matches, PREG_SET_ORDER)) {
  1501. foreach ($matches as $match) {
  1502. if (preg_match('/^escape /', $match[1]))
  1503. continue;
  1504. $modifiers[$match[1]] = html_entity_decode($match[2]);
  1505. }
  1506. }
  1507. return $modifiers;
  1508. }
  1509. function remove_modifiers($body) {
  1510. return preg_replace('@<tinyboard ([\w\s]+)>(.+?)</tinyboard>@usm', '', $body);
  1511. }
  1512. function markup(&$body, $track_cites = false, $op = false) {
  1513. global $board, $config, $markup_urls;
  1514. $modifiers = extract_modifiers($body);
  1515. $body = preg_replace('@<tinyboard (?!escape )([\w\s]+)>(.+?)</tinyboard>@us', '', $body);
  1516. $body = preg_replace('@<(tinyboard) escape ([\w\s]+)>@i', '<$1 $2>', $body);
  1517. if (isset($modifiers['raw html']) && $modifiers['raw html'] == '1') {
  1518. return array();
  1519. }
  1520. $body = str_replace("\r", '', $body);
  1521. $body = utf8tohtml($body);
  1522. if (mysql_version() < 50503)
  1523. $body = mb_encode_numericentity($body, array(0x010000, 0xffffff, 0, 0xffffff), 'UTF-8');
  1524. if ($config['markup_code']) {
  1525. $code_markup = array();
  1526. $body = preg_replace_callback($config['markup_code'], function($matches) use (&$code_markup) {
  1527. $d = count($code_markup);
  1528. $code_markup[] = $matches;
  1529. return "<code $d>";
  1530. }, $body);
  1531. }
  1532. foreach ($config['markup'] as $markup) {
  1533. if (is_string($markup[1])) {
  1534. $body = preg_replace($markup[0], $markup[1], $body);
  1535. } elseif (is_callable($markup[1])) {
  1536. $body = preg_replace_callback($markup[0], $markup[1], $body);
  1537. }
  1538. }
  1539. if ($config['markup_urls']) {
  1540. $markup_urls = array();
  1541. $body = preg_replace_callback(
  1542. '/((?:https?:\/\/|ftp:\/\/|irc:\/\/)[^\s<>()"]+?(?:\([^\s<>()"]*?\)[^\s<>()"]*?)*)((?:\s|<|>|"|\.||\]|!|\?|,|&#44;|&quot;)*(?:[\s<>()"]|$))/',
  1543. 'markup_url',
  1544. $body,
  1545. -1,
  1546. $num_links);
  1547. if ($num_links > $config['max_links'])
  1548. error($config['error']['toomanylinks']);
  1549. }
  1550. if ($config['markup_repair_tidy'])
  1551. $body = str_replace(' ', ' &nbsp;', $body);
  1552. if ($config['auto_unicode']) {
  1553. $body = unicodify($body);
  1554. if ($config['markup_urls']) {
  1555. foreach ($markup_urls as &$url) {
  1556. $body = str_replace(unicodify($url), $url, $body);
  1557. }
  1558. }
  1559. }
  1560. $tracked_cites = array();
  1561. // Cites
  1562. if (isset($board) && preg_match_all('/(^|\s)&gt;&gt;(\d+?)([\s,.)?]|$)/m', $body, $cites, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) {
  1563. if (count($cites[0]) > $config['max_cites']) {
  1564. error($config['error']['toomanycites']);
  1565. }
  1566. $skip_chars = 0;
  1567. $body_tmp = $body;
  1568. $search_cites = array();
  1569. foreach ($cites as $matches) {
  1570. $search_cites[] = '`id` = ' . $matches[2][0];
  1571. }
  1572. $search_cites = array_unique($search_cites);
  1573. $query = query(sprintf('SELECT `thread`, `id` FROM ``posts_%s`` WHERE ' .
  1574. implode(' OR ', $search_cites), $board['uri'])) or error(db_error());
  1575. $cited_posts = array();
  1576. while ($cited = $query->fetch(PDO::FETCH_ASSOC)) {
  1577. $cited_posts[$cited['id']] = $cited['thread'] ? $cited['thread'] : false;
  1578. }
  1579. foreach ($cites as $matches) {
  1580. $cite = $matches[2][0];
  1581. // preg_match_all is not multibyte-safe
  1582. foreach ($matches as &$match) {
  1583. $match[1] = mb_strlen(substr($body_tmp, 0, $match[1]));
  1584. }
  1585. if (isset($cited_posts[$cite])) {
  1586. $replacement = '<a onclick="highlightReply(\''.$cite.'\', event);" href="' .
  1587. $config['root'] . $board['dir'] . $config['dir']['res'] .
  1588. link_for(array('id' => $cite, 'thread' => $cited_posts[$cite])) . '#' . $cite . '">' .
  1589. '&gt;&gt;' . $cite .
  1590. '</a>';
  1591. $body = mb_substr_replace($body, $matches[1][0] . $replacement . $matches[3][0], $matches[0][1] + $skip_chars, mb_strlen($matches[0][0]));
  1592. $skip_chars += mb_strlen($matches[1][0] . $replacement . $matches[3][0]) - mb_strlen($matches[0][0]);
  1593. if ($track_cites && $config['track_cites'])
  1594. $tracked_cites[] = array($board['uri'], $cite);
  1595. }
  1596. }
  1597. }
  1598. // Cross-board linking
  1599. if (preg_match_all('/(^|\s)&gt;&gt;&gt;\/(' . $config['board_regex'] . 'f?)\/(\d+)?([\s,.)?]|$)/um', $body, $cites, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) {
  1600. if (count($cites[0]) > $config['max_cites']) {
  1601. error($config['error']['toomanycross']);
  1602. }
  1603. $skip_chars = 0;
  1604. $body_tmp = $body;
  1605. if (isset($cited_posts)) {
  1606. // Carry found posts from local board >>X links
  1607. foreach ($cited_posts as $cite => $thread) {
  1608. $cited_posts[$cite] = $config['root'] . $board['dir'] . $config['dir']['res'] .
  1609. ($thread ? $thread : $cite) . '.html#' . $cite;
  1610. }
  1611. $cited_posts = array(
  1612. $board['uri'] => $cited_posts
  1613. );
  1614. } else
  1615. $cited_posts = array();
  1616. $crossboard_indexes = array();
  1617. $search_cites_boards = array();
  1618. foreach ($cites as $matches) {
  1619. $_board = $matches[2][0];
  1620. $cite = @$matches[3][0];
  1621. if (!isset($search_cites_boards[$_board]))
  1622. $search_cites_boards[$_board] = array();
  1623. $search_cites_boards[$_board][] = $cite;
  1624. }
  1625. $tmp_board = $board['uri'];
  1626. foreach ($search_cites_boards as $_board => $search_cites) {
  1627. $clauses = array();
  1628. foreach ($search_cites as $cite) {
  1629. if (!$cite || isset($cited_posts[$_board][$cite]))
  1630. continue;
  1631. $clauses[] = '`id` = ' . $cite;
  1632. }
  1633. $clauses = array_unique($clauses);
  1634. if ($board['uri'] != $_board) {
  1635. if (!openBoard($_board))
  1636. continue; // Unknown board
  1637. }
  1638. if (!empty($clauses)) {
  1639. $cited_posts[$_board] = array();
  1640. $query = query(sprintf('SELECT `thread`, `id`, `slug` FROM ``posts_%s`` WHERE ' .
  1641. implode(' OR ', $clauses), $board['uri'])) or error(db_error());
  1642. while ($cite = $query->fetch(PDO::FETCH_ASSOC)) {
  1643. $cited_posts[$_board][$cite['id']] = $config['root'] . $board['dir'] . $config['dir']['res'] .
  1644. link_for($cite) . '#' . $cite['id'];
  1645. }
  1646. }
  1647. $crossboard_indexes[$_board] = $config['root'] . $board['dir'] . $config['file_index'];
  1648. }
  1649. // Restore old board
  1650. if ($board['uri'] != $tmp_board)
  1651. openBoard($tmp_board);
  1652. foreach ($cites as $matches) {
  1653. $_board = $matches[2][0];
  1654. $cite = @$matches[3][0];
  1655. // preg_match_all is not multibyte-safe
  1656. foreach ($matches as &$match) {
  1657. $match[1] = mb_strlen(substr($body_tmp, 0, $match[1]));
  1658. }
  1659. if ($cite) {
  1660. if (isset($cited_posts[$_board][$cite])) {
  1661. $link = $cited_posts[$_board][$cite];
  1662. $replacement = '<a ' .
  1663. ($_board == $board['uri'] ?
  1664. 'onclick="highlightReply(\''.$cite.'\', event);" '
  1665. : '') . 'href="' . $link . '">' .
  1666. '&gt;&gt;&gt;/' . $_board . '/' . $cite .
  1667. '</a>';
  1668. $body = mb_substr_replace($body, $matches[1][0] . $replacement . $matches[4][0], $matches[0][1] + $skip_chars, mb_strlen($matches[0][0]));
  1669. $skip_chars += mb_strlen($matches[1][0] . $replacement . $matches[4][0]) - mb_strlen($matches[0][0]);
  1670. if ($track_cites && $config['track_cites'])
  1671. $tracked_cites[] = array($_board, $cite);
  1672. }
  1673. } elseif(isset($crossboard_indexes[$_board])) {
  1674. $replacement = '<a href="' . $crossboard_indexes[$_board] . '">' .
  1675. '&gt;&gt;&gt;/' . $_board . '/' .
  1676. '</a>';
  1677. $body = mb_substr_replace($body, $matches[1][0] . $replacement . $matches[4][0], $matches[0][1] + $skip_chars, mb_strlen($matches[0][0]));
  1678. $skip_chars += mb_strlen($matches[1][0] . $replacement . $matches[4][0]) - mb_strlen($matches[0][0]);
  1679. }
  1680. }
  1681. }
  1682. $tracked_cites = array_unique($tracked_cites, SORT_REGULAR);
  1683. $body = preg_replace("/^\s*&gt;.*$/m", '<span class="quote">$0</span>', $body);
  1684. if ($config['strip_superfluous_returns'])
  1685. $body = preg_replace('/\s+$/', '', $body);
  1686. $body = preg_replace("/\n/", '<br/>', $body);
  1687. // Fix code markup
  1688. if ($config['markup_code']) {
  1689. foreach ($code_markup as $id => $val) {
  1690. $code = isset($val[2]) ? $val[2] : $val[1];
  1691. $code_lang = isset($val[2]) ? $val[1] : "";
  1692. $code = "<pre class='code lang-$code_lang'>".str_replace(array("\n","\t"), array("&#10;","&#9;"), htmlspecialchars($code))."</pre>";
  1693. $body = str_replace("<code $id>", $code, $body);
  1694. }
  1695. }
  1696. if ($config['markup_repair_tidy']) {
  1697. $tidy = new tidy();
  1698. $body = str_replace("\t", '&#09;', $body);
  1699. $body = $tidy->repairString($body, array(
  1700. 'doctype' => 'omit',
  1701. 'bare' => true,
  1702. 'literal-attributes' => true,
  1703. 'indent' => false,
  1704. 'show-body-only' => true,
  1705. 'wrap' => 0,
  1706. 'output-bom' => false,
  1707. 'output-html' => true,
  1708. 'newline' => 'LF',
  1709. 'quiet' => true,
  1710. ), 'utf8');
  1711. $body = str_replace("\n", '', $body);
  1712. }
  1713. // replace tabs with 8 spaces
  1714. $body = str_replace("\t", ' ', $body);
  1715. return $tracked_cites;
  1716. }
  1717. function escape_markup_modifiers($string) {
  1718. return preg_replace('@<(tinyboard) ([\w\s]+)>@mi', '<$1 escape $2>', $string);
  1719. }
  1720. function utf8tohtml($utf8) {
  1721. return htmlspecialchars($utf8, ENT_NOQUOTES, 'UTF-8');
  1722. }
  1723. function ordutf8($string, &$offset) {
  1724. $code = ord(substr($string, $offset,1));
  1725. if ($code >= 128) { // otherwise 0xxxxxxx
  1726. if ($code < 224)
  1727. $bytesnumber = 2; // 110xxxxx
  1728. else if ($code < 240)
  1729. $bytesnumber = 3; // 1110xxxx
  1730. else if ($code < 248)
  1731. $bytesnumber = 4; // 11110xxx
  1732. $codetemp = $code - 192 - ($bytesnumber > 2 ? 32 : 0) - ($bytesnumber > 3 ? 16 : 0);
  1733. for ($i = 2; $i <= $bytesnumber; $i++) {
  1734. $offset ++;
  1735. $code2 = ord(substr($string, $offset, 1)) - 128; //10xxxxxx
  1736. $codetemp = $codetemp*64 + $code2;
  1737. }
  1738. $code = $codetemp;
  1739. }
  1740. $offset += 1;
  1741. if ($offset >= strlen($string))
  1742. $offset = -1;
  1743. return $code;
  1744. }
  1745. function strip_combining_chars($str) {
  1746. $chars = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
  1747. $str = '';
  1748. foreach ($chars as $char) {
  1749. $o = 0;
  1750. $ord = ordutf8($char, $o);
  1751. 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))
  1752. continue;
  1753. $str .= $char;
  1754. }
  1755. return $str;
  1756. }
  1757. function buildThread($id, $return = false, $mod = false) {
  1758. global $board, $config, $build_pages;
  1759. $id = round($id);
  1760. if (event('build-thread', $id))
  1761. return;
  1762. if ($config['cache']['enabled'] && !$mod) {
  1763. // Clear cache
  1764. cache::delete("thread_index_{$board['uri']}_{$id}");
  1765. cache::delete("thread_{$board['uri']}_{$id}");
  1766. }
  1767. if ($config['try_smarter'] && !$mod)
  1768. $build_pages[] = thread_find_page($id);
  1769. if (!$config['smart_build'] || $return || $mod) {
  1770. $query = prepare(sprintf("SELECT * FROM ``posts_%s`` WHERE (`thread` IS NULL AND `id` = :id) OR `thread` = :id ORDER BY `thread`,`id`", $board['uri']));
  1771. $query->bindValue(':id', $id, PDO::PARAM_INT);
  1772. $query->execute() or error(db_error($query));
  1773. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1774. if (!isset($thread)) {
  1775. $thread = new Thread($post, $mod ? '?/' : $config['root'], $mod);
  1776. } else {
  1777. $thread->add(new Post($post, $mod ? '?/' : $config['root'], $mod));
  1778. }
  1779. }
  1780. // Check if any posts were found
  1781. if (!isset($thread))
  1782. error($config['error']['nonexistant']);
  1783. $hasnoko50 = $thread->postCount() >= $config['noko50_min'];
  1784. $antibot = $mod || $return ? false : create_antibot($board['uri'], $id);
  1785. $body = Element('thread.html', array(
  1786. 'board' => $board,
  1787. 'thread' => $thread,
  1788. 'body' => $thread->build(),
  1789. 'config' => $config,
  1790. 'id' => $id,
  1791. 'mod' => $mod,
  1792. 'hasnoko50' => $hasnoko50,
  1793. 'isnoko50' => false,
  1794. 'antibot' => $antibot,
  1795. 'boardlist' => createBoardlist($mod),
  1796. 'return' => ($mod ? '?' . $board['url'] . $config['file_index'] : $config['root'] . $board['dir'] . $config['file_index'])
  1797. ));
  1798. // json api
  1799. if ($config['api']['enabled']) {
  1800. $api = new Api();
  1801. $json = json_encode($api->translateThread($thread));
  1802. $jsonFilename = $board['dir'] . $config['dir']['res'] . $id . '.json';
  1803. file_write($jsonFilename, $json);
  1804. }
  1805. }
  1806. else {
  1807. $jsonFilename = $board['dir'] . $config['dir']['res'] . $id . '.json';
  1808. file_unlink($jsonFilename);
  1809. }
  1810. if ($config['smart_build'] && !$return && !$mod) {
  1811. $noko50fn = $board['dir'] . $config['dir']['res'] . link_for(array('id' => $id), true);
  1812. file_unlink($noko50fn);
  1813. file_unlink($board['dir'] . $config['dir']['res'] . link_for(array('id' => $id)));
  1814. } else if ($return) {
  1815. return $body;
  1816. } else {
  1817. $noko50fn = $board['dir'] . $config['dir']['res'] . link_for($thread, true);
  1818. if ($hasnoko50 || file_exists($noko50fn)) {
  1819. buildThread50($id, $return, $mod, $thread, $antibot);
  1820. }
  1821. file_write($board['dir'] . $config['dir']['res'] . link_for($thread), $body);
  1822. }
  1823. }
  1824. function buildThread50($id, $return = false, $mod = false, $thread = null, $antibot = false) {
  1825. global $board, $config, $build_pages;
  1826. $id = round($id);
  1827. if ($antibot)
  1828. $antibot->reset();
  1829. if (!$thread) {
  1830. $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']));
  1831. $query->bindValue(':id', $id, PDO::PARAM_INT);
  1832. $query->bindValue(':limit', $config['noko50_count']+1, PDO::PARAM_INT);
  1833. $query->execute() or error(db_error($query));
  1834. $num_images = 0;
  1835. while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1836. if (!isset($thread)) {
  1837. $thread = new Thread($post, $mod ? '?/' : $config['root'], $mod);
  1838. } else {
  1839. if ($post['files'])
  1840. $num_images += $post['num_files'];
  1841. $thread->add(new Post($post, $mod ? '?/' : $config['root'], $mod));
  1842. }
  1843. }
  1844. // Check if any posts were found
  1845. if (!isset($thread))
  1846. error($config['error']['nonexistant']);
  1847. if ($query->rowCount() == $config['noko50_count']+1) {
  1848. $count = prepare(sprintf("SELECT COUNT(`id`) as `num` FROM ``posts_%s`` WHERE `thread` = :thread UNION ALL
  1849. SELECT SUM(`num_files`) FROM ``posts_%s`` WHERE `files` IS NOT NULL AND `thread` = :thread", $board['uri'], $board['uri']));
  1850. $count->bindValue(':thread', $id, PDO::PARAM_INT);
  1851. $count->execute() or error(db_error($count));
  1852. $c = $count->fetch();
  1853. $thread->omitted = $c['num'] - $config['noko50_count'];
  1854. $c = $count->fetch();
  1855. $thread->omitted_images = $c['num'] - $num_images;
  1856. }
  1857. $thread->posts = array_reverse($thread->posts);
  1858. } else {
  1859. $allPosts = $thread->posts;
  1860. $thread->posts = array_slice($allPosts, -$config['noko50_count']);
  1861. $thread->omitted += count($allPosts) - count($thread->posts);
  1862. foreach ($allPosts as $index => $post) {
  1863. if ($index == count($allPosts)-count($thread->posts))
  1864. break;
  1865. if ($post->files)
  1866. $thread->omitted_images += $post->num_files;
  1867. }
  1868. }
  1869. $hasnoko50 = $thread->postCount() >= $config['noko50_min'];
  1870. $body = Element('thread.html', array(
  1871. 'board' => $board,
  1872. 'thread' => $thread,
  1873. 'body' => $thread->build(false, true),
  1874. 'config' => $config,
  1875. 'id' => $id,
  1876. 'mod' => $mod,
  1877. 'hasnoko50' => $hasnoko50,
  1878. 'isnoko50' => true,
  1879. 'antibot' => $mod ? false : ($antibot ? $antibot : create_antibot($board['uri'], $id)),
  1880. 'boardlist' => createBoardlist($mod),
  1881. 'return' => ($mod ? '?' . $board['url'] . $config['file_index'] : $config['root'] . $board['dir'] . $config['file_index'])
  1882. ));
  1883. if ($return) {
  1884. return $body;
  1885. } else {
  1886. file_write($board['dir'] . $config['dir']['res'] . link_for($thread, true), $body);
  1887. }
  1888. }
  1889. function rrmdir($dir) {
  1890. if (is_dir($dir)) {
  1891. $objects = scandir($dir);
  1892. foreach ($objects as $object) {
  1893. if ($object != "." && $object != "..") {
  1894. if (filetype($dir."/".$object) == "dir")
  1895. rrmdir($dir."/".$object);
  1896. else
  1897. file_unlink($dir."/".$object);
  1898. }
  1899. }
  1900. reset($objects);
  1901. rmdir($dir);
  1902. }
  1903. }
  1904. function poster_id($ip, $thread) {
  1905. global $config;
  1906. if ($id = event('poster-id', $ip, $thread))
  1907. return $id;
  1908. // Confusing, hard to brute-force, but simple algorithm
  1909. return substr(sha1(sha1($ip . $config['secure_trip_salt'] . $thread) . $config['secure_trip_salt']), 0, $config['poster_id_length']);
  1910. }
  1911. function generate_tripcode($name) {
  1912. global $config;
  1913. if ($trip = event('tripcode', $name))
  1914. return $trip;
  1915. if (!preg_match('/^([^#]+)?(##|#)(.+)$/', $name, $match))
  1916. return array($name);
  1917. $name = $match[1];
  1918. $secure = $match[2] == '##';
  1919. $trip = $match[3];
  1920. // convert to SHIT_JIS encoding
  1921. $trip = mb_convert_encoding($trip, 'Shift_JIS', 'UTF-8');
  1922. // generate salt
  1923. $salt = substr($trip . 'H..', 1, 2);
  1924. $salt = preg_replace('/[^.-z]/', '.', $salt);
  1925. $salt = strtr($salt, ':;<=>?@[\]^_`', 'ABCDEFGabcdef');
  1926. if ($secure) {
  1927. if (isset($config['custom_tripcode']["##{$trip}"]))
  1928. $trip = $config['custom_tripcode']["##{$trip}"];
  1929. else
  1930. $trip = '!!' . substr(crypt($trip, str_replace('+', '.', '_..A.' . substr(base64_encode(sha1($trip . $config['secure_trip_salt'], true)), 0, 4))), -10);
  1931. } else {
  1932. if (isset($config['custom_tripcode']["#{$trip}"]))
  1933. $trip = $config['custom_tripcode']["#{$trip}"];
  1934. else
  1935. $trip = '!' . substr(crypt($trip, $salt), -10);
  1936. }
  1937. return array($name, $trip);
  1938. }
  1939. // Highest common factor
  1940. function hcf($a, $b){
  1941. $gcd = 1;
  1942. if ($a>$b) {
  1943. $a = $a+$b;
  1944. $b = $a-$b;
  1945. $a = $a-$b;
  1946. }
  1947. if ($b==(round($b/$a))*$a)
  1948. $gcd=$a;
  1949. else {
  1950. for ($i=round($a/2);$i;$i--) {
  1951. if ($a == round($a/$i)*$i && $b == round($b/$i)*$i) {
  1952. $gcd = $i;
  1953. $i = false;
  1954. }
  1955. }
  1956. }
  1957. return $gcd;
  1958. }
  1959. function fraction($numerator, $denominator, $sep) {
  1960. $gcf = hcf($numerator, $denominator);
  1961. $numerator = $numerator / $gcf;
  1962. $denominator = $denominator / $gcf;
  1963. return "{$numerator}{$sep}{$denominator}";
  1964. }
  1965. function getPostByHash($hash) {
  1966. global $board;
  1967. $query = prepare(sprintf("SELECT `id`,`thread` FROM ``posts_%s`` WHERE `filehash` = :hash", $board['uri']));
  1968. $query->bindValue(':hash', $hash, PDO::PARAM_STR);
  1969. $query->execute() or error(db_error($query));
  1970. if ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1971. return $post;
  1972. }
  1973. return false;
  1974. }
  1975. function getPostByHashInThread($hash, $thread) {
  1976. global $board;
  1977. $query = prepare(sprintf("SELECT `id`,`thread` FROM ``posts_%s`` WHERE `filehash` = :hash AND ( `thread` = :thread OR `id` = :thread )", $board['uri']));
  1978. $query->bindValue(':hash', $hash, PDO::PARAM_STR);
  1979. $query->bindValue(':thread', $thread, PDO::PARAM_INT);
  1980. $query->execute() or error(db_error($query));
  1981. if ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  1982. return $post;
  1983. }
  1984. return false;
  1985. }
  1986. function getPostByEmbed($embed) {
  1987. global $board, $config;
  1988. $matches = array();
  1989. foreach ($config['embedding'] as &$e) {
  1990. if (preg_match($e[0], $embed, $matches) && isset($matches[1]) && !empty($matches[1])) {
  1991. $embed = '%'.$matches[1].'%';
  1992. break;
  1993. }
  1994. }
  1995. if (!isset($embed)) return false;
  1996. $query = prepare(sprintf("SELECT `id`,`thread` FROM ``posts_%s`` WHERE `embed` LIKE :embed", $board['uri']));
  1997. $query->bindValue(':embed', $embed, PDO::PARAM_STR);
  1998. $query->execute() or error(db_error($query));
  1999. if ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  2000. return $post;
  2001. }
  2002. return false;
  2003. }
  2004. function getPostByEmbedInThread($embed, $thread) {
  2005. global $board, $config;
  2006. $matches = array();
  2007. foreach ($config['embedding'] as &$e) {
  2008. if (preg_match($e[0], $embed, $matches) && isset($matches[1]) && !empty($matches[1])) {
  2009. $embed = '%'.$matches[1].'%';
  2010. break;
  2011. }
  2012. }
  2013. if (!isset($embed)) return false;
  2014. $query = prepare(sprintf("SELECT `id`,`thread` FROM ``posts_%s`` WHERE `embed` = :embed AND ( `thread` = :thread OR `id` = :thread )", $board['uri']));
  2015. $query->bindValue(':embed', $embed, PDO::PARAM_STR);
  2016. $query->bindValue(':thread', $thread, PDO::PARAM_INT);
  2017. $query->execute() or error(db_error($query));
  2018. if ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  2019. return $post;
  2020. }
  2021. return false;
  2022. }
  2023. function undoImage(array $post) {
  2024. if (!$post['has_file'] || !isset($post['files']))
  2025. return;
  2026. foreach ($post['files'] as $key => $file) {
  2027. if (isset($file['file_path']))
  2028. file_unlink($file['file_path']);
  2029. if (isset($file['thumb_path']))
  2030. file_unlink($file['thumb_path']);
  2031. }
  2032. }
  2033. function rDNS($ip_addr) {
  2034. global $config;
  2035. if ($config['cache']['enabled'] && ($host = cache::get('rdns_' . $ip_addr))) {
  2036. return $host;
  2037. }
  2038. if (!$config['dns_system']) {
  2039. $host = gethostbyaddr($ip_addr);
  2040. } else {
  2041. $resp = shell_exec_error('host -W 1 ' . $ip_addr);
  2042. if (preg_match('/domain name pointer ([^\s]+)$/', $resp, $m))
  2043. $host = $m[1];
  2044. else
  2045. $host = $ip_addr;
  2046. }
  2047. $isip = filter_var($host, FILTER_VALIDATE_IP);
  2048. if ($config['fcrdns'] && !$isip && DNS($host) != $ip_addr) {
  2049. $host = $ip_addr;
  2050. }
  2051. if ($config['cache']['enabled'])
  2052. cache::set('rdns_' . $ip_addr, $host);
  2053. return $host;
  2054. }
  2055. function DNS($host) {
  2056. global $config;
  2057. if ($config['cache']['enabled'] && ($ip_addr = cache::get('dns_' . $host))) {
  2058. return $ip_addr != '?' ? $ip_addr : false;
  2059. }
  2060. if (!$config['dns_system']) {
  2061. $ip_addr = gethostbyname($host);
  2062. if ($ip_addr == $host)
  2063. $ip_addr = false;
  2064. } else {
  2065. $resp = shell_exec_error('host -W 1 ' . $host);
  2066. if (preg_match('/has address ([^\s]+)$/', $resp, $m))
  2067. $ip_addr = $m[1];
  2068. else
  2069. $ip_addr = false;
  2070. }
  2071. if ($config['cache']['enabled'])
  2072. cache::set('dns_' . $host, $ip_addr !== false ? $ip_addr : '?');
  2073. return $ip_addr;
  2074. }
  2075. function shell_exec_error($command, $suppress_stdout = false) {
  2076. global $config, $debug;
  2077. if ($config['debug'])
  2078. $start = microtime(true);
  2079. $return = trim(shell_exec('PATH="' . escapeshellcmd($config['shell_path']) . ':$PATH";' .
  2080. $command . ' 2>&1 ' . ($suppress_stdout ? '> /dev/null ' : '') . '&& echo "TB_SUCCESS"'));
  2081. $return = preg_replace('/TB_SUCCESS$/', '', $return);
  2082. if ($config['debug']) {
  2083. $time = microtime(true) - $start;
  2084. $debug['exec'][] = array(
  2085. 'command' => $command,
  2086. 'time' => '~' . round($time * 1000, 2) . 'ms',
  2087. 'response' => $return ? $return : null
  2088. );
  2089. $debug['time']['exec'] += $time;
  2090. }
  2091. return $return === 'TB_SUCCESS' ? false : $return;
  2092. }
  2093. /* Die rolling:
  2094. * If "dice XdY+/-Z" is in the email field (where X or +/-Z may be
  2095. * missing), X Y-sided dice are rolled and summed, with the modifier Z
  2096. * added on. The result is displayed at the top of the post.
  2097. */
  2098. function diceRoller($post) {
  2099. global $config;
  2100. if(strpos(strtolower($post->email), 'dice%20') === 0) {
  2101. $dicestr = str_split(substr($post->email, strlen('dice%20')));
  2102. // Get params
  2103. $diceX = '';
  2104. $diceY = '';
  2105. $diceZ = '';
  2106. $curd = 'diceX';
  2107. for($i = 0; $i < count($dicestr); $i ++) {
  2108. if(is_numeric($dicestr[$i])) {
  2109. $$curd .= $dicestr[$i];
  2110. } else if($dicestr[$i] == 'd') {
  2111. $curd = 'diceY';
  2112. } else if($dicestr[$i] == '-' || $dicestr[$i] == '+') {
  2113. $curd = 'diceZ';
  2114. $$curd = $dicestr[$i];
  2115. }
  2116. }
  2117. // Default values for X and Z
  2118. if($diceX == '') {
  2119. $diceX = '1';
  2120. }
  2121. if($diceZ == '') {
  2122. $diceZ = '+0';
  2123. }
  2124. // Intify them
  2125. $diceX = intval($diceX);
  2126. $diceY = intval($diceY);
  2127. $diceZ = intval($diceZ);
  2128. // Continue only if we have valid values
  2129. if($diceX > 0 && $diceY > 0) {
  2130. $dicerolls = array();
  2131. $dicesum = $diceZ;
  2132. for($i = 0; $i < $diceX; $i++) {
  2133. $roll = rand(1, $diceY);
  2134. $dicerolls[] = $roll;
  2135. $dicesum += $roll;
  2136. }
  2137. // Prepend the result to the post body
  2138. $modifier = ($diceZ != 0) ? ((($diceZ < 0) ? ' - ' : ' + ') . abs($diceZ)) : '';
  2139. $dicesum = ($diceX > 1) ? ' = ' . $dicesum : '';
  2140. $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;
  2141. }
  2142. }
  2143. }
  2144. function slugify($post) {
  2145. global $config;
  2146. $slug = "";
  2147. if (isset($post['subject']) && $post['subject'])
  2148. $slug = $post['subject'];
  2149. elseif (isset ($post['body_nomarkup']) && $post['body_nomarkup'])
  2150. $slug = $post['body_nomarkup'];
  2151. elseif (isset ($post['body']) && $post['body'])
  2152. $slug = strip_html($post['body']);
  2153. // Fix UTF-8 first
  2154. $slug = mb_convert_encoding($slug, "UTF-8", "UTF-8");
  2155. // Transliterate local characters like ü, I wonder how would it work for weird alphabets :^)
  2156. $slug = iconv("UTF-8", "ASCII//TRANSLIT//IGNORE", $slug);
  2157. // Remove Tinyboard custom markup
  2158. $slug = preg_replace("/<tinyboard [^>]+>.*?<\/tinyboard>/s", '', $slug);
  2159. // Downcase everything
  2160. $slug = strtolower($slug);
  2161. // Strip bad characters, alphanumerics should suffice
  2162. $slug = preg_replace('/[^a-zA-Z0-9]/', '-', $slug);
  2163. // Replace multiple dashes with single ones
  2164. $slug = preg_replace('/-+/', '-', $slug);
  2165. // Strip dashes at the beginning and at the end
  2166. $slug = preg_replace('/^-|-$/', '', $slug);
  2167. // Slug should be X characters long, at max (80?)
  2168. $slug = substr($slug, 0, $config['slug_max_size']);
  2169. // Slug is now ready
  2170. return $slug;
  2171. }
  2172. function link_for($post, $page50 = false, $foreignlink = false, $thread = false) {
  2173. global $config, $board;
  2174. $post = (array)$post;
  2175. // Where do we need to look for OP?
  2176. $b = $foreignlink ? $foreignlink : (isset($post['board']) ? array('uri' => $post['board']) : $board);
  2177. $id = (isset($post['thread']) && $post['thread']) ? $post['thread'] : $post['id'];
  2178. $slug = false;
  2179. if ($config['slugify'] && ( (isset($post['thread']) && $post['thread']) || !isset ($post['slug']) ) ) {
  2180. $cvar = "slug_".$b['uri']."_".$id;
  2181. if (!$thread) {
  2182. $slug = Cache::get($cvar);
  2183. if ($slug === false) {
  2184. $query = prepare(sprintf("SELECT `slug` FROM ``posts_%s`` WHERE `id` = :id", $b['uri']));
  2185. $query->bindValue(':id', $id, PDO::PARAM_INT);
  2186. $query->execute() or error(db_error($query));
  2187. $thread = $query->fetch(PDO::FETCH_ASSOC);
  2188. $slug = $thread['slug'];
  2189. Cache::set($cvar, $slug);
  2190. }
  2191. }
  2192. else {
  2193. $slug = $thread['slug'];
  2194. }
  2195. }
  2196. elseif ($config['slugify']) {
  2197. $slug = $post['slug'];
  2198. }
  2199. if ( $page50 && $slug) $tpl = $config['file_page50_slug'];
  2200. else if (!$page50 && $slug) $tpl = $config['file_page_slug'];
  2201. else if ( $page50 && !$slug) $tpl = $config['file_page50'];
  2202. else if (!$page50 && !$slug) $tpl = $config['file_page'];
  2203. return sprintf($tpl, $id, $slug);
  2204. }
  2205. function prettify_textarea($s){
  2206. return str_replace("\t", '&#09;', str_replace("\n", '&#13;&#10;', htmlentities($s)));
  2207. }
  2208. /*class HTMLPurifier_URIFilter_NoExternalImages extends HTMLPurifier_URIFilter {
  2209. public $name = 'NoExternalImages';
  2210. public function filter(&$uri, $c, $context) {
  2211. global $config;
  2212. $ct = $context->get('CurrentToken');
  2213. if (!$ct || $ct->name !== 'img') return true;
  2214. if (!isset($uri->host) && !isset($uri->scheme)) return true;
  2215. if (!in_array($uri->scheme . '://' . $uri->host . '/', $config['allowed_offsite_urls'])) {
  2216. error('No off-site links in board announcement images.');
  2217. }
  2218. return true;
  2219. }
  2220. }*/
  2221. function purify_html($s) {
  2222. global $config;
  2223. $c = HTMLPurifier_Config::createDefault();
  2224. $c->set('HTML.Allowed', $config['allowed_html']);
  2225. $uri = $c->getDefinition('URI');
  2226. $uri->addFilter(new HTMLPurifier_URIFilter_NoExternalImages(), $c);
  2227. $purifier = new HTMLPurifier($c);
  2228. $clean_html = $purifier->purify($s);
  2229. return $clean_html;
  2230. }
  2231. function markdown($s) {
  2232. $pd = new Parsedown();
  2233. $pd->setMarkupEscaped(true);
  2234. $pd->setimagesEnabled(false);
  2235. return $pd->text($s);
  2236. }