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.

2742 lines
79KB

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