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.

974 lines
32KB

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