-
Notifications
You must be signed in to change notification settings - Fork 8
/
MySQL.pm
4620 lines (3901 loc) · 128 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-2001 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 Digest::MD5 'md5_hex';
use HTML::Entities;
use Slash::Utility;
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 getDecriptions() method
my %descriptions = (
'sortcodes'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='$_[1]'") },
'generic'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='$_[2]'") },
'statuscodes'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='statuscodes'") },
'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'") },
'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') },
'topics_all'
=> sub { $_[0]->sqlSelectMany('tid,alttext', 'topics') },
'topics_section'
=> sub { $_[0]->sqlSelectMany('topics.tid,topics.alttext', 'topics, section_topics', "section='$_[2]' AND section_topics.tid=topics.tid") },
'maillist'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='maillist'") },
'session_login'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='session_login'") },
'displaycodes'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='displaycodes'") },
'commentcodes'
=> sub { $_[0]->sqlSelectMany('code,name', 'code_param', "type='commentcodes'") },
'sections'
=> sub { $_[0]->sqlSelectMany('section,title', 'sections', 'isolate=0', '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'") },
'color_block'
=> sub { $_[0]->sqlSelectMany('bid,bid', 'blocks', "type = 'color'") },
'authors'
=> sub { $_[0]->sqlSelectMany('U.uid,U.nickname', 'users as U, users_param as P', "P.name = 'author' AND U.uid = P.uid and P.value = 1") },
'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,1', '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'") },
);
########################################################
sub _whereFormkey {
my($self, $formkey_id) = @_;
my $where;
my $user = getCurrentUser();
# anonymous user without cookie, check host, not formkey id
if ($user->{anon_id} && ! $user->{anon_cookie}) {
$where = "ipid = '$user->{ipid}'";
} else {
$where = "id='$formkey_id'";
}
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} = {};
}
#######################################################
# Wrapper to get the latest ID from the database
sub getLastInsertId {
my($self, $table, $col) = @_;
my($answer) = $self->sqlSelect('LAST_INSERT_ID()');
return $answer;
}
########################################################
# 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, $user, $pts, $default_user) = @_;
my $header = $comment->{sid};
my $cid;
my $signature = md5_hex($comment->{postercomment});
my $uid = $comment->{postanon} ? $default_user : $user->{uid};
# Basically, this makes sure that the thread is not
# been set read only -Brian
return -1 if ($self->getDiscussion($header, 'type') == 2);
my $insline = "INSERT into comments (sid,pid,date,ipid,subnetid,subject,uid,points,signature) values ($header," .
$self->sqlQuote($comment->{pid}) . ",now(),'$user->{ipid}','$user->{subnetid}'," .
$self->sqlQuote($comment->{postersubj}) . ", $uid, $pts, '$signature')";
if ($self->sqlDo($insline)) {
$cid = $self->getLastInsertId();
} else {
errorLog("$DBI::errstr $insline");
return -1;
}
$self->sqlInsert('comment_text', {
cid => $cid,
comment => $comment->{postercomment},
});
if (getCurrentStatic('mysql_heap_table')) {
my $insline = "INSERT into comment_heap (sid,cid,pid,date,ipid,subnetid,subject,uid,points,signature) values ($header,$cid," .
$self->sqlQuote($comment->{pid}) . ",now(),'$user->{ipid}','$user->{subnetid}'," .
$self->sqlQuote($comment->{postersubj}) . ", $uid, $pts, '$signature')";
$self->sqlDo($insline) or errorLog("$DBI::errstr $insline");
}
# 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
$self->sqlUpdate(
"discussions",
{
-commentcount => 'commentcount+1',
flags => "dirty",
},
"id=$header",
);
return $cid;
}
########################################################
sub setModeratorLog {
my($self, $sid, $cid, $uid, $val, $reason, $active) = @_;
$active ||= 1;
$self->sqlInsert("moderatorlog", {
uid => $uid,
val => $val,
sid => $sid,
cid => $cid,
reason => $reason,
-ts => 'now()',
active => $active,
});
}
########################################################
#this is broke right now -Brian
#
# Work, dammit! - Cliff
sub getMetamodComments {
my($self, $id, $uid, $num_comments) = @_;
my $comment_table = getCurrentStatic('mysql_heap_table') ? 'comment_heap' : 'comments';
# Removed extraneous "users.uid!=$uid" from WHERE clause.
# Also removed "sig" from field list as we anonymize it below.
my $sth = $self->sqlSelectMany(
"$comment_table.cid, $comment_table.sid as sid, date, subject, comment,
users.uid as uid, pid, moderatorlog.id as id,
moderatorlog.reason as modreason, $comment_table.reason,
title, url",
"$comment_table, comment_text, users, users_info, moderatorlog, discussions",
"moderatorlog.cid = $comment_table.cid
AND moderatorlog.id > $id
AND $comment_table.uid != $uid AND moderatorlog.uid != $uid
AND users.uid = $comment_table.uid AND users_info.uid = $comment_table.uid
AND moderatorlog.sid = discussions.id
AND comment_text.cid = $comment_table.cid
AND moderatorlog.reason < 8",
"LIMIT $num_comments"
);
my $comments = [];
while (my $comment = $sth->fetchrow_hashref) {
# Anonymize comment that is to be metamoderated.
@{$comment}{qw(nickname uid points sig)} =
('-', getCurrentStatic('anonymous_coward_uid'), 0, '');
push @$comments, $comment;
}
$sth->finish;
formatDate($comments);
return $comments;
}
########################################################
sub getModeratorCommentLog {
my($self, $cid) = @_;
# why was this removed? -- pudge
# "moderatorlog.active=1
# Probably by accident. -Brian
#
# I've replaced it. - Cliff
my $comment_table = getCurrentStatic('mysql_heap_table') ? 'comment_heap' : 'comments';
# We no longer need SID as CID is now unique.
my $comments = $self->sqlSelectMany("$comment_table.sid as sid,
$comment_table.cid as cid,
$comment_table.points as score,
moderatorlog.uid as uid,
users.nickname as nickname,
moderatorlog.val as val,
moderatorlog.reason as reason,
moderatorlog.ts as ts,
moderatorlog.active as active",
"moderatorlog, users, $comment_table",
"moderatorlog.cid=$cid
AND moderatorlog.uid=users.uid
AND $comment_table.cid=$cid
AND moderatorlog.active=1",
"ORDER BY ts"
);
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 unsetModeratorlog {
my($self, $uid, $sid, $max, $min) = @_;
my $constants = getCurrentStatic();
# SID here really refers to discussions.id, NOT stories.sid
my $cursor = $self->sqlSelectMany("cid,val,active", "moderatorlog",
"moderatorlog.uid=$uid and moderatorlog.sid=$sid"
);
$max ||= $constants->{comment_maxscore};
$min ||= $constants->{comment_minscore};
my @removed;
while (my($cid, $val, $active) = $cursor->fetchrow){
# We undo moderation even for inactive records (but silently for
# inactive ones...)
$self->sqlDo("delete from moderatorlog where
cid=$cid and uid=$uid"
);
# If moderation wasn't actually performed, we skip ahead one.
next if ! $active;
# Insure scores still fall within the proper boundaries
my $scorelogic = $val < 0 ? "points < $max" : "points > $min";
$self->sqlUpdate(
"comments",
{ -points => "points+" . (-1 * $val) },
"cid=$cid AND $scorelogic"
);
if ($constants->{mysql_heap_table}) {
$self->sqlUpdate(
"comment_heap",
{ -points => "points+" . (-1 * $val) },
"cid=$cid AND $scorelogic"
);
}
push(@removed, $cid);
}
return \@removed;
}
########################################################
sub deleteSectionTopicsByTopic {
my($self, $tid) = @_;
$self->sqlDo("DELETE FROM section_topics WHERE tid=$tid");
}
########################################################
sub deleteRelatedLink {
my($self, $id) = @_;
$self->sqlDo("DELETE FROM related_links WHERE id=$id");
}
########################################################
sub createSectionTopic {
my($self, $section, $tid) = @_;
$self->sqlDo("INSERT INTO section_topics (section, tid) VALUES ('$section',$tid)");
}
########################################################
sub getSectionTopicsNamesBySection {
my($self, $section) = @_;
my $answer = $self->sqlSelectColArrayref('topics.alttext', 'topics,section_topics', " section_topics.section = '$section' AND section_topics.tid = topics.tid");
return $answer;
}
########################################################
sub getContentFilters {
my($self, $formname, $field) = @_;
my $field_string = $field ne '' ? " AND field = '$field'" : " AND field != ''";
my $filters = $self->sqlSelectAll("*", "content_filters",
"regex != '' $field_string and form = '$formname'");
return $filters;
}
########################################################
sub createPollVoter {
my($self, $qid, $aid) = @_;
$self->sqlInsert("pollvoters", {
qid => $qid,
id => md5_hex($ENV{REMOTE_ADDR} . $ENV{HTTP_X_FORWARDED_FOR}),
-'time' => 'now()',
uid => $ENV{SLASH_USER}
});
$self->sqlDo("update pollquestions set
voters=voters+1 where qid=$qid");
$self->sqlDo("update pollanswers set votes=votes+1 where
qid=$qid and aid=$aid");
}
########################################################
sub createSubmission {
my($self, $submission) = @_;
return unless $submission;
$submission->{ipid} = getCurrentUser('ipid');
$submission->{subnetid} = getCurrentUser('subnetid');
my($sec, $min, $hour, $mday, $mon, $year) = localtime;
my $subid = "$hour$min$sec.$mon$mday$year";
$submission->{'-time'} = 'now()';
$submission->{'subid'} = $subid;
$self->sqlInsert('submissions', $submission);
return $subid;
}
#################################################################
sub getStoryDiscussions {
my($self) = @_;
my $story_table = getCurrentStatic('mysql_heap_table') ? 'story_heap' : 'stories';
my $discussion = $self->sqlSelectAll("discussions.sid, discussions.title, discussions.url",
"discussions, $story_table",
"displaystatus > -1 AND discussions.sid=$story_table.sid AND time <= NOW() AND type = 0",
"ORDER BY time DESC LIMIT 50"
);
return $discussion;
}
#################################################################
# Less then 2, ince 2 would be a read only discussion
sub getDiscussions {
my($self) = @_;
my $discussion = $self->sqlSelectAll("id, title, url",
"discussions",
"type < 2 AND ts <= now()",
"ORDER BY ts DESC LIMIT 50"
);
return $discussion;
}
#################################################################
# Less then 2, ince 2 would be a read only discussion
sub getDiscussionsByCreator {
my($self, $uid) = @_;
return unless $uid;
my $discussion = $self->sqlSelectAll("id, title, url",
"discussions",
"type < 2 AND ts <= now() AND uid = $uid",
"ORDER BY ts DESC LIMIT 50"
);
return $discussion;
}
########################################################
# Handles admin logins (checks the sessions table for a cookie that
# matches). Called during authentication
sub getSessionInstance {
my($self, $uid, $session_in) = @_;
my $admin_timeout = getCurrentStatic('admin_timeout');
my $session_out = '';
if ($session_in) {
# CHANGE DATE_ FUNCTION
$self->sqlDo("DELETE from sessions WHERE now() > DATE_ADD(lasttime, INTERVAL $admin_timeout MINUTE)");
my $session_in_q = $self->sqlQuote($session_in);
my($uid) = $self->sqlSelect(
'uid',
'sessions',
"session=$session_in_q"
);
if ($uid) {
$self->sqlDo("DELETE from sessions WHERE uid = '$uid' AND " .
"session != $session_in_q"
);
$self->sqlUpdate('sessions', {-lasttime => 'now()'},
"session = $session_in_q"
);
$session_out = $session_in;
}
}
if (!$session_out) {
my($title) = $self->sqlSelect('lasttitle', 'sessions',
"uid=$uid"
);
$title ||= "";
$self->sqlDo("DELETE FROM sessions WHERE uid=$uid");
$self->sqlInsert('sessions', { -uid => $uid,
-logintime => 'now()', -lasttime => 'now()',
lasttitle => $title }
);
$session_out = $self->getLastInsertId('sessions', 'session');
}
return $session_out;
}
########################################################
sub setContentFilter {
my($self, $formname) = @_;
my $form = getCurrentForm();
$self->sqlUpdate("content_filters", {
regex => $form->{regex},
form => $formname,
modifier => $form->{modifier},
field => $form->{field},
ratio => $form->{ratio},
minimum_match => $form->{minimum_match},
minimum_length => $form->{minimum_length},
err_message => $form->{err_message},
}, "filter_id=$form->{filter_id}"
);
}
########################################################
# Only Slashdot uses this method
sub setSectionExtra {
my($self, $full, $story) = @_;
if ($full && $self->sqlTableExists($story->{section}) && $story->{section}) {
my $extra = $self->sqlSelectHashref('*', $story->{section}, "sid='$story->{sid}'");
for (keys %$extra) {
$story->{$_} = $extra->{$_};
}
}
}
########################################################
# This creates an entry in the accesslog
sub createAccessLog {
my($self, $op, $dat) = @_;
my $constants = getCurrentStatic();
my $uid;
if ($ENV{SLASH_USER}) {
$uid = $ENV{SLASH_USER};
} else {
$uid = $constants->{anonymous_coward_uid};
}
my $ipid = getCurrentUser('ipid') || '';
my $subnetid = getCurrentUser('subnetid') || '';
$self->sqlInsert('accesslog', {
host_addr => $ipid,
subnetid => $subnetid,
dat => $dat,
uid => $uid,
op => $op,
-ts => 'now()',
query_string => $ENV{QUERY_STRING} || '0',
user_agent => $ENV{HTTP_USER_AGENT} || '0',
}, 1);
if ($dat =~ /\//) {
$self->sqlUpdate('stories', { -hits => 'hits+1' },
'sid=' . $self->sqlQuote($dat)
);
if ($constants->{mysql_heap_table}) {
$self->sqlUpdate('story_heap', { -hits => 'hits+1' },
'sid=' . $self->sqlQuote($dat)
);
}
}
}
########################################################
# pass in additional optional descriptions
sub getDescriptions {
my($self, $codetype, $optional, $flag, $altdescs) = @_;
return unless $codetype;
my $codeBank_hash_ref = {};
$optional ||= '';
$altdescs ||= '';
# I am extending this, without the extension the cache was
# not always returning the right data -Brian
my $cache = '_getDescriptions_' . $codetype . $optional . $altdescs;
if ($flag) {
undef $self->{$cache};
} else {
return $self->{$cache} if $self->{$cache};
}
$altdescs ||= {};
my $descref = $altdescs->{$codetype} || $descriptions{$codetype};
return $codeBank_hash_ref unless $descref;
my $sth = $descref->(@_);
while (my($id, $desc) = $sth->fetchrow) {
$codeBank_hash_ref->{$id} = $desc;
}
$sth->finish;
$self->{$cache} = $codeBank_hash_ref if getCurrentStatic('cache_enabled');
return $codeBank_hash_ref;
}
########################################################
# Get user info from the users table.
# If you don't pass in a $script, you get everything
# which is handy for you if you need the entire user
# why not just axe this entirely and always get all the data? -- pudge
# Worry about access times. Realize that when MySQL has row level
# locking that we can combine all of the user table (except param)
# into one table again. -Brian
sub getUserInstance {
my($self, $uid, $script) = @_;
my $user;
unless ($script) {
$user = $self->getUser($uid);
return $user || undef;
}
$user = $self->sqlSelectHashref('*', 'users',
' uid = ' . $self->sqlQuote($uid)
);
return undef unless $user;
my $user_extra = $self->sqlSelectHashref('*', "users_prefs", "uid=$uid");
while (my($key, $val) = each %$user_extra) {
$user->{$key} = $val;
}
# what is this for? it appears to want to do the same as the
# code above ... but this assigns a scalar to a scalar ...
# perhaps `@{$user}{ keys %foo } = values %foo` is wanted? -- pudge
# $user->{ keys %$user_extra } = values %$user_extra;
# if (!$script || $script =~ /index|article|comments|metamod|search|pollBooth/)
{
my $user_extra = $self->sqlSelectHashref('*', "users_comments", "uid=$uid");
while (my($key, $val) = each %$user_extra) {
$user->{$key} = $val;
}
}
# Do we want the index stuff?
# if (!$script || $script =~ /index/)
{
my $user_extra = $self->sqlSelectHashref('*', "users_index", "uid=$uid");
while (my($key, $val) = each %$user_extra) {
$user->{$key} = $val;
}
}
return $user;
}
########################################################
sub deleteUser {
my($self, $uid) = @_;
return unless $uid;
$self->setUser($uid, {
bio => '',
nickname => 'deleted user',
matchname => 'deleted user',
realname => 'deleted user',
realemail => '',
fakeemail => '',
newpasswd => '',
homepage => '',
passwd => '',
sig => '',
seclev => 0
});
$self->sqlDo("DELETE FROM users_param WHERE uid=$uid");
}
########################################################
# Get user info from the users table.
sub getUserAuthenticate {
my($self, $user, $passwd, $kind) = @_;
my($uid, $cookpasswd, $newpass, $dbh, $user_db,
$cryptpasswd, @pass);
return unless $user && $passwd;
# if $kind is 1, then only try to auth password as plaintext
# if $kind is 2, then only try to auth password as encrypted
# if $kind is undef or 0, try as encrypted
# (the most common case), then as plaintext
my($EITHER, $PLAIN, $ENCRYPTED) = (0, 1, 2);
my($UID, $PASSWD, $NEWPASSWD) = (0, 1, 2);
$kind ||= $EITHER;
# RECHECK LOGIC!! -- pudge
$dbh = $self->{_dbh};
$user_db = $dbh->quote($user);
$cryptpasswd = encryptPassword($passwd);
@pass = $self->sqlSelect(
'uid,passwd,newpasswd',
'users',
"uid=$user_db"
);
# try ENCRYPTED -> ENCRYPTED
if ($kind == $EITHER || $kind == $ENCRYPTED) {
if ($passwd eq $pass[$PASSWD]) {
$uid = $pass[$UID];
$cookpasswd = $passwd;
}
}
# try PLAINTEXT -> ENCRYPTED
if (($kind == $EITHER || $kind == $PLAIN) && !defined $uid) {
if ($cryptpasswd eq $pass[$PASSWD]) {
$uid = $pass[$UID];
$cookpasswd = $cryptpasswd;
}
}
# try PLAINTEXT -> NEWPASS
if (($kind == $EITHER || $kind == $PLAIN) && !defined $uid) {
if ($passwd eq $pass[$NEWPASSWD]) {
$self->sqlUpdate('users', {
newpasswd => '',
passwd => $cryptpasswd
}, "uid=$user_db");
$newpass = 1;
$uid = $pass[$UID];
$cookpasswd = $cryptpasswd;
}
}
# return UID alone in scalar context
return wantarray ? ($uid, $cookpasswd, $newpass) : $uid;
}
########################################################
# Make a new password, save it in the DB, and return it.
sub getNewPasswd {
my($self, $uid) = @_;
my $newpasswd = changePassword();
$self->sqlUpdate('users', {
newpasswd => $newpasswd
}, 'uid=' . $self->sqlQuote($uid));
return $newpasswd;
}
########################################################
# Get user info from the users table.
# May be worth it to cache this at some point
sub getUserUID {
my($self, $name) = @_;
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# We need to add BINARY to this
# as is, it may be a security flaw
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
my($uid) = $self->sqlSelect('uid', 'users',
'nickname=' . $self->sqlQuote($name)
);
return $uid;
}
########################################################
# Get user info from the users table with email address.
# May be worth it to cache this at some point
sub getUserEmail {
my($self, $email) = @_;
my($uid) = $self->sqlSelect('uid', 'users',
'realemail=' . $self->sqlQuote($email)
);
return $uid;
}
#################################################################
# Turns out it is faster to hit the disk
sub getCommentsByUID {
my($self, $uid, $min) = @_;
my $comment_table = 'comments';
my $sqlquery = "SELECT pid,sid,cid,subject,date,points "
. " FROM $comment_table WHERE uid=$uid "
. " ORDER BY date DESC LIMIT $min ";
my $sth = $self->{_dbh}->prepare($sqlquery);
$sth->execute;
my($comments) = $sth->fetchall_arrayref;
formatDate($comments, 4);
return $comments;
}
#################################################################
sub getCommentsByNetID {
my($self, $id, $min) = @_;
my $comment_table = getCurrentStatic('mysql_heap_table') ? 'comment_heap' : 'comments';
my $sqlquery = "SELECT pid,sid,cid,subject,date,points "
. " FROM $comment_table WHERE ipid='$id' "
. " ORDER BY date DESC LIMIT $min ";
my $sth = $self->{_dbh}->prepare($sqlquery);
$sth->execute;
my($comments) = $sth->fetchall_arrayref;
formatDate($comments, 4);
return $comments;
}
#################################################################
sub getCommentsBySubnetID{
my($self, $subnetid, $min) = @_;
my $comment_table = getCurrentStatic('mysql_heap_table') ? 'comment_heap' : 'comments';
my $sqlquery = "SELECT pid,sid,cid,subject,date,points "
. " FROM $comment_table WHERE subnetid='$subnetid' "
. " ORDER BY date DESC LIMIT $min ";
my $sth = $self->{_dbh}->prepare($sqlquery);
$sth->execute;
my($comments) = $sth->fetchall_arrayref;
formatDate($comments, 4);
return $comments;
}
#################################################################
# Just create an empty content_filter
sub createContentFilter {
my($self, $formname) = @_;
$self->sqlInsert("content_filters", {
regex => '',
form => $formname,
modifier => '',
field => '',
ratio => 0,
minimum_match => 0,
minimum_length => 0,
err_message => ''
});
my $filter_id = $self->getLastInsertId('content_filters', 'filter_id');
return $filter_id;
}
sub checkEmail {
my($self, $email) = @_;
# Returns count of users matching $email.
return ($self->sqlSelect('count(uid)', 'users',
'realemail=' . $self->sqlQuote($email)))[0];
}
#################################################################
# Replication issue. This needs to be a two-phase commit.
sub createUser {
my($self, $matchname, $email, $newuser) = @_;
return unless $matchname && $email && $newuser;
return if ($self->sqlSelect(
"count(uid)", "users",
"matchname=" . $self->sqlQuote($matchname)
))[0] || $self->checkEmail($email);
$self->sqlInsert("users", {
uid => '',
realemail => $email,
nickname => $newuser,
matchname => $matchname,
seclev => 1,
passwd => encryptPassword(changePassword())
});
# This is most likely a transaction problem waiting to
# bite us at some point. -Brian
my $uid = $self->getLastInsertId('users', 'uid');
return unless $uid;
$self->sqlInsert("users_info", {
uid => $uid,
-lastaccess => 'now()',
-created_at => 'now()',
});
$self->sqlInsert("users_prefs", { uid => $uid });
$self->sqlInsert("users_comments", { uid => $uid });
$self->sqlInsert("users_index", { uid => $uid });
# All param fields should be set here, as some code may not behave
# properly if the values don't exist.
#
# You know, I know this might be slow, but maybe this thing could be
# initialized by a template? Wild thought, but that would prevent
# site admins from having to edit CODE to set this stuff up.
#
# - Cliff
# Initialize the expiry variables...
# ...users start out as registered...
# ...the default email view is to SHOW email address...
# (not anymore - Jamie)
my $constants = getCurrentStatic();
# editComm;users;default knows that the default emaildisplay is 0...
# ...as it should be
$self->setUser($uid, {
'registered' => 1,
'expiry_comm' => $constants->{min_expiry_comm},
'expiry_days' => $constants->{min_expiry_days},
'user_expiry_comm' => $constants->{min_expiry_comm},
'user_expiry_days' => $constants->{min_expiry_days},
# 'emaildisplay' => 2,
});
return $uid;
}