/
MySQL.pm
7414 lines (6408 loc) · 218 KB
/
MySQL.pm
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
# This code is a part of Slash, and is released under the GPL.
# Copyright 1997-2003 by Open Source Development Network. See README
# and COPYING for more information, or see http://slashcode.com/.
# $Id$
package Slash::DB::MySQL;
use strict;
use Socket;
use Digest::MD5 'md5_hex';
use Time::HiRes;
use Date::Format qw(time2str);
use Slash::Utility;
use Storable qw(thaw freeze);
use URI ();
use vars qw($VERSION);
use base 'Slash::DB';
use base 'Slash::DB::Utility';
($VERSION) = ' $Revision$ ' =~ /\$Revision:\s+([^\s]+)/;
# Fry: How can I live my life if I can't tell good from evil?
# For the getDescriptions() method
my %descriptions = (
'sortcodes'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='sortcodes'") },
'generic'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='$_[2]'") },
'genericstring'
=> sub { $_[0]->sqlSelectMany('code,name', 'string_param', "type='$_[2]'") },
'statuscodes'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='statuscodes'") },
'yes_no'
=> sub { $_[0]->sqlSelectMany('code,name', 'string_param', "type='yes_no'") },
'submission-notes'
=> sub { $_[0]->sqlSelectMany('code,name', 'string_param', "type='submission-notes'") },
'submission-state'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='submission-state'") },
'months'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='months'") },
'years'
=> sub { $_[0]->sqlSelectMany('name,name', 'code_param', "type='years'") },
'blocktype'
=> sub { $_[0]->sqlSelectMany('name,name', 'code_param', "type='blocktype'") },
'tzcodes'
=> sub { $_[0]->sqlSelectMany('tz,off_set', 'tzcodes') },
'tzdescription'
=> sub { $_[0]->sqlSelectMany('tz,description', 'tzcodes') },
'dateformats'
=> sub { $_[0]->sqlSelectMany('id,description', 'dateformats') },
'datecodes'
=> sub { $_[0]->sqlSelectMany('id,format', 'dateformats') },
'discussiontypes'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='discussiontypes'") },
'commentmodes'
=> sub { $_[0]->sqlSelectMany('mode,name', 'commentmodes') },
'threshcodes'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='threshcodes'") },
'threshcode_values'
=> sub { $_[0]->sqlSelectMany('code,code', 'code_param', "type='threshcodes'") },
'postmodes'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='postmodes'") },
'isolatemodes'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='isolatemodes'") },
'issuemodes'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='issuemodes'") },
'vars'
=> sub { $_[0]->sqlSelectMany('name,name', 'vars') },
'topics'
=> sub { $_[0]->sqlSelectMany('tid,alttext', 'topics') },
'topic_images_section'
=> sub { $_[0]->sqlSelectMany('concat(tid, "|", section), topic_image', 'topic_image_sections') },
'topics_all'
=> sub { $_[0]->sqlSelectMany('tid,alttext', 'topics') },
'topics_section'
=> sub {
my $SECT = $_[0]->getSection($_[2]);
my $where;
if ($SECT->{type} eq 'collected') {
$where = " section IN ('" . join("','", @{$SECT->{contained}}) . "')"
if $SECT->{contained} && @{$SECT->{contained}};
} else {
$where = " section = " . $_[0]->sqlQuote($SECT->{section});
}
$where .= " AND " if $where;
$_[0]->sqlSelectMany('topics.tid,topics.alttext', 'topics, section_topics', "$where section_topics.tid=topics.tid")
},
'topics_section_type'
=> sub { $_[0]->sqlSelectMany('topics.tid as tid,topics.alttext as alttext', 'topics, section_topics', "section='$_[2]' AND section_topics.tid=topics.tid AND type= '$_[3]'") },
'section_subsection'
=> sub { $_[0]->sqlSelectMany('subsections.id, subsections.alttext', 'subsections, section_subsections', 'section_subsections.section=' . $_[0]->sqlQuote($_[2]) . ' AND subsections.id = section_subsections.subsection', 'ORDER BY alttext') },
'section_subsection_names'
=> sub { $_[0]->sqlSelectMany('title, id', 'subsections') },
'maillist'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='maillist'") },
'session_login'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='session_login'") },
'sortorder'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='sortorder'") },
'displaycodes'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='displaycodes'") },
'displaycodes_sectional'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='displaycodes_sectional'") },
'commentcodes'
=> sub { my $user = getCurrentUser();
my $where = " OR type='commentcodes_extended'" if $user->{is_admin} || $user->{is_subscriber};
$_[0]->sqlSelectMany('code,name', 'string_param', "type='commentcodes'" . $where)
},
'sections'
=> sub { $_[0]->sqlSelectMany('section,title', 'sections', 'type="contained"', 'order by title') },
'sections-contained'
=> sub { $_[0]->sqlSelectMany('section,title', 'sections', 'type="contained"', 'order by title') },
'sections-all'
=> sub { $_[0]->sqlSelectMany('section,title', 'sections', '', 'order by title') },
'static_block'
=> sub { $_[0]->sqlSelectMany('bid,bid', 'blocks', "$_[2] >= seclev AND type != 'portald'") },
'portald_block'
=> sub { $_[0]->sqlSelectMany('bid,bid', 'blocks', "$_[2] >= seclev AND type = 'portald'") },
'static_block_section'
=> sub { $_[0]->sqlSelectMany('bid,bid', 'blocks', "$_[2]->{seclev} >= seclev AND section='$_[2]->{section}' AND type != 'portald'") },
'portald_block_section'
=> sub { $_[0]->sqlSelectMany('bid,bid', 'blocks', "$_[2]->{seclev} >= seclev AND section='$_[2]->{section}' AND type = 'portald'") },
'color_block'
=> sub { $_[0]->sqlSelectMany('bid,bid', 'blocks', "type = 'color'") },
'authors'
=> sub { $_[0]->sqlSelectMany('uid,nickname', 'authors_cache', "author = 1") },
'all-authors'
=> sub { $_[0]->sqlSelectMany('uid,nickname', 'authors_cache') },
'admins'
=> sub { $_[0]->sqlSelectMany('uid,nickname', 'users', 'seclev >= 100') },
'users'
=> sub { $_[0]->sqlSelectMany('uid,nickname', 'users') },
'templates'
=> sub { $_[0]->sqlSelectMany('tpid,name', 'templates') },
'templatesbypage'
=> sub { $_[0]->sqlSelectMany('tpid,name', 'templates', "page = '$_[2]'") },
'templatesbysection'
=> sub { $_[0]->sqlSelectMany('tpid,name', 'templates', "section = '$_[2]'") },
'keywords'
=> sub { $_[0]->sqlSelectMany('id,CONCAT(keyword, " - ", name)', 'related_links') },
'pages'
=> sub { $_[0]->sqlSelectMany('distinct page,page', 'templates') },
'templatesections'
=> sub { $_[0]->sqlSelectMany('distinct section, section', 'templates') },
'sectionblocks'
=> sub { $_[0]->sqlSelectMany('bid,title', 'blocks', 'portal=1') },
'plugins'
=> sub { $_[0]->sqlSelectMany('value,description', 'site_info', "name='plugin'") },
'site_info'
=> sub { $_[0]->sqlSelectMany('name,value', 'site_info', "name != 'plugin'") },
'topic-sections'
=> sub { $_[0]->sqlSelectMany('section,type', 'section_topics', "tid = '$_[2]'") },
'forms'
=> sub { $_[0]->sqlSelectMany('value,value', 'site_info', "name = 'form'") },
'journal_discuss'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='journal_discuss'") },
'section_extra_types'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='extra_types'") },
'section-types'
=> sub { $_[0]->sqlSelectMany('code,name', 'string_param', "type='section_types'") },
'otherusersparam',
=> sub { $_[0]->sqlSelectMany('code,name', 'string_param', "type='otherusersparam'") },
countries => sub {
$_[0]->sqlSelectMany(
'code,CONCAT(code," (",name,")") as name',
'string_param',
'type="iso_countries"',
'ORDER BY name'
);
},
);
########################################################
sub _whereFormkey {
my($self) = @_;
my $ipid = getCurrentUser('ipid');
my $uid = getCurrentUser('uid');
my $where;
# anonymous user without cookie, check host, not ipid
if (isAnon($uid)) {
$where = "ipid = '$ipid'";
} else {
$where = "uid = '$uid'";
}
return $where;
};
########################################################
# Notes:
# formAbuse, use defaults as ENV, be able to override
# (pudge idea).
# description method cleanup. (done)
# fetchall_rowref vs fetch the hashses and push'ing
# them into an array (good arguments for both)
# break up these methods into multiple classes and
# use the dB classes to override methods (this
# could end up being very slow though since the march
# is kinda slow...).
# the getAuthorEdit() methods need to be refined
########################################################
########################################################
sub init {
my($self) = @_;
# These are here to remind us of what exists
$self->{_storyBank} = {};
$self->{_codeBank} = {};
$self->{_sectionBank} = {};
$self->{_boxes} = {};
$self->{_sectionBoxes} = {};
$self->{_comment_text} = {};
$self->{_comment_text_full} = {};
$self->{_story_comm} = {};
# Do all cache elements contain '_cache_' in it, if so, we should
# probably perform a delete on anything matching, here.
}
########################################################
# Yes, this is ugly, and we can ditch it in about 6 months
# Turn off autocommit here
sub sqlTransactionStart {
my($self, $arg) = @_;
$self->sqlDo($arg);
}
########################################################
# Put commit here
sub sqlTransactionFinish {
my($self) = @_;
$self->sqlDo("UNLOCK TABLES");
}
########################################################
# In another DB put rollback here
sub sqlTransactionCancel {
my($self) = @_;
$self->sqlDo("UNLOCK TABLES");
}
########################################################
# Bad need of rewriting....
sub createComment {
my($self, $comment) = @_;
my $comment_text = $comment->{comment};
delete $comment->{comment};
$comment->{signature} = md5_hex($comment_text);
$comment->{-date} = 'NOW()';
$comment->{len} = length($comment_text);
$comment->{pointsorig} = $comment->{points} || 0;
$self->{_dbh}->{AutoCommit} = 0;
my $cid;
if ($self->sqlInsert('comments', $comment)) {
$cid = $self->getLastInsertId();
} else {
$self->{_dbh}->rollback;
$self->{_dbh}->{AutoCommit} = 1;
errorLog("$DBI::errstr");
return -1;
}
unless ($self->sqlInsert('comment_text', {
cid => $cid,
comment => $comment_text,
})) {
$self->{_dbh}->rollback;
$self->{_dbh}->{AutoCommit} = 1;
errorLog("$DBI::errstr");
return -1;
}
# should this be conditional on the others happening?
# is there some sort of way to doublecheck that this value
# is correct? -- pudge
# This is fine as is; if the insert failed, we've already
# returned out of this method. - Jamie
unless ($self->sqlUpdate(
"discussions",
{ -commentcount => 'commentcount+1' },
"id=$comment->{sid}",
)) {
$self->{_dbh}->rollback;
$self->{_dbh}->{AutoCommit} = 1;
errorLog("$DBI::errstr");
return -1;
}
$self->{_dbh}->commit;
$self->{_dbh}->{AutoCommit} = 1;
return $cid;
}
########################################################
# Right now, $from and $reason don't matter, but they
# might someday.
sub getModPointsNeeded {
my($self, $from, $to, $reason) = @_;
# Always 1 point for a downmod.
return 1 if $to < $from;
my $constants = getCurrentStatic();
my $pn = $constants->{mod_up_points_needed} || {};
return $pn->{$to} || 1;
}
########################################################
# Given a fractional value representing the fraction of fair M2
# votes, returns the token/karma consequences of that fraction
# in a hashref. Makes the very complex var m2_consequences a
# little easier to use. Note that the value returned has three
# fields: a float, its sign, and an SQL expression which may be
# either an integer or an IF().
sub getM2Consequences {
my($self, $frac) = @_;
my $constants = getCurrentStatic();
my $c = $constants->{m2_consequences};
my $retval = { };
for my $ckey (sort { $a <=> $b } keys %$c) {
if ($frac <= $ckey) {
my @vals = @{$c->{$ckey}};
for my $key (qw( m2_fair_tokens
m2_unfair_tokens
m1_tokens
m1_karma )) {
$retval->{$key}{num} = shift @vals;
}
for my $key (keys %$retval) {
$self->_set_csq($key, $retval->{$key});
}
last;
}
}
return $retval;
}
sub _set_csq {
my($self, $key, $hr) = @_;
my $n = $hr->{num};
if (!$n) {
$hr->{chance} = $hr->{sign} = 0;
$hr->{sql_base} = $hr->{sql_possible} = "";
$hr->{sql_and_where} = undef;
return ;
}
my $constants = getCurrentStatic();
my $column = 'tokens';
$column = 'karma' if $key =~ /karma$/;
my $max = ($column eq 'tokens')
? $constants->{m2_consequences_token_max}
: $constants->{m2_maxbonus_karma};
my $min = ($column eq 'tokens')
? $constants->{m2_consequences_token_min}
: $constants->{minkarma};
my $sign = 1; $sign = -1 if $n < 0;
$hr->{sign} = $sign;
my $a = abs($n);
my $i = int($a);
$hr->{chance} = $a - $i;
$hr->{num_base} = $i * $sign;
$hr->{num_possible} = ($i+1) * $sign;
if ($sign > 0) {
$hr->{sql_and_where}{$column} = "$column < $max";
$hr->{sql_base} = $i ? "LEAST($column+$i, $max)" : "";
$hr->{sql_possible} = "LEAST($column+" . ($i+1) . ", $max)"
if $hr->{chance};
} else {
$hr->{sql_and_where}{$column} = "$column > $min";
$hr->{sql_base} = $i ? "GREATEST($column-$i, $min)" : "";
$hr->{sql_possible} = "GREATEST($column-" . ($i+1) . ", $min)"
if $hr->{chance};
}
}
########################################################
sub createModeratorLog {
my($self, $comment, $user, $val, $reason, $active, $points_spent) = @_;
$active = 1 unless defined $active;
$points_spent = 1 unless defined $points_spent;
$self->sqlInsert("moderatorlog", {
uid => $user->{uid},
ipid => $user->{ipid} || "",
subnetid => $user->{subnetid} || "",
val => $val,
sid => $comment->{sid},
cid => $comment->{cid},
cuid => $comment->{uid},
reason => $reason,
-ts => 'NOW()',
active => $active,
spent => $points_spent,
});
}
########################################################
# A friendlier interface to the "mods_saved" param. Has probably
# more sanity-checking than it needs.
sub getModsSaved {
my($self, $user) = @_;
$user = getCurrentUser() if !$user;
my $mods_saved = $user->{mods_saved} || "";
return ( ) if !$mods_saved;
my %mods_saved =
map { ( $_, 1 ) }
grep /^\d+$/,
split ",", $mods_saved;
return sort { $a <=> $b } keys %mods_saved;
}
sub setModsSaved {
my($self, $user, $mods_saved_ar) = @_;
$user = getCurrentUser() if !$user;
my $mods_saved_txt = join(",",
sort { $a <=> $b }
grep /^\d+$/,
@$mods_saved_ar);
$self->setUser($user->{uid}, { mods_saved => $mods_saved_txt });
}
########################################################
# This is the method that returns the list of comments for a user to
# metamod, at any given time. Its logic was changed significantly
# in August 2002.
sub getMetamodsForUser {
my($self, $user, $num_comments) = @_;
my $constants = getCurrentStatic();
# First step is to see what the user already has marked down to
# be metamoderated. If there are any such id's, that still
# aren't done being M2'd, keep those on the user's to-do list.
# (I.e., once a user sees a list of mods, they keep seeing that
# same list until they click the button; reloading the page
# won't give them new mods.) If after this check, the list is
# short of the requisite number, fill up the list, re-save it,
# and return it.
# Get saved list of mods to M2 (and check its formatting).
my @mods_saved = $self->getModsSaved($user);
# See which still need M2'ing.
if (@mods_saved) {
my $mods_saved = join(",", @mods_saved);
my $mods_not_done = $self->sqlSelectColArrayref(
"id",
"moderatorlog",
"id IN ($mods_saved) AND active=1 AND m2status=0"
);
@mods_saved = grep /^\d+$/, @$mods_not_done;
}
# If we need more, get more.
my $num_needed = $num_comments - scalar(@mods_saved);
if ($num_needed) {
my %mods_saved = map { ( $_, 1 ) } @mods_saved;
my $new_mods = $self->getMetamodsForUserRaw($user->{uid},
$num_needed, \%mods_saved);
for my $id (@$new_mods) { $mods_saved{$id} = 1 }
@mods_saved = sort { $a <=> $b } keys %mods_saved;
}
$self->setModsSaved($user, \@mods_saved);
# If we didn't get enough, that's OK, but note it in the
# error log.
if (scalar(@mods_saved) < $num_comments) {
errorLog("M2 gave uid $user->{uid} "
. scalar(@mods_saved)
. " comments, wanted $num_comments: "
. join(",", @mods_saved)
);
}
# OK, we have the list of moderations this user needs to M2,
# and we have updated the user's data so the next time they
# come back they'll see the same list. Now just retrieve
# the necessary data for those moderations and return it.
return $self->_convertModsToComments(@mods_saved);
}
{ # closure
my %anonymize = ( ); # gets set inside the function
sub _convertModsToComments {
my($self, @mods) = @_;
my $constants = getCurrentStatic();
return { } unless scalar(@mods);
if (!scalar(keys %anonymize)) {
%anonymize = (
nickname => '-',
uid => getCurrentStatic('anonymous_coward_uid'),
points => 0,
);
}
my $mods_text = join(",", @mods);
# We can and probably should get the cid/reason data in
# getMetamodsForUserRaw(), but it's only a minor performance
# slowdown for now.
my $mods_hr = $self->sqlSelectAllHashref(
"id",
"id, cid, reason AS modreason",
"moderatorlog",
"id IN ($mods_text)"
);
my @cids = map { $mods_hr->{$_}{cid} } keys %$mods_hr;
my $cids_text = join(",", @cids);
# Get the comment data required to show the user the list of mods.
my $comments_hr = $self->sqlSelectAllHashref(
"cid",
"comments.cid AS cid, comments.sid AS sid,
comments.uid AS uid,
date, subject, pid, reason, comment,
discussions.sid AS discussions_sid,
title,
sig, nickname",
"comments, comment_text, discussions, users",
"comments.cid IN ($cids_text)
AND comments.cid = comment_text.cid
AND comments.uid = users.uid
AND comments.sid = discussions.id"
);
# Put the comment data into the mods hashref.
for my $mod_id (keys %$mods_hr) {
my $mod_hr = $mods_hr->{$mod_id}; # This mod.
my $cid = $mod_hr->{cid};
my $com_hr = $comments_hr->{$cid}; # This mod's comment.
for my $key (keys %$com_hr) {
next if exists($mod_hr->{$key});
my $val = $com_hr->{$key};
# Anonymize comment identity a bit for fairness.
$val = $anonymize{$key} if exists $anonymize{$key};
$mod_hr->{$key} = $val;
}
if ($mod_hr->{discussions_sid}) {
# This is a comment posted to a story discussion, so
# we can link straight to the story, providing even
# more context for this comment.
$mod_hr->{url} = getCurrentStatic('rootdir')
. "/article.pl?sid=$mod_hr->{discussions_sid}";
} else {
# This is a comment posted to a discussion that isn't
# a story. It could be attached to a poll, a journal
# entry, or nothing at all (user-created discussion).
# Whatever the case, we can't trust the url field, so
# we should just link to the discussion itself.
$mod_hr->{url} = getCurrentStatic('rootdir')
. "/comments.pl?sid=$mod_hr->{sid}";
}
$mod_hr->{no_moderation} = 1;
}
# Copy the hashref into an arrayref, along the way doing a last-minute
# check to make sure every comment has an sid. We're going to sort
# this arrayref first by sid, then by cid, and last by mod id, so mods
# that share a story or even a comment will appear together, saving
# the user a bit of confusion.
my @final_mods = ( );
for my $mod_id (
sort {
$mods_hr->{$a}{sid} <=> $mods_hr->{$b}{sid}
||
$mods_hr->{$a}{cid} <=> $mods_hr->{$b}{cid}
||
$a <=> $b
} keys %$mods_hr
) {
# This "next" is a holdover from old code - is this really
# necessary!? Every cid has a discussion and every
# discussion has an sid.
next unless $mods_hr->{$mod_id}{sid};
push @final_mods, $mods_hr->{$mod_id};
}
return \@final_mods;
}
}
sub getReasons {
my($self) = @_;
my $cache_enabled = getCurrentStatic('cache_enabled');
my $reasons = $self->{_reasons_cache} || undef;
if (!$reasons) {
$reasons = $self->sqlSelectAllHashref(
"id", "*", "modreasons"
);
$self->{_reasons_cache} = $reasons if $cache_enabled;
}
if ($cache_enabled) {
# Return a copy of the cache, just in case anyone munges it up.
$reasons = {( %$reasons )};
}
return $reasons;
}
# Get a list of moderations that the given uid is able to metamod,
# with the oldest not-yet-done mods given highest priority.
sub getMetamodsForUserRaw {
my($self, $uid, $num_needed, $already_have_hr) = @_;
my $uid_q = $self->sqlQuote($uid);
my $constants = getCurrentStatic();
my $reasons = $self->getReasons();
my $m2able_reasons = join(",",
sort grep { $reasons->{$_}{m2able} }
keys %$reasons);
return [ ] if !$m2able_reasons;
my $consensus = $constants->{m2_consensus};
my $waitpow = $constants->{m2_consensus_waitpow} || 1;
my $days_back = $constants->{archive_delay_mod};
my $days_back_cushion = int($days_back/10);
$days_back_cushion = $constants->{m2_min_daysbackcushion} || 2
if $days_back_cushion < ($constants->{m2_min_daysbackcushion} || 2);
$days_back -= $days_back_cushion;
# XXX I'm considering adding a 'WHERE m2status=0' clause to the
# MIN/MAX selects below. This might help choose mods more
# smoothly and make failure (as archive_delay_mod is approached)
# less dramatic too. On the other hand it might screw things
# up, making older mods at N-1 M2's never make it to N. I've
# run tests on changes like this before and there's almost no
# way to predict accurately what it will do on a live site
# without doing it... -Jamie 2002/11/16
my $min_old = $self->getVar('m2_modlogid_min_old', 'value', 1) || 0;
my $max_old = $self->getVar('m2_modlogid_max_old', 'value', 1) || 0;
my $min_new = $self->getVar('m2_modlogid_min_new', 'value', 1) || 0;
my $max_new = $self->getVar('m2_modlogid_max_new', 'value', 1) || 0;
my $min_mid = $max_old+1;
my $max_mid = $min_new-1;
my $old_range = $max_old-$min_old; $old_range = 1 if $old_range < 1;
my $mid_range = $max_mid-$min_mid; $mid_range = 1 if $mid_range < 1;
my $new_range = $max_new-$min_new; $new_range = 1 if $new_range < 1;
# Prepare the lists of ids and cids to exclude.
my $already_id_list = "";
if (%$already_have_hr) {
$already_id_list = join ",", sort keys %$already_have_hr;
}
my $already_cids_hr = { };
my $already_cid_list = "";
if ($already_id_list) {
$already_cids_hr = $self->sqlSelectAllHashref(
"cid",
"cid",
"moderatorlog",
"id IN ($already_id_list)"
);
$already_cid_list = join(",", sort keys %$already_cids_hr);
}
my $reader = getObject('Slash::DB', { db_type => 'reader' });
# We need to consult two tables to get a list of moderatorlog IDs
# that it's OK to M2: moderatorlog of course, and metamodlog to
# check that this user hasn't M2'd them before. Because this is
# necessarily a table scan on moderatorlog, speed will be essential.
# We're going to do the select on moderatorlog first, then run its
# results through the other two tables to exclude what we can't use.
# However, since we can't predict how many of our hits will be
# deemed "bad" (unusable), we may have to loop around more than
# once to get enough.
my $getmods_loops = 0;
my @ids = ( );
my $mod_hr;
my $range_offset = 0.9;
$range_offset = $constants->{m2_range_offset}
if defined($constants->{m2_range_offset});
my $twice_range_offset = $range_offset * 2;
my $if_expr = "";
if ($waitpow != 1) {
$if_expr = <<EOT;
IF( id BETWEEN $min_old AND $max_mid,
IF(
id BETWEEN $min_old and $max_old,
POW( (id-$min_old)/$old_range, $waitpow),
POW(GREATEST((id-$min_mid)/$mid_range, 0), $waitpow)
+ $range_offset
),
POW(GREATEST((id-$min_new)/$new_range, 0), $waitpow)
+ $twice_range_offset )
EOT
} else {
$if_expr = <<EOT;
IF( id BETWEEN $min_old AND $max_mid,
IF(
id BETWEEN $min_old and $max_old,
(id-$min_old)/$old_range,
(id-$min_mid)/$mid_range
+ $range_offset
),
(id-$min_new)/$new_range
+ $twice_range_offset )
EOT
}
GETMODS: while ($num_needed > 0 && ++$getmods_loops <= 3) {
my $limit = $num_needed*2+10; # get more, hope it's enough
my $already_id_clause = "";
$already_id_clause = " AND id NOT IN ($already_id_list)"
if $already_id_list;
my $already_cid_clause = "";
$already_cid_clause = " AND cid NOT IN ($already_cid_list)"
if $already_cid_list;
$mod_hr = { };
$mod_hr = $reader->sqlSelectAllHashref(
"id",
"id, cid,
m2count + $consensus * $if_expr + RAND() AS rank",
"moderatorlog",
"uid != $uid_q AND cuid != $uid_q
AND m2status=0
AND reason IN ($m2able_reasons)
AND active=1
$already_id_clause $already_cid_clause",
"ORDER BY rank LIMIT $limit"
);
last GETMODS if !$mod_hr || !scalar(keys %$mod_hr);
# Exclude any moderations this user has already metamodded.
my $mod_ids = join ",", keys %$mod_hr;
my %mod_ids_bad = map { ( $_, 1 ) }
$self->sqlSelectColArrayref("mmid", "metamodlog",
"mmid IN ($mod_ids) AND uid = $uid_q");
# Add the new IDs to the list.
my @potential_new_ids =
# In order by rank, in case we got more than needed.
sort { $mod_hr->{$a}{rank} <=> $mod_hr->{$b}{rank} }
keys %$mod_hr;
# Walk through the new potential mod IDs, and add them in
# one at a time. Those which are for cids already on our
# list, or for mods this user has already metamodded, don't
# make the cut.
my @new_ids = ( );
for my $id (@potential_new_ids) {
my $cid = $mod_hr->{$id}{cid};
next if $already_cids_hr->{$cid};
next if $mod_ids_bad{$id};
push @new_ids, $id;
$already_cids_hr->{$cid} = 1;
}
$#new_ids = $num_needed-1 if $#new_ids > $num_needed-1;
push @ids, @new_ids;
$num_needed -= scalar(@new_ids);
}
if ($getmods_loops > 3) {
use Data::Dumper;
print STDERR "GETMODS looped the max number of times,"
. " returning '@ids' for uid '$uid'"
. " num_needed '$num_needed'"
. " (maybe out of mods to M2?)"
. " already_had: " . Dumper($already_have_hr);
}
return \@ids;
}
########################################################
# ok, I was tired of trying to mould getDescriptions into
# taking more args.
sub getTemplateList {
my($self, $section, $page) = @_;
my $templatelist = {};
my $where = "seclev <= " . getCurrentUser('seclev');
$where .= " AND section = '$section'" if $section;
$where .= " AND page = '$page'" if $page;
my $templates = $self->sqlSelectMany('tpid,name', 'templates', $where);
while (my($tpid, $name) = $templates->fetchrow) {
$templatelist->{$tpid} = $name;
}
return $templatelist;
}
########################################################
sub getModeratorCommentLog {
my($self, $asc_desc, $limit, $type, $value) = @_;
$asc_desc ||= 'ASC';
$asc_desc = uc $asc_desc;
$asc_desc = 'ASC' if $asc_desc ne 'DESC';
if ($limit and $limit =~ /^(\d+)$/) {
$limit = "LIMIT $1";
} else {
$limit = "";
}
my $select_extra = (($type =~ /ipid/) || ($type =~ /subnetid/)) ? ", comments.uid as uid2, comments.ipid as ipid2" : "";
my $vq = $self->sqlQuote($value);
my $where_clause = "";
my $ipid_table = "moderatorlog";
if ($type eq 'uid') { $where_clause = "moderatorlog.uid=$vq AND comments.uid=users.uid";
$ipid_table = "comments" }
elsif ($type eq 'cid') { $where_clause = "moderatorlog.cid=$vq AND moderatorlog.uid=users.uid" }
elsif ($type eq 'cuid') { $where_clause = "moderatorlog.cuid=$vq AND moderatorlog.uid=users.uid" }
elsif ($type eq 'subnetid') { $where_clause = "comments.subnetid=$vq AND moderatorlog.uid=users.uid" }
elsif ($type eq 'ipid') { $where_clause = "comments.ipid=$vq AND moderatorlog.uid=users.uid" }
elsif ($type eq 'bsubnetid') { $where_clause = "moderatorlog.subnetid=$vq AND moderatorlog.uid=users.uid" }
elsif ($type eq 'bipid') { $where_clause = "moderatorlog.ipid=$vq AND moderatorlog.uid=users.uid" }
return [ ] unless $where_clause;
my $comments = $self->sqlSelectMany("comments.sid AS sid,
comments.cid AS cid,
comments.points AS score,
users.uid AS uid,
users.nickname AS nickname,
$ipid_table.ipid AS ipid,
moderatorlog.val AS val,
moderatorlog.reason AS reason,
moderatorlog.ts AS ts,
moderatorlog.active AS active
$select_extra",
"moderatorlog, users, comments",
"$where_clause
AND moderatorlog.cid=comments.cid",
"ORDER BY ts $asc_desc $limit"
);
my(@comments, $comment);
push @comments, $comment while ($comment = $comments->fetchrow_hashref);
return \@comments;
}
########################################################
sub getModeratorLogID {
my($self, $cid, $uid) = @_;
# We no longer need the SID as CID is now unique.
my($mid) = $self->sqlSelect(
"id", "moderatorlog", "uid=$uid and cid=$cid"
);
return $mid;
}
########################################################
sub undoModeration {
my($self, $uid, $sid) = @_;
my $constants = getCurrentStatic();
# SID here really refers to discussions.id, NOT stories.sid
my $cursor = $self->sqlSelectMany("cid,val,active,cuid,reason",
"moderatorlog",
"moderatorlog.uid=$uid and moderatorlog.sid=$sid"
);
my $min_score = $constants->{comment_minscore};
my $max_score = $constants->{comment_maxscore};
my $min_karma = $constants->{minkarma};
my $max_karma = $constants->{maxkarma};
my @removed;
while (my($cid, $val, $active, $cuid, $reason) = $cursor->fetchrow){
# If moderation wasn't actually performed, we skip ahead one.
next if ! $active;
# We undo moderation even for inactive records (but silently for
# inactive ones...). Leave them in the table but inactive, so
# they are still eligible to be metamodded.
$self->sqlUpdate("moderatorlog",
{ active => 0 },
"cid=$cid and uid=$uid"
);
my $comm_update = { };
# Adjust the comment score up or down, but don't push it beyond the
# maximum or minimum.
my $adjust = -$val;
$adjust =~ s/^([^+-])/+$1/;
$comm_update->{-points} =
$adjust > 0
? "LEAST($max_score, points $adjust)"
: "GREATEST($min_score, points $adjust)";
# Recalculate the comment's reason.
$comm_update->{reason} = $self->getCommentMostCommonReason($cid)
|| 0; # no active moderations? reset reason to empty
$self->sqlUpdate("comments", $comm_update, "cid=$cid");
# Restore modded user's karma, again within the proper boundaries.
# XXX If we don't care about tracking the Anonymous Coward's karma,
# here's a place to take it out.
$self->sqlUpdate(
"users_info",
{ -karma => $adjust > 0
? "LEAST($max_karma, karma $adjust)"
: "GREATEST($min_karma, karma $adjust)" },
"uid=$cuid"
);
push @removed, {
cid => $cid,
reason => $reason,
val => $val,
};
}
return \@removed;
}
########################################################
sub deleteSectionTopicsByTopic {
my($self, $tid, $type) = @_;
# $type ||= 1; # ! is the default type
# arghghg no, it's not, and this caused