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.

1344 line
45KB

  1. <?php
  2. /*
  3. * Copyright (c) 2010-2014 Tinyboard Development Group
  4. */
  5. require_once 'inc/functions.php';
  6. require_once 'inc/anti-bot.php';
  7. require_once 'inc/bans.php';
  8. // Fix for magic quotes
  9. if (get_magic_quotes_gpc()) {
  10. function strip_array($var) {
  11. return is_array($var) ? array_map('strip_array', $var) : stripslashes($var);
  12. }
  13. $_GET = strip_array($_GET);
  14. $_POST = strip_array($_POST);
  15. }
  16. if ((!isset($_POST['mod']) || !$_POST['mod'])
  17. && ($config['board_locked']===true
  18. || (is_array($config['board_locked']) && in_array(strtolower($_POST['board']), $config['board_locked'])))){
  19. error("Board is locked");
  20. }
  21. $dropped_post = false;
  22. // Is it a post coming from NNTP? Let's extract it and pretend it's a normal post.
  23. if (isset($_GET['Newsgroups']) && $config['nntpchan']['enabled']) {
  24. if ($_SERVER['REMOTE_ADDR'] != $config['nntpchan']['trusted_peer']) {
  25. error("NNTPChan: Forbidden. $_SERVER[REMOTE_ADDR] is not a trusted peer");
  26. }
  27. $_POST = array();
  28. $_POST['json_response'] = true;
  29. $headers = json_encode($_GET);
  30. if (!isset ($_GET['Message-Id'])) {
  31. if (!isset ($_GET['Message-ID'])) {
  32. error("NNTPChan: No message ID");
  33. }
  34. else $msgid = $_GET['Message-ID'];
  35. }
  36. else $msgid = $_GET['Message-Id'];
  37. $groups = preg_split("/,\s*/", $_GET['Newsgroups']);
  38. if (count($groups) != 1) {
  39. error("NNTPChan: Messages can go to only one newsgroup");
  40. }
  41. $group = $groups[0];
  42. if (!isset($config['nntpchan']['dispatch'][$group])) {
  43. error("NNTPChan: We don't synchronize $group");
  44. }
  45. $xboard = $config['nntpchan']['dispatch'][$group];
  46. $ref = null;
  47. if (isset ($_GET['References'])) {
  48. $refs = preg_split("/,\s*/", $_GET['References']);
  49. if (count($refs) > 1) {
  50. error("NNTPChan: We don't support multiple references");
  51. }
  52. $ref = $refs[0];
  53. $query = prepare("SELECT `board`,`id` FROM ``nntp_references`` WHERE `message_id` = :ref");
  54. $query->bindValue(':ref', $ref);
  55. $query->execute() or error(db_error($query));
  56. $ary = $query->fetchAll(PDO::FETCH_ASSOC);
  57. if (count($ary) == 0) {
  58. error("NNTPChan: We don't have $ref that $msgid references");
  59. }
  60. $p_id = $ary[0]['id'];
  61. $p_board = $ary[0]['board'];
  62. if ($p_board != $xboard) {
  63. error("NNTPChan: Cross board references not allowed. Tried to reference $p_board on $xboard");
  64. }
  65. $_POST['thread'] = $p_id;
  66. }
  67. $date = isset($_GET['Date']) ? strtotime($_GET['Date']) : time();
  68. list($ct) = explode('; ', $_GET['Content-Type']);
  69. $query = prepare("SELECT COUNT(*) AS `c` FROM ``nntp_references`` WHERE `message_id` = :msgid");
  70. $query->bindValue(":msgid", $msgid);
  71. $query->execute() or error(db_error($query));
  72. $a = $query->fetch(PDO::FETCH_ASSOC);
  73. if ($a['c'] > 0) {
  74. error("NNTPChan: We already have this post. Post discarded.");
  75. }
  76. if ($ct == 'text/plain') {
  77. $content = file_get_contents("php://input");
  78. }
  79. elseif ($ct == 'multipart/mixed' || $ct == 'multipart/form-data') {
  80. _syslog(LOG_INFO, "MM: Files: ".print_r($GLOBALS, true)); // Debug
  81. $content = '';
  82. $newfiles = array();
  83. foreach ($_FILES['attachment']['error'] as $id => $error) {
  84. if ($_FILES['attachment']['type'][$id] == 'text/plain') {
  85. $content .= file_get_contents($_FILES['attachment']['tmp_name'][$id]);
  86. }
  87. elseif ($_FILES['attachment']['type'][$id] == 'message/rfc822') { // Signed message, ignore for now
  88. }
  89. else { // A real attachment :^)
  90. $file = array();
  91. $file['name'] = $_FILES['attachment']['name'][$id];
  92. $file['type'] = $_FILES['attachment']['type'][$id];
  93. $file['size'] = $_FILES['attachment']['size'][$id];
  94. $file['tmp_name'] = $_FILES['attachment']['tmp_name'][$id];
  95. $file['error'] = $_FILES['attachment']['error'][$id];
  96. $newfiles["file$id"] = $file;
  97. }
  98. }
  99. $_FILES = $newfiles;
  100. }
  101. else {
  102. error("NNTPChan: Wrong mime type: $ct");
  103. }
  104. $_POST['subject'] = isset($_GET['Subject']) ? ($_GET['Subject'] == 'None' ? '' : $_GET['Subject']) : '';
  105. $_POST['board'] = $xboard;
  106. if (isset ($_GET['From'])) {
  107. list($name, $mail) = explode(" <", $_GET['From'], 2);
  108. $mail = preg_replace('/>\s+$/', '', $mail);
  109. $_POST['name'] = $name;
  110. //$_POST['email'] = $mail;
  111. $_POST['email'] = '';
  112. }
  113. if (isset ($_GET['X_Sage'])) {
  114. $_POST['email'] = 'sage';
  115. }
  116. $content = preg_replace_callback('/>>([0-9a-fA-F]{6,})/', function($id) use ($xboard) {
  117. $id = $id[1];
  118. $query = prepare("SELECT `board`,`id` FROM ``nntp_references`` WHERE `message_id_digest` LIKE :rule");
  119. $idx = $id . "%";
  120. $query->bindValue(':rule', $idx);
  121. $query->execute() or error(db_error($query));
  122. $ary = $query->fetchAll(PDO::FETCH_ASSOC);
  123. if (count($ary) == 0) {
  124. return ">>>>$id";
  125. }
  126. else {
  127. $ret = array();
  128. foreach ($ary as $v) {
  129. if ($v['board'] != $xboard) {
  130. $ret[] = ">>>/".$v['board']."/".$v['id'];
  131. }
  132. else {
  133. $ret[] = ">>".$v['id'];
  134. }
  135. }
  136. return implode($ret, ", ");
  137. }
  138. }, $content);
  139. $_POST['body'] = $content;
  140. $dropped_post = array(
  141. 'date' => $date,
  142. 'board' => $xboard,
  143. 'msgid' => $msgid,
  144. 'headers' => $headers,
  145. 'from_nntp' => true,
  146. );
  147. }
  148. elseif (isset($_GET['Newsgroups'])) {
  149. error("NNTPChan: NNTPChan support is disabled");
  150. }
  151. if (isset($_POST['delete'])) {
  152. // Delete
  153. if (!isset($_POST['board'], $_POST['password']))
  154. error($config['error']['bot']);
  155. $password = &$_POST['password'];
  156. if ($password == '')
  157. error($config['error']['invalidpassword']);
  158. $delete = array();
  159. foreach ($_POST as $post => $value) {
  160. if (preg_match('/^delete_(\d+)$/', $post, $m)) {
  161. $delete[] = (int)$m[1];
  162. }
  163. }
  164. checkDNSBL();
  165. // Check if board exists
  166. if (!openBoard($_POST['board']))
  167. error($config['error']['noboard']);
  168. // Check if banned
  169. checkBan($board['uri']);
  170. // Check if deletion enabled
  171. if (!$config['allow_delete'])
  172. error(_('Post deletion is not allowed!'));
  173. if (empty($delete))
  174. error($config['error']['nodelete']);
  175. foreach ($delete as &$id) {
  176. $query = prepare(sprintf("SELECT `id`,`thread`, `time`,`password` FROM ``posts_%s`` WHERE `id` = :id", $board['uri']));
  177. $query->bindValue(':id', $id, PDO::PARAM_INT);
  178. $query->execute() or error(db_error($query));
  179. if ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  180. $thread = false;
  181. if ($config['user_moderation'] && $post['thread']) {
  182. $thread_query = prepare(sprintf("SELECT `time`,`password` FROM ``posts_%s`` WHERE `id` = :id", $board['uri']));
  183. $thread_query->bindValue(':id', $post['thread'], PDO::PARAM_INT);
  184. $thread_query->execute() or error(db_error($query));
  185. $thread = $thread_query->fetch(PDO::FETCH_ASSOC);
  186. }
  187. if ($password != '' && $post['password'] != $password && (!$thread || $thread['password'] != $password))
  188. error($config['error']['invalidpassword']);
  189. if ($post['time'] > time() - $config['delete_time'] && (!$thread || $thread['password'] != $password)) {
  190. error(sprintf($config['error']['delete_too_soon'], until($post['time'] + $config['delete_time'])));
  191. }
  192. if (isset($_POST['file'])) {
  193. // Delete just the file
  194. deleteFile($id);
  195. modLog("User deleted file from his own post #$id");
  196. } else {
  197. // Delete entire post
  198. deletePost($id);
  199. modLog("User deleted his own post #$id");
  200. }
  201. _syslog(LOG_INFO, 'Deleted post: ' .
  202. '/' . $board['dir'] . $config['dir']['res'] . sprintf($config['file_page'], $post['thread'] ? $post['thread'] : $id) . ($post['thread'] ? '#' . $id : '')
  203. );
  204. }
  205. }
  206. buildIndex();
  207. $is_mod = isset($_POST['mod']) && $_POST['mod'];
  208. $root = $is_mod ? $config['root'] . $config['file_mod'] . '?/' : $config['root'];
  209. if (!isset($_POST['json_response'])) {
  210. header('Location: ' . $root . $board['dir'] . $config['file_index'], true, $config['redirect_http']);
  211. } else {
  212. header('Content-Type: text/json');
  213. echo json_encode(array('success' => true));
  214. }
  215. // We are already done, let's continue our heavy-lifting work in the background (if we run off FastCGI)
  216. if (function_exists('fastcgi_finish_request'))
  217. @fastcgi_finish_request();
  218. rebuildThemes('post-delete', $board['uri']);
  219. } elseif (isset($_POST['report'])) {
  220. if (!isset($_POST['board'], $_POST['reason']))
  221. error($config['error']['bot']);
  222. $report = array();
  223. foreach ($_POST as $post => $value) {
  224. if (preg_match('/^delete_(\d+)$/', $post, $m)) {
  225. $report[] = (int)$m[1];
  226. }
  227. }
  228. checkDNSBL();
  229. // Check if board exists
  230. if (!openBoard($_POST['board']))
  231. error($config['error']['noboard']);
  232. // Check if banned
  233. checkBan($board['uri']);
  234. if (empty($report))
  235. error($config['error']['noreport']);
  236. if (count($report) > $config['report_limit'])
  237. error($config['error']['toomanyreports']);
  238. if ($config['report_captcha'] && !isset($_POST['captcha_text'], $_POST['captcha_cookie'])) {
  239. error($config['error']['bot']);
  240. }
  241. if ($config['report_captcha']) {
  242. $resp = file_get_contents($config['captcha']['provider_check'] . "?" . http_build_query([
  243. 'mode' => 'check',
  244. 'text' => $_POST['captcha_text'],
  245. 'extra' => $config['captcha']['extra'],
  246. 'cookie' => $_POST['captcha_cookie']
  247. ]));
  248. if ($resp !== '1') {
  249. error($config['error']['captcha']);
  250. }
  251. }
  252. $reason = escape_markup_modifiers($_POST['reason']);
  253. markup($reason);
  254. foreach ($report as &$id) {
  255. $query = prepare(sprintf("SELECT `id`,`thread` , `body_nomarkup` FROM ``posts_%s`` WHERE `id` = :id", $board['uri']));
  256. $query->bindValue(':id', $id, PDO::PARAM_INT);
  257. $query->execute() or error(db_error($query));
  258. $thread = $query->fetch(PDO::FETCH_ASSOC);
  259. $error = event('report', array('ip' => $_SERVER['REMOTE_ADDR'], 'board' => $board['uri'], 'post' => $post, 'reason' => $reason,'link' => link_for($post)));
  260. if ($error) {
  261. error($error);
  262. }
  263. if ($config['syslog'])
  264. _syslog(LOG_INFO, 'Reported post: ' .
  265. '/' . $board['dir'] . $config['dir']['res'] . link_for($post) . ($thread['thread'] ? '#' . $id : '') .
  266. ' for "' . $reason . '"'
  267. );
  268. $query = prepare("INSERT INTO ``reports`` VALUES (NULL, :time, :ip, :board, :post, :reason)");
  269. $query->bindValue(':time', time(), PDO::PARAM_INT);
  270. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
  271. $query->bindValue(':board', $board['uri'], PDO::PARAM_INT);
  272. $query->bindValue(':post', $id, PDO::PARAM_INT);
  273. $query->bindValue(':reason', $reason, PDO::PARAM_STR);
  274. $query->execute() or error(db_error($query));
  275. if ($config['slack'])
  276. {
  277. function slack($message, $room = "reports", $icon = ":no_entry_sign:")
  278. {
  279. $room = ($room) ? $room : "reports";
  280. $data = "payload=" . json_encode(array(
  281. "channel" => "#{$room}",
  282. "text" => urlencode($message),
  283. "icon_emoji" => $icon
  284. ));
  285. // You can get your webhook endpoint from your Slack settings
  286. // For some reason using the configuration key doesn't work
  287. $ch = curl_init($config['slack_incoming_webhook_endpoint']);
  288. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  289. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  290. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  291. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  292. $result = curl_exec($ch);
  293. curl_close($ch);
  294. return $result;
  295. }
  296. $postcontent = mb_substr($thread['body_nomarkup'], 0, 120) . '... _*(POST TRIMMED)*_';
  297. $slackmessage = '<' .$config['domain'] . "/mod.php?/" . $board['dir'] . $config['dir']['res'] . ( $thread['thread'] ? $thread['thread'] : $id ) . ".html" . ($thread['thread'] ? '#' . $id : '') . '> \n ' . $reason . '\n ' . $postcontent . '\n';
  298. $slackresult = slack($slackmessage, $config['slack_channel']);
  299. }
  300. }
  301. $is_mod = isset($_POST['mod']) && $_POST['mod'];
  302. $root = $is_mod ? $config['root'] . $config['file_mod'] . '?/' : $config['root'];
  303. if (!isset($_POST['json_response'])) {
  304. $index = $root . $board['dir'] . $config['file_index'];
  305. $reported_post = $root . $board['dir'] . $config['dir']['res'] . ( $thread['thread'] ? $thread['thread'] : $id ) . ".html" . ($thread['thread'] ? '#' . $id : '') ;
  306. header('Location: ' . $reported_post);
  307. //echo Element('page.html', array('config' => $config, 'body' => '<div style="text-align:center"><a href="javascript:window.close()">[ ' . _('Close window') ." ]</a> <a href='$index'>[ " . _('Return') . ' ]</a></div>', 'title' => _('Report submitted!')));
  308. } else {
  309. header('Content-Type: text/json');
  310. echo json_encode(array('success' => true));
  311. }
  312. } elseif (isset($_POST['post']) || $dropped_post) {
  313. if (!isset($_POST['body'], $_POST['board']) && !$dropped_post)
  314. error($config['error']['bot']);
  315. $post = array('board' => $_POST['board'], 'files' => array());
  316. // Check if board exists
  317. if (!openBoard($post['board']))
  318. error($config['error']['noboard']);
  319. if (!isset($_POST['name']))
  320. $_POST['name'] = $config['anonymous'];
  321. if (!isset($_POST['email']))
  322. $_POST['email'] = '';
  323. if (!isset($_POST['subject']))
  324. $_POST['subject'] = '';
  325. if (!isset($_POST['password']))
  326. $_POST['password'] = '';
  327. if (isset($_POST['thread'])) {
  328. $post['op'] = false;
  329. $post['thread'] = round($_POST['thread']);
  330. } else
  331. $post['op'] = true;
  332. if (!$dropped_post) {
  333. // Check for CAPTCHA right after opening the board so the "return" link is in there
  334. if ($config['recaptcha']) {
  335. if (!isset($_POST['recaptcha_challenge_field']) || !isset($_POST['recaptcha_response_field']))
  336. error($config['error']['bot']);
  337. // Check what reCAPTCHA has to say...
  338. $resp = recaptcha_check_answer($config['recaptcha_private'],
  339. $_SERVER['REMOTE_ADDR'],
  340. $_POST['recaptcha_challenge_field'],
  341. $_POST['recaptcha_response_field']);
  342. if (!$resp->is_valid) {
  343. error($config['error']['captcha']);
  344. }
  345. }
  346. if (!(($post['op'] && $_POST['post'] == $config['button_newtopic']) ||
  347. (!$post['op'] && $_POST['post'] == $config['button_reply'])))
  348. error($config['error']['bot']);
  349. // Check the referrer
  350. if ($config['referer_match'] !== false &&
  351. (!isset($_SERVER['HTTP_REFERER']) || !preg_match($config['referer_match'], rawurldecode($_SERVER['HTTP_REFERER']))))
  352. error($config['error']['referer']);
  353. checkDNSBL();
  354. // Check if banned
  355. checkBan($board['uri']);
  356. if ($post['mod'] = isset($_POST['mod']) && $_POST['mod']) {
  357. check_login(false);
  358. if (!$mod) {
  359. // Liar. You're not a mod.
  360. error($config['error']['notamod']);
  361. }
  362. $post['sticky'] = $post['op'] && isset($_POST['sticky']);
  363. $post['locked'] = $post['op'] && isset($_POST['lock']);
  364. $post['raw'] = isset($_POST['raw']);
  365. if ($post['sticky'] && !hasPermission($config['mod']['sticky'], $board['uri']))
  366. error($config['error']['noaccess']);
  367. if ($post['locked'] && !hasPermission($config['mod']['lock'], $board['uri']))
  368. error($config['error']['noaccess']);
  369. if ($post['raw'] && !hasPermission($config['mod']['rawhtml'], $board['uri']))
  370. error($config['error']['noaccess']);
  371. }
  372. if (!$post['mod']) {
  373. $post['antispam_hash'] = checkSpam(array($board['uri'], isset($post['thread']) ? $post['thread'] : ($config['try_smarter'] && isset($_POST['page']) ? 0 - (int)$_POST['page'] : null)));
  374. if ($post['antispam_hash'] === true)
  375. error($config['error']['spam']);
  376. }
  377. if ($config['robot_enable'] && $config['robot_mute']) {
  378. checkMute();
  379. }
  380. }
  381. else {
  382. $mod = $post['mod'] = false;
  383. }
  384. //Check if thread exists
  385. if (!$post['op']) {
  386. $query = prepare(sprintf("SELECT `sticky`,`locked`,`cycle`,`sage`,`slug` FROM ``posts_%s`` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri']));
  387. $query->bindValue(':id', $post['thread'], PDO::PARAM_INT);
  388. $query->execute() or error(db_error());
  389. if (!$thread = $query->fetch(PDO::FETCH_ASSOC)) {
  390. // Non-existant
  391. error($config['error']['nonexistant']);
  392. }
  393. }
  394. else {
  395. $thread = false;
  396. }
  397. // Check for an embed field
  398. if ($config['enable_embedding'] && isset($_POST['embed']) && !empty($_POST['embed'])) {
  399. // yep; validate it
  400. $value = $_POST['embed'];
  401. foreach ($config['embedding'] as &$embed) {
  402. if (preg_match($embed[0], $value)) {
  403. // Valid link
  404. $post['embed'] = $value;
  405. // This is bad, lol.
  406. $post['no_longer_require_an_image_for_op'] = true;
  407. break;
  408. }
  409. }
  410. if (!isset($post['embed'])) {
  411. error($config['error']['invalid_embed']);
  412. }
  413. }
  414. if (!hasPermission($config['mod']['bypass_field_disable'], $board['uri'])) {
  415. if ($config['field_disable_name'])
  416. $_POST['name'] = $config['anonymous']; // "forced anonymous"
  417. if ($config['field_disable_email'])
  418. $_POST['email'] = '';
  419. if ($config['field_disable_password'])
  420. $_POST['password'] = '';
  421. if ($config['field_disable_subject'] || (!$post['op'] && $config['field_disable_reply_subject']))
  422. $_POST['subject'] = '';
  423. }
  424. if ($config['allow_upload_by_url'] && isset($_POST['file_url1']) && !empty($_POST['file_url1'])) {
  425. function unlink_tmp_file($file) {
  426. @unlink($file);
  427. fatal_error_handler();
  428. }
  429. function upload_by_url($config,$post,$url) {
  430. $post['file_url'] = $url;
  431. if (!preg_match('@^https?://@', $post['file_url']))
  432. error($config['error']['invalidimg']);
  433. if (mb_strpos($post['file_url'], '?') !== false)
  434. $url_without_params = mb_substr($post['file_url'], 0, mb_strpos($post['file_url'], '?'));
  435. else
  436. $url_without_params = $post['file_url'];
  437. $post['extension'] = strtolower(mb_substr($url_without_params, mb_strrpos($url_without_params, '.') + 1));
  438. if ($post['op'] && $config['allowed_ext_op']) {
  439. if (!in_array($post['extension'], $config['allowed_ext_op']))
  440. error($config['error']['unknownext']);
  441. }
  442. else if (!in_array($post['extension'], $config['allowed_ext']) && !in_array($post['extension'], $config['allowed_ext_files']))
  443. error($config['error']['unknownext']);
  444. $post['file_tmp'] = tempnam($config['tmp'], 'url');
  445. register_shutdown_function('unlink_tmp_file', $post['file_tmp']);
  446. $fp = fopen($post['file_tmp'], 'w');
  447. $curl = curl_init();
  448. curl_setopt($curl, CURLOPT_URL, $post['file_url']);
  449. curl_setopt($curl, CURLOPT_FAILONERROR, true);
  450. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
  451. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
  452. curl_setopt($curl, CURLOPT_TIMEOUT, $config['upload_by_url_timeout']);
  453. curl_setopt($curl, CURLOPT_USERAGENT, 'Tinyboard');
  454. curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
  455. curl_setopt($curl, CURLOPT_FILE, $fp);
  456. curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
  457. if (curl_exec($curl) === false)
  458. error($config['error']['nomove'] . '<br/>Curl says: ' . curl_error($curl));
  459. curl_close($curl);
  460. fclose($fp);
  461. $_FILES[$post['file_tmp']] = array(
  462. 'name' => basename($url_without_params),
  463. 'tmp_name' => $post['file_tmp'],
  464. 'file_tmp' => true,
  465. 'error' => 0,
  466. 'size' => filesize($post['file_tmp'])
  467. );
  468. }
  469. for( $counter = 1; $counter <= $config['max_images']; $counter++ ) {
  470. $varname = "file_url". $counter;
  471. if (isset($_POST[$varname]) && !empty($_POST[$varname])){
  472. upload_by_url($config,$post,$_POST[$varname]);
  473. }
  474. }
  475. }
  476. $post['name'] = $_POST['name'] != '' ? $_POST['name'] : $config['anonymous'];
  477. $post['subject'] = $_POST['subject'];
  478. $post['email'] = str_replace(' ', '%20', htmlspecialchars($_POST['email']));
  479. $post['body'] = $_POST['body'];
  480. $post['password'] = $_POST['password'];
  481. $post['has_file'] = (!isset($post['embed']) && (($post['op'] && !isset($post['no_longer_require_an_image_for_op']) && $config['force_image_op']) || count($_FILES) > 0));
  482. if (!$dropped_post) {
  483. if (!($post['has_file'] || isset($post['embed'])) || (($post['op'] && $config['force_body_op']) || (!$post['op'] && $config['force_body']))) {
  484. $stripped_whitespace = preg_replace('/[\s]/u', '', $post['body']);
  485. if ($stripped_whitespace == '') {
  486. error($config['error']['tooshort_body']);
  487. }
  488. }
  489. if (!$post['op']) {
  490. // Check if thread is locked
  491. // but allow mods to post
  492. if ($thread['locked'] && !hasPermission($config['mod']['postinlocked'], $board['uri']))
  493. error($config['error']['locked']);
  494. $numposts = numPosts($post['thread']);
  495. if ($config['reply_hard_limit'] != 0 && $config['reply_hard_limit'] <= $numposts['replies'])
  496. error($config['error']['reply_hard_limit']);
  497. if ($post['has_file'] && $config['image_hard_limit'] != 0 && $config['image_hard_limit'] <= $numposts['images'])
  498. error($config['error']['image_hard_limit']);
  499. }
  500. }
  501. else {
  502. if (!$post['op']) {
  503. $numposts = numPosts($post['thread']);
  504. }
  505. }
  506. if ($post['has_file']) {
  507. // Determine size sanity
  508. $size = 0;
  509. if ($config['multiimage_method'] == 'split') {
  510. foreach ($_FILES as $key => $file) {
  511. $size += $file['size'];
  512. }
  513. } elseif ($config['multiimage_method'] == 'each') {
  514. foreach ($_FILES as $key => $file) {
  515. if ($file['size'] > $size) {
  516. $size = $file['size'];
  517. }
  518. }
  519. } else {
  520. error(_('Unrecognized file size determination method.'));
  521. }
  522. $max_size = $config['max_filesize'];
  523. if (array_key_exists('board_specific',$config)){
  524. if (array_key_exists($board['uri'],$config['board_specific'])){
  525. if (array_key_exists('max_filesize',$config['board_specific'][$board['uri']])){
  526. $max_size = $config['board_specific'][$board['uri']]['max_filesize'];
  527. }
  528. }
  529. }
  530. if ($size > $max_size)
  531. error(sprintf3($config['error']['filesize'], array(
  532. 'sz' => number_format($size),
  533. 'filesz' => number_format($size),
  534. 'maxsz' => number_format($config['max_filesize'])
  535. )));
  536. $post['filesize'] = $size;
  537. }
  538. $post['capcode'] = false;
  539. if ($mod && preg_match('/^((.+) )?## (.+)$/', $post['name'], $matches)) {
  540. $name = $matches[2] != '' ? $matches[2] : $config['anonymous'];
  541. $cap = $matches[3];
  542. if (isset($config['mod']['capcode'][$mod['type']])) {
  543. if ( $config['mod']['capcode'][$mod['type']] === true ||
  544. (is_array($config['mod']['capcode'][$mod['type']]) &&
  545. in_array($cap, $config['mod']['capcode'][$mod['type']])
  546. )) {
  547. $post['capcode'] = utf8tohtml($cap);
  548. $post['name'] = $name;
  549. }
  550. }
  551. }
  552. $trip = generate_tripcode($post['name']);
  553. $post['name'] = $trip[0];
  554. $post['trip'] = isset($trip[1]) ? $trip[1] : ''; // XX: Dropped posts and tripcodes
  555. $noko = false;
  556. if (strtolower($post['email']) == 'noko') {
  557. $noko = true;
  558. $post['email'] = '';
  559. } elseif (strtolower($post['email']) == 'nonoko'){
  560. $noko = false;
  561. $post['email'] = '';
  562. } else $noko = $config['always_noko'];
  563. if ($post['has_file']) {
  564. $i = 0;
  565. foreach ($_FILES as $key => $file) {
  566. if ($file['size'] && $file['tmp_name']) {
  567. $file['filename'] = urldecode($file['name']);
  568. $file['extension'] = strtolower(mb_substr($file['filename'], mb_strrpos($file['filename'], '.') + 1));
  569. if (isset($config['filename_func']))
  570. $file['file_id'] = $config['filename_func']($file);
  571. else
  572. $file['file_id'] = time() . substr(microtime(), 2, 3);
  573. if (sizeof($_FILES) > 1)
  574. $file['file_id'] .= "-$i";
  575. $file['file'] = $board['dir'] . $config['dir']['img'] . $file['file_id'] . '.' . $file['extension'];
  576. $file['thumb'] = $board['dir'] . $config['dir']['thumb'] . $file['file_id'] . '.' . ($config['thumb_ext'] ? $config['thumb_ext'] : $file['extension']);
  577. $post['files'][] = $file;
  578. $i++;
  579. }
  580. }
  581. }
  582. if (empty($post['files'])) $post['has_file'] = false;
  583. if (!$dropped_post) {
  584. // Check for a file
  585. if ($post['op'] && !isset($post['no_longer_require_an_image_for_op'])) {
  586. if (!$post['has_file'] && $config['force_image_op'])
  587. error($config['error']['noimage']);
  588. }
  589. // Check for too many files
  590. if (sizeof($post['files']) > $config['max_images'])
  591. error($config['error']['toomanyimages']);
  592. }
  593. if ($config['strip_combining_chars']) {
  594. $post['name'] = strip_combining_chars($post['name']);
  595. $post['email'] = strip_combining_chars($post['email']);
  596. $post['subject'] = strip_combining_chars($post['subject']);
  597. $post['body'] = strip_combining_chars($post['body']);
  598. }
  599. if (!$dropped_post) {
  600. // Check string lengths
  601. if (mb_strlen($post['name']) > 35)
  602. error(sprintf($config['error']['toolong'], 'name'));
  603. if (mb_strlen($post['email']) > 40)
  604. error(sprintf($config['error']['toolong'], 'email'));
  605. if (mb_strlen($post['subject']) > 100)
  606. error(sprintf($config['error']['toolong'], 'subject'));
  607. if (!$mod && mb_strlen($post['body']) > $config['max_body'])
  608. error($config['error']['toolong_body']);
  609. if (!$mod && mb_strlen($post['body']) > 0 && (mb_strlen($post['body']) < $config['min_body']))
  610. error($config['error']['tooshort_body']);
  611. if (mb_strlen($post['password']) > 20)
  612. error(sprintf($config['error']['toolong'], 'password'));
  613. }
  614. wordfilters($post['body']);
  615. $post['body'] = escape_markup_modifiers($post['body']);
  616. if ($mod && isset($post['raw']) && $post['raw']) {
  617. $post['body'] .= "\n<tinyboard raw html>1</tinyboard>";
  618. }
  619. if (!$dropped_post)
  620. if (($config['country_flags'] && !$config['allow_no_country']) || ($config['country_flags'] && $config['allow_no_country'] && !isset($_POST['no_country']))) {
  621. require 'inc/lib/geoip/geoip.inc';
  622. $gi=geoip\geoip_open('inc/lib/geoip/GeoIPv6.dat', GEOIP_STANDARD);
  623. function ipv4to6($ip) {
  624. if (strpos($ip, ':') !== false) {
  625. if (strpos($ip, '.') > 0)
  626. $ip = substr($ip, strrpos($ip, ':')+1);
  627. else return $ip; //native ipv6
  628. }
  629. $iparr = array_pad(explode('.', $ip), 4, 0);
  630. $part7 = base_convert(($iparr[0] * 256) + $iparr[1], 10, 16);
  631. $part8 = base_convert(($iparr[2] * 256) + $iparr[3], 10, 16);
  632. return '::ffff:'.$part7.':'.$part8;
  633. }
  634. if ($country_code = geoip\geoip_country_code_by_addr_v6($gi, ipv4to6($_SERVER['REMOTE_ADDR']))) {
  635. if (!in_array(strtolower($country_code), array('eu', 'ap', 'o1', 'a1', 'a2')))
  636. $post['body'] .= "\n<tinyboard flag>".strtolower($country_code)."</tinyboard>".
  637. "\n<tinyboard flag alt>".geoip\geoip_country_name_by_addr_v6($gi, ipv4to6($_SERVER['REMOTE_ADDR']))."</tinyboard>";
  638. }
  639. }
  640. if ($config['user_flag'] && isset($_POST['user_flag']))
  641. if (!empty($_POST['user_flag']) ){
  642. $user_flag = $_POST['user_flag'];
  643. if (!isset($config['user_flags'][$user_flag]))
  644. error(_('Invalid flag selection!'));
  645. $flag_alt = isset($user_flag_alt) ? $user_flag_alt : $config['user_flags'][$user_flag];
  646. $post['body'] .= "\n<tinyboard flag>" . strtolower($user_flag) . "</tinyboard>" .
  647. "\n<tinyboard flag alt>" . $flag_alt . "</tinyboard>";
  648. }
  649. if ($config['allowed_tags'] && $post['op'] && isset($_POST['tag']) && isset($config['allowed_tags'][$_POST['tag']])) {
  650. $post['body'] .= "\n<tinyboard tag>" . $_POST['tag'] . "</tinyboard>";
  651. }
  652. if (!$dropped_post)
  653. if ($config['proxy_save'] && isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  654. $proxy = preg_replace("/[^0-9a-fA-F.,: ]/", '', $_SERVER['HTTP_X_FORWARDED_FOR']);
  655. $post['body'] .= "\n<tinyboard proxy>".$proxy."</tinyboard>";
  656. }
  657. if (mysql_version() >= 50503) {
  658. $post['body_nomarkup'] = $post['body']; // Assume we're using the utf8mb4 charset
  659. } else {
  660. // MySQL's `utf8` charset only supports up to 3-byte symbols
  661. // Remove anything >= 0x010000
  662. $chars = preg_split('//u', $post['body'], -1, PREG_SPLIT_NO_EMPTY);
  663. $post['body_nomarkup'] = '';
  664. foreach ($chars as $char) {
  665. $o = 0;
  666. $ord = ordutf8($char, $o);
  667. if ($ord >= 0x010000)
  668. continue;
  669. $post['body_nomarkup'] .= $char;
  670. }
  671. }
  672. $post['tracked_cites'] = markup($post['body'], true);
  673. if ($post['has_file']) {
  674. $md5cmd = false;
  675. if ($config['bsd_md5']) $md5cmd = '/sbin/md5 -r';
  676. if ($config['gnu_md5']) $md5cmd = 'md5sum';
  677. $allhashes = '';
  678. foreach ($post['files'] as $key => &$file) {
  679. if ($post['op'] && $config['allowed_ext_op']) {
  680. if (!in_array($file['extension'], $config['allowed_ext_op']))
  681. error($config['error']['unknownext']);
  682. }
  683. elseif (!in_array($file['extension'], $config['allowed_ext']) && !in_array($file['extension'], $config['allowed_ext_files']))
  684. error($config['error']['unknownext']);
  685. $file['is_an_image'] = !in_array($file['extension'], $config['allowed_ext_files']);
  686. // Truncate filename if it is too long
  687. $file['filename'] = mb_substr($file['filename'], 0, $config['max_filename_len']);
  688. $upload = $file['tmp_name'];
  689. if (!is_readable($upload))
  690. error($config['error']['nomove']);
  691. if ($md5cmd) {
  692. $output = shell_exec_error($md5cmd . " " . escapeshellarg($upload));
  693. $output = explode(' ', $output);
  694. $hash = $output[0];
  695. }
  696. else {
  697. $hash = md5_file($upload);
  698. }
  699. $file['hash'] = $hash;
  700. $allhashes .= $hash;
  701. }
  702. if (count ($post['files']) == 1) {
  703. $post['filehash'] = $hash;
  704. }
  705. else {
  706. $post['filehash'] = md5($allhashes);
  707. }
  708. }
  709. if (!hasPermission($config['mod']['bypass_filters'], $board['uri']) && !$dropped_post) {
  710. require_once 'inc/filters.php';
  711. do_filters($post);
  712. }
  713. if ($post['has_file']) {
  714. foreach ($post['files'] as $key => &$file) {
  715. if ($file['is_an_image']) {
  716. if ($config['ie_mime_type_detection'] !== false) {
  717. // Check IE MIME type detection XSS exploit
  718. $buffer = file_get_contents($upload, null, null, null, 255);
  719. if (preg_match($config['ie_mime_type_detection'], $buffer)) {
  720. undoImage($post);
  721. error($config['error']['mime_exploit']);
  722. }
  723. }
  724. require_once 'inc/image.php';
  725. // find dimensions of an image using GD
  726. if (!$size = @getimagesize($file['tmp_name'])) {
  727. error($config['error']['invalidimg']);
  728. }
  729. if (!in_array($size[2], array(IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_BMP))) {
  730. error($config['error']['invalidimg']);
  731. }
  732. if ($size[0] > $config['max_width'] || $size[1] > $config['max_height']) {
  733. error($config['error']['maxsize']);
  734. }
  735. if ($config['convert_auto_orient'] && ($file['extension'] == 'jpg' || $file['extension'] == 'jpeg')) {
  736. // The following code corrects the image orientation.
  737. // Currently only works with the 'convert' option selected but it could easily be expanded to work with the rest if you can be bothered.
  738. if (!($config['redraw_image'] || (($config['strip_exif'] && !$config['use_exiftool']) && ($file['extension'] == 'jpg' || $file['extension'] == 'jpeg')))) {
  739. if (in_array($config['thumb_method'], array('convert', 'convert+gifsicle', 'gm', 'gm+gifsicle'))) {
  740. $exif = @exif_read_data($file['tmp_name']);
  741. $gm = in_array($config['thumb_method'], array('gm', 'gm+gifsicle'));
  742. if (isset($exif['Orientation']) && $exif['Orientation'] != 1) {
  743. if ($config['convert_manual_orient']) {
  744. $error = shell_exec_error(($gm ? 'gm ' : '') . 'convert ' .
  745. escapeshellarg($file['tmp_name']) . ' ' .
  746. ImageConvert::jpeg_exif_orientation(false, $exif) . ' ' .
  747. ($config['strip_exif'] ? '+profile "*"' :
  748. ($config['use_exiftool'] ? '' : '+profile "*"')
  749. ) . ' ' .
  750. escapeshellarg($file['tmp_name']));
  751. if ($config['use_exiftool'] && !$config['strip_exif']) {
  752. if ($exiftool_error = shell_exec_error(
  753. 'exiftool -overwrite_original -q -q -orientation=1 -n ' .
  754. escapeshellarg($file['tmp_name'])))
  755. error(_('exiftool failed!'), null, $exiftool_error);
  756. } else {
  757. // TODO: Find another way to remove the Orientation tag from the EXIF profile
  758. // without needing `exiftool`.
  759. }
  760. } else {
  761. $error = shell_exec_error(($gm ? 'gm ' : '') . 'convert ' .
  762. escapeshellarg($file['tmp_name']) . ' -auto-orient ' . escapeshellarg($upload));
  763. }
  764. if ($error)
  765. error(_('Could not auto-orient image!'), null, $error);
  766. $size = @getimagesize($file['tmp_name']);
  767. if ($config['strip_exif'])
  768. $file['exif_stripped'] = true;
  769. }
  770. }
  771. }
  772. }
  773. // create image object
  774. $image = new Image($file['tmp_name'], $file['extension'], $size);
  775. if ($image->size->width > $config['max_width'] || $image->size->height > $config['max_height']) {
  776. $image->delete();
  777. error($config['error']['maxsize']);
  778. }
  779. $file['width'] = $image->size->width;
  780. $file['height'] = $image->size->height;
  781. if ($config['spoiler_images'] && isset($_POST['spoiler'])) {
  782. $file['thumb'] = 'spoiler';
  783. $size = @getimagesize($config['spoiler_image']);
  784. $file['thumbwidth'] = $size[0];
  785. $file['thumbheight'] = $size[1];
  786. } elseif ($config['minimum_copy_resize'] &&
  787. $image->size->width <= $config['thumb_width'] &&
  788. $image->size->height <= $config['thumb_height'] &&
  789. $file['extension'] == ($config['thumb_ext'] ? $config['thumb_ext'] : $file['extension'])) {
  790. // Copy, because there's nothing to resize
  791. copy($file['tmp_name'], $file['thumb']);
  792. $file['thumbwidth'] = $image->size->width;
  793. $file['thumbheight'] = $image->size->height;
  794. } else {
  795. $thumb = $image->resize(
  796. $config['thumb_ext'] ? $config['thumb_ext'] : $file['extension'],
  797. $post['op'] ? $config['thumb_op_width'] : $config['thumb_width'],
  798. $post['op'] ? $config['thumb_op_height'] : $config['thumb_height']
  799. );
  800. $thumb->to($file['thumb']);
  801. $file['thumbwidth'] = $thumb->width;
  802. $file['thumbheight'] = $thumb->height;
  803. $thumb->_destroy();
  804. }
  805. if ($config['redraw_image'] || (!@$file['exif_stripped'] && $config['strip_exif'] && ($file['extension'] == 'jpg' || $file['extension'] == 'jpeg'))) {
  806. if (!$config['redraw_image'] && $config['use_exiftool']) {
  807. if($error = shell_exec_error('exiftool -overwrite_original -ignoreMinorErrors -q -q -all= ' .
  808. escapeshellarg($file['tmp_name'])))
  809. error(_('Could not strip EXIF metadata!'), null, $error);
  810. } else {
  811. $image->to($file['file']);
  812. $dont_copy_file = true;
  813. }
  814. }
  815. $image->destroy();
  816. } else {
  817. if ($file['extension'] == "pdf" && $config['pdf_file_thumbnail']){
  818. $path = $file['thumb'];
  819. $error = shell_exec_error( 'convert -thumbnail x300 -background white -alpha remove ' .
  820. escapeshellarg($file['tmp_name']. '[0]') . ' ' .
  821. escapeshellarg($file['thumb']));
  822. if ($error){
  823. $path = sprintf($config['file_thumb'],isset($config['file_icons'][$file['extension']]) ? $config['file_icons'][$file['extension']] : $config['file_icons']['default']);
  824. }
  825. $file['thumb'] = basename($file['thumb']);
  826. $size = @getimagesize($path);
  827. $file['thumbwidth'] = $size[0];
  828. $file['thumbheight'] = $size[1];
  829. $file['width'] = $size[0];
  830. $file['height'] = $size[1];
  831. }
  832. else {
  833. // not an image
  834. //copy($config['file_thumb'], $post['thumb']);
  835. $file['thumb'] = 'file';
  836. $size = @getimagesize(sprintf($config['file_thumb'],
  837. isset($config['file_icons'][$file['extension']]) ?
  838. $config['file_icons'][$file['extension']] : $config['file_icons']['default']));
  839. $file['thumbwidth'] = $size[0];
  840. $file['thumbheight'] = $size[1];
  841. }
  842. }
  843. if ($config['tesseract_ocr'] && $file['thumb'] != 'file') { // Let's OCR it!
  844. $fname = $file['tmp_name'];
  845. if ($file['height'] > 500 || $file['width'] > 500) {
  846. $fname = $file['thumb'];
  847. }
  848. if ($fname == 'spoiler') { // We don't have that much CPU time, do we?
  849. }
  850. else {
  851. $tmpname = __DIR__ . "/tmp/tesseract/".rand(0,10000000);
  852. // Preprocess command is an ImageMagick b/w quantization
  853. $error = shell_exec_error(sprintf($config['tesseract_preprocess_command'], escapeshellarg($fname)) . " | " .
  854. 'tesseract stdin '.escapeshellarg($tmpname).' '.$config['tesseract_params']);
  855. $tmpname .= ".txt";
  856. $value = @file_get_contents($tmpname);
  857. @unlink($tmpname);
  858. if ($value && trim($value)) {
  859. // This one has an effect, that the body is appended to a post body. So you can write a correct
  860. // spamfilter.
  861. $post['body_nomarkup'] .= "<tinyboard ocr image $key>".htmlspecialchars($value)."</tinyboard>";
  862. }
  863. }
  864. }
  865. if (!isset($dont_copy_file) || !$dont_copy_file) {
  866. if (isset($file['file_tmp'])) {
  867. if (!@rename($file['tmp_name'], $file['file']))
  868. error($config['error']['nomove']);
  869. chmod($file['file'], 0644);
  870. } elseif (!@move_uploaded_file($file['tmp_name'], $file['file']))
  871. error($config['error']['nomove']);
  872. }
  873. }
  874. if ($config['image_reject_repost']) {
  875. if ($p = getPostByHash($post['filehash'])) {
  876. undoImage($post);
  877. error(sprintf($config['error']['fileexists'],
  878. ($post['mod'] ? $config['root'] . $config['file_mod'] . '?/' : $config['root']) .
  879. ($board['dir'] . $config['dir']['res'] .
  880. ($p['thread'] ?
  881. $p['thread'] . '.html#' . $p['id']
  882. :
  883. $p['id'] . '.html'
  884. ))
  885. ));
  886. }
  887. } else if (!$post['op'] && $config['image_reject_repost_in_thread']) {
  888. if ($p = getPostByHashInThread($post['filehash'], $post['thread'])) {
  889. undoImage($post);
  890. error(sprintf($config['error']['fileexistsinthread'],
  891. ($post['mod'] ? $config['root'] . $config['file_mod'] . '?/' : $config['root']) .
  892. ($board['dir'] . $config['dir']['res'] .
  893. ($p['thread'] ?
  894. $p['thread'] . '.html#' . $p['id']
  895. :
  896. $p['id'] . '.html'
  897. ))
  898. ));
  899. }
  900. }
  901. }
  902. // Do filters again if OCRing
  903. if ($config['tesseract_ocr'] && !hasPermission($config['mod']['bypass_filters'], $board['uri']) && !$dropped_post) {
  904. do_filters($post);
  905. }
  906. if (!hasPermission($config['mod']['postunoriginal'], $board['uri']) && $config['robot_enable'] && checkRobot($post['body_nomarkup']) && !$dropped_post) {
  907. undoImage($post);
  908. if ($config['robot_mute']) {
  909. error(sprintf($config['error']['muted'], mute()));
  910. } else {
  911. error($config['error']['unoriginal']);
  912. }
  913. }
  914. // Remove board directories before inserting them into the database.
  915. if ($post['has_file']) {
  916. foreach ($post['files'] as $key => &$file) {
  917. $file['file_path'] = $file['file'];
  918. $file['thumb_path'] = $file['thumb'];
  919. $file['file'] = mb_substr($file['file'], mb_strlen($board['dir'] . $config['dir']['img']));
  920. if ($file['is_an_image'] && $file['thumb'] != 'spoiler')
  921. $file['thumb'] = mb_substr($file['thumb'], mb_strlen($board['dir'] . $config['dir']['thumb']));
  922. }
  923. }
  924. $post = (object)$post;
  925. $post->files = array_map(function($a) { return (object)$a; }, $post->files);
  926. $error = event('post', $post);
  927. $post->files = array_map(function($a) { return (array)$a; }, $post->files);
  928. if ($error) {
  929. undoImage((array)$post);
  930. error($error);
  931. }
  932. $post = (array)$post;
  933. if ($post['files'])
  934. $post['files'] = $post['files'];
  935. $post['num_files'] = sizeof($post['files']);
  936. $post['id'] = $id = post($post);
  937. $post['slug'] = slugify($post);
  938. if ($dropped_post && $dropped_post['from_nntp']) {
  939. $query = prepare("INSERT INTO ``nntp_references`` (`board`, `id`, `message_id`, `message_id_digest`, `own`, `headers`) VALUES ".
  940. "(:board , :id , :message_id , :message_id_digest , false, :headers)");
  941. $query->bindValue(':board', $dropped_post['board']);
  942. $query->bindValue(':id', $id);
  943. $query->bindValue(':message_id', $dropped_post['msgid']);
  944. $query->bindValue(':message_id_digest', sha1($dropped_post['msgid']));
  945. $query->bindValue(':headers', $dropped_post['headers']);
  946. $query->execute() or error(db_error($query));
  947. } // ^^^^^ For inbound posts ^^^^^
  948. elseif ($config['nntpchan']['enabled'] && $config['nntpchan']['group']) {
  949. // vvvvv For outbound posts vvvvv
  950. require_once('inc/nntpchan/nntpchan.php');
  951. $msgid = gen_msgid($post['board'], $post['id']);
  952. list($headers, $files) = post2nntp($post, $msgid);
  953. $message = gen_nntp($headers, $files);
  954. $query = prepare("INSERT INTO ``nntp_references`` (`board`, `id`, `message_id`, `message_id_digest`, `own`, `headers`) VALUES ".
  955. "(:board , :id , :message_id , :message_id_digest , true , :headers)");
  956. $query->bindValue(':board', $post['board']);
  957. $query->bindValue(':id', $post['id']);
  958. $query->bindValue(':message_id', $msgid);
  959. $query->bindValue(':message_id_digest', sha1($msgid));
  960. $query->bindValue(':headers', json_encode($headers));
  961. $query->execute() or error(db_error($query));
  962. // Let's broadcast it!
  963. nntp_publish($message, $msgid);
  964. }
  965. insertFloodPost($post);
  966. // Handle cyclical threads
  967. if (!$post['op'] && isset($thread['cycle']) && $thread['cycle']) {
  968. // Query is a bit weird due to "This version of MariaDB doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'" (MariaDB Ver 15.1 Distrib 10.0.17-MariaDB, for Linux (x86_64))
  969. $query = prepare(sprintf('DELETE FROM ``posts_%s`` WHERE `thread` = :thread AND `id` NOT IN (SELECT `id` FROM (SELECT `id` FROM ``posts_%s`` WHERE `thread` = :thread ORDER BY `id` DESC LIMIT :limit) i)', $board['uri'], $board['uri']));
  970. $query->bindValue(':thread', $post['thread']);
  971. $query->bindValue(':limit', $config['cycle_limit'], PDO::PARAM_INT);
  972. $query->execute() or error(db_error($query));
  973. }
  974. if (isset($post['antispam_hash'])) {
  975. incrementSpamHash($post['antispam_hash']);
  976. }
  977. if (isset($post['tracked_cites']) && !empty($post['tracked_cites'])) {
  978. $insert_rows = array();
  979. foreach ($post['tracked_cites'] as $cite) {
  980. $insert_rows[] = '(' .
  981. $pdo->quote($board['uri']) . ', ' . (int)$id . ', ' .
  982. $pdo->quote($cite[0]) . ', ' . (int)$cite[1] . ')';
  983. }
  984. query('INSERT INTO ``cites`` VALUES ' . implode(', ', $insert_rows)) or error(db_error());
  985. }
  986. if (!$post['op'] && strtolower($post['email']) != 'sage' && !$thread['sage'] && ($config['reply_limit'] == 0 || $numposts['replies']+1 < $config['reply_limit'])) {
  987. bumpThread($post['thread']);
  988. }
  989. if (isset($_SERVER['HTTP_REFERER'])) {
  990. // Tell Javascript that we posted successfully
  991. if (isset($_COOKIE[$config['cookies']['js']]))
  992. $js = json_decode($_COOKIE[$config['cookies']['js']]);
  993. else
  994. $js = (object) array();
  995. // Tell it to delete the cached post for referer
  996. $js->{$_SERVER['HTTP_REFERER']} = true;
  997. // Encode and set cookie
  998. setcookie($config['cookies']['js'], json_encode($js), 0, $config['cookies']['jail'] ? $config['cookies']['path'] : '/', null, false, false);
  999. }
  1000. $root = $post['mod'] ? $config['root'] . $config['file_mod'] . '?/' : $config['root'];
  1001. if ($noko) {
  1002. $redirect = $root . $board['dir'] . $config['dir']['res'] .
  1003. link_for($post, false, false, $thread) . (!$post['op'] ? '#' . $id : '');
  1004. if (!$post['op'] && isset($_SERVER['HTTP_REFERER'])) {
  1005. $regex = array(
  1006. 'board' => str_replace('%s', '(\w{1,8})', preg_quote($config['board_path'], '/')),
  1007. 'page' => str_replace('%d', '(\d+)', preg_quote($config['file_page'], '/')),
  1008. 'page50' => '(' . str_replace('%d', '(\d+)', preg_quote($config['file_page50'], '/')) . '|' .
  1009. str_replace(array('%d', '%s'), array('(\d+)', '[a-z0-9-]+'), preg_quote($config['file_page50_slug'], '/')) . ')',
  1010. 'res' => preg_quote($config['dir']['res'], '/'),
  1011. );
  1012. if (preg_match('/\/' . $regex['board'] . $regex['res'] . $regex['page50'] . '([?&].*)?$/', $_SERVER['HTTP_REFERER'])) {
  1013. $redirect = $root . $board['dir'] . $config['dir']['res'] .
  1014. link_for($post, true, false, $thread) . (!$post['op'] ? '#' . $id : '');
  1015. }
  1016. }
  1017. } else {
  1018. $redirect = $root . $board['dir'] . $config['file_index'];
  1019. }
  1020. buildThread($post['op'] ? $id : $post['thread']);
  1021. if ($config['syslog'])
  1022. _syslog(LOG_INFO, 'New post: /' . $board['dir'] . $config['dir']['res'] .
  1023. link_for($post) . (!$post['op'] ? '#' . $id : ''));
  1024. if (!$post['mod']) header('X-Associated-Content: "' . $redirect . '"');
  1025. if (!isset($_POST['json_response'])) {
  1026. header('Location: ' . $redirect, true, $config['redirect_http']);
  1027. } else {
  1028. header('Content-Type: text/json; charset=utf-8');
  1029. echo json_encode(array(
  1030. 'redirect' => $redirect,
  1031. 'noko' => $noko,
  1032. 'id' => $id
  1033. ));
  1034. }
  1035. if ($config['try_smarter'] && $post['op'])
  1036. $build_pages = range(1, $config['max_pages']);
  1037. if ($post['op'])
  1038. clean($id);
  1039. event('post-after', $post);
  1040. buildIndex();
  1041. // We are already done, let's continue our heavy-lifting work in the background (if we run off FastCGI)
  1042. if (function_exists('fastcgi_finish_request'))
  1043. @fastcgi_finish_request();
  1044. if ($post['op'])
  1045. rebuildThemes('post-thread', $board['uri']);
  1046. else
  1047. rebuildThemes('post', $board['uri']);
  1048. } elseif (isset($_POST['appeal'])) {
  1049. if (!isset($_POST['ban_id']))
  1050. error($config['error']['bot']);
  1051. $ban_id = (int)$_POST['ban_id'];
  1052. $bans = Bans::find($_SERVER['REMOTE_ADDR']);
  1053. foreach ($bans as $_ban) {
  1054. if ($_ban['id'] == $ban_id) {
  1055. $ban = $_ban;
  1056. break;
  1057. }
  1058. }
  1059. if (!isset($ban)) {
  1060. error(_("That ban doesn't exist or is not for you."));
  1061. }
  1062. if ($ban['expires'] && $ban['expires'] - $ban['created'] <= $config['ban_appeals_min_length']) {
  1063. error(_("You cannot appeal a ban of this length."));
  1064. }
  1065. $query = query("SELECT `denied` FROM ``ban_appeals`` WHERE `ban_id` = $ban_id") or error(db_error());
  1066. $ban_appeals = $query->fetchAll(PDO::FETCH_COLUMN);
  1067. if (count($ban_appeals) >= $config['ban_appeals_max']) {
  1068. error(_("You cannot appeal this ban again."));
  1069. }
  1070. foreach ($ban_appeals as $is_denied) {
  1071. if (!$is_denied)
  1072. error(_("There is already a pending appeal for this ban."));
  1073. }
  1074. $query = prepare("INSERT INTO ``ban_appeals`` VALUES (NULL, :ban_id, :time, :message, 0)");
  1075. $query->bindValue(':ban_id', $ban_id, PDO::PARAM_INT);
  1076. $query->bindValue(':time', time(), PDO::PARAM_INT);
  1077. $query->bindValue(':message', $_POST['appeal']);
  1078. $query->execute() or error(db_error($query));
  1079. displayBan($ban);
  1080. } else {
  1081. if (!file_exists($config['has_installed'])) {
  1082. header('Location: install.php', true, $config['redirect_http']);
  1083. } else {
  1084. // They opened post.php in their browser manually.
  1085. error($config['error']['nopost']);
  1086. }
  1087. }