-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathkas.cgi
executable file
·2583 lines (2501 loc) · 107 KB
/
kas.cgi
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
#!/usr/bin/perl -w
##############################################################################
# Kas - a webapplication to manage monetary transactions among social groups #
# Copyright (C) 2006-2010 Pieter Wuille #
# #
# 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, version 3. #
# #
# 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, see <http://www.gnu.org/licenses/>. #
##############################################################################
##############################################################################
# declarations & defaults #
##############################################################################
use strict;
use DBI;
use CGI qw/:standard/;
use CGI::Carp;
use HTML::Entities;
use Encode;
use Time::Local;
use Digest;
use Data::Dumper;
# version
my $SYSTEM="Kassys";
my $MAJOR=0;
my $MINOR=9;
my $REVISION=196;
my $VERSION="$SYSTEM v$MAJOR.$MINOR.$REVISION";
# REV=$(svn log kas.cgi | egrep '^r[0-9]+ ' | wc -l); sed -re "s/ \\\$REVISION=[0-9]+;/ \$REVISION=$REV;/" -i kas.cgi
# global constants
my $DENOM=18018000; # 18018000 = kgv(2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,1000)
my $PCT=1.03; # (annual) interest ratio for annuity corrections
my $SEC_PER_YEAR=31556952; # average number of seconds in gregorian year
my $THRESHOLD=0.005; # differences below this many monetary units are ignored
my $SESSION_TIME=15; # session lifetime, in minutes
my $UNIT="€ "; # monetary unit
# boolean configuration parameters
my @BOOLS=('initdb','pathinfo');
# minimal authentication level for certain actions
my $MIN_LEVEL_SUDO=50;
my $MIN_LEVEL_NOPASSSUDO=90;
# database handle and prefix
my $dbh;
my $prefix="";
# authentication info
my $auth_level=0;
my $auth_uid=undef;
my $auth_fullname;
my $auth_username;
my $auth_methods="";
my $auth_active=0;
my $auth_autoaccept=0;
my $session=cookie('session');
# mails should be sent from this e-mail adres
my $mailfrom;
# cached database information
my %USERS; my $haveUSERS=0; my %FUSERS;
my %GROUPS; my $haveGROUPS=0;
my $maxExtra=undef;
my $minExtra=undef;
my ($title,$htmltitle);
my %CONF;
my @msg;
my ($URL,@path,$DIR,$SCRIPT);
##############################################################################
# utility functions #
##############################################################################
sub urldecode {
my $theURL = $_[0];
$theURL =~ tr/+/ /;
$theURL =~ s/%([a-fA-F0-9]{2,2})/chr(hex($1))/eg;
$theURL =~ s/<!–(.|\n)*–>//g;
return $theURL;
}
sub urlencode {
my $theURL = $_[0];
$theURL =~ s/([\W])/"%" . uc(sprintf("%2.2x",ord($1)))/eg;
return $theURL;
}
# cut off dir part
sub filepart {
my ($str) = @_;
my $idx=rindex($str,'/');
$str=substr($str,$idx+1) if ($idx>=0);
$idx=index($str,"\000");
$str=substr($str,0,$idx) if ($idx>=0);
return $str;
}
# generate a url to a given path
sub genurl {
my @p=@_;
my $ret=$URL;
my @q;
my $ps;
if (@p) {
for my $p (@p) {
$ps .= '/';
$ps .= urlencode($p);
}
$ps=substr($ps,1);
}
if (defined $SCRIPT) {
$ret .= "/$ps" if (defined $ps);
} else {
push @q,"/$ps" if (defined $ps);
}
if (@q) {
$ret .= "?" . join('&',@q);
}
return $ret;
}
sub pathurl {
my @p=split(/\//,$_[0]);
return genurl(@p);
}
sub selfurl {
return genurl(@path);
}
# process input
sub process_input {
my $uri=$ENV{REQUEST_URI};
return if (!defined $uri);
my $pos=index($uri,'?');
$uri=substr($uri,0,$pos) if ($pos>=0);
# if ($CONF{pathinfo}) {
$SCRIPT=filepart($ENV{SCRIPT_NAME});
# }
if (defined $SCRIPT && $SCRIPT ne '') {
$pos=index($uri,$SCRIPT);
if ($pos>=0) {
$pos+=length($SCRIPT);
} elsif (substr($SCRIPT,0,1) eq '/') {
$uri=$SCRIPT;
$pos=length($uri);
} else {
$pos=length($uri);
$SCRIPT=undef;
}
} else {
$pos=length($uri);
$SCRIPT=undef;
}
my $pathx=substr($uri,$pos);
for my $arg (split(/\&/,$ENV{QUERY_STRING})) {
$pathx=$arg if (substr($arg,0,1) eq '/');
}
$pathx=urldecode($pathx);
$pathx=param('p') if (defined (param('p')));
$pathx=url_param('p') if (defined (url_param('p')));
@path=grep { $_ ne '' && $_ ne '.' } (split(/\//,$pathx));
$URL=substr($uri,0,$pos);
$pos=rindex($URL,'/');
$DIR = ($pos>=0 ? substr($URL,0,$pos) : "/");
}
# generation of (pseudo)random session id's
my $SIDCHAR='abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMOPQRSTUVWXYZ0123456789';
my $SIDPOS=length($SIDCHAR);
my $SIDGEN=16777216;
sub generate_sid {
my ($bits) = @_;
my $sidlen=int($bits*log(2)/log($SIDPOS)+1);
my $r="";
my $n=0;
my $x=1;
while (length($r)<$sidlen) {
if ($x<$SIDPOS*$SIDPOS) {
$n = $n*$SIDGEN + int(rand($SIDGEN));
$x = $x*$SIDGEN;
}
$r .= substr($SIDCHAR,$n % $SIDPOS,1);
$x = int($x/$SIDPOS);
$n = int($n/$SIDPOS);
}
return $r;
}
# maximum of a list
sub max {
my $val=pop @_;
foreach (@_) {
$val=$_ if ($_ > $val);
}
return $val;
}
# minimum of a list
sub min {
my $val=pop @_;
foreach (@_) {
$val=$_ if ($_ < $val);
}
return $val;
}
# log something
sub log_action {
open LOG,">>kas.log" || die "Cannot open log";
foreach (@_) {
chomp;
print LOG "[".time.(defined $auth_uid ? " $auth_uid($auth_fullname)" : "")."] $_\n";
}
close LOG;
}
# number E
sub e {
return 2.718281828459045235;
}
# allowed functions + function evaluator
my %FUNCS=(abs => 1, exp => 1, log => 1, int => 1, rand => 1, sqrt => 1);
sub calc {
my ($x)=@_;
return undef if (!defined $x);
$x = lc($x);
$x =~ s/\[.*?\]//g; # remove comments
$x =~ s/\,/\./g; # replace , by .
$x =~ s/\s+//g; # remove spaces
return 0 if ($x eq '');
return undef if ($x =~ /[^a-z0-9.+*\/()\t-]/); # exit if non-alphanumeric characters other than .+-*/() are used
foreach (split(/[^a-z]+/,$x)) { # check all alphabetical strings
return undef if (!defined $FUNCS{$_});
}
return eval($x);
}
# greatest common divisor
sub gcd {
my ($a,$b)=@_;
do {
if ($a>$b) { my $c=$a; $a=$b; $b=$c; }
return $b if ($a==0);
$b %= $a;
} while(1);
}
sub gen_key {
my ($pass,$algo) = @_;
$algo='MD5' if (!defined $algo);
my $salt=generate_sid(32);
my $ctx=Digest->new($algo);
$ctx->add("$salt $pass $salt");
return $algo.' '.$salt.' '.($ctx->b64digest);
}
sub test_key {
my ($pass,$key) = @_;
my ($algo,$salt,$digest) = split(/ /,$key);
my $ctx=Digest->new($algo);
$ctx->add("$salt $pass $salt");
return ($digest eq ($ctx->b64digest));
}
sub normalize_name {
my ($name) = @_;
$name =~ s/\A\s*(.*?)\s*\Z/$1/;
$name =~ s/\s+/ /g;
return $name;
}
##############################################################################
# database functions #
##############################################################################
# establish database connection
sub connect_db {
my $dbname=$CONF{dbname};
my $host=$CONF{dbhost} || "localhost";
my $dbusername=$CONF{dbuser};
my $dbpassword=$CONF{dbpass};
$dbh = DBI->connect("dbi:Pg:dbname=$dbname;host=$host", $dbusername, $dbpassword,{AutoCommit => 1,RaiseError => 0});
$prefix=defined($CONF{dbprefix}) ? "$CONF{dbprefix}_" : "";
$title=$CONF{title} || $VERSION;
$htmltitle=$CONF{htmltitle} || $title;
$mailfrom=$CONF{mailfrom};
}
sub reset_db {
die "Resetting database requires 'initdb true' in kas.conf" unless ($CONF{initdb});
$dbh->do("DROP INDEX ${prefix}IDX_SHARES_GID CASCADE");
$dbh->do("DROP INDEX ${prefix}IDX_TR_WWHEN CASCADE");
$dbh->do("DROP INDEX ${prefix}IDX_EF_TID CASCADE");
$dbh->do("DROP INDEX ${prefix}IDX_EF_UID CASCADE");
$dbh->do("DROP INDEX ${prefix}IDX_VISIBLE_SEER CASCADE");
$dbh->do("DROP INDEX ${prefix}IDX_EDGEINFO_ETYP_EFROM CASCADE");
$dbh->do("DROP TABLE ${prefix}SESSION CASCADE");
$dbh->do("DROP TABLE ${prefix}VISIBLE CASCADE");
$dbh->do("DROP TABLE ${prefix}EDGEINFO CASCADE");
$dbh->do("DROP TABLE ${prefix}BILL CASCADE");
$dbh->do("DROP TABLE ${prefix}ITEM CASCADE");
$dbh->do("DROP TABLE ${prefix}EF CASCADE");
$dbh->do("DROP TABLE ${prefix}TR CASCADE");
$dbh->do("DROP TABLE ${prefix}SHARES CASCADE");
$dbh->do("DROP TABLE ${prefix}GROUPS CASCADE");
$dbh->do("DROP TABLE ${prefix}HTAUTH CASCADE");
$dbh->do("DROP TABLE ${prefix}PWAUTH CASCADE");
$dbh->do("DROP TABLE ${prefix}USERREQ CASCADE");
$dbh->do("DROP TABLE ${prefix}USERS CASCADE");
$dbh->do("DROP SEQUENCE ${prefix}NTR CASCADE");
$dbh->do("DROP SEQUENCE ${prefix}NGROUPS CASCADE");
$dbh->do("DROP SEQUENCE ${prefix}NUSERS CASCADE");
$dbh->do("CREATE SEQUENCE ${prefix}NUSERS");
$dbh->do("CREATE SEQUENCE ${prefix}NGROUPS");
$dbh->do("CREATE SEQUENCE ${prefix}NTR");
$dbh->do("CREATE TABLE ${prefix}USERS (". # list of active users
"UID INT4 PRIMARY KEY NOT NULL DEFAULT nextval('${prefix}NUSERS'), ". # unique user id
"UNAME VARCHAR(63) NOT NULL, ". # unique username
"FULLNAME TEXT NOT NULL, ". # full name
"ACCNR VARCHAR(40), ". # bank account number
"ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, ". # active user?
"EMAIL VARCHAR(255) NOT NULL, ". # email address
"TOTALSUM NUMERIC(20,10) NOT NULL DEFAULT 0, ". # sum of all included (counted) transactions for this user
"TOTALPCT NUMERIC(20,10) NOT NULL DEFAULT 0, ". # same, but annuity-corrected for the timestamp represented by 'created' field
"CREATED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, ". # when account was created (not requested)
"I18N VARCHAR(3) NOT NULL DEFAULT 'en', ". # language
"AUTOACCEPT NUMERIC(12,4) NOT NULL DEFAULT 50, ". # automatically accept charges up to this amount
"NICKNAME VARCHAR(40) NULL DEFAULT NULL, ". # nickname
"UNIQUE (UNAME), ".
"UNIQUE (EMAIL)".
") WITHOUT OIDS");
$dbh->do("CREATE TABLE ${prefix}USERREQ (". # list of user-account requests
"RID VARCHAR(63) PRIMARY KEY NOT NULL, ". # unique request ID
"EXPIRE TIMESTAMP NOT NULL DEFAULT (CURRENT_TIMESTAMP + interval '7 days'), ". # when does request expire
"UNAME VARCHAR(63) NULL, ". # requested username
"UID INT4 NULL REFERENCES ${prefix}USERS, ". # user to edit (when changing password)
"FULLNAME TEXT NULL, ". # provided fullname
"ACCNR VARCHAR(40), ". # provided account number
"EMAIL VARCHAR(255) NULL, ". # provided email adres
"HTNAME VARCHAR(64) NULL, ". # http-auth username during account request
"PWKEY VARCHAR(255) NULL, ". # requested password (encoded using gen_key)
"LEVEL INT4 NOT NULL DEFAULT 1". # requested permission level (TODO: check this when creating account...)
") WITHOUT OIDS");
$dbh->do("CREATE TABLE ${prefix}PWAUTH (". # password-based authentication list
"UID INT4 NOT NULL REFERENCES ${prefix}USERS, ". # user-id this password is valid for
"KEY VARCHAR(255) NOT NULL, ". # password stored as a key (using gen_key)
"LEVEL INT4 NOT NULL DEFAULT 1, ". # permission level
"UNIQUE (UID)".
") WITHOUT OIDS");
$dbh->do("CREATE TABLE ${prefix}HTAUTH (". # http-auth based authentication list
"UID INT4 NOT NULL REFERENCES ${prefix}USERS, ". # user-id this http-auth is valid for
"HTNAME VARCHAR(64) PRIMARY KEY NOT NULL, ". # what name to use
"LEVEL INT4 NOT NULL DEFAULT 1, ". # permission level
"UNIQUE (UID)".
") WITHOUT OIDS");
$dbh->do("CREATE TABLE ${prefix}GROUPS (".
"GID INT4 PRIMARY KEY NOT NULL DEFAULT nextval('${prefix}NGROUPS'), ". # unique group identifier
"DEFINER INT4 NOT NULL REFERENCES ${prefix}USERS, ". # who created the group
"NAME VARCHAR(40) NOT NULL, ". # name of the group
"DESCR TEXT NULL, ". # description of the group
"ISPUBLIC BOOL NOT NULL DEFAULT FALSE, ". # whether group is public
"MAX INT4 NOT NULL DEFAULT 0, ". # maximum number of shares (if larger than total: unassigned)
"MAXFORM TEXT, ". # formula for maximum number of shares
"WWHEN TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, ". # creation time
"UNIQUE (NAME,WWHEN)".
") WITHOUT OIDS");
$dbh->do("CREATE TABLE ${prefix}SHARES (".
"GID INT4 REFERENCES ${prefix}GROUPS NOT NULL, ". # group this is a share of
"UID INT4 REFERENCES ${prefix}USERS NOT NULL, ". # user that is share of group
"AMOUNT INT4 NOT NULL CHECK (amount>0), ". # how many shares
"FORMULA TEXT, ". # formula for shares
"UNIQUE (GID,UID)".
") WITHOUT OIDS");
$dbh->do("CREATE TABLE ${prefix}TR (". # transactions (payments, items, bills, ...)
"TID INT8 PRIMARY KEY NOT NULL DEFAULT nextval('${prefix}NTR'), ". # transaction id
"TYP CHAR NOT NULL, ". # what type ('i'=item/payment, 'b'=bill)
"NAME VARCHAR(40) NULL, ". # name of item/bill (nameless item against a user = payment)
"DESCR TEXT NULL, ". # extra description
"AUTHOR INT4 NOT NULL REFERENCES ${prefix}USERS, ". # who created the transaction
"ACTIVE BOOL NOT NULL DEFAULT TRUE, ". # whether the transaction should be counted
"COUNTED BOOL NOT NULL DEFAULT FALSE, ". # whether the transaction is counted in total
"WWHEN TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, ". # creation time of transaction
"AFG INT4 NULL REFERENCES ${prefix}GROUPS, ". # affected user
"AFU INT4 NULL REFERENCES ${prefix}USERS". # affected group
") WITHOUT OIDS");
$dbh->do("CREATE TABLE ${prefix}EF (". # effect of a transaction
"TID INT8 NOT NULL REFERENCES ${prefix}TR, ". # transaction this is an effect of
"UID INT4 NOT NULL REFERENCES ${prefix}USERS, ". # user that is affected
"AMOUNT NUMERIC(18,10) NOT NULL DEFAULT 0, ". # for which amount
"SEEN NUMERIC(18,10) NOT NULL DEFAULT 0, ". # which amount was (either positively or negatively) acknowledged by user
"ACCEPT BOOL NULL, ". # null=not seen, true=accepted, false=declined
"PRIMARY KEY (TID,UID) ".
") WITHOUT OIDS");
$dbh->do("CREATE TABLE ${prefix}ITEM (".
"TID INT8 NOT NULL REFERENCES ${prefix}TR, ".
"AMOUNT NUMERIC(12,4), ".
"UNIQUE (TID) ".
") WITHOUT OIDS");
$dbh->do("CREATE TABLE ${prefix}BILL (".
"TID INT8 NOT NULL REFERENCES ${prefix}TR, ".
"DEFINITION TEXT NOT NULL, ".
"UNIQUE (TID) ".
") WITHOUT OIDS");
$dbh->do("CREATE TABLE ${prefix}EDGEINFO (".
"EFROM INT4 REFERENCES ${prefix}USERS NOT NULL, ".
"ETO INT4 REFERENCES ${prefix}USERS NOT NULL, ".
"ETYP CHAR NOT NULL, ".
"TOTALSUM NUMERIC(20,10) NOT NULL DEFAULT 0, ".
"TOTALPCT NUMERIC(20,10) NOT NULL DEFAULT 0, ".
"CREATED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, ".
"PRIMARY KEY (EFROM,ETO,ETYP)".
") WITHOUT OIDS");
$dbh->do("CREATE TABLE ${prefix}VISIBLE (".
"SEER INT4 REFERENCES ${prefix}USERS NOT NULL, ".
"SEEN INT4 REFERENCES ${prefix}USERS NOT NULL, ".
"LEVEL DOUBLE PRECISION NOT NULL DEFAULT 1, ".
"PRIMARY KEY (SEER,SEEN) ".
") WITHOUT OIDS");
$dbh->do("CREATE TABLE ${prefix}SESSION (".
"SID VARCHAR(86) PRIMARY KEY NOT NULL, ".
"UID INT4 REFERENCES ${prefix}USERS NOT NULL, ".
"EXPIRE TIMESTAMP NOT NULL, ".
"LEVEL INT4 NOT NULL ".
") WITHOUT OIDS");
$dbh->do(
"CREATE VIEW ${prefix}USERLIST AS ".
"SELECT U.UID AS UID, U.ACTIVE, U.FULLNAME AS NAME, U.TOTALSUM as TOTAL, U.TOTALPCT*POW($PCT,EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP-U.CREATED))/$SEC_PER_YEAR)-U.TOTALSUM AS EXTRA, U.ACCNR AS ACCNR ".
"FROM ${prefix}USERS AS U"
);
$dbh->do("CREATE INDEX ${prefix}IDX_SHARES_GID ON ${prefix}SHARES (GID)");
$dbh->do("CREATE INDEX ${prefix}IDX_TR_WWHEN ON ${prefix}TR (WWHEN)");
$dbh->do("CREATE INDEX ${prefix}IDX_EF_TID ON ${prefix}EF (TID)");
$dbh->do("CREATE INDEX ${prefix}IDX_EF_UID ON ${prefix}EF (UID)");
$dbh->do("CREATE INDEX ${prefix}IDX_VISIBLE_SEER ON ${prefix}VISIBLE (SEER)");
$dbh->do("CREATE INDEX ${prefix}IDX_EDGEINFO_ETYP_EFROM ON ${prefix}EDGEINFO (ETYP,EFROM)");
}
# initialize database
sub init_db {
require Term::ReadKey;
import Term::ReadKey;
$|=1;
print "(Re)initializing the database. Cancel now if you do not want to do this.\nAdmin password: ";
ReadMode('noecho');
my $pass1=<STDIN>; chomp $pass1;
ReadMode('normal');
print "\nRepeat: ";
ReadMode('noecho');
my $pass2=<STDIN>; chomp $pass2;
ReadMode('normal');
print "\n";
die "Passwords do not match" if ($pass1 ne $pass2);
die "Password too short" if (length($pass1)<6);
print "Admin e-mail: ";
my $email=<STDIN>; chomp $email;
reset_db;
print STDERR "Start creating entries...\n";
my $sth=$dbh->prepare("INSERT INTO ${prefix}USERS (uid,uname,fullname,email) VALUES (-1,'admin','Administrator',?)");
$sth->execute($email);
$dbh->do("INSERT INTO ${prefix}PWAUTH (uid,key,level) VALUES (-1,'".gen_key($pass1)."',100)");
print STDERR "done initialising...\n";
print "Now remove the 'initdb' setting from kas.conf, and log in using the webinterface as 'admin'.\n";
}
sub check_auth {
my ($usern) = @_;
my $password=param('password');
my $username=$usern || param('username');
$auth_level=-1;
$auth_methods="";
# use session-based auth
if (defined $session) {
$dbh->begin_work;
my $sth2=$dbh->prepare("DELETE FROM ${prefix}SESSION WHERE EXPIRE<CURRENT_TIMESTAMP");
$sth2->execute;
$dbh->commit;
my $sth=$dbh->prepare("SELECT S.UID,S.LEVEL,U.FULLNAME,U.UNAME,U.ACTIVE,U.AUTOACCEPT FROM ${prefix}SESSION AS S, ${prefix}USERS AS U WHERE S.SID=? AND S.UID=U.UID");
$sth->execute($session);
my ($uid,$level,$name,$uname,$active,$autoaccept) = $sth->fetchrow_array;
if (defined $uid) { # not expired, and matching session
$auth_uid=$uid;
$auth_level=max($auth_level,$level);
$auth_fullname=$name;
$auth_active=$active;
$auth_username=$uname;
$auth_autoaccept=$autoaccept;
$auth_methods .= "|session|";
} else {
undef $session; # no valid $session - clear it to recreate it later
}
}
# try http auth
if ($auth_level<0 && defined $ENV{REMOTE_USER}) {
my $sth4=$dbh->prepare("SELECT A.UID,A.LEVEL,U.FULLNAME,U.UNAME,U.ACTIVE,U.AUTOACCEPT FROM ${prefix}HTAUTH AS A, ${prefix}USERS AS U WHERE A.HTNAME=? AND U.UID=A.UID");
$sth4->execute($ENV{REMOTE_USER});
my ($uid,$level,$name,$uname,$active,$autoaccept)=$sth4->fetchrow_array;
if (defined($uid)) {
$auth_uid=$uid;
$auth_level=max($auth_level,$level);
$auth_fullname=$name;
$auth_username=$uname;
$auth_active=$active;
$auth_autoaccept=$autoaccept;
$auth_methods .= "|http|";
$sth4->finish;
}
$sth4->finish;
}
# try password auth
if ($auth_level<0 && (defined $username && $username ne '' && ($auth_level>=$MIN_LEVEL_NOPASSSUDO || defined $password))) {
my $sth3=$dbh->prepare("SELECT A.UID,A.KEY,A.LEVEL,U.FULLNAME,U.UNAME,U.ACTIVE,U.AUTOACCEPT FROM ${prefix}PWAUTH AS A, ${prefix}USERS AS U WHERE U.UNAME=? AND U.UID=A.UID");
$sth3->execute($username);
my $cnt=0;
while (my ($uid,$key,$level,$name,$uname,$active,$autoaccept)=$sth3->fetchrow_array) {
$cnt++;
if (($auth_level>=$MIN_LEVEL_NOPASSSUDO && $level<$auth_level) || (test_key($password,$key))) {
if ($auth_level>=$MIN_LEVEL_SUDO) { # without sudo rights, drop to level of new user, otherwise keep level
$auth_level=max($auth_level,$level);
} else {
$auth_level=$level;
}
$auth_uid=$uid;
$auth_fullname=$name;
$auth_username=$uname;
$auth_active=$active;
$auth_autoaccept=$autoaccept;
$auth_methods .= "|password|";
$sth3->finish;
@path=() if (defined $path[0] && $path[0] eq 'login');
last;
} else {
push @msg,['error',"Password mismatch"] if (!defined $auth_username);
}
}
push @msg,['error',"User not found"] if ($cnt==0 && !defined $auth_username);
$sth3->finish;
}
# update session cache
if ($auth_level>0) {
$dbh->begin_work;
my $sth5;
if (!defined $session) { # no valid session already in session table - create new one
$session=generate_sid(256);
$sth5=$dbh->prepare("INSERT INTO ${prefix}SESSION (UID,LEVEL,SID,EXPIRE) VALUES (?,?,?,CURRENT_TIMESTAMP + INTERVAL '${SESSION_TIME} minutes')");
} else { # update old session entry
$sth5=$dbh->prepare("UPDATE ${prefix}SESSION SET UID=?, LEVEL=?, EXPIRE=CURRENT_TIMESTAMP + INTERVAL '${SESSION_TIME} minutes' WHERE SID=?");
}
$sth5->execute($auth_uid,$auth_level,$session);
trycommit(0);
}
}
# change a password
sub set_password {
my ($key,$uid,$level,$lock)=@_;
$uid=$auth_uid if (!defined $uid);
$level=1 if (!defined $level);
return 0 if (!defined $uid);
$dbh->begin_work if (!defined $lock);
my $sth=$dbh->prepare("DELETE FROM ${prefix}PWAUTH WHERE UID=?");
$sth->execute($uid);
$sth=$dbh->prepare("INSERT INTO ${prefix}PWAUTH (KEY,UID,LEVEL) VALUES (?,?,?)");
$sth->execute($key,$uid,$level);
$sth->finish;
trycommit(0) if (!defined $lock);
return 1;
}
sub set_htlogin {
my ($htname,$uid,$level,$lock)=@_;
$uid=$auth_uid if (!defined $uid);
return 0 if (!defined $uid);
$dbh->begin_work if (!defined $lock);
my $sth=$dbh->prepare("DELETE FROM ${prefix}HTAUTH WHERE HTNAME=?");
$sth->execute($htname);
$sth=$dbh->prepare("INSERT INTO ${prefix}HTAUTH (HTNAME,UID,LEVEL) VALUES (?,?,?)");
$sth->execute($htname,$uid,$level);
$sth->finish;
trycommit(0) if (!defined $lock);
return 1;
}
# create a user
sub create_user {
my ($user,$fullname,$email,$lock)=@_;
$dbh->begin_work if (!defined $lock);
my $sth=$dbh->prepare("SELECT nextval('${prefix}NUSERS')");
$sth->execute;
my ($nuid)=$sth->fetchrow_array;
$sth->finish;
$sth=$dbh->prepare("INSERT INTO ${prefix}USERS (UID,UNAME,FULLNAME,EMAIL,ACTIVE) VALUES (?,?,?,?,?)");
my $ret=$sth->execute($nuid,$user,normalize_name($fullname),$email,0);
if (defined $ret && $ret>0) {
$sth=$dbh->prepare("DELETE FROM ${prefix}USERREQ WHERE UNAME=?");
$sth->execute($user);
$sth->finish;
if (!defined $lock) {
return $nuid if ($dbh->commit);
return undef;
}
return $nuid;
} else {
push @msg,['warn',"Unable to create user. Username or e-mail address may have already been taken."];
$dbh->rollback if (!defined $lock);
return undef;
}
}
# include/exclude transaction from total view
sub count_transaction {
my ($tid,$count,$locked) = @_;
do {
$dbh->begin_work if (!defined $locked);
my $sth=$dbh->prepare("SELECT COUNT(*) FROM ${prefix}TR T WHERE TID=? AND COUNTED=TRUE"); # check whether this transaction is already included in totals
$sth->execute($tid);
my ($cnt)=($sth->fetchrow_array)||0;
if ($cnt!=($count?1:0)) { # if this differs from the requested
$sth=$dbh->prepare("SELECT T.ACTIVE, T.AUTHOR, T.WWHEN FROM ${prefix}TR T WHERE T.TID=?"); # retrieve some global information about the transaction
$sth->execute($tid);
my ($active,$author,$wwhen)=$sth->fetchrow_array;
if ($active || $count==0) { # do not include inactive transactions (but allow temporary exclusion of active ones)
$sth=$dbh->prepare("UPDATE ${prefix}TR SET COUNTED=? WHERE TID=?"); # update them to reflect the requested inclusion
$sth->execute($count?1:0,$tid);
$sth=$dbh->prepare("UPDATE ${prefix}USERS U SET ". # the real magic for the per-user totals
"TOTALSUM=U.TOTALSUM+((SELECT E.AMOUNT FROM ${prefix}EF E WHERE E.UID=U.UID AND E.TID=?)*?)::NUMERIC(20,10), ".
"TOTALPCT=U.TOTALPCT+((SELECT E.AMOUNT FROM ${prefix}EF E WHERE E.UID=U.UID AND E.TID=?)*POW($PCT, EXTRACT(EPOCH FROM (U.CREATED - ?)) / $SEC_PER_YEAR)*?)::NUMERIC(20,10) ".
"WHERE U.UID IN (SELECT E.UID FROM ${prefix}EF E WHERE E.TID=?)"
);
$sth->execute($tid,$count?1:(-1),$tid,$wwhen,$count?1:(-1),$tid);
$sth=$dbh->prepare("SELECT E.UID FROM ${prefix}EF E WHERE E.TID=? AND (SELECT COUNT(*) FROM ${prefix}EDGEINFO I WHERE I.ETO=E.UID AND I.EFROM=? AND I.ETYP='d')=0");
$sth->execute($tid,$author); # make sure per-edge rows exist for the edges between author and affected ones
my $sth2;
while (my ($nuid) = $sth->fetchrow_array) {
$sth2=$dbh->prepare("INSERT INTO ${prefix}EDGEINFO (ETO,EFROM,ETYP) VALUES (?,?,'d')") if (!defined $sth2); # by creating defaults if necessary
$sth2->execute($nuid,$author) if ($nuid!=$author);
}
$sth=$dbh->prepare("SELECT E.UID FROM ${prefix}EF E WHERE E.TID=? AND (SELECT COUNT(*) FROM ${prefix}EDGEINFO I WHERE I.EFROM=E.UID AND I.ETO=? AND I.ETYP='d')=0");
$sth->execute($tid,$author); # and the other way around
while (my ($nuid) = $sth->fetchrow_array) {
$sth2=$dbh->prepare("INSERT INTO ${prefix}EDGEINFO (ETO,EFROM,ETYP) VALUES (?,?,'d')") if (!defined $sth2); # by creating defaults if necessary
$sth2->execute($author,$nuid) if ($nuid!=$author);
}
$sth=$dbh->prepare("UPDATE ${prefix}EDGEINFO I SET ". # and finally updating those
"TOTALSUM=I.TOTALSUM+((SELECT E.AMOUNT FROM ${prefix}EF E WHERE E.UID=I.ETO AND E.TID=?)*?)::NUMERIC(20,10), ".
"TOTALPCT=I.TOTALPCT+((SELECT E.AMOUNT FROM ${prefix}EF E WHERE E.UID=I.ETO AND E.TID=?)*POW($PCT, EXTRACT(EPOCH FROM (I.CREATED - ?)) / $SEC_PER_YEAR)*?)::NUMERIC(20,10) ".
"WHERE I.EFROM=? AND I.EFROM!=I.ETO AND I.ETO IN (SELECT E.UID FROM ${prefix}EF E WHERE E.TID=?)"
);
$sth->execute($tid,$count?1:(-1),$tid,$wwhen,$count?1:(-1),$author,$tid);
$sth=$dbh->prepare("UPDATE ${prefix}EDGEINFO I SET ". # and the other way around
"TOTALSUM=I.TOTALSUM+((SELECT E.AMOUNT FROM ${prefix}EF E WHERE E.UID=I.EFROM AND E.TID=?)*?)::NUMERIC(20,10), ".
"TOTALPCT=I.TOTALPCT+((SELECT E.AMOUNT FROM ${prefix}EF E WHERE E.UID=I.EFROM AND E.TID=?)*POW($PCT, EXTRACT(EPOCH FROM (I.CREATED - ?)) / $SEC_PER_YEAR)*?)::NUMERIC(20,10) ".
"WHERE I.ETO=? AND I.EFROM!=I.ETO AND I.EFROM IN (SELECT E.UID FROM ${prefix}EF E WHERE E.TID=?)"
);
$sth->execute($tid,$count?(-1):1,$tid,$wwhen,$count?(-1):1,$author,$tid);
}
}
} until (defined($locked) || $dbh->commit);
}
# process a request
sub proc_req {
my ($req,$lock)=@_;
my $sth=$dbh->prepare("DELETE FROM ${prefix}USERREQ WHERE EXPIRE<CURRENT_TIMESTAMP");
$sth->execute;
$dbh->begin_work if (!defined $lock);
$sth=$dbh->prepare("SELECT UNAME,FULLNAME,ACCNR,EMAIL,HTNAME,PWKEY,LEVEL FROM ${prefix}USERREQ WHERE RID=?");
$sth->execute($req);
my $sth2=$dbh->prepare("UPDATE ${prefix}USERS SET ACCNR=? WHERE UID=?");
my $nuid;
my $cnt=0;
while (my ($username,$fullname,$accnr,$email,$htname,$pwkey,$level) = $sth->fetchrow_array) {
$cnt++;
$nuid=create_user($username,$fullname,$email,1);
set_password($pwkey,$nuid,$level,1) if (defined $nuid && defined $pwkey);
set_htlogin($htname,$nuid,$level,1) if (defined $nuid && defined $htname);
$sth2->execute($accnr,$nuid) if (defined $nuid && defined $accnr);
}
if ($cnt==0) {
push @msg,['error',"Invalid activation code. It may have been used already, or expired."];
}
if (!defined $lock) {
return $nuid if $dbh->commit;
return undef;
}
return $nuid;
}
# fetch & cache user list
sub need_user_list {
return if (!defined $auth_username);
my ($full)=@_;
if (defined $full) {
my $sth=$dbh->prepare("SELECT UID,FULLNAME,ACTIVE FROM ${prefix}USERS");
$sth->execute;
while (my ($uid,$name,$active)=$sth->fetchrow_array) {
$USERS{$uid}->{NAME}=$name;
$USERS{$uid}->{UID}=$uid;
$USERS{$uid}->{ACTIVE}=$active;
}
$haveUSERS=0;
}
if (!$haveUSERS) {
$haveUSERS=1;
my $sth=$dbh->prepare("SELECT UID,NAME,TOTAL,EXTRA,ACCNR,ACTIVE FROM ${prefix}USERLIST WHERE UID=? OR (UID IN (SELECT SEEN FROM ${prefix}VISIBLE WHERE SEER=? UNION SELECT ETO FROM ${prefix}EDGEINFO WHERE EFROM=? AND (TOTALSUM!=0 OR TOTALPCT!=0) AND ETYP='d')) ORDER BY NAME");
$sth->execute($auth_uid,$auth_uid,$auth_uid);
while (my ($uid,$name,$total,$extra,$accnr,$active) = $sth->fetchrow_array) {
$USERS{$uid}={UID => $uid, NAME => $name, TOTAL => $total, EXTRA => $extra, ACCNR => $accnr, ACTIVE => $active};
$minExtra=$extra if (!defined($minExtra) || (defined($minExtra) && $extra<$minExtra));
$maxExtra=$extra if (!defined($maxExtra) || (defined($maxExtra) && $extra>$maxExtra));
$USERS{$uid}->{ORD} = $total;
my $fname=normalize_name($name);
$FUSERS{lc($fname)}=$uid;
}
$sth->finish;
$sth=$dbh->prepare("SELECT SEEN,LEVEL FROM ${prefix}VISIBLE WHERE SEER=? AND SEEN!=SEER");
$sth->execute($auth_uid);
while (my ($uid,$level) = $sth->fetchrow_array) {
if (defined $USERS{$uid}) {
$USERS{$uid}->{VIS}=$level if ($level>0);
}
}
$sth->finish;
}
}
# fetch & cache group list
sub need_group_list {
my ($gidr) = @_;
my $sth;
if (defined($gidr)) {
return if (defined $GROUPS{$gidr});
$sth=$dbh->prepare("SELECT G.GID,G.DEFINER,G.NAME,G.DESCR,G.ISPUBLIC,G.MAX,G.MAXFORM,G.WWHEN FROM ${prefix}GROUPS G WHERE ((G.DEFINER=?) OR (((SELECT COUNT(*) FROM ${prefix}SHARES S WHERE S.UID=? AND S.GID=G.GID)) > 0)) AND G.GID=? ORDER BY WWHEN");
$sth->execute($auth_uid,$auth_uid,$gidr);
} else {
return if ($haveGROUPS);
$sth=$dbh->prepare("SELECT G.GID,G.DEFINER,G.NAME,G.DESCR,G.ISPUBLIC,G.MAX,G.MAXFORM,G.WWHEN FROM ${prefix}GROUPS G WHERE ((G.DEFINER=?) OR (((SELECT COUNT(*) FROM ${prefix}SHARES S WHERE S.UID=? AND S.GID=G.GID)) > 0)) AND G.ISPUBLIC ORDER BY WWHEN");
$sth->execute($auth_uid,$auth_uid);
$haveGROUPS=1;
}
while (my ($gid,$definer,$name,$descr,$ispublic,$max,$maxform,$wwhen) = $sth->fetchrow_array) {
$GROUPS{$gid}={GID => $gid, DEFINER => $definer, NAME => $name, DESCR => $descr || "",MAX=>$max==0 ? "" : $max,MAXFORM => $maxform,WWHEN=>$wwhen,PUBLIC=>$ispublic,DNAME=>$name."(".substr($wwhen,0,10).")"};
}
}
sub parsedate {
my ($str) = @_;
if ($str =~ /(\d+)-(\d+)-(\d+) (\d+):(\d+):([0-9.]+)/) {
return timelocal(0,$5,$4,$3,$2-1,$1-1900)+$6;
} else {
return time;
}
}
sub trycommit {
my ($ok,@npath)=@_;
my $ret=$dbh->commit;
if (!$ret) {
push @msg,['error',"Database error. Try again."];
return 0;
} else {
@path=@npath if ($ok);
return $ok;
}
}
sub calculate_active {
my ($tid,$locked)=@_;
$dbh->begin_work if (!$locked);
my $active=1;
if ($active) { # do not accept things with a deny on them
my $sth=$dbh->prepare("SELECT COUNT(*) FROM ${prefix}EF E WHERE E.TID=? AND E.ACCEPT=FALSE");
$sth->execute($tid);
my ($cnt) = $sth->fetchrow_array;
$active=0 if ($cnt>0);
}
if ($active) { # do not accept things with a price over auto-accept setting of user without an accept
my $sth=$dbh->prepare("SELECT COUNT(*) FROM ${prefix}EF E, ${prefix}USERS U WHERE E.TID=? AND E.UID=U.UID AND E.ACCEPT IS NULL AND -E.AMOUNT>U.AUTOACCEPT");
$sth->execute($tid);
my ($cnt) = $sth->fetchrow_array;
$active=0 if ($cnt>0);
}
if ($active) { # do not accept things whose charge since last accept has been changed by at least the auto-accept value of affected user
my $sth=$dbh->prepare("SELECT COUNT(*) FROM ${prefix}EF E, ${prefix}USERS U WHERE E.TID=? AND E.UID=U.UID AND E.ACCEPT=TRUE AND E.SEEN-E.AMOUNT>U.AUTOACCEPT");
$sth->execute($tid);
my ($cnt) = $sth->fetchrow_array;
$active=0 if ($cnt>0);
}
my $sth=$dbh->prepare("UPDATE ${prefix}TR SET ACTIVE=? WHERE TID=?");
$sth->execute($active,$tid);
count_transaction($tid,$active,1);
trycommit(0) if (!$locked);
return 1;
}
sub change_accept {
my ($uid,$am,$x,$tid) = @_;
return if (!$auth_active);
my $ok=1;
$am=0 if (!defined($am));
$x=1 if (!defined($x));
$dbh->begin_work;
my $sth=$dbh->prepare("UPDATE ${prefix}EF SET ACCEPT=?, SEEN=? WHERE UID=? AND TID=?");
$sth->execute($x,$am,$uid,$tid);
$ok=calculate_active($tid,1);
trycommit(0);
return $ok;
}
sub delete_transaction {
my ($tid,$typ,$locked) = @_;
$dbh->begin_work if (!$locked);
# verify the transaction can be safely removed
my $sth=$dbh->prepare("SELECT COUNT(*) FROM ${prefix}EF E WHERE E.TID=? AND E.SEEN!=0 AND E.ACCEPT=TRUE");
$sth->execute($tid);
my ($cnt)=$sth->fetchrow_array;
if ($cnt>0) {
push @msg,['warn',"Cannot delete transaction. Please make sure the transaction has value zero, and that all people involved acknowledge it."];
$dbh->rollback;
return 0;
}
# do not count transaction
count_transaction($tid,0,1);
# effectively remove the transaction and all its effects
if ($typ eq 'i') {
$sth=$dbh->prepare("DELETE FROM ${prefix}ITEM WHERE TID=?");
$sth->execute($tid);
} elsif ($typ eq 'b') {
$sth=$dbh->prepare("DELETE FROM ${prefix}BILL WHERE TID=?");
$sth->execute($tid);
}
$sth=$dbh->prepare("DELETE FROM ${prefix}EF WHERE TID=?");
$sth->execute($tid);
$sth=$dbh->prepare("DELETE FROM ${prefix}TR WHERE TID=?");
$sth->execute($tid);
# delete orphan groups (TODO: speedup by only selecting groups which are affected by deleted statement)
$sth=$dbh->prepare("SELECT G.GID FROM ${prefix}GROUPS G WHERE G.ISPUBLIC=FALSE AND (SELECT COUNT(*) FROM ${prefix}TR T WHERE T.AFG=G.GID)=0");
$sth->execute;
my $sth2=$dbh->prepare("DELETE FROM ${prefix}SHARES WHERE GID=?");
my $sth3=$dbh->prepare("DELETE FROM ${prefix}GROUPS WHERE GID=?");
while (my ($dgid) = $sth->fetchrow_array) {
$sth2->execute($dgid);
$sth3->execute($dgid);
}
return trycommit(1) if (!$locked);
@path=();
}
sub calculate_effects {
my ($tid,$locked) = @_;
my @eff;
$dbh->begin_work if (!$locked);
count_transaction($tid,0,1);
my $sth=$dbh->prepare("SELECT T.TYP,T.AFU,T.AFG,T.AUTHOR FROM ${prefix}TR T WHERE T.TID=?");
$sth->execute($tid);
my ($typ,$afu,$afg,$author)=$sth->fetchrow_array;
if (!defined $typ) {
push @msg,['error',"Fatal error: transaction $tid does not exist. Contact administrator."];
$dbh->rollback if (!$locked);
return 0;
}
if ($typ eq 'i') { # ITEM
if (defined $afu && defined $afg) {
push @msg,['error',"Fatal error: item $tid affects both user $afu and group $afg. Contact administrator."];
$dbh->rollback if (!$locked);
return 0;
}
if (!defined $afu && !defined $afg) {
push @msg,['error',"Fatal error: item $tid affects neither a user or a group. Contact administrator."];
$dbh->rollback if (!$locked);;
return 0;
}
$sth=$dbh->prepare("SELECT I.AMOUNT FROM ${prefix}ITEM I WHERE I.TID=?");
$sth->execute($tid);
my ($am)=$sth->fetchrow_array;
if (!defined $am) {
push @msg,['error',"Fatal error: no item-specific data for transaction $tid. Contact administrator."];
$dbh->rollback if (!$locked);;
return 0;
}
if (defined $afu) {
push @eff,[$afu,-1,1,$am];
} else {
$sth=$dbh->prepare("SELECT SUM(S.AMOUNT), G.MAX FROM ${prefix}GROUPS G, ${prefix}SHARES S WHERE G.GID=? AND S.GID=? GROUP BY G.MAX");
$sth->execute($afg,$afg);
my ($tot,$max) = $sth->fetchrow_array;
$tot=0 if (!defined $tot);
$max=0 if (!defined $max);
$max=$tot if ($tot>$max);
$sth=$dbh->prepare("SELECT S.UID, S.AMOUNT FROM ${prefix}SHARES S WHERE S.GID=?");
$sth->execute($afg);
while (my ($uid,$sh) = $sth->fetchrow_array) {
push @eff,[$uid,-$sh,$max,$am];
}
}
} elsif ($typ eq 'b') {
$sth=$dbh->prepare("SELECT B.DEFINITION FROM ${prefix}BILL B WHERE B.TID=?");
$sth->execute($tid);
my ($def)=$sth->fetchrow_array;
if (!defined $def) {
push @msg,['error',"Fatal error: no bill-specific data for transaction $tid. Contact administrator."];
$dbh->rollback if (!$locked);
return 0;
}
my ($ndef,$err,$tot,$cont,@effects)=process_bill($def,0);
if (defined $ndef) {
push @eff,@effects;
} else {
# TODO: warning ofzo, ongeldige bill
}
} else {
push @msg,['error',"Fatal error: transaction $tid has unknown type '$typ'. Contact administrator."];
$dbh->rollback if (!$locked);
return 0;
}
$sth=$dbh->prepare("UPDATE ${prefix}EF SET AMOUNT=0 WHERE TID=?"); # reset all effects to zero
$sth->execute($tid);
my $sth1=$dbh->prepare("SELECT COUNT(*) FROM ${prefix}EF WHERE TID=? AND UID=?"); # check whether they exist
my $sth2=$dbh->prepare("INSERT INTO ${prefix}EF (TID,UID,AMOUNT) VALUES(?,?,((?::NUMERIC(18,10))*?)/?)"); # if not, add them
my $sth3=$dbh->prepare("UPDATE ${prefix}EF SET AMOUNT=AMOUNT+(((?::NUMERIC(18,10))*?)/?) WHERE TID=? AND UID=?"); # otherwise, update them
for my $eff (@eff) {
my ($uid,$num,$den,$am)=@{$eff};
if ($uid != $author) {
$sth1->execute($tid,$uid);
my ($cnt)=$sth1->fetchrow_array;
if ($cnt) {
$sth3->execute($am,$num,$den,$tid,$uid);
} else {
$sth2->execute($tid,$uid,$am,$num,$den);
}
}
}
$sth1->execute($tid,$author);
my ($cnt)=$sth1->fetchrow_array;
if ($cnt) {
$sth=$dbh->prepare("UPDATE ${prefix}EF SET AMOUNT=COALESCE(-(SELECT SUM(E.AMOUNT) FROM ${prefix}EF E WHERE E.TID=?),0) WHERE TID=? AND UID=?");
$sth->execute($tid,$tid,$author);
} else {
$sth=$dbh->prepare("INSERT INTO ${prefix}EF (TID,UID,AMOUNT) VALUES (?,?,COALESCE(-(SELECT SUM(E.AMOUNT) FROM ${prefix}EF E WHERE E.TID=?),0))");
$sth->execute($tid,$author,$tid);
}
calculate_active($tid,1);
trycommit(0) if (!$locked);
return 1;
}
# use -2 for invalid, as -1 is already used for admin user
sub lookup_user {
need_user_list;
my ($prefix) = @_;
my $uid;
$prefix=lc(normalize_name($prefix));
my $len=length($prefix);
for my $name (keys %FUSERS) {
if (length($name) >= $len && substr($name,0,$len) eq $prefix) {
return $FUSERS{$name} if (length($name) == $len);
if (!defined $uid || $FUSERS{$name}==$uid) {
$uid=$FUSERS{$name};
} else {
return -2;
}
}
}
return $uid;
}
sub get_random_names {
my ($want) = @_;
my @rn;
need_user_list;
my @users=grep {$_ != $auth_uid} (keys %USERS);
my $num=scalar @users;
my $rng=$num; $rng=$want if ($rng<$want);
for my $i (0..$want-1) {
while (1) {
my $rn=int(rand($rng));
my $x=0;
for my $j (0..$i-1) {
if ($rn==$rn[$j]) { $x=1; last; }