forked from savetheinternet/Tinyboard
-
Notifications
You must be signed in to change notification settings - Fork 197
/
post.php
1464 lines (1201 loc) · 45.9 KB
/
post.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* Copyright (c) 2010-2014 Tinyboard Development Group
*/
require_once 'inc/bootstrap.php';
/**
* Utility functions
*/
/**
* Get the md5 hash of the file.
*
* @param array $config instance configuration.
* @param string $file file to the the md5 of.
* @return string|false
*/
function md5_hash_of_file($config, $path) {
$cmd = false;
if ($config['bsd_md5']) {
$cmd = '/sbin/md5 -r';
}
if ($config['gnu_md5']) {
$cmd = 'md5sum';
}
if ($cmd) {
$output = shell_exec_error($cmd . " " . escapeshellarg($path));
$output = explode(' ', $output);
return $output[0];
} else {
return md5_file($path);
}
}
/**
* Strip the symbols incompatible with the current database version.
*
* @param string @input The input string.
* @return string The value stripped of incompatible symbols.
*/
function strip_symbols($input) {
if (mysql_version() >= 50503) {
return $input; // Assume we're using the utf8mb4 charset
} else {
// MySQL's `utf8` charset only supports up to 3-byte symbols
// Remove anything >= 0x010000
$chars = preg_split('//u', $input, -1, PREG_SPLIT_NO_EMPTY);
$ret = '';
foreach ($chars as $char) {
$o = 0;
$ord = ordutf8($char, $o);
if ($ord >= 0x010000) {
continue;
}
$ret .= $char;
}
return $ret;
}
}
/**
* Download the url's target with curl.
*
* @param string $url Url to the file to download.
* @param int $timeout Request timeout in seconds.
* @param File $fd File descriptor to save the content to.
* @return null|string Returns a string on error.
*/
function download_file_into($url, $timeout, $fd) {
$err = null;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_USERAGENT, 'Tinyboard');
curl_setopt($curl, CURLOPT_FILE, $fd);
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
if (curl_exec($curl) === false) {
$err = curl_error($curl);
}
curl_close($curl);
return $err;
}
/**
* Download a remote file from the given url.
* The file is deleted at shutdown.
*
* @param string $file_url The url to download the file from.
* @param int $request_timeout Timeout to retrieve the file.
* @param array $extra_extensions Allowed file extensions.
* @param string $tmp_dir Temporary directory to save the file into.
* @param array $error_array An array with error codes, used to create exceptions on failure.
* @return array Returns an array describing the file on success.
* @throws Exception on error.
*/
function download_file_from_url($file_url, $request_timeout, $allowed_extensions, $tmp_dir, &$error_array) {
if (!preg_match('@^https?://@', $file_url)) {
throw new InvalidArgumentException($error_array['invalidimg']);
}
if (mb_strpos($file_url, '?') !== false) {
$url_without_params = mb_substr($file_url, 0, mb_strpos($file_url, '?'));
} else {
$url_without_params = $file_url;
}
$extension = strtolower(mb_substr($url_without_params, mb_strrpos($url_without_params, '.') + 1));
if (!in_array($extension, $allowed_extensions)) {
throw new InvalidArgumentException($error_array['unknownext']);
}
$tmp_file = tempnam($tmp_dir, 'url');
function unlink_tmp_file($file) {
@unlink($file);
fatal_error_handler();
}
register_shutdown_function('unlink_tmp_file', $tmp_file);
$fd = fopen($tmp_file, 'w');
$dl_err = download_file_into($fd, $request_timeout, $fd);
fclose($fd);
if ($dl_err !== null) {
throw new Exception($error_array['nomove'] . '<br/>Curl says: ' . $dl_err);
}
return array(
'name' => basename($url_without_params),
'tmp_name' => $tmp_file,
'file_tmp' => true,
'error' => 0,
'size' => filesize($tmp_file)
);
}
/**
* Try extract text from the given image.
*
* @param array $config Instance configuration.
* @param string $img_path The file path to the image.
* @return string|false Returns a string with the extracted text on success (if any).
* @throws RuntimeException Throws if executing tesseract fails.
*/
function ocr_image(array $config, string $img_path): string {
// The default preprocess command is an ImageMagick b/w quantization.
$ret = shell_exec_error(
sprintf($config['tesseract_preprocess_command'], escapeshellarg($img_path))
. ' | tesseract stdin stdout 2>/dev/null'
. $config['tesseract_params']
);
if ($ret === false) {
throw new RuntimeException('Unable to run tesseract');
}
return trim($ret);
}
/**
* Trim an image's EXIF metadata
*
* @param string $img_path The file path to the image.
* @return int The size of the stripped file.
* @throws RuntimeException Throws on IO errors.
*/
function strip_image_metadata(string $img_path): int {
$err = shell_exec_error('exiftool -overwrite_original -ignoreMinorErrors -q -q -all= ' . escapeshellarg($img_path));
if ($err === false) {
throw new RuntimeException('Could not strip EXIF metadata!');
}
clearstatcache(true, $img_path);
$ret = filesize($img_path);
if ($ret === false) {
throw new RuntimeException('Could not calculate file size!');
}
return $ret;
}
/**
* Delete posts in a cyclical thread.
*
* @param string $boardUri The URI of the board.
* @param int $threadId The ID of the thread.
* @param int $cycleLimit The number of most recent posts to retain.
*/
function delete_cyclical_posts(string $boardUri, int $threadId, int $cycleLimit): void
{
$query = prepare(sprintf('
SELECT p.`id`
FROM ``posts_%s`` p
LEFT JOIN (
SELECT `id`
FROM ``posts_%s``
WHERE `thread` = :thread
ORDER BY `id` DESC
LIMIT :limit
) recent_posts ON p.id = recent_posts.id
WHERE p.thread = :thread
AND recent_posts.id IS NULL',
$boardUri, $boardUri
));
$query->bindValue(':thread', $threadId, PDO::PARAM_INT);
$query->bindValue(':limit', $cycleLimit, PDO::PARAM_INT);
$query->execute() or error(db_error($query));
$ids = $query->fetchAll(PDO::FETCH_COLUMN);
foreach ($ids as $id) {
deletePost($id, false);
}
}
/**
* Method handling functions
*/
$dropped_post = false;
// Is it a post coming from NNTP? Let's extract it and pretend it's a normal post.
if (isset($_GET['Newsgroups']) && $config['nntpchan']['enabled']) {
if ($_SERVER['REMOTE_ADDR'] != $config['nntpchan']['trusted_peer']) {
error("NNTPChan: Forbidden. $_SERVER[REMOTE_ADDR] is not a trusted peer");
}
$_POST = array();
$_POST['json_response'] = true;
$headers = json_encode($_GET);
if (!isset ($_GET['Message-Id'])) {
if (!isset ($_GET['Message-ID'])) {
error("NNTPChan: No message ID");
}
else $msgid = $_GET['Message-ID'];
}
else $msgid = $_GET['Message-Id'];
$groups = preg_split("/,\s*/", $_GET['Newsgroups']);
if (count($groups) != 1) {
error("NNTPChan: Messages can go to only one newsgroup");
}
$group = $groups[0];
if (!isset($config['nntpchan']['dispatch'][$group])) {
error("NNTPChan: We don't synchronize $group");
}
$xboard = $config['nntpchan']['dispatch'][$group];
$ref = null;
if (isset ($_GET['References'])) {
$refs = preg_split("/,\s*/", $_GET['References']);
if (count($refs) > 1) {
error("NNTPChan: We don't support multiple references");
}
$ref = $refs[0];
$query = prepare("SELECT `board`,`id` FROM ``nntp_references`` WHERE `message_id` = :ref");
$query->bindValue(':ref', $ref);
$query->execute() or error(db_error($query));
$ary = $query->fetchAll(PDO::FETCH_ASSOC);
if (count($ary) == 0) {
error("NNTPChan: We don't have $ref that $msgid references");
}
$p_id = $ary[0]['id'];
$p_board = $ary[0]['board'];
if ($p_board != $xboard) {
error("NNTPChan: Cross board references not allowed. Tried to reference $p_board on $xboard");
}
$_POST['thread'] = $p_id;
}
$date = isset($_GET['Date']) ? strtotime($_GET['Date']) : time();
list($ct) = explode('; ', $_GET['Content-Type']);
$query = prepare("SELECT COUNT(*) AS `c` FROM ``nntp_references`` WHERE `message_id` = :msgid");
$query->bindValue(":msgid", $msgid);
$query->execute() or error(db_error($query));
$a = $query->fetch(PDO::FETCH_ASSOC);
if ($a['c'] > 0) {
error("NNTPChan: We already have this post. Post discarded.");
}
if ($ct == 'text/plain') {
$content = file_get_contents("php://input");
}
elseif ($ct == 'multipart/mixed' || $ct == 'multipart/form-data') {
_syslog(LOG_INFO, "MM: Files: ".print_r($GLOBALS, true)); // Debug
$content = '';
$newfiles = array();
foreach ($_FILES['attachment']['error'] as $id => $error) {
if ($_FILES['attachment']['type'][$id] == 'text/plain') {
$content .= file_get_contents($_FILES['attachment']['tmp_name'][$id]);
}
elseif ($_FILES['attachment']['type'][$id] == 'message/rfc822') { // Signed message, ignore for now
}
else { // A real attachment :^)
$file = array();
$file['name'] = $_FILES['attachment']['name'][$id];
$file['type'] = $_FILES['attachment']['type'][$id];
$file['size'] = $_FILES['attachment']['size'][$id];
$file['tmp_name'] = $_FILES['attachment']['tmp_name'][$id];
$file['error'] = $_FILES['attachment']['error'][$id];
$newfiles["file$id"] = $file;
}
}
$_FILES = $newfiles;
}
else {
error("NNTPChan: Wrong mime type: $ct");
}
$_POST['subject'] = isset($_GET['Subject']) ? ($_GET['Subject'] == 'None' ? '' : $_GET['Subject']) : '';
$_POST['board'] = $xboard;
if (isset ($_GET['From'])) {
list($name, $mail) = explode(" <", $_GET['From'], 2);
$mail = preg_replace('/>\s+$/', '', $mail);
$_POST['name'] = $name;
//$_POST['email'] = $mail;
$_POST['email'] = '';
}
if (isset ($_GET['X_Sage'])) {
$_POST['email'] = 'sage';
}
$content = preg_replace_callback('/>>([0-9a-fA-F]{6,})/', function($id) use ($xboard) {
$id = $id[1];
$query = prepare("SELECT `board`,`id` FROM ``nntp_references`` WHERE `message_id_digest` LIKE :rule");
$idx = $id . "%";
$query->bindValue(':rule', $idx);
$query->execute() or error(db_error($query));
$ary = $query->fetchAll(PDO::FETCH_ASSOC);
if (count($ary) == 0) {
return ">>>>$id";
}
else {
$ret = array();
foreach ($ary as $v) {
if ($v['board'] != $xboard) {
$ret[] = ">>>/".$v['board']."/".$v['id'];
}
else {
$ret[] = ">>".$v['id'];
}
}
return implode($ret, ", ");
}
}, $content);
$_POST['body'] = $content;
$dropped_post = array(
'date' => $date,
'board' => $xboard,
'msgid' => $msgid,
'headers' => $headers,
'from_nntp' => true,
);
}
elseif (isset($_GET['Newsgroups'])) {
error("NNTPChan: NNTPChan support is disabled");
}
session_start();
if (!isset($_POST['captcha_cookie']) && isset($_SESSION['captcha_cookie'])) {
$_POST['captcha_cookie'] = $_SESSION['captcha_cookie'];
}
if (isset($_POST['delete'])) {
// Delete
if (!isset($_POST['board'], $_POST['password']))
error($config['error']['bot']);
$password = &$_POST['password'];
if ($password == '')
error($config['error']['invalidpassword']);
$delete = array();
foreach ($_POST as $post => $value) {
if (preg_match('/^delete_(\d+)$/', $post, $m)) {
$delete[] = (int)$m[1];
}
}
checkDNSBL();
// Check if board exists
if (!openBoard($_POST['board']))
error($config['error']['noboard']);
if ((!isset($_POST['mod']) || !$_POST['mod']) && $config['board_locked']) {
error("Board is locked");
}
// Check if banned
checkBan($board['uri']);
// Check if deletion enabled
if (!$config['allow_delete'])
error(_('Post deletion is not allowed!'));
if (empty($delete))
error($config['error']['nodelete']);
foreach ($delete as &$id) {
$query = prepare(sprintf("SELECT `id`,`thread`,`time`,`password` FROM ``posts_%s`` WHERE `id` = :id", $board['uri']));
$query->bindValue(':id', $id, PDO::PARAM_INT);
$query->execute() or error(db_error($query));
if ($post = $query->fetch(PDO::FETCH_ASSOC)) {
$thread = false;
if ($config['user_moderation'] && $post['thread']) {
$thread_query = prepare(sprintf("SELECT `time`,`password` FROM ``posts_%s`` WHERE `id` = :id", $board['uri']));
$thread_query->bindValue(':id', $post['thread'], PDO::PARAM_INT);
$thread_query->execute() or error(db_error($query));
$thread = $thread_query->fetch(PDO::FETCH_ASSOC);
}
if ($post['time'] < time() - $config['max_delete_time'] && $config['max_delete_time'] != false) {
error(sprintf($config['error']['delete_too_late'], until($post['time'] + $config['max_delete_time'])));
}
if ($password != '' && $post['password'] != $password && (!$thread || $thread['password'] != $password))
error($config['error']['invalidpassword']);
if ($post['time'] > time() - $config['delete_time'] && (!$thread || $thread['password'] != $password)) {
error(sprintf($config['error']['delete_too_soon'], until($post['time'] + $config['delete_time'])));
}
$ip = $_SERVER['REMOTE_ADDR'];
if (isset($_POST['file'])) {
// Delete just the file
deleteFile($id);
modLog("User at $ip deleted file from their own post #$id");
} else {
// Delete entire post
deletePost($id);
modLog("User at $ip deleted their own post #$id");
}
_syslog(LOG_INFO, 'Deleted post: ' .
'/' . $board['dir'] . $config['dir']['res'] . link_for($post) . ($post['thread'] ? '#' . $id : '')
);
}
}
buildIndex();
$is_mod = isset($_POST['mod']) && $_POST['mod'];
$root = $is_mod ? $config['root'] . $config['file_mod'] . '?/' : $config['root'];
if (!isset($_POST['json_response'])) {
header('Location: ' . $root . $board['dir'] . $config['file_index'], true, $config['redirect_http']);
} else {
header('Content-Type: text/json');
echo json_encode(array('success' => true));
}
// We are already done, let's continue our heavy-lifting work in the background (if we run off FastCGI)
if (function_exists('fastcgi_finish_request'))
@fastcgi_finish_request();
rebuildThemes('post-delete', $board['uri']);
} elseif (isset($_POST['report'])) {
if (!isset($_POST['board'], $_POST['reason']))
error($config['error']['bot']);
$report = array();
foreach ($_POST as $post => $value) {
if (preg_match('/^delete_(\d+)$/', $post, $m)) {
$report[] = (int)$m[1];
}
}
checkDNSBL();
// Check if board exists
if (!openBoard($_POST['board']))
error($config['error']['noboard']);
if ((!isset($_POST['mod']) || !$_POST['mod']) && $config['board_locked']) {
error("Board is locked");
}
// Check if banned
checkBan($board['uri']);
if (empty($report))
error($config['error']['noreport']);
if (count($report) > $config['report_limit'])
error($config['error']['toomanyreports']);
if ($config['report_captcha'] && !isset($_POST['captcha_text'], $_POST['captcha_cookie'])) {
error($config['error']['bot']);
}
if ($config['report_captcha']) {
$ch = curl_init($config['domain'].'/'.$config['captcha']['provider_check'] . "?" . http_build_query([
'mode' => 'check',
'text' => $_POST['captcha_text'],
'extra' => $config['captcha']['extra'],
'cookie' => $_POST['captcha_cookie']
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($ch);
if ($resp !== '1') {
error($config['error']['captcha']);
}
}
$reason = escape_markup_modifiers($_POST['reason']);
markup($reason);
if (mb_strlen($reason) > $config['report_max_length']) {
error($config['error']['toolongreport']);
}
foreach ($report as &$id) {
$query = prepare(sprintf("SELECT `id`, `thread` FROM ``posts_%s`` WHERE `id` = :id", $board['uri']));
$query->bindValue(':id', $id, PDO::PARAM_INT);
$query->execute() or error(db_error($query));
$post = $query->fetch(PDO::FETCH_ASSOC);
if ($post === false) {
if ($config['syslog']) {
_syslog(LOG_INFO, "Failed to report non-existing post #{$id} in {$board['dir']}");
}
error($config['error']['nopost']);
}
$error = event('report', array('ip' => $_SERVER['REMOTE_ADDR'], 'board' => $board['uri'], 'post' => $post, 'reason' => $reason, 'link' => link_for($post)));
if ($error) {
error($error);
}
if ($config['syslog'])
_syslog(LOG_INFO, 'Reported post: ' .
'/' . $board['dir'] . $config['dir']['res'] . link_for($post) . ($post['thread'] ? '#' . $id : '') .
' for "' . $reason . '"'
);
$query = prepare("INSERT INTO ``reports`` VALUES (NULL, :time, :ip, :board, :post, :reason)");
$query->bindValue(':time', time(), PDO::PARAM_INT);
$query->bindValue(':ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
$query->bindValue(':board', $board['uri'], PDO::PARAM_STR);
$query->bindValue(':post', $id, PDO::PARAM_INT);
$query->bindValue(':reason', $reason, PDO::PARAM_STR);
$query->execute() or error(db_error($query));
}
$is_mod = isset($_POST['mod']) && $_POST['mod'];
$root = $is_mod ? $config['root'] . $config['file_mod'] . '?/' : $config['root'];
if (!isset($_POST['json_response'])) {
$index = $root . $board['dir'] . $config['file_index'];
echo Element($config['file_page_template'], 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!')));
} else {
header('Content-Type: text/json');
echo json_encode(array('success' => true));
}
} elseif (isset($_POST['post']) || $dropped_post) {
if (!isset($_POST['body'], $_POST['board']) && !$dropped_post)
error($config['error']['bot']);
$post = array('board' => $_POST['board'], 'files' => array());
// Check if board exists
if (!openBoard($post['board']))
error($config['error']['noboard']);
if ((!isset($_POST['mod']) || !$_POST['mod']) && $config['board_locked']) {
error("Board is locked");
}
if (!isset($_POST['name']))
$_POST['name'] = $config['anonymous'];
if (!isset($_POST['email']))
$_POST['email'] = '';
if (!isset($_POST['subject']))
$_POST['subject'] = '';
if (!isset($_POST['password']))
$_POST['password'] = '';
if (isset($_POST['thread'])) {
$post['op'] = false;
$post['thread'] = round($_POST['thread']);
} else
$post['op'] = true;
if (!$dropped_post) {
if ($config['simple_spam'] && $post['op']) {
if (!isset($_POST['simple_spam']) || strtolower($config['simple_spam']['answer']) != strtolower($_POST['simple_spam'])) {
error($config['error']['simple_spam']);
}
}
// Check if banned
checkBan($board['uri']);
// Check for CAPTCHA right after opening the board so the "return" link is in there
if ($config['recaptcha']) {
if (!isset($_POST['g-recaptcha-response']))
error($config['error']['bot']);
// Check what reCAPTCHA has to say...
$resp = json_decode(file_get_contents(sprintf('https://www.recaptcha.net/recaptcha/api/siteverify?secret=%s&response=%s&remoteip=%s',
$config['recaptcha_private'],
urlencode($_POST['g-recaptcha-response']),
$_SERVER['REMOTE_ADDR'])), true);
if (!$resp['success']) {
error($config['error']['captcha']);
}
}
// hCaptcha
if ($config['hcaptcha']) {
if (!isset($_POST['h-captcha-response'])) {
error($config['error']['bot']);
}
$data = array(
'secret' => $config['hcaptcha_private'],
'response' => $_POST['h-captcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
);
$hcaptchaverify = curl_init();
curl_setopt($hcaptchaverify, CURLOPT_URL, "https://hcaptcha.com/siteverify");
curl_setopt($hcaptchaverify, CURLOPT_POST, true);
curl_setopt($hcaptchaverify, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($hcaptchaverify, CURLOPT_RETURNTRANSFER, true);
$hcaptcharesponse = curl_exec($hcaptchaverify);
$resp = json_decode($hcaptcharesponse, true); // Decoding $hcaptcharesponse instead of $response
if (!$resp['success']) {
error($config['error']['captcha']);
}
}
// Same, but now with our custom captcha provider
if (($config['captcha']['enabled']) || (($post['op']) && ($config['new_thread_capt'])) ) {
$ch = curl_init($config['domain'].'/'.$config['captcha']['provider_check'] . "?" . http_build_query([
'mode' => 'check',
'text' => $_POST['captcha_text'],
'extra' => $config['captcha']['extra'],
'cookie' => $_POST['captcha_cookie']
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($ch);
if ($resp !== '1') {
error($config['error']['captcha'] .
'<script>if (actually_load_captcha !== undefined) actually_load_captcha("'.$config['captcha']['provider_get'].'", "'.$config['captcha']['extra'].'");</script>');
}
}
if (!(($post['op'] && $_POST['post'] == $config['button_newtopic']) ||
(!$post['op'] && $_POST['post'] == $config['button_reply'])))
error($config['error']['bot']);
// Check the referrer
if ($config['referer_match'] !== false &&
(!isset($_SERVER['HTTP_REFERER']) || !preg_match($config['referer_match'], rawurldecode($_SERVER['HTTP_REFERER']))))
error($config['error']['referer']);
checkDNSBL();
if ($post['mod'] = isset($_POST['mod']) && $_POST['mod']) {
check_login(false);
if (!$mod) {
// Liar. You're not a mod.
error($config['error']['notamod']);
}
$post['sticky'] = $post['op'] && isset($_POST['sticky']);
$post['locked'] = $post['op'] && isset($_POST['lock']);
$post['raw'] = isset($_POST['raw']);
if ($post['sticky'] && !hasPermission($config['mod']['sticky'], $board['uri']))
error($config['error']['noaccess']);
if ($post['locked'] && !hasPermission($config['mod']['lock'], $board['uri']))
error($config['error']['noaccess']);
if ($post['raw'] && !hasPermission($config['mod']['rawhtml'], $board['uri']))
error($config['error']['noaccess']);
}
if (!$post['mod']) {
$post['antispam_hash'] = checkSpam(array($board['uri'], isset($post['thread']) ? $post['thread'] : ($config['try_smarter'] && isset($_POST['page']) ? 0 - (int)$_POST['page'] : null)));
if ($post['antispam_hash'] === true)
error($config['error']['spam']);
}
if ($config['robot_enable'] && $config['robot_mute']) {
checkMute();
}
}
else {
$mod = $post['mod'] = false;
}
//Check if thread exists
if (!$post['op']) {
$query = prepare(sprintf("SELECT `sticky`,`locked`,`cycle`,`sage`,`slug` FROM ``posts_%s`` WHERE `id` = :id AND `thread` IS NULL LIMIT 1", $board['uri']));
$query->bindValue(':id', $post['thread'], PDO::PARAM_INT);
$query->execute() or error(db_error());
if (!$thread = $query->fetch(PDO::FETCH_ASSOC)) {
// Non-existant
error($config['error']['nonexistant']);
}
}
else {
$thread = false;
}
// Check for an embed field
if ($config['enable_embedding'] && isset($_POST['embed']) && !empty($_POST['embed'])) {
// yep; validate it
$value = $_POST['embed'];
foreach ($config['embedding'] as &$embed) {
if (preg_match($embed[0], $value)) {
// Valid link
$post['embed'] = $value;
// This is bad, lol.
$post['no_longer_require_an_image_for_op'] = true;
break;
}
}
if (!isset($post['embed'])) {
error($config['error']['invalid_embed']);
}
}
if (!hasPermission($config['mod']['bypass_field_disable'], $board['uri'])) {
if ($config['field_disable_name'])
$_POST['name'] = $config['anonymous']; // "forced anonymous"
if ($config['field_disable_email'])
$_POST['email'] = '';
if ($config['field_disable_password'])
$_POST['password'] = '';
if ($config['field_disable_subject'] || (!$post['op'] && $config['field_disable_reply_subject']))
$_POST['subject'] = '';
}
if ($config['allow_upload_by_url'] && isset($_POST['file_url']) && !empty($_POST['file_url'])) {
$allowed_extensions = $config['allowed_ext_files'];
// Add allowed extensions for OP, if enabled.
if ($post['op'] && $config['allowed_ext_op']) {
array_merge($allowed_extensions, $config['allowed_ext_op']);
}
try {
$_FILES['file'] = download_file_from_url($_POST['file_url'], $config['upload_by_url_timeout'], $allowed_extensions, $config['tmp'], $config['error']);
} catch (Exception $e) {
error($e->getMessage());
}
}
$post['name'] = $_POST['name'] != '' ? $_POST['name'] : $config['anonymous'];
$post['subject'] = $_POST['subject'];
$post['email'] = str_replace(' ', '%20', htmlspecialchars($_POST['email']));
$post['body'] = $_POST['body'];
$post['password'] = $_POST['password'];
$post['has_file'] = (!isset($post['embed']) && (($post['op'] && !isset($post['no_longer_require_an_image_for_op']) && $config['force_image_op']) || count($_FILES) > 0));
if (!$dropped_post) {
if (!($post['has_file'] || isset($post['embed'])) || (($post['op'] && $config['force_body_op']) || (!$post['op'] && $config['force_body']))) {
$stripped_whitespace = preg_replace('/[\s]/u', '', $post['body']);
if ($stripped_whitespace == '') {
error($config['error']['tooshort_body']);
}
}
if (!$post['op']) {
// Check if thread is locked
// but allow mods to post
if ($thread['locked'] && !hasPermission($config['mod']['postinlocked'], $board['uri']))
error($config['error']['locked']);
$numposts = numPosts($post['thread']);
if ($config['reply_hard_limit'] != 0 && $config['reply_hard_limit'] <= $numposts['replies'])
error($config['error']['reply_hard_limit']);
if ($post['has_file'] && $config['image_hard_limit'] != 0 && $config['image_hard_limit'] <= $numposts['images'])
error($config['error']['image_hard_limit']);
}
}
else {
if (!$post['op']) {
$numposts = numPosts($post['thread']);
}
}
if ($post['has_file']) {
// Determine size sanity
$size = 0;
if ($config['multiimage_method'] == 'split') {
foreach ($_FILES as $key => $file) {
$size += $file['size'];
}
} elseif ($config['multiimage_method'] == 'each') {
foreach ($_FILES as $key => $file) {
if ($file['size'] > $size) {
$size = $file['size'];
}
}
} else {
error(_('Unrecognized file size determination method.'));
}
if ($size > $config['max_filesize'])
error(sprintf3($config['error']['filesize'], array(
'sz' => number_format($size),
'filesz' => number_format($size),
'maxsz' => number_format($config['max_filesize'])
)));
$post['filesize'] = $size;
}
$post['capcode'] = false;
if ($mod && preg_match('/^((.+) )?## (.+)$/', $post['name'], $matches)) {
$name = $matches[2] != '' ? $matches[2] : $config['anonymous'];
$cap = $matches[3];
if (isset($config['mod']['capcode'][$mod['type']])) {
if ( $config['mod']['capcode'][$mod['type']] === true ||
(is_array($config['mod']['capcode'][$mod['type']]) &&
in_array($cap, $config['mod']['capcode'][$mod['type']])
)) {
$post['capcode'] = utf8tohtml($cap);
$post['name'] = $name;
}
}
}
$trip = generate_tripcode($post['name']);
$post['name'] = $trip[0];
$post['trip'] = isset($trip[1]) ? $trip[1] : ''; // XX: Dropped posts and tripcodes
$noko = false;
if (strtolower($post['email']) == 'noko') {
$noko = true;
$post['email'] = '';
} elseif (strtolower($post['email']) == 'nonoko'){
$noko = false;
$post['email'] = '';
} else $noko = $config['always_noko'];
if ($post['has_file']) {
$i = 0;
foreach ($_FILES as $key => $file) {
if (!in_array($file['error'], array(UPLOAD_ERR_NO_FILE, UPLOAD_ERR_OK))) {
error(sprintf3($config['error']['phpfileserror'], array(
'index' => $i+1,
'code' => $file['error']
)));
}
if ($file['size'] && $file['tmp_name']) {
$file['filename'] = urldecode($file['name']);
$file['extension'] = strtolower(mb_substr($file['filename'], mb_strrpos($file['filename'], '.') + 1));
if (isset($config['filename_func']))
$file['file_id'] = $config['filename_func']($file);
else
$file['file_id'] = time() . substr(microtime(), 2, 3);
if (sizeof($_FILES) > 1)
$file['file_id'] .= "-$i";
$file['file'] = $board['dir'] . $config['dir']['img'] . $file['file_id'] . '.' . $file['extension'];
$file['thumb'] = $board['dir'] . $config['dir']['thumb'] . $file['file_id'] . '.' . ($config['thumb_ext'] ? $config['thumb_ext'] : $file['extension']);
$post['files'][] = $file;
$i++;
}
}
}
if (empty($post['files'])) $post['has_file'] = false;
if (!$dropped_post) {
// Check for a file
if ($post['op'] && !isset($post['no_longer_require_an_image_for_op'])) {
if (!$post['has_file'] && $config['force_image_op'])
error($config['error']['noimage']);
}
// Check for too many files
if (sizeof($post['files']) > $config['max_images'])
error($config['error']['toomanyimages']);
}
if ($config['strip_combining_chars']) {
$post['name'] = strip_combining_chars($post['name']);
$post['email'] = strip_combining_chars($post['email']);
$post['subject'] = strip_combining_chars($post['subject']);
$post['body'] = strip_combining_chars($post['body']);
}
if (!$dropped_post) {
// Check string lengths
if (mb_strlen($post['name']) > 35)
error(sprintf($config['error']['toolong'], 'name'));
if (mb_strlen($post['email']) > 40)
error(sprintf($config['error']['toolong'], 'email'));
if (mb_strlen($post['subject']) > 100)
error(sprintf($config['error']['toolong'], 'subject'));
if (!$mod && mb_strlen($post['body']) > $config['max_body'])
error($config['error']['toolong_body']);
if (!$mod && substr_count($post['body'], "\n") >= $config['maximum_lines'])
error($config['error']['toomanylines']);
if (mb_strlen($post['password']) > 20)
error(sprintf($config['error']['toolong'], 'password'));
}
wordfilters($post['body']);
$post['body'] = escape_markup_modifiers($post['body']);
if ($mod && isset($post['raw']) && $post['raw']) {
$post['body'] .= "\n<tinyboard raw html>1</tinyboard>";
}
if (!$dropped_post)
if (($config['country_flags'] && !$config['allow_no_country']) || ($config['country_flags'] && $config['allow_no_country'] && !isset($_POST['no_country']))) {
$gi=geoip_open('inc/lib/geoip/GeoIPv6.dat', GEOIP_STANDARD);
function ipv4to6($ip) {
if (strpos($ip, ':') !== false) {
if (strpos($ip, '.') > 0)
$ip = substr($ip, strrpos($ip, ':')+1);
else return $ip; //native ipv6
}
$iparr = array_pad(explode('.', $ip), 4, 0);
$part7 = base_convert(($iparr[0] * 256) + $iparr[1], 10, 16);
$part8 = base_convert(($iparr[2] * 256) + $iparr[3], 10, 16);
return '::ffff:'.$part7.':'.$part8;
}
if ($country_code = geoip_country_code_by_addr_v6($gi, ipv4to6($_SERVER['REMOTE_ADDR']))) {
if (!in_array(strtolower($country_code), array('eu', 'ap', 'o1', 'a1', 'a2')))
$post['body'] .= "\n<tinyboard flag>".strtolower($country_code)."</tinyboard>".
"\n<tinyboard flag alt>".geoip_country_name_by_addr_v6($gi, ipv4to6($_SERVER['REMOTE_ADDR']))."</tinyboard>";
}
}
if ($config['user_flag'] && isset($_POST['user_flag']) && !empty($_POST['user_flag'])) {
$user_flag = $_POST['user_flag'];
if (!isset($config['user_flags'][$user_flag])) {
error(_('Invalid flag selection!'));
}
$flag_alt = isset($user_flag_alt) ? $user_flag_alt : $config['user_flags'][$user_flag];