-
Notifications
You must be signed in to change notification settings - Fork 2
/
imgboard.php
2708 lines (2456 loc) · 95.1 KB
/
imgboard.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
<?
if(file_exists('/www/global/lockdown')) {
if($_COOKIE['4chan_auser'] && $_COOKIE['4chan_apass'] && ($_POST['mode']=='usrdel'||$_GET['mode']=='latest')) {
// ok
}
else {
die('Posting temporarily disabled. Come back later!<br/>—Team 4chan (uptime? what\'s that?)');
}
}
include_once "./yotsuba_config.php";
include_once "./strings_e.php";
//include("./postfilter.php");
//include("./ads.php");
define('SQLLOGBAN', 'banned_users'); //Table (NOT DATABASE) used for holding banned users
define('SQLLOGMOD', 'mod_users'); //Table (NOT DATABASE) used for holding mod users
define('SQLLOGDEL', 'del_log'); //Table (NOT DATABASE) used for holding deletion log
if(BOARD_DIR == 'test') {
ini_set('display_errors', 1);
}
extract($_POST);
extract($_GET);
extract($_COOKIE);
$id = intval($id);
if(array_key_exists('upfile',$_FILES)) {
$upfile_name=$_FILES["upfile"]["name"];
$upfile=$_FILES["upfile"]["tmp_name"];
}
else {
$upfile_name=$upfile='';
}
$path = realpath("./").'/'.IMG_DIR;
ignore_user_abort(TRUE);
if(WORD_FILT&&file_exists("wf.php")){include_once("wf.php");}
if(JANITOR_BOARD == 1)
include_once '/www/global/plugins/broomcloset.php';
//mysqli_board_connect();
if(!$con=mysqli_connect(SQLHOST,SQLUSER,SQLPASS)){
echo S_SQLCONF; //unable to connect to DB (wrong user/pass?)
exit;
}
$db_id=mysqli_select_db($con, SQLDB);
if(!$db_id){echo S_SQLDBSF;}
if (!table_exist($con, SQLLOG)) {
echo (SQLLOG.S_TCREATE);
$result = mysqli_board_call($con, "create table ".SQLLOG." (primary key(no),
no int not null auto_increment,
now text,
name text,
email text,
sub text,
com text,
host text,
pwd text,
filename text,
ext text,
w int,
h int,
tn_w int,
tn_h int,
tim text,
time int,
md5 text,
fsize int,
root timestamp,
resto int,
sticky int,
permasage int,
closed int)");
if(!$result){echo S_TCREATEF;}
}
// https://www.php.net/manual/en/class.mysqli-result.php
function mysqli_result($result,$row,$field=0) {
if ($result===false) return false;
if ($row>=mysqli_num_rows($result)) return false;
if (is_string($field) && !(strpos($field,".")===false)) {
$t_field=explode(".",$field);
$field=-1;
$t_fields=mysqli_fetch_fields($result);
for ($id=0;$id<mysqli_num_fields($result);$id++) {
if ($t_fields[$id]->table==$t_field[0] && $t_fields[$id]->name==$t_field[1]) {
$field=$id;
break;
}
}
if ($field==-1) return false;
}
mysqli_data_seek($result,$row);
$line=mysqli_fetch_array($result);
return isset($line[$field])?$line[$field]:false;
}
// truncate $str to $max_lines lines and return $str and $abbr
// where $abbr = whether or not $str was actually truncated
function abbreviate($str,$max_lines) {
if(!defined('MAX_LINES_SHOWN')) {
if(defined('BR_CHECK')) {
define('MAX_LINES_SHOWN', BR_CHECK);
} else {
define('MAX_LINES_SHOWN', 20);
}
$max_lines = MAX_LINES_SHOWN;
}
$lines = explode("<br />", $str);
if(count($lines) > $max_lines) {
$abbr = 1;
$lines = array_slice($lines, 0, $max_lines);
$str = implode("<br />", $lines);
} else {
$abbr = 0;
}
//close spans after abbreviating
//XXX will not work with more html - use abbreviate_html from shiichan
$str .= str_repeat("</span>", substr_count($str, "<span") - substr_count($str, "</span"));
return array($str, $abbr);
}
// print $contents to $filename by using a temporary file and renaming it
// (makes *.html and *.gz if USE_GZIP is on)
function print_page($filename,$contents,$force_nogzip=0) {
$gzip = (USE_GZIP == 1 && !$force_nogzip);
$tempfile = tempnam(realpath(RES_DIR), "tmp"); //note: THIS actually creates the file
file_put_contents($tempfile, $contents, FILE_APPEND);
rename($tempfile, $filename);
chmod($filename, 0664); //it was created 0600
if($gzip) {
$tempgz = tempnam(realpath(RES_DIR), "tmp"); //note: THIS actually creates the file
$gzfp = gzopen($tempgz, "w");
gzwrite($gzfp, $contents);
gzclose($gzfp);
rename($tempgz, $filename . '.gz');
chmod($filename . '.gz', 0664); //it was created 0600
}
}
function file_get_contents_cached($filename) {
static $cache = array();
if(isset($cache[$filename]))
return $cache[$filename];
//$cache[$filename] = file_get_contents($filename);
return $cache[$filename];
}
function blotter_contents() {
static $cache;
global $con;
if(isset($cache)) return $cache;
$ret = "";
$topN = 4; //how many lines to print
$bl_lines = file( BLOTTER_PATH );
$bl_top = array_slice($bl_lines, 0, $topN);
$date = "";
foreach($bl_top as $line) {
if(!$date) {
$lineparts = explode(' - ', $line);
if(strpos($lineparts[0],'<font')!==FALSE) {
$dateparts = explode('>', $lineparts[0]);
$date = $dateparts[1];
$date = "<li><font color=\"red\">Blotter updated: $date</font>";
}
else {
$date = $lineparts[0];
$date = "<li>Blotter updated: $date";
}
}
$line = trim($line);
$line = str_replace("\\", "\\\\", $line);
$line = str_replace("'", "\'", $line);
$ret .= "'<li>$line'+\n";
}
$ret .= "''";
$cache = array($date,$ret);
return array($date,$ret);
}
// insert into the rapidsearch queue
function rapidsearch_insert($board, $no, $body) {
global $con;
$board = mysqli_real_escape_string($board);
$no = (int)$no;
$body = mysqli_real_escape_string($body);
mysqli_board_call($con, "INSERT INTO rs.rsqueue (`board`,`no`,`ts`,`com`) VALUES ('$board',$no,NOW(),'$body')");
}
function find_match_and_prefix($regex, $str, $off, &$match)
{
if (!preg_match($regex, $str, $m, PREG_OFFSET_CAPTURE, $off)) return FALSE;
$moff = $m[0][1];
$match = array(substr($str, $off, $moff-$off), $m[0][0]);
return TRUE;
}
function spoiler_parse($com) {
if (!find_match_and_prefix("/\[spoiler\]/", $com, 0, $m)) return $com;
$bl = strlen("[spoiler]"); $el = $bl+1;
$st = '<span class="spoiler" onmouseover="this.style.color=\'#FFF\';" onmouseout="this.style.color=this.style.backgroundColor=\'#000\'" style="color:#000;background:#000">';
$et = '</span>';
$ret = $m[0].$st; $lev = 1;
$off = strlen($m[0]) + $bl;
while (1) {
if (!find_match_and_prefix("@\[/?spoiler\]@", $com, $off, $m)) break;
list($txt, $tag) = $m;
$ret .= $txt;
$off += strlen($txt) + strlen($tag);
if ($tag == "[spoiler]") {
$ret .= $st;
$lev++;
} else if ($lev) {
$ret .= $et;
$lev--;
}
}
$ret .= substr($com, $off, strlen($com)-$off);
$ret .= str_repeat($et, $lev);
return $ret;
}
//rebuild the bans in array $boards
function rebuild_bans($boards) {
$cmd = "nohup /usr/local/bin/suid_run_global bin/rebuildbans $boards >/dev/null 2>&1 &";
exec($cmd);
}
function append_ban($board, $ip) {
$cmd = "nohup /usr/local/bin/suid_run_global bin/appendban $board $ip >/dev/null 2>&1 &";
exec($cmd);
}
// check whether the current user can perform $action (on $no, for some actions)
// board-level access is cached in $valid_cache.
function valid($action='moderator', $no=0){
global $con;
static $valid_cache; // the access level of the user
$access_level = array('none' => 0, 'janitor' => 1, 'janitor_this_board' => 2, 'moderator' => 5, 'manager' => 10, 'admin' => 20);
if(!isset($valid_cache)) {
$valid_cache = $access_level['none'];
if(isset($_COOKIE['4chan_auser'])&&isset($_COOKIE['4chan_apass'])){
$user = mysqli_real_escape_string($_COOKIE['4chan_auser']);
$pass = mysqli_real_escape_string($_COOKIE['4chan_apass']);
}
if($user&&$pass) {
$result=mysqli_board_call($con, "SELECT allow,deny FROM ".SQLLOGMOD." WHERE username='$user' and password='$pass'");
list($allow,$deny) = mysqli_fetch_row($result);
mysqli_free_result($result);
if($allow) {
$allows = explode(',', $allow);
$seen_janitor_token = false;
// each token can increase the access level,
// except that we only know that they're a moderator or a janitor for another board
// AFTER we read all the tokens
foreach($allows as $token) {
if($token == 'janitor')
$seen_janitor_token = true;
else if($token == 'manager' && $valid_cache < $access_level['manager'])
$valid_cache = $access_level['manager'];
else if($token == 'admin' && $valid_cache < $access_level['admin'])
$valid_cache = $access_level['admin'];
else if(($token == BOARD_DIR || $token == 'all') && $valid_cache < $access_level['janitor_this_board'])
$valid_cache = $access_level['janitor_this_board']; // or could be moderator, will be increased in next step
}
// now we can set moderator or janitor status
if(!$seen_janitor_token) {
if($valid_cache < $access_level['moderator'])
$valid_cache = $access_level['moderator'];
}
else {
if($valid_cache < $access_level['janitor'])
$valid_cache = $access_level['janitor'];
}
if($deny) {
$denies = explode(',', $deny);
if(in_array(BOARD_DIR,$denies)) {
$valid_cache = $access_level['none'];
}
}
}
}
}
switch($action) {
case 'moderator':
return $valid_cache >= $access_level['moderator'];
case 'textonly':
return $valid_cache >= $access_level['moderator'];
case 'janitor_board':
return $valid_cache >= $access_level['janitor'];
case 'delete':
if($valid_cache >= $access_level['janitor_this_board']) {
return true;
}
// if they're a janitor on another board, check for illegal post unlock
else if($valid_cache >= $access_level['janitor']) {
$query=mysqli_board_call($con, "SELECT COUNT(*) from reports WHERE board='".BOARD_DIR."' AND no=$no AND cat=2");
$illegal_count = mysqli_result($query, 0, 0);
mysqli_free_result($query);
return $illegal_count >= 3;
}
case 'reportflood':
return $valid_cache >= $access_level['janitor'];
case 'floodbypass':
return $valid_cache >= $access_level['moderator'];
default: // unsupported action
return false;
}
}
function sticky_post($no, $position) {
global $log; log_cache();
global $con;
$post_sticknum="202701010000".sprintf("%02d",$position);
$log[$no]['root'] = $post_sticknum;
$log[$no]['sticky'] = '1';
mysqli_board_call('UPDATE '.SQLLOG." SET sticky='1'".
", root='".$post_sticknum."'".
" WHERE no='".mysqli_real_escape_string($no)."'");
}
function permasage_post($no) {
global $log; log_cache();
global $con;
$log[$no]['permasage'] = '1';
mysqli_board_call('UPDATE '.SQLLOG." SET permasage='1'".
" WHERE no='".mysqli_real_escape_string($no)."'");
}
function rebuildqueue_create_table() {
global $con;
$sql = <<<EOSQL
CREATE TABLE `rebuildqueue` (
`board` char(4) NOT NULL,
`no` int(11) NOT NULL,
`ownedby` int(11) NOT NULL default '0',
`ts` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`board`,`no`,`ownedby`)
)
EOSQL;
mysqli_board_call($con, $sql);
}
function rebuildqueue_add($no) {
global $con;
$board = BOARD_DIR;
$no = (int)$no;
for($i=0;$i<2;$i++)
if(!mysqli_board_call($con, "INSERT IGNORE INTO rebuildqueue (board,no) VALUES ('$board','$no')"))
rebuildqueue_create_table();
else
break;
}
function rebuildqueue_remove($no) {
global $con;
$board = BOARD_DIR;
$no = (int)$no;
for($i=0;$i<2;$i++)
if(!mysqli_board_call($con, "DELETE FROM rebuildqueue WHERE board='$board' AND no='$no'"))
rebuildqueue_create_table();
else
break;
}
function rebuildqueue_take_all() {
global $con;
$board = BOARD_DIR;
$uid = mt_rand(1, mt_getrandmax());
for($i=0;$i<2;$i++)
if(!mysqli_board_call($con, "UPDATE rebuildqueue SET ownedby=$uid,ts=ts WHERE board='$board' AND ownedby=0"))
rebuildqueue_create_table();
else
break;
$q = mysqli_board_call($con, "SELECT no FROM rebuildqueue WHERE board='$board' AND ownedby=$uid");
$posts = array();
while($post=mysqli_fetch_assoc($q))
$posts[] = $post['no'];
return $posts;
}
function iplog_add($board, $no, $ip) {
$board = mysqli_real_escape_string($board);
$no = (int)$no;
$ip = mysqli_real_escape_string($ip);
mysqli_board_call($con, "INSERT INTO iplog (board,no,ip) VALUES ('$board',$no,'$ip')");
}
// build a structure out of all the posts in the database.
// this lets us replace a LOT of queries with a simple array access.
// it only builds the first time it was called.
// rather than calling log_cache(1) to rebuild everything,
// you should just manipulate the structure directly.
function log_cache($invalidate=0) {
global $log, $ipcount, $mysqli_unbuffered_reads, $lastno;
global $con;
$ips = array();
$threads = array(); // no's
if($invalidate==0 && isset($log)) return;
$log = array(); // no -> [ data ]
mysqli_board_call($con, "SET read_buffer_size=1048576");
$mysqli_unbuffered_reads = 1;
$query = mysqli_board_call($con, "SELECT * FROM ".SQLLOG);
$offset = 0;
$lastno = 0;
while($row = mysqli_fetch_assoc($query)) {
if($row['no'] > $lastno) $lastno = $row['no'];
$ips[$row['host']] = 1;
// initialize log row if necessary
if( !isset($log[$row['no']]) ) {
$log[$row['no']] = $row;
$log[$row['no']]['children'] = array();
} else { // otherwise merge it with $row
foreach($row as $key=>$val)
$log[$row['no']][$key] = $val;
}
// if this is a reply
if($row['resto']) {
// initialize whatever we need to
if( !isset($log[$row['resto']]) )
$log[$row['resto']] = array();
if( !isset($log[$row['resto']]['children']) )
$log[$row['resto']]['children'] = array();
// add this post to list of children
$log[$row['resto']]['children'][$row['no']] = 1;
if($row['fsize']) {
if(!isset($log[$row['resto']]['imgreplycount']))
$log[$row['resto']]['imgreplycount'] = 0;
else
$log[$row['resto']]['imgreplycount']++;
}
} else {
$threads[] = $row['no'];
}
}
$query = mysqli_board_call($con, "SELECT no FROM ".SQLLOG." WHERE root>0 order by root desc");
while($row = mysqli_fetch_assoc($query)) {
if(isset($log[$row['no']]) && $log[$row['no']]['resto']==0)
$threads[] = $row['no'];
}
$log['THREADS'] = $threads;
$mysqli_unbuffered_reads = 0;
// calculate old-status for PAGE_MAX mode
if(EXPIRE_NEGLECTED != 1) {
rsort($threads, SORT_NUMERIC);
$threadcount = count($threads);
if(PAGE_MAX > 0) // the lowest 5% of maximum threads get marked old
for($i = floor(0.95*PAGE_MAX*PAGE_DEF); $i < $threadcount; $i++) {
if(!$log[$threads[$i]]['sticky'] && EXPIRE_NEGLECTED != 1)
$log[$threads[$i]]['old'] = 1;
}
else { // threads w/numbers below 5% of LOG_MAX get marked old
foreach($threads as $thread) {
if($lastno-LOG_MAX*0.95>$thread)
if(!$log[$thread]['sticky'])
$log[$thread]['old'] = 1;
}
}
}
$ipcount = count($ips);
}
// deletes a post from the database
// imgonly: whether to just delete the file or to delete from the database as well
// automatic: always delete regardless of password/admin (for self-pruning)
// children: whether to delete just the parent post of a thread or also delete the children
// die: whether to die on error
// careful, setting children to 0 could leave orphaned posts.
function delete_post($resno, $pwd, $imgonly=0, $automatic=0, $children=1, $die=1) {
global $log, $path;
global $con;
log_cache();
$resno = intval($resno);
// get post info
if(!isset($log[$resno])){if ($die) error("Can't find the post $resno.");}
$row=$log[$resno];
// check password- if not ok, check admin status (and set $admindel if allowed)
$delete_ok = ( $automatic || (substr(md5($pwd),2,8) == $row['pwd']) || ($row['host'] == $_SERVER['REMOTE_ADDR']) || ADMIN_PASS == $pwd );
//if( ($pwd==ADMIN_PASS || $pwd==ADMIN_PASS2) ) { $delete_ok = $admindel = valid('delete', $resno); }
if(!$delete_ok) error(S_BADDELPASS);
// check ghost bumping
if(!isset($admindel) || !$admindel) {
if(BOARD_DIR == 'a' && (int)$row['time'] > (time() - 25) && $row['email'] != 'sage') {
$ghostdump = var_export(array(
'server'=>$_SERVER,
'post'=>$_POST,
'cookie'=>$_COOKIE,
'row'=>$row),true);
//file_put_contents('ghostbump.'.time(),$ghostdump);
}
}
if(isset($admindel) && $admindel) { // extra actions for admin user
$auser = mysqli_escape_string($_COOKIE['4chan_auser']);
$adfsize=($row['fsize']>0)?1:0;
$adname=str_replace('</span> <span class="postertrip">!','#',$row['name']);
if($imgonly) { $imgonly=1; } else { $imgonly=0; }
$row['sub'] = mysqli_escape_string($row['sub']);
$row['com'] = mysqli_escape_string($row['com']);
$row['filename'] = mysqli_escape_string($row['filename']);
mysqli_board_call($con, "INSERT INTO ".SQLLOGDEL." (imgonly,postno,board,name,sub,com,img,filename,admin) values('$imgonly','$resno','".SQLLOG."','$adname','{$row['sub']}','{$row['com']}','$adfsize','{$row['filename']}','$auser')");
}
if($row['resto']==0 && $children && !$imgonly) // select thread and children
$result=mysqli_board_call($con, "select no,resto,tim,ext from ".SQLLOG." where no=$resno or resto=$resno");
else // just select the post
$result=mysqli_board_call($con, "select no,resto,tim,ext from ".SQLLOG." where no=$resno");
while($delrow=mysqli_fetch_array($result)) {
// delete
$delfile = $path.$delrow['tim'].$delrow['ext']; //path to delete
$delthumb = THUMB_DIR.$delrow['tim'].'s.jpg';
if(is_file($delfile)) unlink($delfile); // delete image
if(is_file($delthumb)) unlink($delthumb); // delete thumb
if(OEKAKI_BOARD == 1 && is_file($path.$delrow['tim'].'.pch'))
unlink($path.$delrow['tim'].'.pch'); // delete oe animation
if(!$imgonly){ // delete thread page & log_cache row
if($delrow['resto'])
unset( $log[$delrow['resto']]['children'][$delrow['no']] );
unset( $log[$delrow['no']] );
$log['THREADS'] = array_diff($log['THREADS'], array($delrow['no'])); // remove from THREADS
//mysqli_board_call($con, "DELETE FROM reports WHERE no=".$delrow['no']); // clear reports
if(USE_GZIP == 1) {
@unlink(RES_DIR.$delrow['no'].PHP_EXT);
@unlink(RES_DIR.$delrow['no'].PHP_EXT.'.gz');
}
else {
@unlink(RES_DIR.$delrow['no'].PHP_EXT);
}
}
}
//delete from DB
if($row['resto']==0 && $children && !$imgonly) // delete thread and children
$result=mysqli_board_call($con, "delete from ".SQLLOG." where no=$resno or resto=$resno");
elseif(!$imgonly) // just delete the post
$result=mysqli_board_call($con, "delete from ".SQLLOG." where no=$resno");
return $row['resto']; // so the caller can know what pages need to be rebuilt
}
// purge old posts
// should be called whenever a new post is added.
function trim_db() {
global $con;
if(JANITOR_BOARD == 1) return;
log_cache();
$maxposts = LOG_MAX;
// max threads = max pages times threads-per-page
$maxthreads = (PAGE_MAX > 0)?(PAGE_MAX * PAGE_DEF):0;
// New max-page method
if($maxthreads) {
$exp_order = 'no';
if(EXPIRE_NEGLECTED == 1) $exp_order = 'root';
//logtime('trim_db before select threads');
$result = mysqli_board_call($con, "SELECT no FROM ".SQLLOG." WHERE sticky=0 AND resto=0 ORDER BY $exp_order ASC");
//logtime('trim_db after select threads');
$threadcount = mysqli_num_rows($result);
while($row=mysqli_fetch_array($result) and $threadcount >= $maxthreads) {
delete_post($row['no'], 'trim', 0, 1); // imgonly=0, automatic=1, children=1
$threadcount--;
}
mysqli_free_result($result);
// Original max-posts method (note: cleans orphaned posts later than parent posts)
} else {
// make list of stickies
$stickies = array(); // keys are stickied thread numbers
$result = mysqli_board_call($con, "SELECT no from ".SQLLOG." where sticky=1 and resto=0");
while($row=mysqli_fetch_array($result)) {
$stickies[ $row['no'] ] = 1;
}
$result = mysqli_board_call($con, "SELECT no,resto,sticky FROM ".SQLLOG." ORDER BY no ASC");
$postcount = mysqli_num_rows($result);
while($row=mysqli_fetch_array($result) and $postcount >= $maxposts) {
// don't delete if this is a sticky thread
if($row['sticky'] == 1) continue;
// don't delete if this is a REPLY to a sticky
if($row['resto'] != 0 && $stickies[ $row['resto'] ] == 1) continue;
delete_post($row['no'], 'trim', 0, 1, 0); // imgonly=0, automatic=1, children=0
$postcount--;
}
mysqli_free_result($result);
}
}
//resno - thread page to update (no of thread OP)
//rebuild - don't rebuild page indexes
function updatelog($resno=0,$rebuild=0){
global $log,$path;
global $con;
set_time_limit(60);
if($_SERVER['REQUEST_METHOD']=='GET' && !valid()) die(''); // anti ddos
log_cache();
$imgdir = ((USE_SRC_CGI==1)?str_replace('src','src.cgi',IMG_DIR2):IMG_DIR2);
if(defined('INTERSTITIAL_LINK')) $imgdir .= INTERSTITIAL_LINK;
$thumbdir = THUMB_DIR2;
$imgurl = DATA_SERVER;
$resno=(int)$resno;
if($resno){
if(!isset($log[$resno])) {
updatelog(0,$rebuild); // the post didn't exist, just rebuild the indexes
return;
}
else if($log[$resno]['resto']) {
updatelog($log[$resno]['resto'],$rebuild); // $resno is a reply, try rebuilding the parent
return;
}
}
if($resno){
$treeline = array($resno); //logtime("Formatting thread page");
if(!$treeline=mysqli_board_call($con, "select * from ".SQLLOG." where root>0 and no=".$resno." order by root desc")){echo S_SQLFAIL;}
}else{
$treeline = $log['THREADS']; //logtime("Formatting index page");
if(!$treeline=mysqli_board_call($con, "select * from ".SQLLOG." where root>0 order by root desc")){echo S_SQLFAIL;}
}
//$counttree=count($treeline);
$counttree=mysqli_num_rows($treeline);
if(!$counttree){
$logfilename=PHP_SELF2;
$dat='';
head($dat,$resno);
form($dat,$resno);
print_page($logfilename, $dat);
}
if(UPDATE_THROTTLING >= 1) {
$update_start = time();
touch("updatelog.stamp", $update_start);
$low_priority = false;
clearstatcache();
if(@filemtime(PHP_SELF) > $update_start-UPDATE_THROTTLING) {
$low_priority = true;
//touch($update_start . ".lowprio");
}
else {
touch(PHP_SELF,$update_start);
}
// $mt = @filemtime(PHP_SELF);
// touch($update_start . ".$mt.highprio");
}
// if we're using CACHE_TTL method
if(CACHE_TTL >= 1) {
if($resno) {
$logfilename = RES_DIR.$resno.PHP_EXT;
}
else {
$logfilename = PHP_SELF2;
}
//if(USE_GZIP == 1) $logfilename .= '.html';
// if the file has been made and it's younger than CACHE_TTL seconds ago
clearstatcache();
if(file_exists($logfilename) && filemtime($logfilename) > (time() - CACHE_TTL)) {
// save the post to be rebuilt later
rebuildqueue_add($resno);
// if it's a thread, try again on the indexes
if($resno && !$rebuild) updatelog();
// and we don't do any more rebuilding on this request
return true;
}
else {
// we're gonna update it now, so take it out of the queue
rebuildqueue_remove($resno);
// and make sure nobody else starts trying to update it because it's too old
touch($logfilename);
}
}
for($page=0;$page<$counttree;$page+=PAGE_DEF){
$dat='';
head($dat,$resno);
form($dat,$resno);
if(!$resno){
$st = $page;
}
$dat.='<form name="delform" action="';
$dat.=PHP_SELF_ABS.'" method=POST>';
for($i = $st; $i < $st+PAGE_DEF; $i++){
if(UPDATE_THROTTLING >= 1) {
clearstatcache();
if($low_priority && @filemtime("updatelog.stamp") > $update_start) {
//touch($update_start . ".throttled");
return;
}
if(rand(0,15)==0) return;
}
//list($_unused,$no) = each($treeline);
list($no,$sticky,$permasage,$closed,$now,$name,$email,$sub,$com,$host,$pwd,$filename,$ext,$w,$h,$tn_w,$tn_h,$tim,$time,$md5,$fsize,$root,$resto)=mysqli_fetch_row($treeline);
if(!$no){break;}
extract($log[$no]);
//if(!$resno&&!file_exists(RES_DIR.$no.PHP_EXT)) { updatelog($no); break; } // uhh
//POST FILTERING
if(JANITOR_BOARD == 1) {
$name = broomcloset_capcode($name);
}
if($email) $name = "<a href=\"mailto:$email\" class=\"linkmail\">$name</a>";
if(strpos($sub,"SPOILER<>")===0) {
$sub = substr($sub,strlen("SPOILER<>")); //trim out SPOILER<>
$spoiler = 1;
} else $spoiler = 0;
$com = auto_link($com,$resno);
if(MAKE_AMERICAN == 1) {
$com = make_american($com);
}
if(!$resno) list($com,$abbreviated) = abbreviate($com, MAX_LINES_SHOWN);
if(isset($abbreviated) && $abbreviated) $com .= "<br /><span class=\"abbr\">Comment too long. Click <a href=\"".RES_DIR.($resto?$resto:$no).PHP_EXT."#$no\">here</a> to view the full text.</span>";
// Picture file name
$img = $path.$tim.$ext;
$displaysrc = $imgdir.$tim.$ext;
$linksrc = ((USE_SRC_CGI==1)?(str_replace(".cgi","",$imgdir).$tim.$ext):$displaysrc);
if(defined('INTERSTITIAL_LINK')) $linksrc = str_replace(INTERSTITIAL_LINK,"",$linksrc);
$src = IMG_DIR.$tim.$ext;
$longname = $filename.$ext;
if (strlen($filename)>40) {
$shortname = substr($filename, 0, 40)."(...)".$ext;
} else {
$shortname = $longname;
}
// img tag creation
$imgsrc = "";
if($ext){
// turn the 32-byte ascii md5 into a 24-byte base64 md5
$shortmd5 = base64_encode(pack("H*", $md5));
if ($fsize >= 1048576) { $size = round(($fsize/1048576),2)." M";
} else if ($fsize >= 1024) { $size = round($fsize/1024)." K";
} else { $size = $fsize." "; }
if(!$tn_w && !$tn_h && $ext==".gif"){
$tn_w=$w;
$tn_h=$h;
}
if($spoiler) {
$size= "Spoiler Image, $size";
$imgsrc = "<br><a href=\"".$displaysrc."\" target=_blank><img src=\"".SPOILER_THUMB."\" border=0 align=left hspace=20 alt=\"".$size."B\" md5=\"$shortmd5\"></a>";
} elseif($tn_w && $tn_h){//when there is size...
if(@is_file(THUMB_DIR.$tim.'s.jpg')){
$imgsrc = "<br><a href=\"".$displaysrc."\" target=_blank><img src=".$thumbdir.$tim.'s.jpg'." border=0 align=left width=$tn_w height=$tn_h hspace=20 alt=\"".$size."B\" md5=\"$shortmd5\"></a>";
}else{
$imgsrc = "<a href=\"".$displaysrc."\" target=_blank><span class=\"tn_thread\" title=\"".$size."B\">Thumbnail unavailable</span></a>";
}
}else{
if(@is_file(THUMB_DIR.$tim.'s.jpg')){
$imgsrc = "<br><a href=\"".$displaysrc."\" target=_blank><img src=".$thumbdir.$tim.'s.jpg'." border=0 align=left hspace=20 alt=\"".$size."B\" md5=\"$shortmd5\"></a>";
}else{
$imgsrc = "<a href=\"".$displaysrc."\" target=_blank><span class=\"tn_thread\" title=\"".$size."B\">Thumbnail unavailable</span></a>";
}
}
if (!is_file($src)) {
$dat.='<img src="'.$imgurl.'filedeleted.gif" alt="File deleted.">';
} else {
$dimensions=($ext=='.pdf')?'PDF':"{$w}x{$h}";
if ($resno) {
$dat.="<span class=\"filesize\">".S_PICNAME."<a href=\"$linksrc\" target=\"_blank\">$time$ext</a>-(".$size."B, ".$dimensions.", <span title=\"".$longname."\">".$shortname."</span>)</span>".$imgsrc;
} else {
$dat.="<span class=\"filesize\">".S_PICNAME."<a href=\"$linksrc\" target=\"_blank\">$time$ext</a>-(".$size."B, ".$dimensions.")</span>".$imgsrc;
}
}
}
// Main creation
$dat.="<a name=\"$resno\"></a>\n<input type=checkbox name=\"$no\" value=delete><span class=\"filetitle\">$sub</span> \n";
$dat.="<span class=\"postername\">$name</span> $now <span id=\"nothread$no\">";
if($sticky==1) {
$stickyicon=' <img src="'.$imgurl.'sticky.gif" alt="sticky"> ';
} else { $stickyicon=""; }
if($closed==1) {
$stickyicon .= ' <img src="'.$imgurl.'closed.gif" alt="closed"> ';
}
if(PARTY==1) {
$dat .= "<img src='https://s.4cdn.org/image/partyhat.gif' style='position:absolute;margin-top:-100px;left:0px;'>";
}
if($resno) {
$dat.="<a href=\"#$no\" class=\"quotejs\">No.</a><a href=\"javascript:quote('$no')\" class=\"quotejs\">$no</a> $stickyicon ";
} else {
$dat.="<a href=\"".RES_DIR.$no.PHP_EXT."#".$no."\" class=\"quotejs\">No.</a><a href=\"".RES_DIR.$no.PHP_EXT."#q".$no."\" class=\"quotejs\">$no</a> $stickyicon [<a href=\"".RES_DIR.$no.PHP_EXT."\">".S_REPLY."</a>]";
}
$dat.="</span>\n<blockquote>$com</blockquote>";
// Deletion pending
if(isset($log[$no]['old'])) $dat.="<span class=\"oldpost\">".S_OLD."</span><br>\n";
$resline = $log[$no]['children'];
ksort($resline);
$countres=count($log[$no]['children']);
$t=0;
if($sticky==1) {
$disam=1;
} elseif(defined('REPLIES_SHOWN')) {
$disam=REPLIES_SHOWN;
} else {
$disam=5;
}
$s=$countres - $disam;
$cur=1;
while ($s >= $cur) {
list($row) = each($resline);
if($log[$row]["fsize"]!=0) { $t++; }
$cur++;
}
if ($countres!=0) reset($resline);
if(!$resno){
if ($s<2) { $posts=" post"; } else { $posts=" posts"; }
if ($t<2) { $replies="reply"; } else { $replies="replies"; }
if(($s>0)&&($t==0)){
$dat.="<span class=\"omittedposts\">".$s.$posts." omitted. Click Reply to view.</span>\n";
} elseif (($s>0)&&($t>0)) {
$dat.="<span class=\"omittedposts\">".$s.$posts." and ".$t." image ".$replies." omitted. Click Reply to view.</span>\n";
}
}else{$s=0;}
while(list($resrow)=each($resline)){
if($s>0){$s--;continue;}
//list($no,$sticky,$permasage,$closed,$now,$name,$email,$sub,$com,$host,$pwd,$filename,$ext,$w,$h,$tn_w,$tn_h,$tim,$time,$md5,$fsize,$root,$resto)=$resrow;
extract($log[$resrow]);
if(!$no){break;}
//POST FILTERING
if(JANITOR_BOARD == 1) {
$name = broomcloset_capcode($name);
}
if($email) $name = "<a href=\"mailto:$email\" class=\"linkmail\">$name</a>";
if(strpos($sub,"SPOILER<>")===0) {
$sub = substr($sub,strlen("SPOILER<>")); //trim out SPOILER<>
$spoiler = 1;
} else $spoiler = 0;
$com = auto_link($com,$resno);
if(MAKE_AMERICAN == 1) {
$com = make_american($com);
}
if(!$resno) list($com,$abbreviated) = abbreviate($com, MAX_LINES_SHOWN);
if(isset($abbreviated)&&$abbreviated) $com .= "<br /><span class=\"abbr\">Comment too long. Click <a href=\"".RES_DIR.($resto?$resto:$no).PHP_EXT."#$no\">here</a> to view the full text.</span>";
// Picture file name
$r_img = $path.$tim.$ext;
$r_displaysrc = $imgdir.$tim.$ext;
$r_linksrc = ((USE_SRC_CGI==1)?(str_replace(".cgi","",$imgdir).$tim.$ext):$r_displaysrc);
if(defined('INTERSTITIAL_LINK')) $r_linksrc = str_replace(INTERSTITIAL_LINK,"",$r_linksrc);
$r_src = IMG_DIR.$tim.$ext;
$longname = $filename.$ext;
if (strlen($filename)>30) {
$shortname = substr($filename, 0, 30)."(...)".$ext;
} else {
$shortname = $longname;
}
// img tag creation
$r_imgsrc = "";
if($ext){
// turn the 32-byte ascii md5 into a 24-byte base64 md5
$shortmd5 = base64_encode(pack("H*", $md5));
if ($fsize >= 1048576) { $size = round(($fsize/1048576),2)." M";
} else if ($fsize >= 1024) { $size = round($fsize/1024)." K";
} else { $size = $fsize." "; }
if(!$tn_w && !$tn_h && $ext==".gif"){
$tn_w=$w;
$tn_h=$h;
}
if($spoiler) {
$size= "Spoiler Image, $size";
$r_imgsrc = "<br><a href=\"".$r_displaysrc."\" target=_blank><img src=\"".SPOILER_THUMB."\" border=0 align=left hspace=20 alt=\"".$size."B\" md5=\"$shortmd5\"></a>";
}
elseif($tn_w && $tn_h){//when there is size...
if(@is_file(THUMB_DIR.$tim.'s.jpg')){
$r_imgsrc = "<br><a href=\"".$r_displaysrc."\" target=_blank><img src=".$thumbdir.$tim.'s.jpg'." border=0 align=left width=$tn_w height=$tn_h hspace=20 alt=\"".$size."B\" md5=\"$shortmd5\"></a>";
}else{
$r_imgsrc = "<a href=\"".$r_displaysrc."\" target=_blank><span class=\"tn_reply\" title=\"".$size."B\">Thumbnail unavailable</span></a>";
}
}else{
if(@is_file(THUMB_DIR.$tim.'s.jpg')){
$r_imgsrc = "<br><a href=\"".$r_displaysrc."\" target=_blank><img src=".$thumbdir.$tim.'s.jpg'." border=0 align=left hspace=20 alt=\"".$size."B\" md5=\"$shortmd5\"></a>";
}else{
$r_imgsrc = "<a href=\"".$r_displaysrc."\" target=_blank><span class=\"tn_reply\" title=\"".$size."B\">Thumbnail unavailable</span></a>";
}
}
if (!is_file($r_src)) {
$r_imgreply='<br><img src="'.$imgurl.'filedeleted-res.gif" alt="File deleted.">';
} else {
$dimensions=($ext=='.pdf')?'PDF':"{$w}x{$h}";
if ($resno) {
$r_imgreply="<br> <span class=\"filesize\">".S_PICNAME."<a href=\"$r_linksrc\" target=\"_blank\">$time$ext</a>-(".$size."B, ".$dimensions.", <span title=\"".$longname."\">".$shortname."</span>)</span>".$r_imgsrc;
} else {
$r_imgreply="<br> <span class=\"filesize\">".S_PICNAME."<a href=\"$r_linksrc\" target=\"_blank\">$time$ext</a>-(".$size."B, ".$dimensions.")</span>".$r_imgsrc;
}
}
}
// Main Reply creation
$dat.="<a name=\"$no\"></a>\n";
$dat.="<table><tr><td nowrap class=\"doubledash\">>></td><td id=\"$no\" class=\"reply\">\n";
// if (($t>3)&&($fsize!=0)) {
// $dat.=" <b>Image hidden</b> $now No.$no \n";
// } else {
$dat.="<input type=checkbox name=\"$no\" value=delete><span class=\"replytitle\">$sub</span> \n";
$dat.="<span class=\"commentpostername\">$name</span> $now <span id=\"norep$no\">";
if($resno) {
$dat.="<a href=\"#$no\" class=\"quotejs\">No.</a><a href=\"javascript:quote('$no')\" class=\"quotejs\">$no</a></span>";
} else {
$dat.="<a href=\"".RES_DIR.$resto.PHP_EXT."#$no\" class=\"quotejs\">No.</a><a href=\"".RES_DIR.$resto.PHP_EXT."#q$no\" class=\"quotejs\">$no</a></span>";
}
if(isset($r_imgreply)) $dat.=$r_imgreply;
$dat.="<blockquote>$com</blockquote>";
// }
$dat.="</td></tr></table>\n";
unset($r_imgreply);
}
$dat.="<br clear=left><hr>\n";
clearstatcache();//clear stat cache of a file
//mysqli_free_result($resline);
$p++;
if($resno){break;} //only one tree line at time of res
}
// bottom of a page
if(BOTTOM_AD == 1) {
$bottomad = "";
if (defined("BOTTOM_TXT") && BOTTOM_TXT) {
$bottomad .= ad_text_for(BOTTOM_TXT);
}
if (defined("BOTTOM_TABLE") && BOTTOM_TABLE) {
list($bottomimg,$bottomlink) = rid(BOTTOM_TABLE,1);
$bottomad .= "<center><a href=\"$bottomlink\" target=\"_blank\"><img style=\"border:1px solid black;\" src=\"$bottomimg\" width=728 height=90 border=0 /></a></center>";
}
if($bottomad)
$dat .= "$bottomad<hr>";
}
$dat.='<table align=right><tr><td nowrap align=center class=deletebuttons>
<input type=hidden name=mode value=usrdel>'.S_REPDEL.' [<input class=checkbox type=checkbox name=onlyimgdel value=on>'.S_DELPICONLY.']<br>
'.S_DELKEY.' <input class=inputtext type=password name="pwd" size=8 maxlength=8 value="">
<input type=submit value="'.S_DELETE.'"><input type="button" value="Report" onclick="var o=document.getElementsByTagName(\'INPUT\');for(var i=0;i<o.length;i++)if(o[i].type==\'checkbox\' && o[i].checked && o[i].value==\'delete\') return reppop(\''.PHP_SELF_ABS.'?mode=report&no=\'+o[i].name+\'\');"></form><script>document.delform.pwd.value=get_pass("4chan_pass");</script></td></tr>';
if (strpos($_SERVER['SERVER_NAME'],".example.com")) {
$dat.='<tr><td align="right">Style [';
$dat.='<a href="#" onclick="setActiveStyleSheet(\'Yotsuba\'); return false;">Yotsuba</a> | ';
$dat.='<a href="#" onclick="setActiveStyleSheet(\'Yotsuba B\'); return false;">Yotsuba B</a> | ';
$dat.='<a href="#" onclick="setActiveStyleSheet(\'Futaba\'); return false;">Futaba</a> | ';
$dat.='<a href="#" onclick="setActiveStyleSheet(\'Burichan\'); return false;">Burichan</a>]</td></tr>';
}
$dat.='</table>';
if(!$resno){ // if not in res display mode
$prev = $st - PAGE_DEF;
$next = $st + PAGE_DEF;
// Page navigation
$dat.="<table class=pages align=left border=1><tr>";
if($prev >= 0){ //ok to make prev button
if($prev==0){
$dat.="<form action=\"".PHP_SELF2."\" onsubmit='location=this.action;return false;' method=get><td>";
}else{
$dat.="<form action=\"".$prev/PAGE_DEF.PHP_EXT."\" onsubmit='location=this.action;return false;' method=get><td>";
}
$dat.="<input type=submit value=\"".S_PREV."\" accesskey=\"z\">";
$dat.="</td></form>";
}else{$dat.="<td>".S_FIRSTPG."</td>";}
// page listing
$dat.="<td>";
for($i = 0; $i < $counttree ; $i+=PAGE_DEF){