-
Notifications
You must be signed in to change notification settings - Fork 3
/
Sldb.pm
2016 lines (1815 loc) · 72.2 KB
/
Sldb.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
# Perl module implementing the SLDB data model.
# This file is part of SLDB.
#
# Copyright (C) 2013-2021 Yann Riou <[email protected]>
#
# SLDB 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 3 of the License, or
# (at your option) any later version.
#
# SLDB 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 SLDB. If not, see <http://www.gnu.org/licenses/>.
#
package Sldb;
use strict;
use DBI;
use File::Basename 'dirname';
use File::Spec::Functions qw'catfile rel2abs';
use List::Util 'sum';
use Time::HiRes;
use SimpleConf;
use SimpleLog;
my $scriptDir=dirname(rel2abs($0));
my $confFile=catfile($scriptDir,'etc','sldb.conf');
my %conf=(defaultPref => { ircColors => 1,
privacyMode => 1 } );
SimpleConf::readConf($confFile,\%conf) if(-f $confFile);
my $moduleVersion='0.8';
my %ADMIN_EVT_TYPE=('UPD_USERDETAILS' => 0,
'JOIN_ACC' => 1,
'SPLIT_ACC' => 2,
'ADD_PROB_SMURF' => 3,
'DEL_PROB_SMURF' => 4,
'ADD_NOT_SMURF' => 5,
'DEL_NOT_SMURF' => 6,
'SET_STARTSKILL' => 7,
'RESET_STARTSKILL' => 8);
my %ADMIN_EVT_PARAMS=(0 => [qw/updatedUserId updatedParam oldValue newValue/],
1 => [qw/mainUserId childUserId/],
2 => [qw/oldUserId newUserId accountId/],
3 => [qw/accountId1 accountId2/],
4 => [qw/accountId1 accountId2/],
5 => [qw/accountId1 accountId2/],
6 => [qw/accountId1 accountId2/],
7 => [qw'accountId modShortName startSkill'],
8 => [qw'accountId modShortName']);
my %ADMIN_EVT_MSG=(0 => 'Update of setting "%updatedParam%" for user "%updatedUserId%": "%oldValue%" --> "%newValue%"',
1 => 'Join of account "%childUserId%" with user "%mainUserId%"',
2 => 'Split of account "%accountId%" and user "%oldUserId%" (new user: "%newUserId%")',
3 => 'New probable smurfs: "%accountId1%" <-> "%accountId2%"',
4 => 'Removal of probable smurfs: "%accountId1%" <-> "%accountId2%"',
5 => 'New not-smurfs record: "%accountId1%" <-> "%accountId2%"',
6 => 'Removal of not-smurfs record: "%accountId1%" <-> "%accountId2%"',
7 => 'Set "%modShortName%" start skill of account "%accountId%" to "%startSkill%"',
8 => 'Reset "%modShortName%" start skill of account "%accountId%"');
my %gameTypeMapping=('Duel' => 'Duel',
'FFA' => 'Ffa',
'Team' => 'Team',
'TeamFFA' => 'TeamFfa',
'Global' => '');
my %ACCOUNTS_PREF=( ircColors => ['[01]',$conf{defaultPref}{ircColors}] );
my %USERS_PREF=( privacyMode => ['[012]',$conf{defaultPref}{privacyMode}] );
my $chartClickerUnavailable;
sub new {
my ($objectOrClass,$p_params)=@_;
my $class = ref($objectOrClass) || $objectOrClass;
my $self={ dbDs => undef,
dbLogin => undef,
dbPwd => undef,
sLog => undef,
sqlErrorHandler => undef };
foreach my $param (keys %{$p_params}) {
if(grep(/^$param$/,(keys %{$self}))) {
$self->{$param}=$p_params->{$param};
}else{
$self->{sLog}=SimpleLog->new(prefix => "[Sldb] ") unless(defined $self->{sLog});
$self->{sLog}->log("Ignoring invalid constructor parameter ($param)",2);
}
}
foreach my $param (keys %{$self}) {
if(! defined $self->{$param}) {
$self->{sLog}=SimpleLog->new(prefix => "[Sldb] ") unless(defined $self->{sLog});
$self->{sLog}->log("Missing parameter \"$param\" in constructor call",1);
exit;
}
}
$self->{dbh}=undef;
bless ($self, $class);
return $self;
}
sub getVersion {
return $moduleVersion;
}
sub log {
my ($self,$m,$l)=@_;
$self->{sLog}->log($m,$l);
}
###################
# Basic functions #
###################
sub connect {
my ($self,$p_options)=@_;
my $p_connectOptions={AutoCommit => 1, mysql_auto_reconnect => 1};
if(defined $p_options && %{$p_options}) {
foreach my $option (keys %{$p_options}) {
$p_connectOptions->{$option}=$p_options->{$option}
}
}
if(defined $self->{dbh}) {
$self->log("connect(): Already connected to a database, use \"disconnect()\" first",2);
return 0;
}
$self->{dbh}=DBI->connect($self->{dbDs},$self->{dbLogin},$self->{dbPwd},$p_connectOptions);
if(! $self->{dbh}) {
&{$self->{sqlErrorHandler}}("Unable to connect to Spring Lobby Database ($DBI::errstr)");
return 0;
}
return 1;
}
sub disconnect {
my $self=shift;
if(! defined $self->{dbh}) {
$self->log("disconnect(): module is not connected to any database, use \"connect()\" first",2);
return 0;
}
if(! $self->{dbh}->disconnect()) {
$self->log("disconnect(): unable to disconnect from database ($DBI::errstr)",1);
return 0;
}
return 1;
}
sub quote {
my ($self,@params)=@_;
if(! defined $self->{dbh}) {
my $paramsString=join(',',@params);
&{$self->{sqlErrorHandler}}("Unable to quote value(s) \"$paramsString\" (module is not connected!)");
return @params;
}
my @res=map {$self->{dbh}->quote($_)} @params;
if($#res == 0) {
return $res[0];
}else{
return @res;
}
}
sub do {
my ($self,$sqlCommand,$desc,$p_errorHandler)=@_;
$desc="execute \"$sqlCommand\"" unless(defined $desc);
$self->log("SLDB: $desc",5);
$desc="Unable to $desc";
$p_errorHandler=$self->{sqlErrorHandler} unless(defined $p_errorHandler);
if(! defined $self->{dbh}) {
&{$p_errorHandler}("$desc (module is not connected!)");
return 0;
}
$self->log("SQL DO: $sqlCommand",5);
if(! $self->{dbh}->do($sqlCommand)) {
&{$p_errorHandler}("$desc ($DBI::errstr)");
return 0;
}
return 1;
}
sub prepExec {
my ($self,$sqlCommand,$desc)=@_;
$desc="select \"$sqlCommand\"" unless(defined $desc);
$self->log("SLDB: $desc",5);
$desc="Unable to $desc";
if(! defined $self->{dbh}) {
&{$self->{sqlErrorHandler}}("$desc (module is not connected!)");
return 0;
}
$self->log("SQL PREPARE AND EXEC: $sqlCommand",5);
my $sth=$self->{dbh}->prepare($sqlCommand);
if(! $sth->execute()) {
&{$self->{sqlErrorHandler}}("$desc (".$sth->errstr.')');
return 0;
}
return $sth;
}
#################
# Init function #
#################
# Called by sldbSetup.pl
sub createTablesIfNeeded {
my $self=shift;
$self->do('
create table if not exists accounts (
id int unsigned primary key,
rank tinyint(1) unsigned,
admin tinyint(1) unsigned,
bot tinyint(1) unsigned,
lastUpdate timestamp,
index (lastUpdate)
) engine=MyISAM','create table "accounts"');
$self->do('
create table if not exists names (
accountId int unsigned,
name char(20),
lastConnection timestamp,
primary key (accountId,name),
index (name),
index (lastConnection)
) engine=MyISAM','create table "names"');
$self->do('
create table if not exists countries (
accountId int unsigned,
country char(2),
lastConnection timestamp,
primary key (accountId,country),
index (country),
index (lastConnection)
) engine=MyISAM','create table "countries"');
$self->do('
create table if not exists hardwareIds (
accountId int unsigned,
hardwareId int unsigned,
lastConnection timestamp,
primary key (accountId,hardwareId),
index (lastConnection)
) engine=MyISAM','create table "hardwareIds"');
$self->do('
create table if not exists systemIds (
accountId int unsigned,
systemId bigint unsigned,
lastConnection timestamp,
primary key (accountId,systemId),
index (lastConnection)
) engine=MyISAM','create table "systemIds"');
$self->do('
create table if not exists games (
hostAccountId int unsigned,
startTimestamp timestamp default 0,
endTimestamp timestamp default 0,
endCause tinyint(1) unsigned,
hostName char(20),
modName varchar(255),
mapName varchar(255),
nbSpec tinyint unsigned,
nbPlayer tinyint unsigned,
description varchar(255),
passworded tinyint(1) unsigned,
engineName varchar(30),
engineVersion varchar(100),
gameId char(32),
primary key (hostAccountId,startTimestamp),
index (startTimestamp),
index (endTimestamp),
index (modName),
index (mapName),
index (engineVersion),
unique index (gameId)
) engine=MyISAM','create table "games"');
$self->do('
create table if not exists players (
hostAccountId int unsigned,
startTimestamp timestamp default 0,
accountId int unsigned,
name char(20),
primary key (hostAccountId,startTimestamp,accountId),
index (startTimestamp),
index (accountId)
) engine=MyISAM','create table "players"');
$self->do('
create table if not exists gamesDetails (
gameId char(32) primary key,
gdrTimestamp timestamp default 0,
startTimestamp timestamp default 0,
endTimestamp timestamp default 0,
duration int unsigned,
engine varchar(64),
type char(16),
structure varchar(64),
bots tinyint unsigned,
undecided tinyint unsigned,
cheating tinyint unsigned,
index (gdrTimestamp),
index (startTimestamp),
index (endTimestamp)
) engine=MyISAM','create table "gamesDetails"');
$self->do('
create table if not exists playersDetails (
gameId char(32),
accountId int unsigned,
name char(20),
ip int unsigned,
team tinyint unsigned,
allyTeam tinyint unsigned,
win tinyint(1) unsigned,
primary key (gameId,accountId),
index (accountId),
index (name),
index (ip)
) engine=MyISAM','create table "playersDetails"');
$self->do('
create table if not exists botsDetails (
gameId char(32),
name char(20),
ownerAccountId int unsigned,
ai varchar(64),
team tinyint unsigned,
allyTeam tinyint unsigned,
win tinyint(1) unsigned,
primary key (gameId,name)
) engine=MyISAM','create table "botsDetails"');
$self->do('
create table if not exists userAccounts (
accountId int unsigned primary key,
userId int unsigned,
nbIps int unsigned,
noSmurf tinyint(1) unsigned,
index (userId)
) engine=MyISAM','create table "userAccounts"');
$self->do('
create table if not exists userDetails (
userId int unsigned primary key,
name char(24),
clanTag char(18),
email varchar(64),
forumId int unsigned,
nbIps int unsigned,
unique index (name)
) engine=MyISAM','create table "userDetails"');
$self->do('
create table if not exists ips (
accountId int unsigned,
ip int unsigned,
lastSeen timestamp,
primary key (accountId,ip),
index (ip),
index (lastSeen)
) engine=MyISAM','create table "ips"');
$self->do('
create table if not exists ipRanges (
accountId int unsigned,
ip1 int unsigned,
ip2 int unsigned,
lastSeen timestamp,
primary key (accountId,ip1),
index (ip1),
index (ip2),
index (lastSeen)
) engine=MyISAM','create table "ipRanges"');
$self->do('
create table if not exists userIps (
userId int unsigned,
ip int unsigned,
lastSeen timestamp,
primary key (userId,ip),
index (ip),
index (lastSeen)
) engine=MyISAM','create table "userIps"');
$self->do('
create table if not exists userIpRanges (
userId int unsigned,
ip1 int unsigned,
ip2 int unsigned,
lastSeen timestamp,
primary key (userId,ip1),
index (ip1),
index (ip2),
index (lastSeen)
) engine=MyISAM','create table "userIpRanges"');
$self->do('
create table if not exists smurfs (
id1 int unsigned,
id2 int unsigned,
status tinyint unsigned,
orig int unsigned,
primary key (id1,id2),
index (id2)
) engine=MyISAM','create table "notSmurf"');
$self->do('
create table if not exists adminEvents (
eventId int unsigned auto_increment primary key,
date timestamp,
type smallint unsigned,
subType smallint unsigned,
orig tinyint unsigned,
origId int unsigned,
message varchar(255),
index (date)
) engine=MyISAM','create table "adminEvents"');
$self->do('
create table if not exists adminEventsParams (
eventId int unsigned,
paramName char(16),
paramValue varchar(64),
primary key (eventId,paramName)
) engine=MyISAM','create table "adminEventsParams"');
$self->do('
create table if not exists rtBattles (
battleId int unsigned primary key,
founderId int unsigned,
founder varchar(30),
ip int unsigned,
port smallint unsigned,
type tinyint(1),
natType tinyint(1),
locked tinyint(1),
passworded tinyint(1),
rankLimit tinyint(1) unsigned,
modName varchar(255),
mapName varchar(255),
mapHash int,
description varchar(255),
maxPlayers int,
nbSpec tinyint unsigned,
engineName varchar(30),
engineVersion varchar(100),
index(founderId),
index(founder),
index(ip),
index(port),
index(modName),
index(mapName),
index(mapHash),
index(description),
index(maxPlayers),
index(nbSpec)
) engine=MyISAM','create table "rtBattles"');
$self->do('
create table if not exists rtPlayers (
accountId int unsigned primary key,
name varchar(30),
access tinyint(1),
bot tinyint(1),
country char(2),
lobbyClient varchar(64),
rank tinyint(1),
inGame tinyint(1),
gameTimestamp timestamp default 0,
away tinyint(1),
awayTimestamp timestamp default 0,
index(name),
index(country)
) engine=MyISAM','create table "rtPlayers"');
$self->do('
create table if not exists rtBattlePlayers (
accountId int unsigned primary key,
battleId int unsigned,
index(battleId)
) engine=MyISAM','create table "rtBattlePlayers"');
$self->do('
create table if not exists gamesNames (
name varchar(64) primary key,
shortName char(8),
regex varchar(64),
testRegex varchar(64),
chickenRegex varchar(64),
index(shortName)
) engine=MyISAM','create table "gamesNames"');
my @lTime=localtime();
my $currentPeriod=($lTime[5]+1900).sprintf('%02d',$lTime[4]+1);
foreach my $gameType (values %gameTypeMapping) {
$self->do("
create table if not exists ts${gameType}Games (
gameId char(32),
accountId int unsigned,
userId int unsigned,
modShortName char(8),
gdrTimestamp timestamp,
muBefore decimal(7,4),
sigmaBefore decimal(7,4),
muAfter decimal(7,4),
sigmaAfter decimal(7,4),
primary key (gameId,accountId),
index(accountId),
index(userId),
index(gdrTimestamp)
) engine=MyISAM","create table \"ts${gameType}Games\"");
$self->do("
create table if not exists ts${gameType}Players (
period int unsigned,
userId int unsigned,
modShortName char(8),
skill decimal(7,4),
mu decimal(7,4),
sigma decimal(7,4),
nbPenalties smallint unsigned,
primary key (period,userId,modShortName),
index(skill)
) engine=MyISAM partition by list(period) ( partition p$currentPeriod values in ($currentPeriod) )","create partitioned table \"ts${gameType}Players\"");
}
$self->do("
create table if not exists tsStartSkills (
accountId int unsigned,
modShortName char(8),
startSkill smallint unsigned,
primary key (accountId,modShortName)
) engine=MyISAM",'create table "tsStartSkills"');
$self->do('
create table if not exists tsRatingQueue (
gameId char(32) primary key,
gdrTimestamp timestamp default 0,
status tinyint(1),
index(gdrTimestamp)
) engine=MyISAM','create table "tsRatingQueue"');
$self->do('
create table if not exists tsRatingState (
param varchar(32) primary key,
value varchar(32)
) engine=MyISAM','create table "tsRatingState"');
$self->do('
create table if not exists rerateRequests (
type char(1),
id char(32),
startPeriod int unsigned,
status tinyint(1),
requestTimestamp Timestamp default 0,
primary key (type,id,status)
) engine=MyISAM','create table "rerateRequests"');
$self->do('
create table if not exists pendingRerates (
modShortName char(8) primary key,
startPeriod int unsigned,
requestTimestamp Timestamp default 0
) engine=MyISAM','create table "pendingRerates"');
$self->do('
create table if not exists prefAccounts (
accountId int unsigned,
prefName char(16),
prefValue varchar(64),
primary key (accountId,prefName)
) engine=MyISAM','create table "prefAccounts"');
$self->do('
create table if not exists prefUsers (
userId int unsigned,
prefName char(16),
prefValue varchar(64),
primary key (userId,prefName)
) engine=MyISAM','create table "prefUsers"');
}
##################################
# User/account lookup functions #
##################################
# Called by sldbLi.pl, getIdType(), getUserPref(), setUserPref(), getSkills(), getPlayerStats()
sub getUserId {
my ($self,$id)=@_;
my $sth=$self->prepExec("select userId from userAccounts where accountId=$id","retrieve userId for accountId \"$id\" from userAccounts table");
my @results=$sth->fetchrow_array();
return $results[0] if(@results);
return undef;
}
# Called by getUserSmurfs()
sub getUserIds {
my ($self,$p_ids)=@_;
return [] unless(@{$p_ids});
my $idsString=join(',',@{$p_ids});
my $sth=$self->prepExec("select distinct(userId) from userAccounts where accountId in ($idsString)","retrieve userIds for accountIds \"$idsString\" from userAccounts table");
my @userIds;
my @result;
while(@result=$sth->fetchrow_array()) {
push(@userIds,$result[0]);
}
return \@userIds;
}
# Called by sldbLi.pl, identifyUniqueAccountByString(), identifyUniqueAccountByStringUserFirst()
sub getUserIdByName {
my ($self,$name)=@_;
my $quotedName=$self->quote($name);
my $sth=$self->prepExec("select ud.userId from userDetails ud,userAccounts ua where ud.name=$quotedName and ua.userId=ud.userId and ua.userId=ua.accountId");
my @results=$sth->fetchrow_array();
if(@results) {
return $results[0];
}else{
return undef;
}
}
# Called by sldbLi.pl
sub getIdType {
my ($self,$id)=@_;
return 'invalid' unless($id =~ /^\d+$/);
my $userId=$self->getUserId($id);
return 'unknown' unless(defined $userId);
return 'user' if($userId == $id);
return 'account';
}
# Called by sldbLi.pl, getUsersSmurfStates(), deleteUsersSmurfStates(), getUserOrderedSmurfGroups()
sub getUserAccounts {
my ($self,$userId)=@_;
my @accounts;
my $sth=$self->prepExec("select accountId from userAccounts where userId=$userId","retrieve accounts of user \"$userId\"");
my @account;
while(@account=$sth->fetchrow_array()) {
push(@accounts,$account[0]);
}
return \@accounts;
}
# Called by sldbLi.pl
sub identifyUniqueAccountByString {
my ($self,$search)=@_;
my $quotedSearch=$self->quote($search);
my $sth=$self->prepExec("select accountId from names where name=$quotedSearch limit 2","search $quotedSearch in names table");
my $p_results=$sth->fetchall_arrayref();
return -1 if($#{$p_results} > 0);
return $p_results->[0]->[0] if($#{$p_results} == 0);
my $getByNameRes=$self->getUserIdByName($search);
return $getByNameRes if(defined $getByNameRes);
$quotedSearch=$self->quote('%'.$search.'%');
$sth=$self->prepExec("select distinct(accountId) from names where name like $quotedSearch limit 2","search $quotedSearch matches in names table");
$p_results=$sth->fetchall_arrayref();
return -3 if($#{$p_results} > 0);
return $p_results->[0]->[0] if($#{$p_results} == 0);
$sth=$self->prepExec("select ud.userId from userDetails ud,userAccounts ua where ud.name like $quotedSearch and ud.userId=ua.userId and ua.accountId=ua.userId limit 2","search $quotedSearch matches in userDetails and userAccounts tables");
$p_results=$sth->fetchall_arrayref();
return -2 if($#{$p_results} > 0);
return $p_results->[0]->[0] if($#{$p_results} == 0);
return undef;
}
# Called by sldbLi.pl
sub identifyUniqueAccountByStringUserFirst {
my ($self,$search)=@_;
my $getByNameRes=$self->getUserIdByName($search);
return $getByNameRes if(defined $getByNameRes);
my $quotedSearch=$self->quote($search);
my $sth=$self->prepExec("select accountId from names where name=$quotedSearch limit 2","search $quotedSearch in names table");
my $p_results=$sth->fetchall_arrayref();
return -1 if($#{$p_results} > 0);
return $p_results->[0]->[0] if($#{$p_results} == 0);
$quotedSearch=$self->quote('%'.$search.'%');
$sth=$self->prepExec("select ud.userId from userDetails ud,userAccounts ua where ud.name like $quotedSearch and ud.userId=ua.userId and ua.accountId=ua.userId limit 2","search $quotedSearch matches in userDetails and userAccounts tables");
$p_results=$sth->fetchall_arrayref();
return -2 if($#{$p_results} > 0);
return $p_results->[0]->[0] if($#{$p_results} == 0);
$sth=$self->prepExec("select distinct(accountId) from names where name like $quotedSearch limit 2","search $quotedSearch matches in names table");
$p_results=$sth->fetchall_arrayref();
return -3 if($#{$p_results} > 0);
return $p_results->[0]->[0] if($#{$p_results} == 0);
return undef;
}
####################################
# Preferences management functions #
####################################
# Called by sldbLi.pl
sub getAccountPref {
my ($self,$accountId,$pref,$p_val)=@_;
foreach my $realPref (keys %ACCOUNTS_PREF) {
if(lc($pref) eq lc($realPref)) {
$pref=$realPref;
last;
}
}
return 0 if(! exists $ACCOUNTS_PREF{$pref});
my $quotedPref=$self->quote($pref);
my $sth=$self->prepExec("select prefValue from prefAccounts where accountId=$accountId and prefName=$quotedPref");
my @result=$sth->fetchrow_array();
if(@result) {
${$p_val}=$result[0] if(defined $p_val);
return 1;
}else{
${$p_val}=$ACCOUNTS_PREF{$pref}->[1] if(defined $p_val);
return 2;
}
}
# Called by sldbLi.pl
sub setAccountPref {
my ($self,$accountId,$pref,$val)=@_;
foreach my $realPref (keys %ACCOUNTS_PREF) {
if(lc($pref) eq lc($realPref)) {
$pref=$realPref;
last;
}
}
return 0 unless(exists $ACCOUNTS_PREF{$pref});
my $quotedPref=$self->quote($pref);
if(defined $val) {
return -1 if($val !~ /^$ACCOUNTS_PREF{$pref}->[0]$/);
my $quotedVal=$self->quote($val);
$self->do("insert into prefAccounts values ($accountId,$quotedPref,$quotedVal) on duplicate key update prefValue=$quotedVal");
return 1;
}else{
$self->do("delete from prefAccounts where accountId=$accountId and prefName=$quotedPref");
return 2;
}
}
# Called by sldbLi.pl, xmlRpc.pl
sub getUserPref {
my ($self,$id,$pref,$p_val)=@_;
foreach my $realPref (keys %USERS_PREF) {
if(lc($pref) eq lc($realPref)) {
$pref=$realPref;
last;
}
}
return 0 if(! exists $USERS_PREF{$pref});
my $userId=$self->getUserId($id);
if(defined $userId) {
my $quotedPref=$self->quote($pref);
my $sth=$self->prepExec("select prefValue from prefUsers where userId=$userId and prefName=$quotedPref");
my @result=$sth->fetchrow_array();
if(@result) {
${$p_val}=$result[0] if(defined $p_val);
return 1;
}
}
${$p_val}=$USERS_PREF{$pref}->[1] if(defined $p_val);
return 2;
}
# Called by sldbLi.pl, xmlRpc.pl
sub setUserPref {
my ($self,$id,$pref,$val)=@_;
foreach my $realPref (keys %USERS_PREF) {
if(lc($pref) eq lc($realPref)) {
$pref=$realPref;
last;
}
}
return 0 unless(exists $USERS_PREF{$pref});
my $userId=$self->getUserId($id);
return -2 unless(defined $userId);
my $quotedPref=$self->quote($pref);
if(defined $val) {
return -1 if($val !~ /^$USERS_PREF{$pref}->[0]$/);
my $quotedVal=$self->quote($val);
$self->do("insert into prefUsers values ($userId,$quotedPref,$quotedVal) on duplicate key update prefValue=$quotedVal");
return 1;
}else{
$self->do("delete from prefUsers where userId=$userId and prefName=$quotedPref");
return 2;
}
}
#####################################
# Parameterization access functions #
#####################################
# Called by sldbLi.pl
sub getModNameFromShortName {
my ($self,$modShortName)=@_;
my $quotedModShortName=$self->quote($modShortName);
my $sth=$self->prepExec("select name from gamesNames where shortName=$quotedModShortName");
my @found=$sth->fetchrow_array();
return $found[0] if(@found);
return undef;
}
# Called by sldbLi.pl
sub getModShortName {
my ($self,$mod)=@_;
my $quotedMod=$self->quote($mod);
my $sth=$self->prepExec("select shortName from gamesNames where $quotedMod regexp regex or $quotedMod regexp testRegex");
my @found=$sth->fetchrow_array();
return $found[0] if(@found);
return undef;
}
# Called by sldbLi.pl, ratingEngine.pl, fixModShortName()
sub getModsShortNames {
my $self=shift;
my $sth=$self->prepExec('select shortName from gamesNames','retrieve mods short names from gamesNames');
my @shortNames;
my @shortName;
while(@shortName=$sth->fetchrow_array()) {
push(@shortNames,$shortName[0]);
}
return \@shortNames;
}
# Called by sldbLi.pl, xmlRpc.pl
sub fixModShortName {
my ($self,$modShortName)=@_;
my $p_allowedMods=$self->getModsShortNames();
for my $msn (@{$p_allowedMods}) {
return $msn if(lc($modShortName) eq lc($msn));
}
return;
}
# Called by sldbLi.pl, xmlRpc.pl
sub fixGameType {
my ($self,$gameType)=@_;
foreach my $gt (keys %gameTypeMapping) {
return $gt if(lc($gameType) eq lc($gt));
}
return;
}
#######################
# Statistics function #
#######################
# Called by xmlRpc.pl
sub getPlayerStats {
my ($self,$accountId,$modShortName,$mode)=@_;
my $userId=$self->getUserId($accountId);
if(! defined $userId) {
$self->log("getPlayerStats called for an unknown ID \"$accountId\"",2);
return {};
}
if(! defined $mode) {
my $userPrivacyMode;
$self->getUserPref($accountId,'privacyMode',\$userPrivacyMode);
if($userPrivacyMode) {
$mode='account';
}else{
$mode='user';
}
}
my $sqlWherePart;
if($mode eq 'user') {
$sqlWherePart=", userAccounts ua where ua.userId=$userId and ua.accountId=pd.accountId";
}else{
$sqlWherePart=" where pd.accountId=$accountId";
}
my $quotedModShortName=$self->quote($modShortName);
my %results;
foreach my $gameType (keys %gameTypeMapping) {
next if($gameType eq 'Global');
$results{$gameType}={won => 0, lost => 0, draw => 0};
}
my @resultMapping=('lost','won','draw');
my $sth=$self->prepExec("select gd.type,pd.win,count(*) from games g,gamesNames gn, gamesDetails gd, playersDetails pd$sqlWherePart and pd.gameId=gd.gameId and gd.type!='Solo' and gd.bots=0 and gd.undecided=0 and gd.cheating=0 and gd.gameId=g.gameId and g.modName regexp gn.regex and gn.shortName=$quotedModShortName and pd.team is not null group by gd.type,pd.win","extract players stats data from games,gamesNames,gamesDetails,playersDetails,userAccounts tables");
my @sqlResults;
while(@sqlResults=$sth->fetchrow_array()) {
my ($gameType,$result,$count)=@sqlResults;
$result=$resultMapping[$result];
$results{$gameType}->{$result}=$count;
}
return \%results;
}
# Called by xmlRpc.pl
sub getPlayerSkillGraphs {
my ($self,$accountId,$modShortName)=@_;
my $sth=$self->prepExec("select ua.userId,ud.name from userAccounts ua,userDetails ud where ua.accountId=$accountId and ua.userId=ud.userId");
my @results=$sth->fetchrow_array();
if(! @results) {
$self->log("getPlayerSkillGraphs called for an unknown ID \"$accountId\"",2);
return undef;
}
my ($userId,$userName)=@results;
return $self->generateSkillGraphs($userId,$userName,$modShortName);
}
# Called by sldbLi.pl, getPlayerSkillGraphs()
sub generateSkillGraphs {
my ($self,$userId,$userName,$modShortName,$tmpDir)=@_;
if(! defined $chartClickerUnavailable) {
eval <<'END_OF_EVAL_LIST';
use Chart::Clicker;
use Chart::Clicker::Context;
use Chart::Clicker::Data::DataSet;
use Chart::Clicker::Data::Series;
use Chart::Clicker::Drawing::ColorAllocator;
use Chart::Clicker::Renderer::Line;
use Chart::Clicker::Renderer::StackedArea;
use Graphics::Color::RGB;
use Graphics::Primitive::Font;
END_OF_EVAL_LIST
$chartClickerUnavailable=$@;
$self->log("Chart::Clicker module could not be loaded, skill graph functionality disabled: $chartClickerUnavailable",1) if($chartClickerUnavailable);
}
return undef if($chartClickerUnavailable);
my $quotedModShortName=$self->quote($modShortName);
my $sth;
my @skillGraphsFiles;
my %skillGraphsData;
foreach my $gameType (qw'Duel Team FFA TeamFFA Global') {
my $gType=$gameTypeMapping{$gameType};
$sth=$self->prepExec("select muBefore,sigmaBefore from ts${gType}Games where userId=$userId and modShortName=$quotedModShortName order by gdrTimestamp limit 1","retrieve initial skill data for mod $modShortName, user $userId and game type $gameType from table ts${gType}Games");
my @result=$sth->fetchrow_array();
next unless(@result);
my ($initMu,$initSigma)=@result;
$sth=$self->prepExec("select period,skill,mu,sigma from ts${gType}Players where modShortName=$quotedModShortName and userId=$userId order by period","retrieve historical skill data for mod $modShortName, user $userId and game type $gameType from ts${gType}Players table");
my @periods;
my %estimatedSkills;
my %trustedSkills;
my %skillRegions;
my $index=0;
$estimatedSkills{0}=$initMu;
$trustedSkills{0}=$initMu-3*$initSigma;
$skillRegions{0}=6*$initSigma;
while(@result=$sth->fetchrow_array()) {
$index++;
if($result[0]=~/^(\d{4})(\d\d)$/) {
push(@periods,"$1-$2");
}else{
$self->log("Invalid period string \"$result[0]\" encountered in generateSkillGraphs for mod $modShortName, user $userId and game type $gameType",1);
return undef;
}
$estimatedSkills{$index}=$result[2];
$trustedSkills{$index}=$result[2]-3*$result[3];
$skillRegions{$index}=6*$result[3];
}
next if($index < 2);
my $ca = Chart::Clicker::Drawing::ColorAllocator->new( {
colors => [ Graphics::Color::RGB->new(red => 0.9, green => 0.9, blue => 0.9, alpha => 0),
Graphics::Color::RGB->new(red => 0.2, green => 0.2, blue => 1.0, alpha => 0.5),
Graphics::Color::RGB->new(red => 0, green => 0, blue => 1, alpha => 0.5) ] } );
my $cc = Chart::Clicker->new(width => 1024, height => 512, format => 'png', color_allocator => $ca);
my $defctx = $cc->get_context('default');
$defctx->range_axis->range->min(0);
$defctx->range_axis->range->max(50);
$defctx->range_axis->ticks(10);
$defctx->range_axis->format(sub { return int(shift); });
$defctx->range_axis->label('TrueSkill');
$defctx->range_axis->label_color(Graphics::Color::RGB->new(red => 0, green => 0, blue => 1, alpha => 1));
$defctx->range_axis->label_font->weight('bold');
my (@xAxisValues,@xAxisLabels);
if($index > 20) {
for my $i (1..19) {
my $xValue=int($index * $i / 20);
push(@xAxisValues,$xValue);
push(@xAxisLabels,$periods[$xValue-1]);
}
}else{
@xAxisLabels = @periods;
@xAxisValues = (1..$index-1);
}
$defctx->domain_axis->tick_labels(\@xAxisLabels);
$defctx->domain_axis->tick_values(\@xAxisValues);
$defctx->domain_axis->tick_label_angle(0.785);
$defctx->domain_axis->label('Time');