The version of vichan running on lainchan.org
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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