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.

2796 line
80KB

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