forked from RetroAchievements/RAWeb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_db_utility.php
1311 lines (1128 loc) · 36.8 KB
/
_db_utility.php
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
<?php
require_once('db.inc.php');
//////////////////////////////////////////////////////////////////////////////////////////
// Validation
//////////////////////////////////////////////////////////////////////////////////////////
function validateUser( &$user, $pass, &$fbUser, $permissionRequired )
{
// Note: avoid this wherever possible!! Requires raw use of user's password!
$query = "SELECT User, SaltedPass, fbUser, cookie, Permissions FROM UserAccounts WHERE User='$user'";
$result = s_mysql_query( $query );
if( $result == FALSE )
{
error_log( __FUNCTION__ . " failed: bad query: $query" );
return FALSE;
}
else
{
$row = mysqli_fetch_array( $result );
// Add salt
$saltedHash = md5( $pass . RA_PASSWORD_SALT );
if( $row[ 'SaltedPass' ] == $saltedHash )
{
$fbUser = $row[ 'fbUser' ];
$user = $row[ 'User' ];
return ( $row[ 'Permissions' ] >= $permissionRequired );
}
else
{
error_log( __FUNCTION__ . " failed: passwords don't match for user:$user pass:" . $row[ 'SaltedPass' ] . ", but $pass was given." );
return FALSE;
}
}
}
function validateUser_app( &$user, $token, &$fbUser, $permissionRequired )
{
$fbUser = 0; // TBD: Remove!
return RA_ReadTokenCredentials( $user, $token, $pointsUnused, $truePointsUnused, $unreadMessagesUnused, $permissionsUnused, $permissionRequired );
}
function validateUser_cookie( &$user, $cookie, $permissionRequired )
{
return validateFromCookie( $user, $points, $permissions, $permissionRequired );
}
function validateFromCookie( &$userOut, &$pointsOut, &$permissionsOut, $permissionRequired = 0 )
{
$userOut = RA_ReadCookie( "RA_User" );
$cookie = RA_ReadCookie( "RA_Cookie" );
if( strlen( $userOut ) < 2 || strlen( $cookie ) < 2 )
{
// There is no cookie
return FALSE;
}
else
{
// Cookie maybe stale: check it!
$query = "SELECT User, cookie, RAPoints, Permissions FROM UserAccounts WHERE User='$userOut'";
$dbResult = s_mysql_query( $query );
if( $dbResult == FALSE )
{
error_log( __FUNCTION__ . " failed: bad query: $query" );
return FALSE;
}
else
{
$data = mysqli_fetch_array( $dbResult );
if( $data[ 'cookie' ] == $cookie )
{
$pointsOut = $data[ 'RAPoints' ];
$userOut = $data[ 'User' ]; // Case correction
$permissionsOut = $data[ 'Permissions' ];
return ( $permissionsOut >= $permissionRequired );
}
else
{
error_log( __FUNCTION__ . " failed: cookie doesn't match for user:$userOut (given: $cookie, should be " . $data[ 'cookie' ] . ")" );
return FALSE;
}
}
}
}
function getCookie( &$userOut, &$cookieOut )
{
$userOut = RA_ReadCookie( 'RA_User' );
$cookie = RA_ReadCookie( 'RA_Cookie' );
}
function RA_ReadCookieCredentials( &$userOut, &$pointsOut, &$truePointsOut, &$unreadMessagesOut, &$permissionOut, $minPermissions = NULL )
{
// Promise some values:
$userOut = RA_ReadCookie( 'RA_User' );
$cookie = RA_ReadCookie( 'RA_Cookie' );
$pointsOut = 0;
$truePointsOut = 0;
$unreadMessagesOut = 0;
$permissionOut = 0;
if( strlen( $userOut ) < 2 || strlen( $cookie ) < 10 )
{
RA_ClearCookie( 'RA_User' );
RA_ClearCookie( 'RA_Cookie' );
$userOut = NULL;
//error_log( __FUNCTION__ . " User invalid, bailing..." );
return FALSE;
}
$query = "SELECT ua.cookie, ua.RAPoints, ua.UnreadMessageCount, ua.TrueRAPoints, ua.Permissions
FROM UserAccounts AS ua
WHERE User='$userOut'";
$result = s_mysql_query( $query );
if( $result == FALSE )
{
RA_ClearCookie( 'RA_User' );
RA_ClearCookie( 'RA_Cookie' );
$userOut = NULL;
//error_log( __FUNCTION__ . " failed: bad query: query:$query" );
return FALSE;
}
else
{
$dbResult = mysqli_fetch_array( $result );
$serverCookie = $dbResult[ 'cookie' ];
if( strcmp( $serverCookie, $cookie ) !== 0 )
{
RA_ClearCookie( 'RA_User' );
RA_ClearCookie( 'RA_Cookie' );
$userOut = NULL;
//error_log( __FUNCTION__ . " failed: bad cookie: query:$query cookies: local:$cookie server:$serverCookie. Removing it!" );
return FALSE;
}
else
{
userActivityPing( $userOut );
// Cookies match: now validate permissions if required
$pointsOut = $dbResult[ 'RAPoints' ];
$unreadMessagesOut = $dbResult[ 'UnreadMessageCount' ];
$truePointsOut = $dbResult[ 'TrueRAPoints' ];
$permissionOut = $dbResult[ 'Permissions' ];
// Only compare if requested, otherwise return true meaning 'logged in'
if( isset( $minPermissions ) )
return ( $permissionOut >= $minPermissions );
else
return TRUE;
}
}
}
function RA_ReadTokenCredentials( &$userOut, $token, &$pointsOut, &$truePointsOut, &$unreadMessagesOut, &$permissionOut, $permissionRequired = NULL )
{
if( $userOut == NULL || $userOut == '' )
{
error_log( __FUNCTION__ . " failed: no user given: $userOut, $token " );
return FALSE;
}
$query = "SELECT ua.User, ua.appToken, ua.RAPoints, ua.UnreadMessageCount, ua.TrueRAPoints, ua.Permissions
FROM UserAccounts AS ua
WHERE User='$userOut'";
$result = s_mysql_query( $query );
if( $result == FALSE )
{
error_log( __FUNCTION__ . " failed: bad query: $query" );
return FALSE;
}
else
{
$row = mysqli_fetch_array( $result );
$permissionOut = $row[ 'Permissions' ];
if( $row[ 'appToken' ] == $token )
{
$userOut = $row[ 'User' ]; // Case correction
if( isset( $permissionRequired ) )
return( $permissionOut >= $permissionRequired );
else
return TRUE;
}
else
{
error_log( __FUNCTION__ . " failed: passwords don't match for user:$userOut (given: $token, should be " . $row[ 'appToken' ] . ")" );
return FALSE;
}
}
}
function RA_ClearCookie( $cookieName )
{
return setcookie( "$cookieName", "", 1, '/', AT_HOST_DOT );
}
function RA_ReadCookie( $cookieName )
{
if( RA_CookieExists( $cookieName ) )
return htmlspecialchars( $_COOKIE[ $cookieName ] );
return NULL;
}
function RA_SetCookie( $cookieName, $cookieValue )
{
return setcookie( "$cookieName", "$cookieValue", time() + 60 * 60 * 24 * 30, '/', AT_HOST_DOT );
}
function RA_CookieExists( $cookieName )
{
return ( isset( $_COOKIE ) &&
array_key_exists( $cookieName, $_COOKIE ) &&
$_COOKIE[ $cookieName ] !== FALSE );
}
function ValidatePOSTChars( $charsIn )
{
$numChars = strlen( $charsIn );
for( $i = 0; $i < $numChars; $i++ )
{
if( !array_key_exists( $charsIn[ $i ], $_POST ) )
{
error_log( __FUNCTION__ . " failed, missing " . $charsIn[ $i ] . " in POST!" );
return FALSE;
}
}
return TRUE;
}
function ValidateGETChars( $charsIn )
{
$numChars = strlen( $charsIn );
for( $i = 0; $i < $numChars; $i++ )
{
if( !array_key_exists( $charsIn[ $i ], $_GET ) )
{
error_log( __FUNCTION__ . " failed, missing " . $charsIn[ $i ] . " in GET!" );
return FALSE;
}
}
return TRUE;
}
function ValidatePOSTorGETChars( $charsIn )
{
$numChars = strlen( $charsIn );
for( $i = 0; $i < $numChars; $i++ )
{
if( !array_key_exists( $charsIn[ $i ], $_GET ) )
{
if( !array_key_exists( $charsIn[ $i ], $_POST ) )
{
error_log( __FUNCTION__ . " failed, missing " . $charsIn[ $i ] . " in GET or POST!" );
return FALSE;
}
}
}
return TRUE;
}
function generateAPIKey( $user )
{
if( !getAccountDetails( $user, $userData ) )
{
error_log( __FUNCTION__ . " API Key gen fail 1: not a user?" );
return "";
}
if( $userData[ 'Permissions' ] < 1 )
{
error_log( __FUNCTION__ . " API Key gen fail 2: not a full account!" );
return "";
}
$newKey = rand_string( 32 );
$query = "UPDATE UserAccounts AS ua
SET ua.APIKey='$newKey'
WHERE ua.User = '$user'";
$dbResult = s_mysql_query( $query );
if( $dbResult == FALSE )
{
log_email( __FUNCTION__ . " API Key gen fail 3: sql fail?!" );
error_log( __FUNCTION__ . " API Key gen fail 3: sql fail?!" );
return "";
}
return $newKey;
}
function GetAPIKey( $user )
{
$query = "SELECT APIKey FROM UserAccounts AS ua
WHERE ua.User = '$user' AND ua.Permissions >= 1";
$dbResult = s_mysql_query( $query );
if( $dbResult == FALSE )
{
error_log( __FUNCTION__ );
error_log( "errors fetching API Key for $user!" );
log_email( __FUNCTION__ . " cannot fetch API key for $user" );
return "No API Key found!";
}
else
{
$db_entry = mysqli_fetch_assoc( $dbResult );
return $db_entry[ 'APIKey' ];
}
}
function LogSuccessfulAPIAccess( $user )
{
$query = "UPDATE UserAccounts AS ua
SET ua.APIUses=ua.APIUses+1
WHERE ua.User = '$user' ";
s_mysql_query( $query );
}
function ValidateAPIKey( $user, $key )
{
if( strlen( $key ) < 20 )
return FALSE;
$query = "SELECT COUNT(*)
FROM UserAccounts AS ua
WHERE ua.User = '$user' AND ua.Permissions >= 1 AND ua.APIKey = '$key' ";
$dbResult = s_mysql_query( $query );
if( $dbResult == FALSE )
{
error_log( __FUNCTION__ );
error_log( "errors validating API Key for $user (given: $key)!" );
log_email( __FUNCTION__ . " errors validating API Key for $user (given: $key)!" );
return FALSE;
}
LogSuccessfulAPIAccess( $user );
$data = mysqli_fetch_assoc( $dbResult );
return ( $data[ 'COUNT(*)' ] != 0 );
}
//////////////////////////////////////////////////////////////////////////////////////////
// Utility
//////////////////////////////////////////////////////////////////////////////////////////
// 23:23 05/03/2014 retired
// function getAvailableBadgesList( &$arrayOut )
// {
// //path to directory to scan
// $directory = "./Badge/";
// //get all image files with a .png extension.
// $filesFound = glob($directory . "*.png");
// //print each file name
// $numFound = 0;
// foreach( $filesFound as $filename )
// {
// //error_log( $filename );
// if( strlen( $filename ) > 8 && $filename[8+5] == '.' )
// {
// //error_log( $filename );
// $newFile = substr( $filename, 8, 5 );
// if( ctype_digit( $newFile ) )
// {
// //error_log( $filename );
// $arrayOut[$numFound] = $newFile;
// $numFound++;
// }
// }
// }
// return $numFound;
// }
function GetGameNumUniquePlayersByAwards( $gameID )
{
$query = "SELECT MAX( Inner1.MaxAwarded ) AS TotalPlayers FROM
(
SELECT ach.ID, COUNT(*) AS MaxAwarded
FROM Awarded AS aw
LEFT JOIN Achievements AS ach ON ach.ID = aw.AchievementID
LEFT JOIN GameData AS gd ON gd.ID = ach.GameID
WHERE gd.ID = $gameID AND aw.HardcoreMode = 0
GROUP BY ach.ID
) AS Inner1";
$dbResult = s_mysql_query( $query );
$data = mysqli_fetch_assoc( $dbResult );
return $data[ 'TotalPlayers' ];
}
// 16:32 16/10/2014
function GetAchievementRecentWinnersData( $achID, $offset, $count, $user = NULL, $friendsOnly = NULL )
{
$retVal = array();
// Fetch the number of times this has been earned whatsoever (excluding hardcore)
$query = "SELECT COUNT(*) AS NumEarned, ach.GameID
FROM Awarded AS aw
LEFT JOIN Achievements AS ach ON ach.ID = aw.AchievementID
WHERE AchievementID=$achID AND aw.HardcoreMode = 0";
$dbResult = s_mysql_query( $query );
$data = mysqli_fetch_assoc( $dbResult );
$retVal[ 'NumEarned' ] = $data[ 'NumEarned' ];
settype( $retVal[ 'NumEarned' ], 'integer' );
$retVal[ 'GameID' ] = $data[ 'GameID' ];
settype( $retVal[ 'GameID' ], 'integer' );
// Fetch the total number of players for this game:
$retVal[ 'TotalPlayers' ] = GetGameNumUniquePlayersByAwards( $retVal[ 'GameID' ] );
settype( $retVal[ 'TotalPlayers' ], 'integer' );
$extraWhere = "";
if( isset( $friendsOnly ) && $friendsOnly && isset( $user ) && $user )
$extraWhere = " AND aw.User IN ( SELECT Friend FROM Friends WHERE User = '$user' ) ";
// Get recent winners, and their most recent activity:
$query = "SELECT aw.User, ua.RAPoints, UNIX_TIMESTAMP(aw.Date) AS DateAwarded
FROM Awarded AS aw
LEFT JOIN UserAccounts AS ua ON ua.User = aw.User
WHERE AchievementID=$achID AND aw.HardcoreMode = 0 $extraWhere
ORDER BY aw.Date DESC
LIMIT $offset, $count";
$dbResult = s_mysql_query( $query );
while( $db_entry = mysqli_fetch_assoc( $dbResult ) )
{
//settype( $db_entry['HardcoreMode'], 'integer' );
settype( $db_entry[ 'RAPoints' ], 'integer' );
settype( $db_entry[ 'DateAwarded' ], 'integer' );
$retVal[ 'RecentWinner' ][] = $db_entry;
}
return $retVal;
}
// Deprecated (but in use?)
function getAchievementWonData( $achID, &$numWinners, &$numPossibleWinners, &$numRecentWinners, &$winnerInfo, $user )
{
$winnerInfo = array();
$query = "SELECT COUNT(*) AS NumEarned, ach.GameID
FROM Awarded AS aw
LEFT JOIN Achievements AS ach ON ach.ID = aw.AchievementID
LEFT JOIN UserAccounts AS ua ON ua.User = aw.User
WHERE ( !ua.Untracked || ua.User = \"$user\" ) AND AchievementID=$achID AND aw.HardcoreMode = 0";
$dbResult = s_mysql_query( $query );
if( $dbResult == FALSE )
return FALSE;
$data = mysqli_fetch_assoc( $dbResult );
$numWinners = $data[ 'NumEarned' ];
$gameID = $data[ 'GameID' ]; // Grab GameID at this point
//$query = "SELECT COUNT(*) FROM UserAccounts WHERE Permissions>0";
$query = "SELECT MAX( Inner1.MaxAwarded ) AS TotalPlayers FROM
(
SELECT ach.ID, COUNT(*) AS MaxAwarded
FROM Awarded AS aw
LEFT JOIN Achievements AS ach ON ach.ID = aw.AchievementID
LEFT JOIN GameData AS gd ON gd.ID = ach.GameID
WHERE gd.ID = $gameID AND aw.HardcoreMode = 0
GROUP BY ach.ID
) AS Inner1";
$dbResult = s_mysql_query( $query );
if( $dbResult == FALSE )
return FALSE;
$arrayResult = mysqli_fetch_assoc( $dbResult );
$numPossibleWinners = $arrayResult[ 'TotalPlayers' ];
$numRecentWinners = 0;
// Get recent winners, and their most recent activity:
$query = "SELECT aw.User, ua.RAPoints, aw.Date AS DateAwarded, aw.HardcoreMode
FROM Awarded AS aw
LEFT JOIN UserAccounts AS ua ON ua.User = aw.User
WHERE ( !ua.Untracked || ua.User = \"$user\" ) AND AchievementID=$achID
ORDER BY aw.Date DESC
LIMIT 0, 100";
$dbResult = s_mysql_query( $query );
if( $dbResult !== FALSE )
{
while( $db_entry = mysqli_fetch_assoc( $dbResult ) )
{
if( isset( $winnerInfo[ $db_entry[ 'User' ] ] ) && $winnerInfo[ $db_entry[ 'User' ] ][ 'HardcoreMode' ] == 1 )
{
// Prefer this value
continue;
}
// This will overwrite hardcore if found, in order; meaning the result will be
// either hardcore has been earned ever, or not at all by this user
$winnerInfo[ $db_entry[ 'User' ] ] = $db_entry;
$numRecentWinners++;
}
}
if( $user !== NULL && !array_key_exists( $user, $winnerInfo ) )
{
// Do the same again if I wasn't found:
$query = "SELECT aw.User, aw.Date AS DateAwarded, aw.HardcoreMode
FROM Awarded AS aw
LEFT JOIN UserAccounts AS ua ON ua.User = aw.User
WHERE aw.AchievementID=$achID AND aw.User='$user'
ORDER BY aw.Date DESC, HardcoreMode ASC";
$dbResult = s_mysql_query( $query );
if( $dbResult !== FALSE )
{
while( $db_entry = mysqli_fetch_assoc( $dbResult ) )
{
$winnerInfo[ $db_entry[ 'User' ] ] = $db_entry;
$numRecentWinners++;
}
}
}
return TRUE;
}
function getConsoleList()
{
$query = "SELECT ID, Name FROM Console";
$dbResult = s_mysql_query( $query );
$consoleList = array();
if( $dbResult !== FALSE )
{
while( $db_entry = mysqli_fetch_assoc( $dbResult ) )
{
$consoleList[ $db_entry[ 'ID' ] ] = $db_entry[ 'Name' ];
}
}
return $consoleList;
}
function getStaticData()
{
$query = "SELECT sd.*, ach.Title AS LastAchievementEarnedTitle, gd.Title AS NextGameTitleToScan, gd.ImageIcon AS NextGameToScanIcon, c.Name AS NextGameToScanConsole, ua.User AS NextUserToScan
FROM StaticData AS sd
LEFT JOIN Achievements AS ach ON ach.ID = sd.LastAchievementEarnedID
LEFT JOIN GameData AS gd ON gd.ID = sd.NextGameToScan
LEFT JOIN Console AS c ON c.ID = gd.ConsoleID
LEFT JOIN UserAccounts AS ua ON ua.ID = sd.NextUserIDToScan ";
$dbResult = s_mysql_query( $query );
if( $dbResult !== FALSE )
{
return mysqli_fetch_assoc( $dbResult );
}
error_log( __FUNCTION__ );
error_log( $query );
return NULL;
}
function GetCodeNotesData( $gameID )
{
$codeNotesOut = array();
settype( $gameID, 'integer' );
$query = "SELECT ua.User, cn.Address, cn.Note
FROM CodeNotes AS cn
LEFT JOIN UserAccounts AS ua ON ua.ID = cn.AuthorID
WHERE cn.GameID = '$gameID'
ORDER BY cn.Address ";
$dbResult = s_mysql_query( $query );
if( $dbResult !== FALSE )
{
while( $db_entry = mysqli_fetch_assoc( $dbResult ) )
{
// Seamless :)
$db_entry[ 'Address' ] = sprintf( "0x%06x", $db_entry[ 'Address' ] );
$codeNotesOut[] = $db_entry;
}
}
else
{
error_log( __FUNCTION__ . " error" );
error_log( $query );
}
return $codeNotesOut;
}
// 21:26 30/04/2013
function getCodeNotes( $gameID, &$codeNotesOut )
{
settype( $gameID, 'integer' );
$query = "SELECT ua.User, cn.Address, cn.Note
FROM CodeNotes AS cn
LEFT JOIN UserAccounts AS ua ON ua.ID = cn.AuthorID
WHERE cn.GameID = $gameID
ORDER BY cn.Address ";
$dbResult = s_mysql_query( $query );
if( $dbResult !== FALSE )
{
$codeNotesOut = Array();
$numResults = 0;
while( $db_entry = mysqli_fetch_assoc( $dbResult ) )
{
// Seamless :)
$db_entry[ 'Address' ] = sprintf( "0x%06x", $db_entry[ 'Address' ] );
$codeNotesOut[ $numResults++ ] = $db_entry;
}
return TRUE;
}
else
{
error_log( __FUNCTION__ . " error" );
error_log( $query );
return FALSE;
}
}
function SubmitCodeNote2( $user, $gameID, $address, $note )
{
global $db;
if( !isset( $user ) || !isset( $gameID ) || !isset( $address ) )
return FALSE;
$userID = getUserIDFromUser( $user );
// Nope! $address will be an integer
// turn '0x00000f' into '15'
//$addressAsInt = hexdec( substr( $address, 2 ) );
$note = mysqli_real_escape_string( $db, $note );
$note = str_replace( "#", "_", $note ); // Remove hashes. Sorry. hash is now a delim.
$query = "INSERT INTO CodeNotes ( GameID, Address, AuthorID, Note )
VALUES( '$gameID', '$address', '$userID', '$note' )
ON DUPLICATE KEY UPDATE AuthorID=VALUES(AuthorID), Note=VALUES(Note)";
log_sql( $query );
$dbResult = mysqli_query( $db, $query );
return( $dbResult !== FALSE );
}
// 21:55 30/04/2013
function SubmitCodeNote( $user, $gameID, $address, $note )
{
global $db;
$userID = getUserIDFromUser( $user );
// turn '0x00000f' into '15'
$addressAsInt = hexdec( substr( $address, 2 ) );
//$note = str_replace( "'", "''", $note );
$note = mysqli_real_escape_string( $db, $note );
// Remove hashes. Sorry. hash is now a delim.
$note = str_replace( "#", "_", $note );
$query = "UPDATE CodeNotes AS cn
SET cn.AuthorID = $userID, cn.Note = \"$note\"
WHERE cn.Address = $addressAsInt AND cn.GameID = $gameID ";
log_sql( $query );
$dbResult = mysqli_query( $db, $query );
if( $dbResult !== FALSE )
{
if( mysqli_affected_rows( $db ) == 0 )
{
// Insert required
$query = "INSERT INTO CodeNotes VALUES ( $gameID, $addressAsInt, $userID, \"$note\" )";
log_sql( $query );
global $db;
$dbResult = mysqli_query( $db, $query );
if( $dbResult == FALSE )
{
//log_sql_fail();
error_log( __FUNCTION__ . " error2" );
error_log( $query );
return FALSE;
}
else
{
// Done :)
//error_log( __FUNCTION__ . " success2!" );
//error_log( $query );
return TRUE;
}
}
else
{
// Done :)
//error_log( __FUNCTION__ . " success1!" );
//error_log( $query );
return TRUE;
}
}
else
{
log_sql_fail();
error_log( __FUNCTION__ . " error1" );
error_log( $query );
return FALSE;
}
}
// 23:12 02/05/2013
function performSearch( $searchQuery, $offset, $count, &$searchResultsOut )
{
global $db;
$resultCount = 0;
$searchQuery = mysqli_real_escape_string( $db, $searchQuery );
$query = "
(
SELECT 'Game' AS Type, gd.ID, CONCAT( '/Game/', gd.ID ) AS Target, gd.Title FROM GameData AS gd
LEFT JOIN Achievements AS ach ON ach.GameID = gd.ID AND ach.Flags = 3
WHERE gd.Title LIKE '%$searchQuery%'
GROUP BY ach.GameID
)
UNION
(
SELECT 'Achievement' AS Type, ach.ID, CONCAT( '/Achievement/', ach.ID ) AS Target, ach.Title FROM Achievements AS ach
WHERE ach.Flags = 3 AND ach.Title LIKE '%$searchQuery%'
)
UNION
(
SELECT 'User' AS Type,
ua.User AS ID,
CONCAT( '/User/', ua.User ) AS Target,
ua.User AS Title
FROM UserAccounts AS ua
WHERE ua.User LIKE '%$searchQuery%'
)
UNION
(
SELECT 'Forum Comment' AS Type,
ua.User AS ID,
CONCAT( '/viewtopic.php?t=', ftc.ForumTopicID, '&c=', ftc.ID ) AS Target,
CONCAT( '...', MID( ftc.Payload, GREATEST( LOCATE('$searchQuery', ftc.Payload)-25, 1), 60 ), '...' ) AS Title
FROM ForumTopicComment AS ftc
LEFT JOIN UserAccounts AS ua ON ua.ID = ftc.AuthorID
WHERE ftc.Payload LIKE '%$searchQuery%'
GROUP BY ftc.ID DESC
)
UNION
(
SELECT 'Comment' AS Type, cua.User AS ID,
IF( c.articletype=1, CONCAT( '/Game/', c.ArticleID ),
IF( c.articletype=2, CONCAT( '/Achievement/', c.ArticleID ),
IF( c.articletype=3, CONCAT( '/User/', ua.User ),
IF( c.articletype=5, CONCAT( '/feed.php?a=', c.ArticleID ), c.articletype )
)
)
)
AS Target,
CONCAT( '...', MID( c.Payload, GREATEST( LOCATE('$searchQuery', c.Payload)-40, 1), 60 ), '...' ) AS Title
FROM Comment AS c
LEFT JOIN UserAccounts AS ua ON ( ua.ID = c.ArticleID )
LEFT JOIN UserAccounts AS cua ON cua.ID = c.UserID
WHERE c.Payload LIKE '%$searchQuery%'
GROUP BY c.Submitted DESC
)
LIMIT $offset, $count
";
$dbResult = mysqli_query( $db, $query );
if( $dbResult == FALSE )
{
error_log( __FUNCTION__ . " gone wrong!" );
error_log( $query );
log_sql_fail();
}
else
{
while( $nextData = mysqli_fetch_assoc( $dbResult ) )
{
$searchResultsOut[ $resultCount ] = $nextData;
$resultCount++;
}
}
return $resultCount;
}
function requestModifyGame( $author, $gameID, $field, $value )
{
global $db;
settype( $field, 'integer' );
if( $field == 1 ) // Title
{
if( !isset( $value ) || strlen( $value ) < 2 )
{
log_email( "bad data $author, $gameID, $field, $value" );
return FALSE;
}
$newTitle = str_replace( "'", "''", $value );
$newTitle = mysqli_real_escape_string( $db, $newTitle );
//$newTitle = str_replace( "/", "/", $newTitle );
//$newTitle = str_replace( "\\", "\", $newTitle );
$query = "UPDATE GameData SET Title='$newTitle' WHERE ID=$gameID";
log_sql( "$user: $query" );
$dbResult = mysqli_query( $db, $query );
return ( $dbResult !== FALSE );
}
else if( $field == 2 ) // GameHashTable
{
$query = "DELETE FROM GameHashLibrary WHERE GameID=$gameID";
log_sql( "$user: $query" );
$dbResult = s_mysql_query( $query );
return ( $dbResult !== FALSE );
}
return FALSE;
}
// 23:10 30/12/2013
function mergeGameID( $user, $oldGameID, $newGameID )
{
if( $oldGameID == $newGameID )
{
log_email( "Cannot progress: both games are the same, $user, $oldGameID, $newGameID" );
return FALSE;
}
// We want $oldGameID to now point to $newGameID. $gameID, $user, &$achievementDataOut, &$gameDataOut
$numAchievements = getGameMetadata( $oldGameID, NULL, $achievementData, $gameData );
if( $numAchievements > 0 )
{
echo "Cannot progress: this game has achievements! Please attempt merge the new game to the old game.";
log_email( "Bad merge, $user, $oldGameID, $newGameID" );
return FALSE;
}
// old game has no achievements; merge to new game entry!
// DELETE FROM GameData WHERE ID=$oldGameID
// UPDATE GameHashLibrary SET GameID = $newGameID WHERE GameID = $oldGameID
$query = " SELECT COUNT(*) AS DataExists
FROM GameData
WHERE ID=$oldGameID ";
$dbResult = s_mysql_query( $query );
if( $dbResult == NULL )
{
log_email( $query );
log_email( "bad times 2" );
return FALSE;
}
$data = mysqli_fetch_assoc( $dbResult );
if( $data[ 'DataExists' ] == 0 )
{
log_email( "existing title doesn't exist!" );
return FALSE;
}
$query = " SELECT COUNT(*) AS DataExists
FROM GameHashLibrary
WHERE GameID=$oldGameID ";
$dbResult = s_mysql_query( $query );
if( $dbResult == NULL )
{
log_email( "bad times 3" );
return FALSE;
}
$data = mysqli_fetch_assoc( $dbResult );
if( $data[ 'DataExists' ] == 0 )
{
log_email( "existing title doesn't exist in GameHashLibrary!" );
return FALSE;
}
$query = " DELETE FROM GameData
WHERE ID=$oldGameID ";
log_sql( $query );
$dbResult = s_mysql_query( $query );
if( $dbResult == NULL )
{
log_email( "bad times 4" );
return FALSE;
}
$query = " UPDATE GameHashLibrary
SET GameID = $newGameID
WHERE GameID = $oldGameID ";
log_sql( $query );
$dbResult = s_mysql_query( $query );
if( $dbResult == NULL )
{
log_email( "bad times 5" );
return FALSE;
}
return TRUE;
}
function recalcScore( $user )
{
$query = "UPDATE UserAccounts SET RAPoints = (
SELECT SUM(ach.Points) FROM Awarded AS aw
LEFT JOIN Achievements AS ach ON ach.ID = aw.AchievementID
WHERE aw.User = '$user'
),
TrueRAPoints = (
SELECT SUM(ach.TrueRatio) FROM Awarded AS aw
LEFT JOIN Achievements AS ach ON ach.ID = aw.AchievementID
WHERE aw.User = '$user'
)
WHERE User = '$user' ";
$dbResult = s_mysql_query( $query );
if( $dbResult == FALSE )
{
log_email( __FUNCTION__ . " failed for $user!" );
return FALSE;
}
else
{
//error_log( __FUNCTION__ );
//error_log( "recalc'd $user's score as " . getScore($user) . ", OK!" );
return TRUE;
}
}
// 15:12 20/10/2013
function getConsoleIDs()
{
$retVal = array();
$query = "SELECT ID, Name FROM Console";
$dbResult = s_mysql_query( $query );
while( $db_entry = mysqli_fetch_assoc( $dbResult ) )
$retVal[] = $db_entry;
return $retVal;
}
// 18:05 26/10/2013
function attributeDevelopmentAuthor( $author, $points )
{
$query = "SELECT ContribCount, ContribYield FROM UserAccounts WHERE User = '$author'";
$dbResult = s_mysql_query( $query );
$oldResults = mysqli_fetch_assoc( $dbResult );
$oldContribCount = $oldResults[ 'ContribCount' ];
$oldContribYield = $oldResults[ 'ContribYield' ];
// Update the fact that this author made an achievement that just got earned.
$query = "UPDATE UserAccounts AS ua
SET ua.ContribCount = ua.ContribCount+1, ua.ContribYield = ua.ContribYield + $points
WHERE ua.User = '$author'";
$dbResult = s_mysql_query( $query );
if( $dbResult == FALSE )
{
log_email( $query );
global $db;
log_email( mysqli_error( $db ) );
}
else
{