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.

986 line
33KB

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