The version of vichan running on lainchan.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1013 lines
34KB

  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. if ((!isset($_POST['mod']) || !$_POST['mod']) && $config['board_locked']) {
  9. error("Board is locked");
  10. }
  11. if (isset($_POST['delete'])) {
  12. // Delete
  13. if (!isset($_POST['board'], $_POST['password']))
  14. error($config['error']['bot']);
  15. $password = &$_POST['password'];
  16. if ($password == '')
  17. error($config['error']['invalidpassword']);
  18. $delete = array();
  19. foreach ($_POST as $post => $value) {
  20. if (preg_match('/^delete_(\d+)$/', $post, $m)) {
  21. $delete[] = (int)$m[1];
  22. }
  23. }
  24. checkDNSBL();
  25. // Check if board exists
  26. if (!openBoard($_POST['board']))
  27. error($config['error']['noboard']);
  28. // Check if banned
  29. checkBan($board['uri']);
  30. // Check if deletion enabled
  31. if (!$config['allow_delete'])
  32. error(_('Post deletion is not allowed!'));
  33. if (empty($delete))
  34. error($config['error']['nodelete']);
  35. foreach ($delete as &$id) {
  36. $query = prepare(sprintf("SELECT `thread`, `time`,`password` FROM ``posts_%s`` WHERE `id` = :id", $board['uri']));
  37. $query->bindValue(':id', $id, PDO::PARAM_INT);
  38. $query->execute() or error(db_error($query));
  39. if ($post = $query->fetch(PDO::FETCH_ASSOC)) {
  40. $thread = false;
  41. if ($config['user_moderation'] && $post['thread']) {
  42. $thread_query = prepare(sprintf("SELECT `time`,`password` FROM ``posts_%s`` WHERE `id` = :id", $board['uri']));
  43. $thread_query->bindValue(':id', $post['thread'], PDO::PARAM_INT);
  44. $thread_query->execute() or error(db_error($query));
  45. $thread = $thread_query->fetch(PDO::FETCH_ASSOC);
  46. }
  47. if ($password != '' && $post['password'] != $password && (!$thread || $thread['password'] != $password))
  48. error($config['error']['invalidpassword']);
  49. if ($post['time'] > time() - $config['delete_time'] && (!$thread || $thread['password'] != $password)) {
  50. error(sprintf($config['error']['delete_too_soon'], until($post['time'] + $config['delete_time'])));
  51. }
  52. if (isset($_POST['file'])) {
  53. // Delete just the file
  54. deleteFile($id);
  55. modLog("User deleted file from his own post #$id");
  56. } else {
  57. // Delete entire post
  58. deletePost($id);
  59. modLog("User deleted his own post #$id");
  60. }
  61. _syslog(LOG_INFO, 'Deleted post: ' .
  62. '/' . $board['dir'] . $config['dir']['res'] . link_for($post) . ($post['thread'] ? '#' . $id : '')
  63. );
  64. }
  65. }
  66. buildIndex();
  67. $is_mod = isset($_POST['mod']) && $_POST['mod'];
  68. $root = $is_mod ? $config['root'] . $config['file_mod'] . '?/' : $config['root'];
  69. if (!isset($_POST['json_response'])) {
  70. header('Location: ' . $root . $board['dir'] . $config['file_index'], true, $config['redirect_http']);
  71. } else {
  72. header('Content-Type: text/json');
  73. echo json_encode(array('success' => true));
  74. }
  75. // We are already done, let's continue our heavy-lifting work in the background (if we run off FastCGI)
  76. if (function_exists('fastcgi_finish_request'))
  77. @fastcgi_finish_request();
  78. rebuildThemes('post-delete', $board['uri']);
  79. } elseif (isset($_POST['report'])) {
  80. if (!isset($_POST['board'], $_POST['reason']))
  81. error($config['error']['bot']);
  82. $report = array();
  83. foreach ($_POST as $post => $value) {
  84. if (preg_match('/^delete_(\d+)$/', $post, $m)) {
  85. $report[] = (int)$m[1];
  86. }
  87. }
  88. checkDNSBL();
  89. // Check if board exists
  90. if (!openBoard($_POST['board']))
  91. error($config['error']['noboard']);
  92. // Check if banned
  93. checkBan($board['uri']);
  94. if (empty($report))
  95. error($config['error']['noreport']);
  96. if (count($report) > $config['report_limit'])
  97. error($config['error']['toomanyreports']);
  98. if ($config['report_captcha'] && !isset($_POST['captcha_text'], $_POST['captcha_cookie'])) {
  99. error($config['error']['bot']);
  100. }
  101. if ($config['report_captcha']) {
  102. $resp = file_get_contents($config['captcha']['provider_check'] . "?" . http_build_query([
  103. 'mode' => 'check',
  104. 'text' => $_POST['captcha_text'],
  105. 'extra' => $config['captcha']['extra'],
  106. 'cookie' => $_POST['captcha_cookie']
  107. ]));
  108. if ($resp !== '1') {
  109. error($config['error']['captcha']);
  110. }
  111. }
  112. $reason = escape_markup_modifiers($_POST['reason']);
  113. markup($reason);
  114. foreach ($report as &$id) {
  115. $query = prepare(sprintf("SELECT `thread` FROM ``posts_%s`` WHERE `id` = :id", $board['uri']));
  116. $query->bindValue(':id', $id, PDO::PARAM_INT);
  117. $query->execute() or error(db_error($query));
  118. $thread = $query->fetchColumn();
  119. if ($config['syslog'])
  120. _syslog(LOG_INFO, 'Reported post: ' .
  121. '/' . $board['dir'] . $config['dir']['res'] . link_for($post) . ($thread ? '#' . $id : '') .
  122. ' for "' . $reason . '"'
  123. );
  124. $query = prepare("INSERT INTO ``reports`` VALUES (NULL, :time, :ip, :board, :post, :reason)");
  125. $query->bindValue(':time', time(), PDO::PARAM_INT);
  126. $query->bindValue(':ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
  127. $query->bindValue(':board', $board['uri'], PDO::PARAM_INT);
  128. $query->bindValue(':post', $id, PDO::PARAM_INT);
  129. $query->bindValue(':reason', $reason, PDO::PARAM_STR);
  130. $query->execute() or error(db_error($query));
  131. }
  132. $is_mod = isset($_POST['mod']) && $_POST['mod'];
  133. $root = $is_mod ? $config['root'] . $config['file_mod'] . '?/' : $config['root'];
  134. if (!isset($_POST['json_response'])) {
  135. $index = $root . $board['dir'] . $config['file_index'];
  136. 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!')));
  137. } else {
  138. header('Content-Type: text/json');
  139. echo json_encode(array('success' => true));
  140. }
  141. } elseif (isset($_POST['post'])) {
  142. if (!isset($_POST['body'], $_POST['board']))
  143. error($config['error']['bot']);
  144. $post = array('board' => $_POST['board'], 'files' => array());
  145. // Check if board exists
  146. if (!openBoard($post['board']))
  147. error($config['error']['noboard']);
  148. if (!isset($_POST['name']))
  149. $_POST['name'] = $config['anonymous'];
  150. if (!isset($_POST['email']))
  151. $_POST['email'] = '';
  152. if (!isset($_POST['subject']))
  153. $_POST['subject'] = '';
  154. if (!isset($_POST['password']))
  155. $_POST['password'] = '';
  156. if (isset($_POST['thread'])) {
  157. $post['op'] = false;
  158. $post['thread'] = round($_POST['thread']);
  159. } else
  160. $post['op'] = true;
  161. // Check for CAPTCHA right after opening the board so the "return" link is in there
  162. if ($config['recaptcha']) {
  163. if (!isset($_POST['recaptcha_challenge_field']) || !isset($_POST['recaptcha_response_field']))
  164. error($config['error']['bot']);
  165. // Check what reCAPTCHA has to say...
  166. $resp = recaptcha_check_answer($config['recaptcha_private'],
  167. $_SERVER['REMOTE_ADDR'],
  168. $_POST['recaptcha_challenge_field'],
  169. $_POST['recaptcha_response_field']);
  170. if (!$resp->is_valid) {
  171. error($config['error']['captcha']);
  172. }
  173. }
  174. if (!(($post['op'] && $_POST['post'] == $config['button_newtopic']) ||
  175. (!$post['op'] && $_POST['post'] == $config['button_reply'])))
  176. error($config['error']['bot']);
  177. // Check the referrer
  178. if ($config['referer_match'] !== false &&
  179. (!isset($_SERVER['HTTP_REFERER']) || !preg_match($config['referer_match'], rawurldecode($_SERVER['HTTP_REFERER']))))
  180. error($config['error']['referer']);
  181. checkDNSBL();
  182. // Check if banned
  183. checkBan($board['uri']);
  184. if ($post['mod'] = isset($_POST['mod']) && $_POST['mod']) {
  185. check_login(false);
  186. if (!$mod) {
  187. // Liar. You're not a mod.
  188. error($config['error']['notamod']);
  189. }
  190. $post['sticky'] = $post['op'] && isset($_POST['sticky']);
  191. $post['locked'] = $post['op'] && isset($_POST['lock']);
  192. $post['raw'] = isset($_POST['raw']);
  193. if ($post['sticky'] && !hasPermission($config['mod']['sticky'], $board['uri']))
  194. error($config['error']['noaccess']);
  195. if ($post['locked'] && !hasPermission($config['mod']['lock'], $board['uri']))
  196. error($config['error']['noaccess']);
  197. if ($post['raw'] && !hasPermission($config['mod']['rawhtml'], $board['uri']))
  198. error($config['error']['noaccess']);
  199. }
  200. if (!$post['mod']) {
  201. $post['antispam_hash'] = checkSpam(array($board['uri'], isset($post['thread']) ? $post['thread'] : ($config['try_smarter'] && isset($_POST['page']) ? 0 - (int)$_POST['page'] : null)));
  202. if ($post['antispam_hash'] === true)
  203. error($config['error']['spam']);
  204. }
  205. if ($config['robot_enable'] && $config['robot_mute']) {
  206. checkMute();
  207. }
  208. //Check if thread exists
  209. if (!$post['op']) {
  210. $query = prepare(sprintf("SELECT `sticky`,`locked`,`sage`,`slug` FROM ``posts_%s`` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri']));
  211. $query->bindValue(':id', $post['thread'], PDO::PARAM_INT);
  212. $query->execute() or error(db_error());
  213. if (!$thread = $query->fetch(PDO::FETCH_ASSOC)) {
  214. // Non-existant
  215. error($config['error']['nonexistant']);
  216. }
  217. }
  218. else {
  219. $thread = false;
  220. }
  221. // Check for an embed field
  222. if ($config['enable_embedding'] && isset($_POST['embed']) && !empty($_POST['embed'])) {
  223. // yep; validate it
  224. $value = $_POST['embed'];
  225. foreach ($config['embedding'] as &$embed) {
  226. if (preg_match($embed[0], $value)) {
  227. // Valid link
  228. $post['embed'] = $value;
  229. // This is bad, lol.
  230. $post['no_longer_require_an_image_for_op'] = true;
  231. break;
  232. }
  233. }
  234. if (!isset($post['embed'])) {
  235. error($config['error']['invalid_embed']);
  236. }
  237. if ($config['image_reject_repost']) {
  238. if ($p = getPostByEmbed($post['embed'])) {
  239. error(sprintf($config['error']['fileexists'],
  240. ($post['mod'] ? $config['root'] . $config['file_mod'] . '?/' : $config['root']) .
  241. ($board['dir'] . $config['dir']['res'] .
  242. ($p['thread'] ?
  243. $p['thread'] . '.html#' . $p['id']
  244. :
  245. $p['id'] . '.html'
  246. ))
  247. ));
  248. }
  249. } else if (!$post['op'] && $config['image_reject_repost_in_thread']) {
  250. if ($p = getPostByEmbedInThread($post['embed'], $post['thread'])) {
  251. error(sprintf($config['error']['fileexistsinthread'],
  252. ($post['mod'] ? $config['root'] . $config['file_mod'] . '?/' : $config['root']) .
  253. ($board['dir'] . $config['dir']['res'] .
  254. ($p['thread'] ?
  255. $p['thread'] . '.html#' . $p['id']
  256. :
  257. $p['id'] . '.html'
  258. ))
  259. ));
  260. }
  261. }
  262. }
  263. if (!hasPermission($config['mod']['bypass_field_disable'], $board['uri'])) {
  264. if ($config['field_disable_name'])
  265. $_POST['name'] = $config['anonymous']; // "forced anonymous"
  266. if ($config['field_disable_email'])
  267. $_POST['email'] = '';
  268. if ($config['field_disable_password'])
  269. $_POST['password'] = '';
  270. if ($config['field_disable_subject'] || (!$post['op'] && $config['field_disable_reply_subject']))
  271. $_POST['subject'] = '';
  272. }
  273. if ($config['allow_upload_by_url'] && isset($_POST['file_url']) && !empty($_POST['file_url'])) {
  274. $post['file_url'] = $_POST['file_url'];
  275. if (!preg_match('@^https?://@', $post['file_url']))
  276. error($config['error']['invalidimg']);
  277. if (mb_strpos($post['file_url'], '?') !== false)
  278. $url_without_params = mb_substr($post['file_url'], 0, mb_strpos($post['file_url'], '?'));
  279. else
  280. $url_without_params = $post['file_url'];
  281. $post['extension'] = strtolower(mb_substr($url_without_params, mb_strrpos($url_without_params, '.') + 1));
  282. if ($post['op'] && $config['allowed_ext_op']) {
  283. if (!in_array($post['extension'], $config['allowed_ext_op']))
  284. error($config['error']['unknownext']);
  285. }
  286. else if (!in_array($post['extension'], $config['allowed_ext']) && !in_array($post['extension'], $config['allowed_ext_files']))
  287. error($config['error']['unknownext']);
  288. $post['file_tmp'] = tempnam($config['tmp'], 'url');
  289. function unlink_tmp_file($file) {
  290. @unlink($file);
  291. fatal_error_handler();
  292. }
  293. register_shutdown_function('unlink_tmp_file', $post['file_tmp']);
  294. $fp = fopen($post['file_tmp'], 'w');
  295. $curl = curl_init();
  296. curl_setopt($curl, CURLOPT_URL, $post['file_url']);
  297. curl_setopt($curl, CURLOPT_FAILONERROR, true);
  298. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
  299. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
  300. curl_setopt($curl, CURLOPT_TIMEOUT, $config['upload_by_url_timeout']);
  301. curl_setopt($curl, CURLOPT_USERAGENT, 'Tinyboard');
  302. curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
  303. curl_setopt($curl, CURLOPT_FILE, $fp);
  304. curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
  305. if (curl_exec($curl) === false)
  306. error($config['error']['nomove'] . '<br/>Curl says: ' . curl_error($curl));
  307. curl_close($curl);
  308. fclose($fp);
  309. $_FILES['file'] = array(
  310. 'name' => basename($url_without_params),
  311. 'tmp_name' => $post['file_tmp'],
  312. 'file_tmp' => true,
  313. 'error' => 0,
  314. 'size' => filesize($post['file_tmp'])
  315. );
  316. }
  317. $post['name'] = $_POST['name'] != '' ? $_POST['name'] : $config['anonymous'];
  318. $post['subject'] = $_POST['subject'];
  319. $post['email'] = str_replace(' ', '%20', htmlspecialchars($_POST['email']));
  320. $post['body'] = $_POST['body'];
  321. $post['password'] = $_POST['password'];
  322. $post['has_file'] = (!isset($post['embed']) && (($post['op'] && !isset($post['no_longer_require_an_image_for_op']) && $config['force_image_op']) || !empty($_FILES['file']['name'])));
  323. if (!($post['has_file'] || isset($post['embed'])) || (($post['op'] && $config['force_body_op']) || (!$post['op'] && $config['force_body']))) {
  324. $stripped_whitespace = preg_replace('/[\s]/u', '', $post['body']);
  325. if ($stripped_whitespace == '') {
  326. error($config['error']['tooshort_body']);
  327. }
  328. }
  329. if (!$post['op']) {
  330. // Check if thread is locked
  331. // but allow mods to post
  332. if ($thread['locked'] && !hasPermission($config['mod']['postinlocked'], $board['uri']))
  333. error($config['error']['locked']);
  334. $numposts = numPosts($post['thread']);
  335. if ($config['reply_hard_limit'] != 0 && $config['reply_hard_limit'] <= $numposts['replies'])
  336. error($config['error']['reply_hard_limit']);
  337. if ($post['has_file'] && $config['image_hard_limit'] != 0 && $config['image_hard_limit'] <= $numposts['images'])
  338. error($config['error']['image_hard_limit']);
  339. }
  340. if ($post['has_file']) {
  341. // Determine size sanity
  342. $size = 0;
  343. if ($config['multiimage_method'] == 'split') {
  344. foreach ($_FILES as $key => $file) {
  345. $size += $file['size'];
  346. }
  347. } elseif ($config['multiimage_method'] == 'each') {
  348. foreach ($_FILES as $key => $file) {
  349. if ($file['size'] > $size) {
  350. $size = $file['size'];
  351. }
  352. }
  353. } else {
  354. error(_('Unrecognized file size determination method.'));
  355. }
  356. if ($size > $config['max_filesize'])
  357. error(sprintf3($config['error']['filesize'], array(
  358. 'sz' => number_format($size),
  359. 'filesz' => number_format($size),
  360. 'maxsz' => number_format($config['max_filesize'])
  361. )));
  362. $post['filesize'] = $size;
  363. }
  364. $post['capcode'] = false;
  365. if ($mod && preg_match('/^((.+) )?## (.+)$/', $post['name'], $matches)) {
  366. $name = $matches[2] != '' ? $matches[2] : $config['anonymous'];
  367. $cap = $matches[3];
  368. if (isset($config['mod']['capcode'][$mod['type']])) {
  369. if ( $config['mod']['capcode'][$mod['type']] === true ||
  370. (is_array($config['mod']['capcode'][$mod['type']]) &&
  371. in_array($cap, $config['mod']['capcode'][$mod['type']])
  372. )) {
  373. $post['capcode'] = utf8tohtml($cap);
  374. $post['name'] = $name;
  375. }
  376. }
  377. }
  378. $trip = generate_tripcode($post['name']);
  379. $post['name'] = $trip[0];
  380. $post['trip'] = isset($trip[1]) ? $trip[1] : '';
  381. $noko = false;
  382. if (strtolower($post['email']) == 'noko') {
  383. $noko = true;
  384. $post['email'] = '';
  385. } elseif (strtolower($post['email']) == 'nonoko'){
  386. $noko = false;
  387. $post['email'] = '';
  388. } else $noko = $config['always_noko'];
  389. if ($post['has_file']) {
  390. $i = 0;
  391. foreach ($_FILES as $key => $file) {
  392. if ($file['size'] && $file['tmp_name']) {
  393. $file['filename'] = urldecode($file['name']);
  394. $file['extension'] = strtolower(mb_substr($file['filename'], mb_strrpos($file['filename'], '.') + 1));
  395. if (isset($config['filename_func']))
  396. $file['file_id'] = $config['filename_func']($file);
  397. else
  398. $file['file_id'] = time() . substr(microtime(), 2, 3);
  399. if (sizeof($_FILES) > 1)
  400. $file['file_id'] .= "-$i";
  401. $file['file'] = $board['dir'] . $config['dir']['img'] . $file['file_id'] . '.' . $file['extension'];
  402. $file['thumb'] = $board['dir'] . $config['dir']['thumb'] . $file['file_id'] . '.' . ($config['thumb_ext'] ? $config['thumb_ext'] : $file['extension']);
  403. $post['files'][] = $file;
  404. $i++;
  405. }
  406. }
  407. }
  408. if (empty($post['files'])) $post['has_file'] = false;
  409. // Check for a file
  410. if ($post['op'] && !isset($post['no_longer_require_an_image_for_op'])) {
  411. if (!$post['has_file'] && $config['force_image_op'])
  412. error($config['error']['noimage']);
  413. }
  414. // Check for too many files
  415. if (sizeof($post['files']) > $config['max_images'])
  416. error($config['error']['toomanyimages']);
  417. if ($config['strip_combining_chars']) {
  418. $post['name'] = strip_combining_chars($post['name']);
  419. $post['email'] = strip_combining_chars($post['email']);
  420. $post['subject'] = strip_combining_chars($post['subject']);
  421. $post['body'] = strip_combining_chars($post['body']);
  422. }
  423. // Check string lengths
  424. if (mb_strlen($post['name']) > 35)
  425. error(sprintf($config['error']['toolong'], 'name'));
  426. if (mb_strlen($post['email']) > 40)
  427. error(sprintf($config['error']['toolong'], 'email'));
  428. if (mb_strlen($post['subject']) > 100)
  429. error(sprintf($config['error']['toolong'], 'subject'));
  430. if (!$mod && mb_strlen($post['body']) > $config['max_body'])
  431. error($config['error']['toolong_body']);
  432. if (mb_strlen($post['password']) > 20)
  433. error(sprintf($config['error']['toolong'], 'password'));
  434. wordfilters($post['body']);
  435. $post['body'] = escape_markup_modifiers($post['body']);
  436. if ($mod && isset($post['raw']) && $post['raw']) {
  437. $post['body'] .= "\n<tinyboard raw html>1</tinyboard>";
  438. }
  439. if (($config['country_flags'] && !$config['allow_no_country']) || ($config['country_flags'] && $config['allow_no_country'] && !isset($_POST['no_country']))) {
  440. require 'inc/lib/geoip/geoip.inc';
  441. $gi=geoip\geoip_open('inc/lib/geoip/GeoIPv6.dat', GEOIP_STANDARD);
  442. function ipv4to6($ip) {
  443. if (strpos($ip, ':') !== false) {
  444. if (strpos($ip, '.') > 0)
  445. $ip = substr($ip, strrpos($ip, ':')+1);
  446. else return $ip; //native ipv6
  447. }
  448. $iparr = array_pad(explode('.', $ip), 4, 0);
  449. $part7 = base_convert(($iparr[0] * 256) + $iparr[1], 10, 16);
  450. $part8 = base_convert(($iparr[2] * 256) + $iparr[3], 10, 16);
  451. return '::ffff:'.$part7.':'.$part8;
  452. }
  453. if ($country_code = geoip\geoip_country_code_by_addr_v6($gi, ipv4to6($_SERVER['REMOTE_ADDR']))) {
  454. if (!in_array(strtolower($country_code), array('eu', 'ap', 'o1', 'a1', 'a2')))
  455. $post['body'] .= "\n<tinyboard flag>".strtolower($country_code)."</tinyboard>".
  456. "\n<tinyboard flag alt>".geoip\geoip_country_name_by_addr_v6($gi, ipv4to6($_SERVER['REMOTE_ADDR']))."</tinyboard>";
  457. }
  458. }
  459. if ($config['user_flag'] && isset($_POST['user_flag']))
  460. if (!empty($_POST['user_flag']) ){
  461. $user_flag = $_POST['user_flag'];
  462. if (!isset($config['user_flags'][$user_flag]))
  463. error(_('Invalid flag selection!'));
  464. $flag_alt = isset($user_flag_alt) ? $user_flag_alt : $config['user_flags'][$user_flag];
  465. $post['body'] .= "\n<tinyboard flag>" . strtolower($user_flag) . "</tinyboard>" .
  466. "\n<tinyboard flag alt>" . $flag_alt . "</tinyboard>";
  467. }
  468. if ($config['allowed_tags'] && $post['op'] && isset($_POST['tag']) && isset($config['allowed_tags'][$_POST['tag']])) {
  469. $post['body'] .= "\n<tinyboard tag>" . $_POST['tag'] . "</tinyboard>";
  470. }
  471. if ($config['proxy_save'] && isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  472. $proxy = preg_replace("/[^0-9a-fA-F.,: ]/", '', $_SERVER['HTTP_X_FORWARDED_FOR']);
  473. $post['body'] .= "\n<tinyboard proxy>".$proxy."</tinyboard>";
  474. }
  475. if (mysql_version() >= 50503) {
  476. $post['body_nomarkup'] = $post['body']; // Assume we're using the utf8mb4 charset
  477. } else {
  478. // MySQL's `utf8` charset only supports up to 3-byte symbols
  479. // Remove anything >= 0x010000
  480. $chars = preg_split('//u', $post['body'], -1, PREG_SPLIT_NO_EMPTY);
  481. $post['body_nomarkup'] = '';
  482. foreach ($chars as $char) {
  483. $o = 0;
  484. $ord = ordutf8($char, $o);
  485. if ($ord >= 0x010000)
  486. continue;
  487. $post['body_nomarkup'] .= $char;
  488. }
  489. }
  490. $post['tracked_cites'] = markup($post['body'], true);
  491. if ($post['has_file']) {
  492. $md5cmd = false;
  493. if ($config['bsd_md5']) $md5cmd = '/sbin/md5 -r';
  494. if ($config['gnu_md5']) $md5cmd = 'md5sum';
  495. $allhashes = '';
  496. foreach ($post['files'] as $key => &$file) {
  497. if ($post['op'] && $config['allowed_ext_op']) {
  498. if (!in_array($file['extension'], $config['allowed_ext_op']))
  499. error($config['error']['unknownext']);
  500. }
  501. elseif (!in_array($file['extension'], $config['allowed_ext']) && !in_array($file['extension'], $config['allowed_ext_files']))
  502. error($config['error']['unknownext']);
  503. $file['is_an_image'] = !in_array($file['extension'], $config['allowed_ext_files']);
  504. // Truncate filename if it is too long
  505. $file['filename'] = mb_substr($file['filename'], 0, $config['max_filename_len']);
  506. $upload = $file['tmp_name'];
  507. if (!is_readable($upload))
  508. error($config['error']['nomove']);
  509. if ($md5cmd) {
  510. $output = shell_exec_error($md5cmd . " < " . escapeshellarg($upload));
  511. $output = explode(' ', $output);
  512. $hash = $output[0];
  513. }
  514. else {
  515. $hash = md5_file($upload);
  516. }
  517. $file['hash'] = $hash;
  518. $allhashes .= $hash;
  519. }
  520. if (count ($post['files']) == 1) {
  521. $post['filehash'] = $hash;
  522. }
  523. else {
  524. $post['filehash'] = md5($allhashes);
  525. }
  526. }
  527. if (!hasPermission($config['mod']['bypass_filters'], $board['uri'])) {
  528. require_once 'inc/filters.php';
  529. do_filters($post);
  530. }
  531. if ($post['has_file']) {
  532. foreach ($post['files'] as $key => &$file) {
  533. if ($file['is_an_image']) {
  534. if ($config['ie_mime_type_detection'] !== false) {
  535. // Check IE MIME type detection XSS exploit
  536. $buffer = file_get_contents($upload, null, null, null, 255);
  537. if (preg_match($config['ie_mime_type_detection'], $buffer)) {
  538. undoImage($post);
  539. error($config['error']['mime_exploit']);
  540. }
  541. }
  542. require_once 'inc/image.php';
  543. // find dimensions of an image using GD
  544. if (!$size = @getimagesize($file['tmp_name'])) {
  545. error($config['error']['invalidimg']);
  546. }
  547. if (!in_array($size[2], array(IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_BMP))) {
  548. error($config['error']['invalidimg']);
  549. }
  550. if ($size[0] > $config['max_width'] || $size[1] > $config['max_height']) {
  551. error($config['error']['maxsize']);
  552. }
  553. if ($config['convert_auto_orient'] && ($file['extension'] == 'jpg' || $file['extension'] == 'jpeg')) {
  554. // The following code corrects the image orientation.
  555. // Currently only works with the 'convert' option selected but it could easily be expanded to work with the rest if you can be bothered.
  556. if (!($config['redraw_image'] || (($config['strip_exif'] && !$config['use_exiftool']) && ($file['extension'] == 'jpg' || $file['extension'] == 'jpeg')))) {
  557. if (in_array($config['thumb_method'], array('convert', 'convert+gifsicle', 'gm', 'gm+gifsicle'))) {
  558. $exif = @exif_read_data($file['tmp_name']);
  559. $gm = in_array($config['thumb_method'], array('gm', 'gm+gifsicle'));
  560. if (isset($exif['Orientation']) && $exif['Orientation'] != 1) {
  561. if ($config['convert_manual_orient']) {
  562. $error = shell_exec_error(($gm ? 'gm ' : '') . 'convert ' .
  563. escapeshellarg($file['tmp_name']) . ' ' .
  564. ImageConvert::jpeg_exif_orientation(false, $exif) . ' ' .
  565. ($config['strip_exif'] ? '+profile "*"' :
  566. ($config['use_exiftool'] ? '' : '+profile "*"')
  567. ) . ' ' .
  568. escapeshellarg($file['tmp_name']));
  569. if ($config['use_exiftool'] && !$config['strip_exif']) {
  570. if ($exiftool_error = shell_exec_error(
  571. 'exiftool -overwrite_original -q -q -orientation=1 -n ' .
  572. escapeshellarg($file['tmp_name'])))
  573. error(_('exiftool failed!'), null, $exiftool_error);
  574. } else {
  575. // TODO: Find another way to remove the Orientation tag from the EXIF profile
  576. // without needing `exiftool`.
  577. }
  578. } else {
  579. $error = shell_exec_error(($gm ? 'gm ' : '') . 'convert ' .
  580. escapeshellarg($file['tmp_name']) . ' -auto-orient ' . escapeshellarg($upload));
  581. }
  582. if ($error)
  583. error(_('Could not auto-orient image!'), null, $error);
  584. $size = @getimagesize($file['tmp_name']);
  585. if ($config['strip_exif'])
  586. $file['exif_stripped'] = true;
  587. }
  588. }
  589. }
  590. }
  591. // create image object
  592. $image = new Image($file['tmp_name'], $file['extension'], $size);
  593. if ($image->size->width > $config['max_width'] || $image->size->height > $config['max_height']) {
  594. $image->delete();
  595. error($config['error']['maxsize']);
  596. }
  597. $file['width'] = $image->size->width;
  598. $file['height'] = $image->size->height;
  599. if ($config['spoiler_images'] && isset($_POST['spoiler'])) {
  600. $file['thumb'] = 'spoiler';
  601. $size = @getimagesize($config['spoiler_image']);
  602. $file['thumbwidth'] = $size[0];
  603. $file['thumbheight'] = $size[1];
  604. } elseif ($config['minimum_copy_resize'] &&
  605. $image->size->width <= $config['thumb_width'] &&
  606. $image->size->height <= $config['thumb_height'] &&
  607. $file['extension'] == ($config['thumb_ext'] ? $config['thumb_ext'] : $file['extension'])) {
  608. // Copy, because there's nothing to resize
  609. copy($file['tmp_name'], $file['thumb']);
  610. $file['thumbwidth'] = $image->size->width;
  611. $file['thumbheight'] = $image->size->height;
  612. } else {
  613. $thumb = $image->resize(
  614. $config['thumb_ext'] ? $config['thumb_ext'] : $file['extension'],
  615. $post['op'] ? $config['thumb_op_width'] : $config['thumb_width'],
  616. $post['op'] ? $config['thumb_op_height'] : $config['thumb_height']
  617. );
  618. $thumb->to($file['thumb']);
  619. $file['thumbwidth'] = $thumb->width;
  620. $file['thumbheight'] = $thumb->height;
  621. $thumb->_destroy();
  622. }
  623. if ($config['redraw_image'] || (!@$file['exif_stripped'] && $config['strip_exif'] && ($file['extension'] == 'jpg' || $file['extension'] == 'jpeg'))) {
  624. if (!$config['redraw_image'] && $config['use_exiftool']) {
  625. if($error = shell_exec_error('exiftool -overwrite_original -ignoreMinorErrors -q -q -all= ' .
  626. escapeshellarg($file['tmp_name'])))
  627. error(_('Could not strip EXIF metadata!'), null, $error);
  628. } else {
  629. $image->to($file['file']);
  630. $dont_copy_file = true;
  631. }
  632. }
  633. $image->destroy();
  634. } else {
  635. // not an image
  636. //copy($config['file_thumb'], $post['thumb']);
  637. $file['thumb'] = 'file';
  638. $size = @getimagesize(sprintf($config['file_thumb'],
  639. isset($config['file_icons'][$file['extension']]) ?
  640. $config['file_icons'][$file['extension']] : $config['file_icons']['default']));
  641. $file['thumbwidth'] = $size[0];
  642. $file['thumbheight'] = $size[1];
  643. }
  644. if (!isset($dont_copy_file) || !$dont_copy_file) {
  645. if (isset($file['file_tmp'])) {
  646. if (!@rename($file['tmp_name'], $file['file']))
  647. error($config['error']['nomove']);
  648. chmod($file['file'], 0644);
  649. } elseif (!@move_uploaded_file($file['tmp_name'], $file['file']))
  650. error($config['error']['nomove']);
  651. }
  652. }
  653. if ($config['image_reject_repost']) {
  654. if ($p = getPostByHash($post['filehash'])) {
  655. undoImage($post);
  656. error(sprintf($config['error']['fileexists'],
  657. ($post['mod'] ? $config['root'] . $config['file_mod'] . '?/' : $config['root']) .
  658. ($board['dir'] . $config['dir']['res'] .
  659. ($p['thread'] ?
  660. $p['thread'] . '.html#' . $p['id']
  661. :
  662. $p['id'] . '.html'
  663. ))
  664. ));
  665. }
  666. } else if (!$post['op'] && $config['image_reject_repost_in_thread']) {
  667. if ($p = getPostByHashInThread($post['filehash'], $post['thread'])) {
  668. undoImage($post);
  669. error(sprintf($config['error']['fileexistsinthread'],
  670. ($post['mod'] ? $config['root'] . $config['file_mod'] . '?/' : $config['root']) .
  671. ($board['dir'] . $config['dir']['res'] .
  672. ($p['thread'] ?
  673. $p['thread'] . '.html#' . $p['id']
  674. :
  675. $p['id'] . '.html'
  676. ))
  677. ));
  678. }
  679. }
  680. }
  681. if (!hasPermission($config['mod']['postunoriginal'], $board['uri']) && $config['robot_enable'] && checkRobot($post['body_nomarkup'])) {
  682. undoImage($post);
  683. if ($config['robot_mute']) {
  684. error(sprintf($config['error']['muted'], mute()));
  685. } else {
  686. error($config['error']['unoriginal']);
  687. }
  688. }
  689. // Remove board directories before inserting them into the database.
  690. if ($post['has_file']) {
  691. foreach ($post['files'] as $key => &$file) {
  692. $file['file_path'] = $file['file'];
  693. $file['thumb_path'] = $file['thumb'];
  694. $file['file'] = mb_substr($file['file'], mb_strlen($board['dir'] . $config['dir']['img']));
  695. if ($file['is_an_image'] && $file['thumb'] != 'spoiler')
  696. $file['thumb'] = mb_substr($file['thumb'], mb_strlen($board['dir'] . $config['dir']['thumb']));
  697. }
  698. }
  699. $post = (object)$post;
  700. $post->files = array_map(function($a) { return (object)$a; }, $post->files);
  701. $error = event('post', $post);
  702. $post->files = array_map(function($a) { return (array)$a; }, $post->files);
  703. if ($error) {
  704. undoImage((array)$post);
  705. error($error);
  706. }
  707. $post = (array)$post;
  708. if ($post['files'])
  709. $post['files'] = $post['files'];
  710. $post['num_files'] = sizeof($post['files']);
  711. $post['id'] = $id = post($post);
  712. $post['slug'] = slugify($post);
  713. insertFloodPost($post);
  714. if (isset($post['antispam_hash'])) {
  715. incrementSpamHash($post['antispam_hash']);
  716. }
  717. if (isset($post['tracked_cites']) && !empty($post['tracked_cites'])) {
  718. $insert_rows = array();
  719. foreach ($post['tracked_cites'] as $cite) {
  720. $insert_rows[] = '(' .
  721. $pdo->quote($board['uri']) . ', ' . (int)$id . ', ' .
  722. $pdo->quote($cite[0]) . ', ' . (int)$cite[1] . ')';
  723. }
  724. query('INSERT INTO ``cites`` VALUES ' . implode(', ', $insert_rows)) or error(db_error());
  725. }
  726. if (!$post['op'] && strtolower($post['email']) != 'sage' && !$thread['sage'] && ($config['reply_limit'] == 0 || $numposts['replies']+1 < $config['reply_limit'])) {
  727. bumpThread($post['thread']);
  728. }
  729. if (isset($_SERVER['HTTP_REFERER'])) {
  730. // Tell Javascript that we posted successfully
  731. if (isset($_COOKIE[$config['cookies']['js']]))
  732. $js = json_decode($_COOKIE[$config['cookies']['js']]);
  733. else
  734. $js = (object) array();
  735. // Tell it to delete the cached post for referer
  736. $js->{$_SERVER['HTTP_REFERER']} = true;
  737. // Encode and set cookie
  738. setcookie($config['cookies']['js'], json_encode($js), 0, $config['cookies']['jail'] ? $config['cookies']['path'] : '/', null, false, false);
  739. }
  740. $root = $post['mod'] ? $config['root'] . $config['file_mod'] . '?/' : $config['root'];
  741. if ($noko) {
  742. $redirect = $root . $board['dir'] . $config['dir']['res'] .
  743. link_for($post, false, false, $thread) . (!$post['op'] ? '#' . $id : '');
  744. if (!$post['op'] && isset($_SERVER['HTTP_REFERER'])) {
  745. $regex = array(
  746. 'board' => str_replace('%s', '(\w{1,8})', preg_quote($config['board_path'], '/')),
  747. 'page' => str_replace('%d', '(\d+)', preg_quote($config['file_page'], '/')),
  748. 'page50' => '(' . str_replace('%d', '(\d+)', preg_quote($config['file_page50'], '/')) . '|' .
  749. str_replace(array('%d', '%s'), array('(\d+)', '[a-z0-9-]+'), preg_quote($config['file_page50_slug'], '/')) . ')',
  750. 'res' => preg_quote($config['dir']['res'], '/'),
  751. );
  752. if (preg_match('/\/' . $regex['board'] . $regex['res'] . $regex['page50'] . '([?&].*)?$/', $_SERVER['HTTP_REFERER'])) {
  753. $redirect = $root . $board['dir'] . $config['dir']['res'] .
  754. link_for($post, true, false, $thread) . (!$post['op'] ? '#' . $id : '');
  755. }
  756. }
  757. } else {
  758. $redirect = $root . $board['dir'] . $config['file_index'];
  759. }
  760. buildThread($post['op'] ? $id : $post['thread']);
  761. if ($config['syslog'])
  762. _syslog(LOG_INFO, 'New post: /' . $board['dir'] . $config['dir']['res'] .
  763. link_for($post) . (!$post['op'] ? '#' . $id : ''));
  764. if (!$post['mod']) header('X-Associated-Content: "' . $redirect . '"');
  765. if (!isset($_POST['json_response'])) {
  766. header('Location: ' . $redirect, true, $config['redirect_http']);
  767. } else {
  768. header('Content-Type: text/json; charset=utf-8');
  769. echo json_encode(array(
  770. 'redirect' => $redirect,
  771. 'noko' => $noko,
  772. 'id' => $id
  773. ));
  774. }
  775. if ($config['try_smarter'] && $post['op'])
  776. $build_pages = range(1, $config['max_pages']);
  777. if ($post['op'])
  778. clean($pid);
  779. event('post-after', $post);
  780. buildIndex();
  781. // We are already done, let's continue our heavy-lifting work in the background (if we run off FastCGI)
  782. if (function_exists('fastcgi_finish_request'))
  783. @fastcgi_finish_request();
  784. if ($post['op'])
  785. rebuildThemes('post-thread', $board['uri']);
  786. else
  787. rebuildThemes('post', $board['uri']);
  788. } elseif (isset($_POST['appeal'])) {
  789. if (!isset($_POST['ban_id']))
  790. error($config['error']['bot']);
  791. $ban_id = (int)$_POST['ban_id'];
  792. $bans = Bans::find($_SERVER['REMOTE_ADDR']);
  793. foreach ($bans as $_ban) {
  794. if ($_ban['id'] == $ban_id) {
  795. $ban = $_ban;
  796. break;
  797. }
  798. }
  799. if (!isset($ban)) {
  800. error(_("That ban doesn't exist or is not for you."));
  801. }
  802. if ($ban['expires'] && $ban['expires'] - $ban['created'] <= $config['ban_appeals_min_length']) {
  803. error(_("You cannot appeal a ban of this length."));
  804. }
  805. $query = query("SELECT `denied` FROM ``ban_appeals`` WHERE `ban_id` = $ban_id") or error(db_error());
  806. $ban_appeals = $query->fetchAll(PDO::FETCH_COLUMN);
  807. if (count($ban_appeals) >= $config['ban_appeals_max']) {
  808. error(_("You cannot appeal this ban again."));
  809. }
  810. foreach ($ban_appeals as $is_denied) {
  811. if (!$is_denied)
  812. error(_("There is already a pending appeal for this ban."));
  813. }
  814. $query = prepare("INSERT INTO ``ban_appeals`` VALUES (NULL, :ban_id, :time, :message, 0)");
  815. $query->bindValue(':ban_id', $ban_id, PDO::PARAM_INT);
  816. $query->bindValue(':time', time(), PDO::PARAM_INT);
  817. $query->bindValue(':message', $_POST['appeal']);
  818. $query->execute() or error(db_error($query));
  819. displayBan($ban);
  820. } else {
  821. if (!file_exists($config['has_installed'])) {
  822. header('Location: install.php', true, $config['redirect_http']);
  823. } else {
  824. // They opened post.php in their browser manually.
  825. error($config['error']['nopost']);
  826. }
  827. }