/
Slash.pm
2966 lines (2479 loc) · 79.5 KB
/
Slash.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
package Slash;
###############################################################################
# Slash.pm (aka, the BEAST)
# This is the primary perl module for the slash engine.
#
# Copyright (C) 1997 Rob "CmdrTaco" Malda
# malda@slashdot.org
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#
# $Id$
###############################################################################
use strict; # ha ha ha ha ha!
use Apache::SIG ();
use CGI ();
use DBI;
use Date::Manip;
use File::Spec::Functions;
use HTML::Entities;
use Mail::Sendmail;
Apache::SIG->set;
BEGIN {
# this is the worst damned warning ever, so SHUT UP ALREADY!
$SIG{__WARN__} = sub { warn @_ unless $_[0] =~ /Use of uninitialized value/ };
require Exporter;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS %I $CRLF);
$VERSION = '1.0.5';
@ISA = 'Exporter';
@EXPORT = qw(
sqlSelectMany sqlSelect sqlSelectHash sqlSelectAll approveTag
sqlSelectHashref sqlUpdate sqlInsert sqlReplace sqlConnect
sqlTableExists sqlSelectColumns getSlash linkStory getSection
selectForm selectGeneric selectTopic selectSection fixHref
getvars getvar setvar newvar getblock getsid getsiddir getWidgetBlock
writelog anonLog pollbooth stripByMode header footer pollItem
prepEvalBlock prepBlock nukeBlockCache blockCache formLabel
titlebar fancybox portalbox printComments displayStory
sendEmail getOlderStories selectStories timeCalc
getEvalBlock getTopic getAuthor dispStory lockTest getSlashConf
getDateFormat dispComment getDateOffset linkComment redirect
insertFormkey getFormkeyId checkSubmission checkTimesPosted
updateFormkeyId formSuccess formAbuse formFailure errorMessage
);
$CRLF = "\015\012";
}
getSlashConf();
# The actual connect statement appears in this function. Edit it.
sqlConnect();
###############################################################################
#
# Let's get this party Started
#
# Load in config for proper SERVER_NAME. If you do not want to use SERVER_NAME,
# adjust here and in slashdotrc.pl
sub getSlashConf {
my $serv = exists $Slash::home{lc $ENV{SERVER_NAME}}
? lc $ENV{SERVER_NAME}
: 'DEFAULT';
require($Slash::home{$serv} ? catfile($Slash::home{$serv}, 'slashdotrc.pl')
: 'slashdotrc.pl');
$serv = exists $Slash::conf{lc $ENV{SERVER_NAME}}
? lc $ENV{SERVER_NAME}
: 'DEFAULT';
*I = $Slash::conf{$ENV{SERVER_NAME} ? $serv : $$};
$I{reasons} = [
'Normal', # "Normal"
'Offtopic', # Bad Responses
'Flamebait',
'Troll',
'Redundant',
'Insightful', # Good Responses
'Interesting',
'Informative',
'Funny',
'Overrated', # The last 2 are "Special"
'Underrated'
];
$I{badreasons} = 4; # number of "Bad" reasons in @$I{reasons}, skip 0 (which is neutral)
return \%I;
}
# Blank variables, get $I{r} (apache) $I{query} (CGI) $I{U} (User) and $I{F} (Form)
# Handles logging in, sql connection, and prints HTTP headers
sub getSlash {
for (qw[r query F U SETCOOKIE]) {
undef $I{$_} if $I{$_};
}
$I{r} = Apache->request if $ENV{GATEWAY_INTERFACE} =~ m|^CGI-Perl/|;
sqlConnect();
$I{query} = new CGI;
# fields that are numeric only
my %nums = map {($_ => 1)} qw(
last next artcount bseclev cid clbig clsmall
commentlimit commentsort commentspill commentstatus
del displaystatus filter_id height
highlightthresh isolate issue maillist max
maxcommentsize maximum_length maxstories min minimum_length
minimum_match ordernum pid
retrieve seclev startat uid uthreshold voters width
writestatus ratio
);
# regexes to match dynamically generated numeric fields
my @regints = (qr/^reason_.+$/, qr/^votes.+$/);
# special few
my %special = (
sid => sub { $_[0] =~ s|[^A-Za-z0-9/.]||g },
);
for ($I{query}->param) {
$I{F}{$_} = $I{query}->param($_);
# clean up numbers
if (exists $nums{$_}) {
$I{F}{$_} = fixint($I{F}{$_});
} elsif (exists $special{$_}) {
$special{$_}->($I{F}{$_});
} else {
for my $ri (@regints) {
$I{F}{$_} = fixint($I{F}{$_}) if /$ri/;
}
}
}
$I{F}{ssi} ||= '';
$ENV{SCRIPT_NAME} ||= '';
($I{anon_name}) = sqlSelect('nickname', 'users', 'uid=-1') unless $I{anon_name};
my $op = $I{query}->param('op') || '';
if (($op eq 'userlogin' || $I{query}->param('rlogin') )
&& length($I{F}{upasswd}) > 1) {
$I{U} = getUser(userLogin($I{F}{unickname}, $I{F}{upasswd}));
} elsif ($op eq 'userclose' ) {
$I{SETCOOKIE} = setCookie('user', ' ');
} elsif ($op eq 'adminclose') {
$I{SETCOOKIE} = setCookie('session', ' ');
} elsif ($I{query}->cookie('user')) {
$I{U} = getUser(userCheckCookie($I{query}->cookie('user')));
} else {
$I{U} ||= getUser(-1);
}
return 1;
}
########################################################
# Quick Form Creation Functions
# Generic way to convert a table into a drop down list
sub selectGeneric {
my($table, $label, $code, $name, $default, $where, $order, $limit) = @_;
$default = '' unless defined $default;
$code = '' unless defined $code;
print qq!\n<SELECT name="$label">\n!;
my $sql = " SELECT $code,$name FROM $table ";
$sql .= " WHERE $where" if $where;
$sql .= " ORDER BY $name" unless $order;
$sql .= " ORDER BY $order" if $order;
$sql .= " LIMIT $limit" if $limit;
my $c = $I{dbh}->prepare_cached($sql);
$c->execute;
while (my($code, $name) = $c->fetchrow) {
my $selected = $default eq $code ? ' SELECTED' : '';
print qq!\t<OPTION value="$code"$selected>$name</OPTION>\n!;
}
$c->finish;
print "</SELECT>\n";
}
########################################################
# This really is an obsolete function for quick form generation
sub selectForm {
my($table, $label, $default, $where) = @_;
selectGeneric($table, $label, 'code', 'name', $default, $where, 'name');
}
########################################################
sub selectTopic {
my($name, $tid) = @_;
getTopicBank();
my $o = qq!<SELECT NAME="$name">\n!;
foreach my $thistid (sort keys %{$I{topicBank}}) {
my $T = $I{topicBank}{$thistid};
my $selected = $T->{tid} eq $tid ? ' SELECTED' : '';
$o .= qq!\t<OPTION VALUE="$T->{tid}"$selected>$T->{alttext}</OPTION>\n!;
}
$o .= "</SELECT>\n";
print $o;
}
########################################################
# Drop down list of available sections (based on admin seclev)
sub selectSection {
my($name, $section, $SECT) = @_;
getSectionBank();
if ($SECT->{isolate}) {
print qq!<INPUT TYPE="hidden" NAME="$name" VALUE="$section">\n!;
return;
}
my $o = qq!<SELECT NAME="$name">\n!;
foreach my $s (sort keys %{$I{sectionBank}}) {
my $S = $I{sectionBank}{$s};
next if $S->{isolate} && $I{U}{aseclev} < 500;
my $selected = $s eq $section ? ' SELECTED' : '';
$o .= qq!\t<OPTION VALUE="$s"$selected>$S->{title}</OPTION>\n!;
}
$o .= "</SELECT>";
print $o;
}
########################################################
sub selectSortcode {
# Get a sortcode hash
unless ($I{sortcodeBank}) {
my $c = sqlSelectMany('code,name', 'sortcodes');
while (my($id, $desc) = $c->fetchrow) {
$I{sortcodeBank}{$id} = $desc;
}
$c->finish;
}
my $o .= qq!<SELECT NAME="commentsort">\n!;
foreach my $id (keys %{$I{sortcodeBank}}) {
my $selected = $id eq $I{U}{commentsort} ? ' SELECTED' : '';
$o .= qq!<OPTION VALUE="$id"$selected>$I{sortcodeBank}{$id}</OPTION>\n!;
}
$o .= "</SELECT>";
return $o;
}
########################################################
sub selectMode {
unless ($I{modeBank}) {
my $c = sqlSelectMany('mode,name', 'commentmodes');
while (my($id,$desc) = $c->fetchrow) {
$I{modeBank}{$id} = $desc;
}
$c->finish;
}
my $o .= qq!<SELECT NAME="mode">\n!;
foreach my $id (keys %{$I{modeBank}}) {
my $selected = $id eq $I{U}{mode} ? ' SELECTED' : '';
$o .= qq!<OPTION VALUE="$id"$selected>$I{modeBank}{$id}</OPTION>\n!;
}
$o .= "</SELECT>";
return $o;
}
#############################################################################
# Functions for dealing with Blocks (big chunks of data)
sub getblock {
my($bid) = @_;
getBlockBank();
return $I{blockBank}{$bid}; # unless $blockBank{$bid} eq "-1";
}
########################################################
# Blank the block cache.
sub nukeBlockCache {
undef $I{blockBank};
}
########################################################
sub getBlockBank {
return if $I{blockBank}{cached};
$I{blockBank}{cached} = localtime;
my $c = sqlSelectMany('bid,block', 'blocks');
while (my($thisbid, $thisblock) = $c->fetchrow) {
$I{blockBank}{$thisbid} = $thisblock;
}
$c->finish;
}
########################################################
# Gets a block. Stores a block. Returns a block. Future requests read
# from cache. Nice and quick.
sub blockCache {
my($bid) = @_;
getBlockBank();
return $I{blockBank}{$bid}; # unless $blockBank{$bid} eq "-1");
}
########################################################
# Prep for evaling (no \r allowed)
sub prepEvalBlock {
my($b) = @_;
$b =~ s/\r//g;
return $b;
}
########################################################
# Preps a block for evaling (escaping out " mostly)
sub prepBlock {
my($b) = @_;
$b =~ s/\r//g;
$b =~ s/"/\\"/g;
$b = qq!"$b";!;
return $b;
}
########################################################
# Gets a block, and ready's it for evaling
sub getEvalBlock {
my($name) = @_;
my $block = getSectionBlock($name);
my $execme = prepEvalBlock($block);
return $execme;
}
########################################################
# Gets the appropriate block depending on your section
# or else fall back to one that exists
sub getSectionBlock {
my $name = shift;
my $thissect = $I{U}{light} ? 'light' : $I{currentSection};
my $block;
if ($thissect) {
$block = blockCache($thissect . "_$name");
}
$block ||= blockCache($name);
return $block;
}
########################################################
# Get a Block based on mode, section & name, and prep it for evaling
sub getWidgetBlock {
my $name = shift;
my $block = getSectionBlock($name);
my $execme = prepBlock($block);
return $execme;
}
###############################################################################
# Functions for dealing with vars (system config variables)
########################################################
sub getvars {
my(@invars, @vars) = @_;
for (@invars) {
push @vars, sqlSelect('value', 'vars', "name='$_'");
}
return @vars;
}
########################################################
sub getvar {
my($value, $desc) = sqlSelect('value,description', 'vars', "name='$_[0]'");
}
########################################################
sub setvar {
my($name, $value) = @_;
sqlUpdate('vars', {value => $value}, 'name=' . $I{dbh}->quote($name));
}
########################################################
sub newvar {
my($name, $value, $desc) = @_;
sqlInsert('vars', {name => $name, value => $value, description => $desc});
}
###############################################################################
# Stuff for dealing with Logging In
#
# It does what it says, it says what it does.
########################################################
sub userLogin {
my($name, $passwd) = @_;
$passwd = substr $passwd, 0, 12;
my($uid) = sqlSelect('uid', 'users',
'passwd=' . $I{dbh}->quote($passwd) .
' AND nickname=' . $I{dbh}->quote($name)
);
if ($uid > 0) {
my $cookie = $uid . '::' . $passwd;
$cookie =~ s/(.)/sprintf("%%%02x",ord($1))/ge;
$I{SETCOOKIE} = setCookie('user', $cookie);
return($uid, $passwd);
} else {
return(-1, '');
}
}
########################################################
# Decode the Cookie: Cookies have all the special charachters encoded
# in standard URL format. This converts it back. then it is split
# on '::' to get the users info.
sub userCheckCookie {
my($cookie) = @_;
$cookie =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack('C', hex($1))/eg;
my($uid, $passwd) = split('::', $cookie);
return(-1, '') if $uid eq ' ';
return($uid, $passwd);
}
########################################################
# Replace $_[0] with $_[1] || "0" in the User Hash
# users by getUser to allow form parameters to override user parameters
sub overRide {
my($p, $d) = @_;
if (defined $I{query}->param($p)) {
$I{U}{$p} = $I{query}->param($p);
} else {
$I{U}{$p} ||= $d || '0';
}
}
########################################################
# Add this hashref to $U
sub addToUser {
my $H = shift;
@{$I{U}}{ keys %$H } = values %$H;
}
########################################################
# Get users_$_ and at it to $U
sub getExtraStuff {
my $s = shift;
my $H = sqlSelectHashref('*', "users_$s", "uid=$I{U}{uid}");
addToUser($H);
}
########################################################
# IF passed a valid uid & passwd, it logs in $U
# else $U becomes Anonymous Coward (eg UID -1)
sub getUser {
my($uid, $passwd) = @_;
undef $I{U};
if ($uid > 0) { # Authenticate
$I{U} = sqlSelectHashref('*', 'users',
' uid = ' . $I{dbh}->quote($uid) .
' AND passwd = ' . $I{dbh}->quote($passwd)
);
}
if ($uid > 0 && $I{U}{uid}) { # registered user
# Get User Prefs
getExtraStuff('prefs');
# Get the Timezone Stuff
unless (defined $I{timezones}) {
my $c = sqlSelectMany('tz,offset', 'tzcodes');
while (my($tzcode, $offset) = $c->fetchrow) {
$I{timezones}{$tzcode} = $offset;
}
$c->finish;
}
$I{U}{offset} = $I{timezones}{ $I{U}{tzcode} };
unless (defined $I{dateformats}) {
my $c = sqlSelectMany('id,format', 'dateformats');
while (my($dfid, $dateformat) = $c->fetchrow) {
$I{dateformats}{$dfid} = $dateformat;
}
$c->finish;
}
$I{U}{'format'} = $I{dateformats}{ $I{U}{dfid} };
# Do we want the comments stuff?
if (!$ENV{SCRIPT_NAME}
|| $ENV{SCRIPT_NAME} =~ /index|article|comments|metamod|search|pollBooth/) {
getExtraStuff('comments');
}
# Do we want the index stuff?
if (!$ENV{SCRIPT_NAME} || $ENV{SCRIPT_NAME} =~ /index/) {
getExtraStuff('index');
}
} else {
getAnonCookie();
$I{SETCOOKIE} = setCookie('anon', $I{U}{anon_id}, 1);
unless ($I{AC}) {
# Get ourselves an AC if we don't already have one.
# (we have to get it /all/ remember!)
$I{AC} = sqlSelectHashref('*',
'users, users_index, users_comments, users_prefs',
'users.uid=-1 AND users_index.uid=-1 AND ' .
'users_comments.uid=-1 AND users_prefs.uid=-1'
);
# timezone stuff
$I{ACTZ} = sqlSelectHashref('*',
'tzcodes,dateformats',
"tzcodes.tz='$I{AC}{tzcode}' AND dateformats.id=$I{AC}{dfid}"
);
@{$I{AC}}{ keys %{$I{ACTZ}} } = values %{$I{ACTZ}};
}
addToUser($I{AC});
}
# Add On Admin Junk
if ($I{F}{op} eq 'adminlogin') {
($I{U}{aid}, $I{U}{aseclev}) =
setAdminInfo($I{F}{aaid}, $I{F}{apasswd});
} elsif (length($I{query}->cookie('session')) > 3) {
(@{$I{U}}{qw[aid aseclev asection url]}) =
getAdminInfo($I{query}->cookie('session'));
} else {
$I{U}{aid} = '';
$I{U}{aseclev} = 0;
}
# Set a few defaults
overRide('mode', 'thread');
overRide('savechanges');
overRide('commentsort');
overRide('threshold');
overRide('posttype');
overRide('noboxes');
overRide('light');
$I{currentMode} = $I{U}{mode};
$I{U}{seclev} = $I{U}{aseclev} if $I{U}{aseclev} > $I{U}{seclev};
$I{U}{breaking}=0;
if ($I{U}{commentlimit} > $I{breaking} && $I{U}{mode} ne 'archive') {
$I{U}{commentlimit} = int($I{breaking} / 2);
$I{U}{breaking} = 1;
}
# All sorts of checks on user data
$I{U}{tzcode} = uc($I{U}{tzcode});
$I{U}{clbig} ||= 0;
$I{U}{clsmall} ||= 0;
$I{U}{exaid} = testExStr($I{U}{exaid}) if $I{U}{exaid};
$I{U}{exboxes} = testExStr($I{U}{exboxes}) if $I{U}{exboxes};
$I{U}{extid} = testExStr($I{U}{extid}) if $I{U}{extid};
$I{U}{points} = 0 unless $I{U}{willing}; # No points if you dont want 'em
return $I{U};
}
########################################################
# Handles admin logins (checks the sessions table for a cookie that
# matches). Called by getSlash
sub getAdminInfo {
my($session) = @_;
$I{dbh}->do("DELETE from sessions WHERE now() > DATE_ADD(lasttime, INTERVAL $I{admin_timeout} MINUTE)");
my($aid, $seclev, $section, $url) = sqlSelect(
'sessions.aid, authors.seclev, section, url',
'sessions, authors',
'sessions.aid=authors.aid AND session=' . $I{dbh}->quote($session)
);
unless ($aid) {
return('', 0, '', '');
} else {
$I{dbh}->do("DELETE from sessions WHERE aid = '$aid' AND session != " .
$I{dbh}->quote($session)
);
sqlUpdate('sessions', {-lasttime => 'now()'},
'session=' . $I{dbh}->quote($session)
);
return($aid, $seclev, $section, $url);
}
}
########################################################
# Initial Administrator Login.
sub setAdminInfo {
my($aid, $pwd) = @_;
if (my($aid, $seclev) = sqlSelect('aid,seclev', 'authors',
'aid=' . $I{dbh}->quote($aid) .
' AND pwd=' . $I{dbh}->quote($pwd) ) ) {
my $sid = generatesession($aid);
my($title) = sqlSelect('lasttitle', 'sessions',
'aid=' . $I{dbh}->quote($aid)
);
$I{dbh}->do('DELETE FROM sessions WHERE aid=' . $I{dbh}->quote($aid) );
sqlInsert('sessions', { session => $sid, aid => $aid,
-logintime => 'now()', -lasttime => 'now()',
lasttitle => $title }
);
$I{SETCOOKIE} = setCookie('session', $sid);
return($aid, $seclev);
} else {
return('', 0);
}
}
###############################################################
# What is it? Where does it go? The Random Leftover Shit
########################################################
sub setCookie {
my($name, $val, $session) = @_;
# domain must start with a . and have one more .
# embedded in it, else we ignore it
my $domain = $I{cookiedomain} &&
$I{cookiedomain} =~ /^\..+\./ ? $I{cookiedomain} : '';
my %cookie = (
-name => $name,
-path => $I{cookiepath},
-value => $val,
);
$cookie{-expires} = '+1y' unless $session;
$cookie{-domain} = $domain if $domain;
return {
-date => CGI::expires(0, 'http'),
-set_cookie => $I{query}->cookie(%cookie)
};
}
########################################################
# Returns YY/MM/DD/HHMMSS all ready to be inserted
sub getsid {
my($sec, $min, $hour, $mday, $mon, $year) = localtime;
$year = $year % 100;
my $sid = sprintf('%02d/%02d/%02d/%02d%0d2%02d',
$year, $mon+1, $mday, $hour, $min, $sec);
return $sid;
}
########################################################
# Get a unique string for an admin session
sub generatesession {
my $newsid = crypt(rand(99999), shift);
$newsid =~ s/[^A-Za-z0-9]//i;
return $newsid;
}
########################################################
# Returns the directory (eg YY/MM/DD/) that stories are being written in today
sub getsiddir {
my($mday, $mon, $year) = (localtime)[3, 4, 5];
$year = $year % 100;
my $sid = sprintf('%02d/%02d/%02d/', $year, $mon+1, $mday);
return $sid;
}
########################################################
# writes error message to apache's error_log if we're running under mod_perl
# Called wherever we have errors.
sub apacheLog {
if ($I{r}) {
$I{r}->log_error("$ENV{SCRIPT_NAME}:@_");
} else {
print @_, "\n";
}
return 0;
}
########################################################
# Saves an entry to the access log for static pages
# typically called now as part of getAd()
sub anonLog {
my($op, $data) = ('/', '');
$I{U}{uid} = -1;
$_ = $ENV{REQUEST_URI};
s/(.*)\?/$1/;
if (/404/) {
$op = '404';
} elsif (m[/(.*?)/(.*).shtml]) {
($op, $data) = ($1,$2);
} elsif (m[/(.*).shtml]) {
$op = $1;
} elsif (m[/(.+)]) {
$data = $op = $1;
} else {
$data = $op = 'index';
}
$data =~ s/_F//;
$op =~ s/_F//;
writelog($op, $data);
}
########################################################
sub writelog {
my $op = shift;
my $dat = join("\t", @_);
sqlInsert('accesslog', {
host_addr => $ENV{REMOTE_ADDR} || '0',
dat => $dat,
uid => $I{U}{uid} || '-1',
op => $op,
-ts => 'now()',
query_string => $ENV{QUERY_STRING} || '0',
user_agent => $ENV{HTTP_USER_AGENT} || '0',
}, 2);
if ($dat =~ m[/]) {
sqlUpdate('storiestuff', { -hits => 'hits+1' },
'sid=' . $I{dbh}->quote($dat)
);
} elsif ($op eq 'index') {
# Update Section Counter
}
}
########################################################
# Takes the address, subject and an email, and does what it says
# used by dailyStuff, users.pl, and someday submit.pl
sub sendEmail {
my($addr, $subject, $content) = @_;
sendmail(
smtp => $I{smtp_server},
subject => $subject,
to => $addr,
body => $content,
from => $I{mailfrom}
) or apacheLog("Can't send mail '$subject' to $addr: $Mail::Sendmail::error");
}
########################################################
# The generic "Link a Story" function, used wherever stories need linking
sub linkStory {
my $c = shift;
my($l, $dynamic);
if ($I{currentMode} ne 'archive' && ($ENV{SCRIPT_NAME} || !$c->{section})) {
$dynamic = 1 if $c->{mode} || exists $c->{threshold} || $ENV{SCRIPT_NAME};
$l .= '&mode=' . ($c->{mode} || $I{U}{mode});
$l .= "&threshold=$c->{threshold}" if exists $c->{threshold};
}
return qq!<A HREF="$I{rootdir}/! .
($dynamic ? "article.pl?sid=$c->{sid}$l" : "$c->{section}/$c->{sid}.shtml") .
qq!">$c->{'link'}</A>!;
# "$c->{section}/$c->{sid}$userMode".".shtml").
}
########################################################
# Sets the appropriate @fg and @bg color pallete's based
# on what section you're in. Used during initialization
sub getSectionColors {
my $color_block = shift;
my @colors;
# they damn well better be legit
if ($I{F}{colorblock}) {
@colors = map { s/[^\w#]+//g ; $_ } split m/,/, $I{F}{colorblock};
} else {
@colors = split m/,/, getSectionBlock('colors');
}
$I{fg} = [@colors[0..3]];
$I{bg} = [@colors[4..7]];
}
########################################################
sub getSectionBank {
return if keys %{$I{sectionBank}};
my $c = sqlSelectMany('*', 'sections');
while (my $S = $c->fetchrow_hashref) {
$I{sectionBank}{ $S->{section} } = $S;
}
$c->finish;
}
########################################################
# Gets sections wherver needed. if blank, gets settings for homepage, and
# if defined tries to use cache.
sub getSection {
my $section = shift;
return { title => $I{slogan}, artcount => $I{U}{maxstories} || 30, issue => 3 }
unless $section;
return $I{sectionBank}{$section} if $I{sectionBank}{$section};
getSectionBank();
return $I{sectionBank}{$section};
}
########################################################
sub getTopicBank {
return if keys %{$I{topicBank}};
my $c = sqlSelectMany('*', 'topics');
while (my $T = $c->fetchrow_hashref) {
$I{topicBank}{ $T->{tid} } = $T;
}
$c->finish;
}
########################################################
sub getTopic {
my $topic = shift;
return $I{topicBank}{$topic} if $I{topicBank}{$topic};
getTopicBank();
return $I{topicBank}{$topic};
}
########################################################
sub getAuthor {
my $aid = shift;
return $I{authorBank}{$aid} if $I{authorBank}{$aid};
# Get all the authors and throw them in a hash for later use:
my $c = sqlSelectMany('*', 'authors');
while (my $A = $c->fetchrow_hashref) {
$I{authorBank}{ $A->{aid} } = $A;
}
$c->finish;
return $I{authorBank}{$aid};
}
################################################################################
# SQL Timezone things
sub getDateOffset {
my $col = shift || return;
return $col unless $I{U}{offset};
return " DATE_ADD($col, INTERVAL $I{U}{offset} SECOND) ";
}
########################################################
sub getDateFormat {
my $col = shift || return;
my $as = shift || 'time';
$I{U}{'format'} ||= '%W %M %d, @%h:%i%p ';
unless ($I{U}{tzcode}) {
$I{U}{tzcode} = 'EDT';
$I{U}{offset} = '-14400';
}
$I{U}{offset} ||= '0';
return ' CONCAT(DATE_FORMAT(' . getDateOffset($col) .
qq!,"$I{U}{'format'}")," $I{U}{tzcode}") as $as !;
}
###############################################################################
# Dealing with Polls
########################################################
sub latestpoll {
my($qid) = sqlSelect('qid', 'pollquestions', '', 'ORDER BY date DESC LIMIT 1');
return $qid;
}
########################################################
sub pollbooth {
my($qid, $notable) = @_;
($qid) = getvar("currentqid") unless $qid;
my $qid_dbi = $I{dbh}->quote($qid);
my $qid_htm = stripByMode($qid, 'attribute');
my $cursor = $I{dbh}->prepare_cached("
SELECT question,answer,aid from pollquestions, pollanswers
WHERE pollquestions.qid=pollanswers.qid AND
pollquestions.qid=$qid_dbi
ORDER BY pollanswers.aid
");
$cursor->execute;
my($x, $tablestuff) = (0);
while (my($question, $answer, $aid) = $cursor->fetchrow) {
if ($x == 0) {
$tablestuff = <<EOT;
<FORM ACTION="$I{rootdir}/pollBooth.pl">
\t<INPUT TYPE="hidden" NAME="qid" VALUE="$qid_htm">
<B>$question</B>
EOT
$tablestuff .= <<EOT if $I{currentSection};
\t<INPUT TYPE="hidden" NAME="section" VALUE="$I{currentSection}">
EOT
$x++;
}
$tablestuff .= qq!<BR><INPUT TYPE="radio" NAME="aid" VALUE="$aid">$answer\n!;
}
my($voters) = sqlSelect('voters', 'pollquestions', " qid=$qid_dbi");
my($comments) = sqlSelect('count(*)', 'comments', " sid=$qid_dbi");
my $sect = "section=$I{currentSection}&" if $I{currentSection};
$tablestuff .= qq!<BR><INPUT TYPE="submit" VALUE="Vote"> ! .
qq![ <A HREF="$I{rootdir}/pollBooth.pl?${sect}qid=$qid_htm&aid=-1"><B>Results</B></A> | !;
$tablestuff .= qq!<A HREF="$I{rootdir}/pollBooth.pl?$sect"><B>Polls</B></A> !
unless $notable eq 'rh';
$tablestuff .= "Votes:<B>$voters</B>" if $notable eq 'rh';
$tablestuff .= " ] <BR>\n";
$tablestuff .= "Comments:<B>$comments</B> | Votes:<B>$voters</B>\n" if $notable ne 'rh';
$tablestuff .="</FORM>\n";
$cursor->finish;
return $tablestuff if $notable;
fancybox(200, 'Poll', $tablestuff, 'c');
}
########################################################
# Useful SQL Wrapper Functions
########################################################
########################################################
sub sqlSelectMany {
my($select, $from, $where, $other) = @_;
my $sql = "SELECT $select ";
$sql .= " FROM $from " if $from;
$sql .= " WHERE $where " if $where;
$sql .= " $other" if $other;
sqlConnect();
my $c = $I{dbh}->prepare_cached($sql);
if ($c->execute) {
return $c;
} else {
$c->finish;
apacheLog($sql);
die;
return undef;
}
}
########################################################
sub sqlSelect {
my($select, $from, $where, $other) = @_;
my $sql = "SELECT $select ";
$sql .= "FROM $from " if $from;
$sql .= "WHERE $where " if $where;
$sql .= "$other" if $other;
sqlConnect();
my $c = $I{dbh}->prepare_cached($sql) or die "Sql has gone away\n";