The version of vichan running on lainchan.org
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

1294 rindas
43KB

  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 `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'] . link_for($post) . ($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. if ($config['syslog'])
  260. _syslog(LOG_INFO, 'Reported post: ' .
  261. '/' . $board['dir'] . $config['dir']['res'] . link_for($post) . ($thread['thread'] ? '#' . $id : '') .
  262. ' for "' . $reason . '"'
  263. );
  264. $query = prepare("INSERT INTO ``reports`` VALUES (NULL, :time, :ip, :board, :post, :reason)");
  265. $query->bindValue(':time', time(), PDO::PARAM_INT);
  266. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
  267. $query->bindValue(':board', $board['uri'], PDO::PARAM_INT);
  268. $query->bindValue(':post', $id, PDO::PARAM_INT);
  269. $query->bindValue(':reason', $reason, PDO::PARAM_STR);
  270. $query->execute() or error(db_error($query));
  271. if ($config['slack'])
  272. {
  273. function slack($message, $room = "reports", $icon = ":no_entry_sign:")
  274. {
  275. $room = ($room) ? $room : "reports";
  276. $data = "payload=" . json_encode(array(
  277. "channel" => "#{$room}",
  278. "text" => urlencode($message),
  279. "icon_emoji" => $icon
  280. ));
  281. // You can get your webhook endpoint from your Slack settings
  282. // For some reason using the configuration key doesn't work
  283. $ch = curl_init($config['slack_incoming_webhook_endpoint']);
  284. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  285. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  286. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  287. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  288. $result = curl_exec($ch);
  289. curl_close($ch);
  290. return $result;
  291. }
  292. $postcontent = mb_substr($thread['body_nomarkup'], 0, 120) . '... _*(POST TRIMMED)*_';
  293. $slackmessage = '<' .$config['domain'] . "/mod.php?/" . $board['dir'] . $config['dir']['res'] . ( $thread['thread'] ? $thread['thread'] : $id ) . ".html" . ($thread['thread'] ? '#' . $id : '') . '> \n ' . $reason . '\n ' . $postcontent . '\n';
  294. $slackresult = slack($slackmessage, $config['slack_channel']);
  295. }
  296. }
  297. $is_mod = isset($_POST['mod']) && $_POST['mod'];
  298. $root = $is_mod ? $config['root'] . $config['file_mod'] . '?/' : $config['root'];
  299. if (!isset($_POST['json_response'])) {
  300. $index = $root . $board['dir'] . $config['file_index'];
  301. 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!')));
  302. } else {
  303. header('Content-Type: text/json');
  304. echo json_encode(array('success' => true));
  305. }
  306. } elseif (isset($_POST['post']) || $dropped_post) {
  307. if (!isset($_POST['body'], $_POST['board']) && !$dropped_post)
  308. error($config['error']['bot']);
  309. $post = array('board' => $_POST['board'], 'files' => array());
  310. // Check if board exists
  311. if (!openBoard($post['board']))
  312. error($config['error']['noboard']);
  313. if (!isset($_POST['name']))
  314. $_POST['name'] = $config['anonymous'];
  315. if (!isset($_POST['email']))
  316. $_POST['email'] = '';
  317. if (!isset($_POST['subject']))
  318. $_POST['subject'] = '';
  319. if (!isset($_POST['password']))
  320. $_POST['password'] = '';
  321. if (isset($_POST['thread'])) {
  322. $post['op'] = false;
  323. $post['thread'] = round($_POST['thread']);
  324. } else
  325. $post['op'] = true;
  326. if (!$dropped_post) {
  327. // Check for CAPTCHA right after opening the board so the "return" link is in there
  328. if ($config['recaptcha']) {
  329. if (!isset($_POST['recaptcha_challenge_field']) || !isset($_POST['recaptcha_response_field']))
  330. error($config['error']['bot']);
  331. // Check what reCAPTCHA has to say...
  332. $resp = recaptcha_check_answer($config['recaptcha_private'],
  333. $_SERVER['REMOTE_ADDR'],
  334. $_POST['recaptcha_challenge_field'],
  335. $_POST['recaptcha_response_field']);
  336. if (!$resp->is_valid) {
  337. error($config['error']['captcha']);
  338. }
  339. }
  340. if (!(($post['op'] && $_POST['post'] == $config['button_newtopic']) ||
  341. (!$post['op'] && $_POST['post'] == $config['button_reply'])))
  342. error($config['error']['bot']);
  343. // Check the referrer
  344. if ($config['referer_match'] !== false &&
  345. (!isset($_SERVER['HTTP_REFERER']) || !preg_match($config['referer_match'], rawurldecode($_SERVER['HTTP_REFERER']))))
  346. error($config['error']['referer']);
  347. checkDNSBL();
  348. // Check if banned
  349. checkBan($board['uri']);
  350. if ($post['mod'] = isset($_POST['mod']) && $_POST['mod']) {
  351. check_login(false);
  352. if (!$mod) {
  353. // Liar. You're not a mod.
  354. error($config['error']['notamod']);
  355. }
  356. $post['sticky'] = $post['op'] && isset($_POST['sticky']);
  357. $post['locked'] = $post['op'] && isset($_POST['lock']);
  358. $post['raw'] = isset($_POST['raw']);
  359. if ($post['sticky'] && !hasPermission($config['mod']['sticky'], $board['uri']))
  360. error($config['error']['noaccess']);
  361. if ($post['locked'] && !hasPermission($config['mod']['lock'], $board['uri']))
  362. error($config['error']['noaccess']);
  363. if ($post['raw'] && !hasPermission($config['mod']['rawhtml'], $board['uri']))
  364. error($config['error']['noaccess']);
  365. }
  366. if (!$post['mod']) {
  367. $post['antispam_hash'] = checkSpam(array($board['uri'], isset($post['thread']) ? $post['thread'] : ($config['try_smarter'] && isset($_POST['page']) ? 0 - (int)$_POST['page'] : null)));
  368. if ($post['antispam_hash'] === true)
  369. error($config['error']['spam']);
  370. }
  371. if ($config['robot_enable'] && $config['robot_mute']) {
  372. checkMute();
  373. }
  374. }
  375. else {
  376. $mod = $post['mod'] = false;
  377. }
  378. //Check if thread exists
  379. if (!$post['op']) {
  380. $query = prepare(sprintf("SELECT `sticky`,`locked`,`cycle`,`sage`,`slug` FROM ``posts_%s`` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri']));
  381. $query->bindValue(':id', $post['thread'], PDO::PARAM_INT);
  382. $query->execute() or error(db_error());
  383. if (!$thread = $query->fetch(PDO::FETCH_ASSOC)) {
  384. // Non-existant
  385. error($config['error']['nonexistant']);
  386. }
  387. }
  388. else {
  389. $thread = false;
  390. }
  391. // Check for an embed field
  392. if ($config['enable_embedding'] && isset($_POST['embed']) && !empty($_POST['embed'])) {
  393. // yep; validate it
  394. $value = $_POST['embed'];
  395. foreach ($config['embedding'] as &$embed) {
  396. if (preg_match($embed[0], $value)) {
  397. // Valid link
  398. $post['embed'] = $value;
  399. // This is bad, lol.
  400. $post['no_longer_require_an_image_for_op'] = true;
  401. break;
  402. }
  403. }
  404. if (!isset($post['embed'])) {
  405. error($config['error']['invalid_embed']);
  406. }
  407. }
  408. if (!hasPermission($config['mod']['bypass_field_disable'], $board['uri'])) {
  409. if ($config['field_disable_name'])
  410. $_POST['name'] = $config['anonymous']; // "forced anonymous"
  411. if ($config['field_disable_email'])
  412. $_POST['email'] = '';
  413. if ($config['field_disable_password'])
  414. $_POST['password'] = '';
  415. if ($config['field_disable_subject'] || (!$post['op'] && $config['field_disable_reply_subject']))
  416. $_POST['subject'] = '';
  417. }
  418. if ($config['allow_upload_by_url'] && isset($_POST['file_url']) && !empty($_POST['file_url'])) {
  419. $post['file_url'] = $_POST['file_url'];
  420. if (!preg_match('@^https?://@', $post['file_url']))
  421. error($config['error']['invalidimg']);
  422. if (mb_strpos($post['file_url'], '?') !== false)
  423. $url_without_params = mb_substr($post['file_url'], 0, mb_strpos($post['file_url'], '?'));
  424. else
  425. $url_without_params = $post['file_url'];
  426. $post['extension'] = strtolower(mb_substr($url_without_params, mb_strrpos($url_without_params, '.') + 1));
  427. if ($post['op'] && $config['allowed_ext_op']) {
  428. if (!in_array($post['extension'], $config['allowed_ext_op']))
  429. error($config['error']['unknownext']);
  430. }
  431. else if (!in_array($post['extension'], $config['allowed_ext']) && !in_array($post['extension'], $config['allowed_ext_files']))
  432. error($config['error']['unknownext']);
  433. $post['file_tmp'] = tempnam($config['tmp'], 'url');
  434. function unlink_tmp_file($file) {
  435. @unlink($file);
  436. fatal_error_handler();
  437. }
  438. register_shutdown_function('unlink_tmp_file', $post['file_tmp']);
  439. $fp = fopen($post['file_tmp'], 'w');
  440. $curl = curl_init();
  441. curl_setopt($curl, CURLOPT_URL, $post['file_url']);
  442. curl_setopt($curl, CURLOPT_FAILONERROR, true);
  443. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
  444. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
  445. curl_setopt($curl, CURLOPT_TIMEOUT, $config['upload_by_url_timeout']);
  446. curl_setopt($curl, CURLOPT_USERAGENT, 'Tinyboard');
  447. curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
  448. curl_setopt($curl, CURLOPT_FILE, $fp);
  449. curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
  450. if (curl_exec($curl) === false)
  451. error($config['error']['nomove'] . '<br/>Curl says: ' . curl_error($curl));
  452. curl_close($curl);
  453. fclose($fp);
  454. $_FILES['file'] = array(
  455. 'name' => basename($url_without_params),
  456. 'tmp_name' => $post['file_tmp'],
  457. 'file_tmp' => true,
  458. 'error' => 0,
  459. 'size' => filesize($post['file_tmp'])
  460. );
  461. }
  462. $post['name'] = $_POST['name'] != '' ? $_POST['name'] : $config['anonymous'];
  463. $post['subject'] = $_POST['subject'];
  464. $post['email'] = str_replace(' ', '%20', htmlspecialchars($_POST['email']));
  465. $post['body'] = $_POST['body'];
  466. $post['password'] = $_POST['password'];
  467. $post['has_file'] = (!isset($post['embed']) && (($post['op'] && !isset($post['no_longer_require_an_image_for_op']) && $config['force_image_op']) || count($_FILES) > 0));
  468. if (!$dropped_post) {
  469. if (!($post['has_file'] || isset($post['embed'])) || (($post['op'] && $config['force_body_op']) || (!$post['op'] && $config['force_body']))) {
  470. $stripped_whitespace = preg_replace('/[\s]/u', '', $post['body']);
  471. if ($stripped_whitespace == '') {
  472. error($config['error']['tooshort_body']);
  473. }
  474. }
  475. if (!$post['op']) {
  476. // Check if thread is locked
  477. // but allow mods to post
  478. if ($thread['locked'] && !hasPermission($config['mod']['postinlocked'], $board['uri']))
  479. error($config['error']['locked']);
  480. $numposts = numPosts($post['thread']);
  481. if ($config['reply_hard_limit'] != 0 && $config['reply_hard_limit'] <= $numposts['replies'])
  482. error($config['error']['reply_hard_limit']);
  483. if ($post['has_file'] && $config['image_hard_limit'] != 0 && $config['image_hard_limit'] <= $numposts['images'])
  484. error($config['error']['image_hard_limit']);
  485. }
  486. }
  487. else {
  488. if (!$post['op']) {
  489. $numposts = numPosts($post['thread']);
  490. }
  491. }
  492. if ($post['has_file']) {
  493. // Determine size sanity
  494. $size = 0;
  495. if ($config['multiimage_method'] == 'split') {
  496. foreach ($_FILES as $key => $file) {
  497. $size += $file['size'];
  498. }
  499. } elseif ($config['multiimage_method'] == 'each') {
  500. foreach ($_FILES as $key => $file) {
  501. if ($file['size'] > $size) {
  502. $size = $file['size'];
  503. }
  504. }
  505. } else {
  506. error(_('Unrecognized file size determination method.'));
  507. }
  508. if ($size > $config['max_filesize'])
  509. error(sprintf3($config['error']['filesize'], array(
  510. 'sz' => number_format($size),
  511. 'filesz' => number_format($size),
  512. 'maxsz' => number_format($config['max_filesize'])
  513. )));
  514. $post['filesize'] = $size;
  515. }
  516. $post['capcode'] = false;
  517. if ($mod && preg_match('/^((.+) )?## (.+)$/', $post['name'], $matches)) {
  518. $name = $matches[2] != '' ? $matches[2] : $config['anonymous'];
  519. $cap = $matches[3];
  520. if (isset($config['mod']['capcode'][$mod['type']])) {
  521. if ( $config['mod']['capcode'][$mod['type']] === true ||
  522. (is_array($config['mod']['capcode'][$mod['type']]) &&
  523. in_array($cap, $config['mod']['capcode'][$mod['type']])
  524. )) {
  525. $post['capcode'] = utf8tohtml($cap);
  526. $post['name'] = $name;
  527. }
  528. }
  529. }
  530. $trip = generate_tripcode($post['name']);
  531. $post['name'] = $trip[0];
  532. $post['trip'] = isset($trip[1]) ? $trip[1] : ''; // XX: Dropped posts and tripcodes
  533. $noko = false;
  534. if (strtolower($post['email']) == 'noko') {
  535. $noko = true;
  536. $post['email'] = '';
  537. } elseif (strtolower($post['email']) == 'nonoko'){
  538. $noko = false;
  539. $post['email'] = '';
  540. } else $noko = $config['always_noko'];
  541. if ($post['has_file']) {
  542. $i = 0;
  543. foreach ($_FILES as $key => $file) {
  544. if ($file['size'] && $file['tmp_name']) {
  545. $file['filename'] = urldecode($file['name']);
  546. $file['extension'] = strtolower(mb_substr($file['filename'], mb_strrpos($file['filename'], '.') + 1));
  547. if (isset($config['filename_func']))
  548. $file['file_id'] = $config['filename_func']($file);
  549. else
  550. $file['file_id'] = time() . substr(microtime(), 2, 3);
  551. if (sizeof($_FILES) > 1)
  552. $file['file_id'] .= "-$i";
  553. $file['file'] = $board['dir'] . $config['dir']['img'] . $file['file_id'] . '.' . $file['extension'];
  554. $file['thumb'] = $board['dir'] . $config['dir']['thumb'] . $file['file_id'] . '.' . ($config['thumb_ext'] ? $config['thumb_ext'] : $file['extension']);
  555. $post['files'][] = $file;
  556. $i++;
  557. }
  558. }
  559. }
  560. if (empty($post['files'])) $post['has_file'] = false;
  561. if (!$dropped_post) {
  562. // Check for a file
  563. if ($post['op'] && !isset($post['no_longer_require_an_image_for_op'])) {
  564. if (!$post['has_file'] && $config['force_image_op'])
  565. error($config['error']['noimage']);
  566. }
  567. // Check for too many files
  568. if (sizeof($post['files']) > $config['max_images'])
  569. error($config['error']['toomanyimages']);
  570. }
  571. if ($config['strip_combining_chars']) {
  572. $post['name'] = strip_combining_chars($post['name']);
  573. $post['email'] = strip_combining_chars($post['email']);
  574. $post['subject'] = strip_combining_chars($post['subject']);
  575. $post['body'] = strip_combining_chars($post['body']);
  576. }
  577. if (!$dropped_post) {
  578. // Check string lengths
  579. if (mb_strlen($post['name']) > 35)
  580. error(sprintf($config['error']['toolong'], 'name'));
  581. if (mb_strlen($post['email']) > 40)
  582. error(sprintf($config['error']['toolong'], 'email'));
  583. if (mb_strlen($post['subject']) > 100)
  584. error(sprintf($config['error']['toolong'], 'subject'));
  585. if (!$mod && mb_strlen($post['body']) > $config['max_body'])
  586. error($config['error']['toolong_body']);
  587. if (mb_strlen($post['password']) > 20)
  588. error(sprintf($config['error']['toolong'], 'password'));
  589. }
  590. wordfilters($post['body']);
  591. $post['body'] = escape_markup_modifiers($post['body']);
  592. if ($mod && isset($post['raw']) && $post['raw']) {
  593. $post['body'] .= "\n<tinyboard raw html>1</tinyboard>";
  594. }
  595. if (!$dropped_post)
  596. if (($config['country_flags'] && !$config['allow_no_country']) || ($config['country_flags'] && $config['allow_no_country'] && !isset($_POST['no_country']))) {
  597. require 'inc/lib/geoip/geoip.inc';
  598. $gi=geoip\geoip_open('inc/lib/geoip/GeoIPv6.dat', GEOIP_STANDARD);
  599. function ipv4to6($ip) {
  600. if (strpos($ip, ':') !== false) {
  601. if (strpos($ip, '.') > 0)
  602. $ip = substr($ip, strrpos($ip, ':')+1);
  603. else return $ip; //native ipv6
  604. }
  605. $iparr = array_pad(explode('.', $ip), 4, 0);
  606. $part7 = base_convert(($iparr[0] * 256) + $iparr[1], 10, 16);
  607. $part8 = base_convert(($iparr[2] * 256) + $iparr[3], 10, 16);
  608. return '::ffff:'.$part7.':'.$part8;
  609. }
  610. if ($country_code = geoip\geoip_country_code_by_addr_v6($gi, ipv4to6($_SERVER['REMOTE_ADDR']))) {
  611. if (!in_array(strtolower($country_code), array('eu', 'ap', 'o1', 'a1', 'a2')))
  612. $post['body'] .= "\n<tinyboard flag>".strtolower($country_code)."</tinyboard>".
  613. "\n<tinyboard flag alt>".geoip\geoip_country_name_by_addr_v6($gi, ipv4to6($_SERVER['REMOTE_ADDR']))."</tinyboard>";
  614. }
  615. }
  616. if ($config['user_flag'] && isset($_POST['user_flag']))
  617. if (!empty($_POST['user_flag']) ){
  618. $user_flag = $_POST['user_flag'];
  619. if (!isset($config['user_flags'][$user_flag]))
  620. error(_('Invalid flag selection!'));
  621. $flag_alt = isset($user_flag_alt) ? $user_flag_alt : $config['user_flags'][$user_flag];
  622. $post['body'] .= "\n<tinyboard flag>" . strtolower($user_flag) . "</tinyboard>" .
  623. "\n<tinyboard flag alt>" . $flag_alt . "</tinyboard>";
  624. }
  625. if ($config['allowed_tags'] && $post['op'] && isset($_POST['tag']) && isset($config['allowed_tags'][$_POST['tag']])) {
  626. $post['body'] .= "\n<tinyboard tag>" . $_POST['tag'] . "</tinyboard>";
  627. }
  628. if (!$dropped_post)
  629. if ($config['proxy_save'] && isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  630. $proxy = preg_replace("/[^0-9a-fA-F.,: ]/", '', $_SERVER['HTTP_X_FORWARDED_FOR']);
  631. $post['body'] .= "\n<tinyboard proxy>".$proxy."</tinyboard>";
  632. }
  633. if (mysql_version() >= 50503) {
  634. $post['body_nomarkup'] = $post['body']; // Assume we're using the utf8mb4 charset
  635. } else {
  636. // MySQL's `utf8` charset only supports up to 3-byte symbols
  637. // Remove anything >= 0x010000
  638. $chars = preg_split('//u', $post['body'], -1, PREG_SPLIT_NO_EMPTY);
  639. $post['body_nomarkup'] = '';
  640. foreach ($chars as $char) {
  641. $o = 0;
  642. $ord = ordutf8($char, $o);
  643. if ($ord >= 0x010000)
  644. continue;
  645. $post['body_nomarkup'] .= $char;
  646. }
  647. }
  648. $post['tracked_cites'] = markup($post['body'], true);
  649. if ($post['has_file']) {
  650. $md5cmd = false;
  651. if ($config['bsd_md5']) $md5cmd = '/sbin/md5 -r';
  652. if ($config['gnu_md5']) $md5cmd = 'md5sum';
  653. $allhashes = '';
  654. foreach ($post['files'] as $key => &$file) {
  655. if ($post['op'] && $config['allowed_ext_op']) {
  656. if (!in_array($file['extension'], $config['allowed_ext_op']))
  657. error($config['error']['unknownext']);
  658. }
  659. elseif (!in_array($file['extension'], $config['allowed_ext']) && !in_array($file['extension'], $config['allowed_ext_files']))
  660. error($config['error']['unknownext']);
  661. $file['is_an_image'] = !in_array($file['extension'], $config['allowed_ext_files']);
  662. // Truncate filename if it is too long
  663. $file['filename'] = mb_substr($file['filename'], 0, $config['max_filename_len']);
  664. $upload = $file['tmp_name'];
  665. if (!is_readable($upload))
  666. error($config['error']['nomove']);
  667. if ($md5cmd) {
  668. $output = shell_exec_error($md5cmd . " " . escapeshellarg($upload));
  669. $output = explode(' ', $output);
  670. $hash = $output[0];
  671. }
  672. else {
  673. $hash = md5_file($upload);
  674. }
  675. $file['hash'] = $hash;
  676. $allhashes .= $hash;
  677. }
  678. if (count ($post['files']) == 1) {
  679. $post['filehash'] = $hash;
  680. }
  681. else {
  682. $post['filehash'] = md5($allhashes);
  683. }
  684. }
  685. if (!hasPermission($config['mod']['bypass_filters'], $board['uri']) && !$dropped_post) {
  686. require_once 'inc/filters.php';
  687. do_filters($post);
  688. }
  689. if ($post['has_file']) {
  690. foreach ($post['files'] as $key => &$file) {
  691. if ($file['is_an_image']) {
  692. if ($config['ie_mime_type_detection'] !== false) {
  693. // Check IE MIME type detection XSS exploit
  694. $buffer = file_get_contents($upload, null, null, null, 255);
  695. if (preg_match($config['ie_mime_type_detection'], $buffer)) {
  696. undoImage($post);
  697. error($config['error']['mime_exploit']);
  698. }
  699. }
  700. require_once 'inc/image.php';
  701. // find dimensions of an image using GD
  702. if (!$size = @getimagesize($file['tmp_name'])) {
  703. error($config['error']['invalidimg']);
  704. }
  705. if (!in_array($size[2], array(IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_BMP))) {
  706. error($config['error']['invalidimg']);
  707. }
  708. if ($size[0] > $config['max_width'] || $size[1] > $config['max_height']) {
  709. error($config['error']['maxsize']);
  710. }
  711. if ($config['convert_auto_orient'] && ($file['extension'] == 'jpg' || $file['extension'] == 'jpeg')) {
  712. // The following code corrects the image orientation.
  713. // Currently only works with the 'convert' option selected but it could easily be expanded to work with the rest if you can be bothered.
  714. if (!($config['redraw_image'] || (($config['strip_exif'] && !$config['use_exiftool']) && ($file['extension'] == 'jpg' || $file['extension'] == 'jpeg')))) {
  715. if (in_array($config['thumb_method'], array('convert', 'convert+gifsicle', 'gm', 'gm+gifsicle'))) {
  716. $exif = @exif_read_data($file['tmp_name']);
  717. $gm = in_array($config['thumb_method'], array('gm', 'gm+gifsicle'));
  718. if (isset($exif['Orientation']) && $exif['Orientation'] != 1) {
  719. if ($config['convert_manual_orient']) {
  720. $error = shell_exec_error(($gm ? 'gm ' : '') . 'convert ' .
  721. escapeshellarg($file['tmp_name']) . ' ' .
  722. ImageConvert::jpeg_exif_orientation(false, $exif) . ' ' .
  723. ($config['strip_exif'] ? '+profile "*"' :
  724. ($config['use_exiftool'] ? '' : '+profile "*"')
  725. ) . ' ' .
  726. escapeshellarg($file['tmp_name']));
  727. if ($config['use_exiftool'] && !$config['strip_exif']) {
  728. if ($exiftool_error = shell_exec_error(
  729. 'exiftool -overwrite_original -q -q -orientation=1 -n ' .
  730. escapeshellarg($file['tmp_name'])))
  731. error(_('exiftool failed!'), null, $exiftool_error);
  732. } else {
  733. // TODO: Find another way to remove the Orientation tag from the EXIF profile
  734. // without needing `exiftool`.
  735. }
  736. } else {
  737. $error = shell_exec_error(($gm ? 'gm ' : '') . 'convert ' .
  738. escapeshellarg($file['tmp_name']) . ' -auto-orient ' . escapeshellarg($upload));
  739. }
  740. if ($error)
  741. error(_('Could not auto-orient image!'), null, $error);
  742. $size = @getimagesize($file['tmp_name']);
  743. if ($config['strip_exif'])
  744. $file['exif_stripped'] = true;
  745. }
  746. }
  747. }
  748. }
  749. // create image object
  750. $image = new Image($file['tmp_name'], $file['extension'], $size);
  751. if ($image->size->width > $config['max_width'] || $image->size->height > $config['max_height']) {
  752. $image->delete();
  753. error($config['error']['maxsize']);
  754. }
  755. $file['width'] = $image->size->width;
  756. $file['height'] = $image->size->height;
  757. if ($config['spoiler_images'] && isset($_POST['spoiler'])) {
  758. $file['thumb'] = 'spoiler';
  759. $size = @getimagesize($config['spoiler_image']);
  760. $file['thumbwidth'] = $size[0];
  761. $file['thumbheight'] = $size[1];
  762. } elseif ($config['minimum_copy_resize'] &&
  763. $image->size->width <= $config['thumb_width'] &&
  764. $image->size->height <= $config['thumb_height'] &&
  765. $file['extension'] == ($config['thumb_ext'] ? $config['thumb_ext'] : $file['extension'])) {
  766. // Copy, because there's nothing to resize
  767. copy($file['tmp_name'], $file['thumb']);
  768. $file['thumbwidth'] = $image->size->width;
  769. $file['thumbheight'] = $image->size->height;
  770. } else {
  771. $thumb = $image->resize(
  772. $config['thumb_ext'] ? $config['thumb_ext'] : $file['extension'],
  773. $post['op'] ? $config['thumb_op_width'] : $config['thumb_width'],
  774. $post['op'] ? $config['thumb_op_height'] : $config['thumb_height']
  775. );
  776. $thumb->to($file['thumb']);
  777. $file['thumbwidth'] = $thumb->width;
  778. $file['thumbheight'] = $thumb->height;
  779. $thumb->_destroy();
  780. }
  781. if ($config['redraw_image'] || (!@$file['exif_stripped'] && $config['strip_exif'] && ($file['extension'] == 'jpg' || $file['extension'] == 'jpeg'))) {
  782. if (!$config['redraw_image'] && $config['use_exiftool']) {
  783. if($error = shell_exec_error('exiftool -overwrite_original -ignoreMinorErrors -q -q -all= ' .
  784. escapeshellarg($file['tmp_name'])))
  785. error(_('Could not strip EXIF metadata!'), null, $error);
  786. } else {
  787. $image->to($file['file']);
  788. $dont_copy_file = true;
  789. }
  790. }
  791. $image->destroy();
  792. } else {
  793. // not an image
  794. //copy($config['file_thumb'], $post['thumb']);
  795. $file['thumb'] = 'file';
  796. $size = @getimagesize(sprintf($config['file_thumb'],
  797. isset($config['file_icons'][$file['extension']]) ?
  798. $config['file_icons'][$file['extension']] : $config['file_icons']['default']));
  799. $file['thumbwidth'] = $size[0];
  800. $file['thumbheight'] = $size[1];
  801. }
  802. if ($config['tesseract_ocr'] && $file['thumb'] != 'file') { // Let's OCR it!
  803. $fname = $file['tmp_name'];
  804. if ($file['height'] > 500 || $file['width'] > 500) {
  805. $fname = $file['thumb'];
  806. }
  807. if ($fname == 'spoiler') { // We don't have that much CPU time, do we?
  808. }
  809. else {
  810. $tmpname = "tmp/tesseract/".rand(0,10000000);
  811. // Preprocess command is an ImageMagick b/w quantization
  812. $error = shell_exec_error(sprintf($config['tesseract_preprocess_command'], escapeshellarg($fname)) . " | " .
  813. 'tesseract stdin '.escapeshellarg($tmpname).' '.$config['tesseract_params']);
  814. $tmpname .= ".txt";
  815. $value = @file_get_contents($tmpname);
  816. @unlink($tmpname);
  817. if ($value && trim($value)) {
  818. // This one has an effect, that the body is appended to a post body. So you can write a correct
  819. // spamfilter.
  820. $post['body_nomarkup'] .= "<tinyboard ocr image $key>".htmlspecialchars($value)."</tinyboard>";
  821. }
  822. }
  823. }
  824. if (!isset($dont_copy_file) || !$dont_copy_file) {
  825. if (isset($file['file_tmp'])) {
  826. if (!@rename($file['tmp_name'], $file['file']))
  827. error($config['error']['nomove']);
  828. chmod($file['file'], 0644);
  829. } elseif (!@move_uploaded_file($file['tmp_name'], $file['file']))
  830. error($config['error']['nomove']);
  831. }
  832. }
  833. if ($config['image_reject_repost']) {
  834. if ($p = getPostByHash($post['filehash'])) {
  835. undoImage($post);
  836. error(sprintf($config['error']['fileexists'],
  837. ($post['mod'] ? $config['root'] . $config['file_mod'] . '?/' : $config['root']) .
  838. ($board['dir'] . $config['dir']['res'] .
  839. ($p['thread'] ?
  840. $p['thread'] . '.html#' . $p['id']
  841. :
  842. $p['id'] . '.html'
  843. ))
  844. ));
  845. }
  846. } else if (!$post['op'] && $config['image_reject_repost_in_thread']) {
  847. if ($p = getPostByHashInThread($post['filehash'], $post['thread'])) {
  848. undoImage($post);
  849. error(sprintf($config['error']['fileexistsinthread'],
  850. ($post['mod'] ? $config['root'] . $config['file_mod'] . '?/' : $config['root']) .
  851. ($board['dir'] . $config['dir']['res'] .
  852. ($p['thread'] ?
  853. $p['thread'] . '.html#' . $p['id']
  854. :
  855. $p['id'] . '.html'
  856. ))
  857. ));
  858. }
  859. }
  860. }
  861. // Do filters again if OCRing
  862. if ($config['tesseract_ocr'] && !hasPermission($config['mod']['bypass_filters'], $board['uri']) && !$dropped_post) {
  863. do_filters($post);
  864. }
  865. if (!hasPermission($config['mod']['postunoriginal'], $board['uri']) && $config['robot_enable'] && checkRobot($post['body_nomarkup']) && !$dropped_post) {
  866. undoImage($post);
  867. if ($config['robot_mute']) {
  868. error(sprintf($config['error']['muted'], mute()));
  869. } else {
  870. error($config['error']['unoriginal']);
  871. }
  872. }
  873. // Remove board directories before inserting them into the database.
  874. if ($post['has_file']) {
  875. foreach ($post['files'] as $key => &$file) {
  876. $file['file_path'] = $file['file'];
  877. $file['thumb_path'] = $file['thumb'];
  878. $file['file'] = mb_substr($file['file'], mb_strlen($board['dir'] . $config['dir']['img']));
  879. if ($file['is_an_image'] && $file['thumb'] != 'spoiler')
  880. $file['thumb'] = mb_substr($file['thumb'], mb_strlen($board['dir'] . $config['dir']['thumb']));
  881. }
  882. }
  883. $post = (object)$post;
  884. $post->files = array_map(function($a) { return (object)$a; }, $post->files);
  885. $error = event('post', $post);
  886. $post->files = array_map(function($a) { return (array)$a; }, $post->files);
  887. if ($error) {
  888. undoImage((array)$post);
  889. error($error);
  890. }
  891. $post = (array)$post;
  892. if ($post['files'])
  893. $post['files'] = $post['files'];
  894. $post['num_files'] = sizeof($post['files']);
  895. $post['id'] = $id = post($post);
  896. $post['slug'] = slugify($post);
  897. if ($dropped_post && $dropped_post['from_nntp']) {
  898. $query = prepare("INSERT INTO ``nntp_references`` (`board`, `id`, `message_id`, `message_id_digest`, `own`, `headers`) VALUES ".
  899. "(:board , :id , :message_id , :message_id_digest , false, :headers)");
  900. $query->bindValue(':board', $dropped_post['board']);
  901. $query->bindValue(':id', $id);
  902. $query->bindValue(':message_id', $dropped_post['msgid']);
  903. $query->bindValue(':message_id_digest', sha1($dropped_post['msgid']));
  904. $query->bindValue(':headers', $dropped_post['headers']);
  905. $query->execute() or error(db_error($query));
  906. } // ^^^^^ For inbound posts ^^^^^
  907. elseif ($config['nntpchan']['enabled'] && $config['nntpchan']['group']) {
  908. // vvvvv For outbound posts vvvvv
  909. require_once('inc/nntpchan/nntpchan.php');
  910. $msgid = gen_msgid($post['board'], $post['id']);
  911. list($headers, $files) = post2nntp($post, $msgid);
  912. $message = gen_nntp($headers, $files);
  913. $query = prepare("INSERT INTO ``nntp_references`` (`board`, `id`, `message_id`, `message_id_digest`, `own`, `headers`) VALUES ".
  914. "(:board , :id , :message_id , :message_id_digest , true , :headers)");
  915. $query->bindValue(':board', $post['board']);
  916. $query->bindValue(':id', $post['id']);
  917. $query->bindValue(':message_id', $msgid);
  918. $query->bindValue(':message_id_digest', sha1($msgid));
  919. $query->bindValue(':headers', json_encode($headers));
  920. $query->execute() or error(db_error($query));
  921. // Let's broadcast it!
  922. nntp_publish($message, $msgid);
  923. }
  924. insertFloodPost($post);
  925. // Handle cyclical threads
  926. if (!$post['op'] && isset($thread['cycle']) && $thread['cycle']) {
  927. // 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))
  928. $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']));
  929. $query->bindValue(':thread', $post['thread']);
  930. $query->bindValue(':limit', $config['cycle_limit'], PDO::PARAM_INT);
  931. $query->execute() or error(db_error($query));
  932. }
  933. if (isset($post['antispam_hash'])) {
  934. incrementSpamHash($post['antispam_hash']);
  935. }
  936. if (isset($post['tracked_cites']) && !empty($post['tracked_cites'])) {
  937. $insert_rows = array();
  938. foreach ($post['tracked_cites'] as $cite) {
  939. $insert_rows[] = '(' .
  940. $pdo->quote($board['uri']) . ', ' . (int)$id . ', ' .
  941. $pdo->quote($cite[0]) . ', ' . (int)$cite[1] . ')';
  942. }
  943. query('INSERT INTO ``cites`` VALUES ' . implode(', ', $insert_rows)) or error(db_error());
  944. }
  945. if (!$post['op'] && strtolower($post['email']) != 'sage' && !$thread['sage'] && ($config['reply_limit'] == 0 || $numposts['replies']+1 < $config['reply_limit'])) {
  946. bumpThread($post['thread']);
  947. }
  948. if (isset($_SERVER['HTTP_REFERER'])) {
  949. // Tell Javascript that we posted successfully
  950. if (isset($_COOKIE[$config['cookies']['js']]))
  951. $js = json_decode($_COOKIE[$config['cookies']['js']]);
  952. else
  953. $js = (object) array();
  954. // Tell it to delete the cached post for referer
  955. $js->{$_SERVER['HTTP_REFERER']} = true;
  956. // Encode and set cookie
  957. setcookie($config['cookies']['js'], json_encode($js), 0, $config['cookies']['jail'] ? $config['cookies']['path'] : '/', null, false, false);
  958. }
  959. $root = $post['mod'] ? $config['root'] . $config['file_mod'] . '?/' : $config['root'];
  960. if ($noko) {
  961. $redirect = $root . $board['dir'] . $config['dir']['res'] .
  962. link_for($post, false, false, $thread) . (!$post['op'] ? '#' . $id : '');
  963. if (!$post['op'] && isset($_SERVER['HTTP_REFERER'])) {
  964. $regex = array(
  965. 'board' => str_replace('%s', '(\w{1,8})', preg_quote($config['board_path'], '/')),
  966. 'page' => str_replace('%d', '(\d+)', preg_quote($config['file_page'], '/')),
  967. 'page50' => '(' . str_replace('%d', '(\d+)', preg_quote($config['file_page50'], '/')) . '|' .
  968. str_replace(array('%d', '%s'), array('(\d+)', '[a-z0-9-]+'), preg_quote($config['file_page50_slug'], '/')) . ')',
  969. 'res' => preg_quote($config['dir']['res'], '/'),
  970. );
  971. if (preg_match('/\/' . $regex['board'] . $regex['res'] . $regex['page50'] . '([?&].*)?$/', $_SERVER['HTTP_REFERER'])) {
  972. $redirect = $root . $board['dir'] . $config['dir']['res'] .
  973. link_for($post, true, false, $thread) . (!$post['op'] ? '#' . $id : '');
  974. }
  975. }
  976. } else {
  977. $redirect = $root . $board['dir'] . $config['file_index'];
  978. }
  979. buildThread($post['op'] ? $id : $post['thread']);
  980. if ($config['syslog'])
  981. _syslog(LOG_INFO, 'New post: /' . $board['dir'] . $config['dir']['res'] .
  982. link_for($post) . (!$post['op'] ? '#' . $id : ''));
  983. if (!$post['mod']) header('X-Associated-Content: "' . $redirect . '"');
  984. if (!isset($_POST['json_response'])) {
  985. header('Location: ' . $redirect, true, $config['redirect_http']);
  986. } else {
  987. header('Content-Type: text/json; charset=utf-8');
  988. echo json_encode(array(
  989. 'redirect' => $redirect,
  990. 'noko' => $noko,
  991. 'id' => $id
  992. ));
  993. }
  994. if ($config['try_smarter'] && $post['op'])
  995. $build_pages = range(1, $config['max_pages']);
  996. if ($post['op'])
  997. clean($id);
  998. event('post-after', $post);
  999. buildIndex();
  1000. // We are already done, let's continue our heavy-lifting work in the background (if we run off FastCGI)
  1001. if (function_exists('fastcgi_finish_request'))
  1002. @fastcgi_finish_request();
  1003. if ($post['op'])
  1004. rebuildThemes('post-thread', $board['uri']);
  1005. else
  1006. rebuildThemes('post', $board['uri']);
  1007. } elseif (isset($_POST['appeal'])) {
  1008. if (!isset($_POST['ban_id']))
  1009. error($config['error']['bot']);
  1010. $ban_id = (int)$_POST['ban_id'];
  1011. $bans = Bans::find($_SERVER['REMOTE_ADDR']);
  1012. foreach ($bans as $_ban) {
  1013. if ($_ban['id'] == $ban_id) {
  1014. $ban = $_ban;
  1015. break;
  1016. }
  1017. }
  1018. if (!isset($ban)) {
  1019. error(_("That ban doesn't exist or is not for you."));
  1020. }
  1021. if ($ban['expires'] && $ban['expires'] - $ban['created'] <= $config['ban_appeals_min_length']) {
  1022. error(_("You cannot appeal a ban of this length."));
  1023. }
  1024. $query = query("SELECT `denied` FROM ``ban_appeals`` WHERE `ban_id` = $ban_id") or error(db_error());
  1025. $ban_appeals = $query->fetchAll(PDO::FETCH_COLUMN);
  1026. if (count($ban_appeals) >= $config['ban_appeals_max']) {
  1027. error(_("You cannot appeal this ban again."));
  1028. }
  1029. foreach ($ban_appeals as $is_denied) {
  1030. if (!$is_denied)
  1031. error(_("There is already a pending appeal for this ban."));
  1032. }
  1033. $query = prepare("INSERT INTO ``ban_appeals`` VALUES (NULL, :ban_id, :time, :message, 0)");
  1034. $query->bindValue(':ban_id', $ban_id, PDO::PARAM_INT);
  1035. $query->bindValue(':time', time(), PDO::PARAM_INT);
  1036. $query->bindValue(':message', $_POST['appeal']);
  1037. $query->execute() or error(db_error($query));
  1038. displayBan($ban);
  1039. } else {
  1040. if (!file_exists($config['has_installed'])) {
  1041. header('Location: install.php', true, $config['redirect_http']);
  1042. } else {
  1043. // They opened post.php in their browser manually.
  1044. error($config['error']['nopost']);
  1045. }
  1046. }