-
Notifications
You must be signed in to change notification settings - Fork 18
/
functions.php
982 lines (792 loc) · 24.7 KB
/
functions.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
<?php
/*
RPCS3.net Compatibility List (https://github.com/AniLeo/rpcs3-compatibility)
Copyright (C) 2017 AniLeo
https://github.com/AniLeo or [email protected]
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
if(!@include_once("config.php")) throw new Exception("Compat: config.php is missing. Failed to include config.php");
if(!@include_once(__DIR__."/html/HTML.php")) throw new Exception("Compat: HTML.php is missing. Failed to include HTML.php");
// Productcode info: PSDevWiki (http://www.psdevwiki.com/ps3/Productcode)
/**
* getDatabase
*
* Establishes a database connection and sets utf8mb4 charset
*
* @return mysqli Connection to MySQL Server
*/
function getDatabase() : mysqli
{
if (!defined("db_host") || !defined("db_user") || !defined("db_pass") ||
!defined("db_name") || !defined("db_port"))
exit("[COMPAT] Database: Missing connection data");
$db = mysqli_connect(db_host, db_user, db_pass, db_name, (int) db_port);
if (!$db)
trigger_error("[COMPAT] Database: Connection could not be established", E_USER_ERROR);
mysqli_set_charset($db, "utf8mb4");
return $db;
}
/**
* getGameType
*
* Obtains Game Type by checking Game ID's fourth character.
* Returns Game Type as a string, empty if Game Type is invalid/unknown.
*
* @param string $gid GameID: 9 character ID that identifies a game
*
* @return string
*/
function getGameType(string $gid) : string
{
// Physical
if (substr($gid, 0, 1) === "B" || substr($gid, 0, 1) === "X")
{
if (substr($gid, 3, 1) === "D") { return "Demo"; } // Demo
if (substr($gid, 3, 1) === "M") { return "Malayan Release"; } // Malayan Release
if (substr($gid, 3, 1) === "S") { return "Retail Release"; } // Retail Release
}
// Digital
else if (substr($gid, 0, 1) === "N")
{
if (substr($gid, 3, 1) === "A") { return "First Party PS3"; } // First Party PS3 (Demo/Retail)
if (substr($gid, 3, 1) === "B") { return "Licensed PS3"; } // Licensed PS3 (Demo/Retail)
if (substr($gid, 3, 1) === "C") { return "First Party PS2"; } // First Party PS2 Classic (Demo/Retail)
if (substr($gid, 3, 1) === "D") { return "Licensed PS2"; } // Licensed PS2 (Demo/Retail)
if (substr($gid, 3, 1) === "E") { return "First Party PS1"; } // First Party PS1 Classic (Demo/Retail)
if (substr($gid, 3, 1) === "F") { return "Licensed PS1"; } // Licensed PS1 (Demo/Retail)
}
// We don't care about the other types as they won't be listed
return "";
}
/**
* isValid
*
* Checks if string only has allowed characters.
* Returns true if valid or false if invalid.
* Used for the searchbox.
*
* @param string $str Some text
*
* @return bool
*/
function isValid(string $str) : bool
{
return !preg_match("/[^\p{L}0-9.#&~;:\* \/\'\-,!]/", $str);
}
/**
* highlightText
*
* Returns provided string with increased size and font-weight
*
* @param string $str Some text
* @param bool $cond Condition to be met for text to be highlighted
*
* @return string
*/
function highlightText(string $str, bool $cond = true)
{
return $cond ? "<span class=\"highlightedText\">{$str}</span>" : $str;
}
/**
* @return array<string, array<string>|bool|int|string|null> $get
*/
function validateGet() : array
{
global $a_pageresults, $c_pageresults, $a_status, $a_histdates, $a_currenthist, $a_media;
// Start new $get array for sanitized input
$get = array();
// Unexpected, UTF-8 is the default for PHP 7
if (mb_internal_encoding() !== "UTF-8")
{
// Ensure internal encoding is UTF-8 even if it's changed on server config
mb_internal_encoding("UTF-8");
}
// Sanitize and store boolean values
if (isset($_GET['rss']))
{
// RSS feed
$get['rss'] = true;
}
if (isset($_GET['b']))
{
// Builds page
$get['b'] = true;
}
else if (isset($_GET['h']))
{
// History page
$get['h'] = true;
}
// First pass of sanitization on user input from $_GET
foreach ($_GET as $key => $value)
{
// Remove non-string arguments (f.ex: arrays)
if (!is_string($value))
{
unset($_GET[$key]);
}
// Remove non UTF-8 strings
else if (!mb_check_encoding($value))
{
unset($_GET[$key]);
}
}
// Set default values
$get['r'] = (int) $c_pageresults;
$get['s'] = 0; // All
// $get['o'] = "";
// $get['c'] = '';
// $get['g'] = "";
// $get['d'] = "";
// $get['t'] = '';
// $get['m'] = '';
// $get["move"] = 0;
$get["3D"] = 0;
$get["type"] = 0;
// $get["network"] = 0;
// API version
if (isset($_GET['api']))
{
$get['api'] = (string) $_GET['api'];
}
// Page counter
if (isset($_GET['p']))
{
$get['p'] = (int) $_GET['p'];
}
// Results per page
if (isset($_GET['r']) && in_array($_GET['r'], $a_pageresults))
{
$get['r'] = (int) $_GET['r'];
}
// Status
if (isset($_GET['s']) && ((int) $_GET['s'] === 0 || array_key_exists($_GET['s'], $a_status)))
{
$get['s'] = (int) $_GET['s'];
}
// Order by
if (isset($_GET['o']) && strlen($_GET['o']) == 2 && is_numeric(substr($_GET['o'], 0, 1)) && (substr($_GET['o'], 1, 1) == 'a' || substr($_GET['o'], 1, 1) == 'd'))
{
$get['o'] = (string) $_GET['o'];
}
// Character
if (isset($_GET['c']))
{
// If it is a single alphabetic character
if (ctype_alpha($_GET['c']) && strlen($_GET['c']) === 1)
{
$get['c'] = strtolower($_GET['c']);
}
else if ($_GET['c'] == '09') { $get['c'] = '09'; } // Numbers
else if ($_GET['c'] == 'sym') { $get['c'] = 'sym'; } // Symbols
}
// Searchbox
if (isset($_GET['g']) && !empty($_GET['g']) && mb_strlen($_GET['g']) <= 128 && isValid($_GET['g']))
{
$get['g'] = (string) $_GET['g'];
// Trim all unnecessary double spaces
while (str_contains($get['g'], " "))
$get['g'] = str_replace(" ", " ", $get['g']);
}
// Date
if (isset($_GET['d']) && is_numeric($_GET['d']) && strlen((string) $_GET['d']) === 8 && strpos((string) $_GET['d'], '20') === 0)
{
$get['d'] = (int) $_GET['d'];
}
// Media type
if (isset($_GET['t']) && array_key_exists(strtoupper($_GET['t']), $a_media))
{
$get['t'] = strtolower($_GET['t']);
}
// Move support
if (isset($_GET['move']))
{
// No move support
if ((int) $_GET['move'] === 0)
{
$get['move'] = 0;
}
// Has move support
else if ((int) $_GET['move'] === 1)
{
$get['move'] = 1;
}
}
// Stereoscopic 3D support
if (isset($_GET['3D']) && $_GET['3D'] != 0)
{
$get['3D'] = 1;
}
// Game type
if (isset($_GET['type']) && $_GET['type'] != 0)
{
// PS3 Game
if ((int) $_GET['type'] === 1)
{
$get['type'] = 1;
}
// PS3 App
else if ((int) $_GET['type'] === 2)
{
$get['type'] = 2;
}
}
// Network requirement
if (isset($_GET['network']))
{
// No move support
if ((int) $_GET['network'] === 0)
{
$get['network'] = 0;
}
// Has move support
else if ((int) $_GET['network'] === 1)
{
$get['network'] = 1;
}
}
// History
if (isset($_GET['h']) && array_key_exists($_GET['h'], $a_histdates))
{
$get['h'] = (string) $_GET['h'];
}
// History mode
if (isset($_GET['m']) && ($_GET['m'] === 'c' || $_GET['m'] === 'n'))
{
$get['m'] = strtolower($_GET['m']);
}
// Patch system: Version
if (isset($_GET['v']) && strlen($_GET['v']) === 3 && ctype_digit($_GET['v'][0]) && $_GET['v'][1] === '.' && ctype_digit($_GET['v'][2]))
{
$get['v'] = (string) $_GET['v'];
}
// Patch system: Sha256
if (isset($_GET['sha256']) && strlen($_GET['sha256']) === 64 && ctype_alnum($_GET['sha256']))
{
$get['sha256'] = (string) $_GET['sha256'];
}
// Get debug permissions, if any
$get['w'] = getDebugPermissions();
// Enable error reporting for admins
if (!is_null($get['w']))
{
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Admin debug mode
if (isset($_GET['a']) && array_search("debug.view", $get['w']) !== false)
{
$get['a'] = (string) $_GET['a'];
}
}
return $get;
}
// Select the count of games in each status, subjective to query restrictions
/**
* @return array<string, array<int, int>> $count
*/
function countGames(mysqli $db, string $query = "") : array
{
global $get, $a_status;
$scount = array();
$and = empty($query) ? "" : " AND ({$query}) ";
// Without network only games
$q_gen1 = mysqli_query($db, "SELECT `status`+0 AS `statusID`, count(*) AS `c`
FROM `game_list`
WHERE (`network` = 0
OR (`network` = 1 && `status` <= 2)) {$and}
GROUP BY `status`;");
// With network only games
$q_gen2 = mysqli_query($db, "SELECT `status`+0 AS `statusID`, count(*) AS `c`
FROM `game_list`
WHERE (`network` = 0
OR `network` = 1) {$and}
GROUP BY `status`;");
// Zero-fill the array keys that are going to be used
for ($id = 0; $id <= count($a_status); $id++)
{
$scount["status"][$id] = 0;
$scount["nostatus"][$id] = 0;
// Derivative of status mode but with network games
$scount["network"][$id] = 0;
}
if (is_bool($q_gen1) || is_bool($q_gen2))
return $scount;
while ($row1 = mysqli_fetch_object($q_gen1))
{
// This should be unreachable unless the database structure is damaged
if (!property_exists($row1, "statusID") ||
!property_exists($row1, "c"))
{
continue;
}
$sid = (int) $row1->statusID;
$count = (int) $row1->c;
$scount["nostatus"][$sid] = $count;
$scount["nostatus"][0] += $count;
// For count with specified status, include only results for the specified status
// If there is no specified status, replicate nostatus mode
if ($get['s'] === 0 || $sid === $get['s'])
{
$scount["status"][$sid] = $count;
$scount["status"][0] += $count;
}
}
while ($row2 = mysqli_fetch_object($q_gen2))
{
// This should be unreachable unless the database structure is damaged
if (!property_exists($row2, "statusID") ||
!property_exists($row2, "c"))
{
continue;
}
$sid = (int) $row2->statusID;
$count = (int) $row2->c;
if ($get['s'] === 0 || $sid === $get['s'])
{
$scount["network"][$sid] = $count;
$scount["network"][0] += $count;
}
}
return $scount;
}
function count_game_entry_all(bool $ignore_cache = false) : int
{
// If we don't ignore cache, try to retrieve the value from cache
if (!$ignore_cache)
{
$count = file_get_contents(__DIR__.'/cache/count_game_entry_all.txt');
// Return value from cache only if available
if ($count !== false)
return (int) $count;
}
$db = getDatabase();
$ret = 0;
// Total game count (without network games)
$q_unique = mysqli_query($db, "SELECT count(*) AS `c`
FROM `game_list`
WHERE (`network` = 0
OR (`network` = 1 && `status` <= 2))
AND `type` = 'PS3 Game'; ");
if (!is_bool($q_unique) && mysqli_num_rows($q_unique) === 1)
{
$row = mysqli_fetch_object($q_unique);
// This should be unreachable unless the database structure is damaged
if (!$row || !property_exists($row, "c"))
{
return 0;
}
$ret = (int) $row->c;
}
mysqli_close($db);
return $ret;
}
function count_game_id_all(bool $ignore_cache = false) : int
{
// If we don't ignore cache, try to retrieve the value from cache
if (!$ignore_cache)
{
$count = file_get_contents(__DIR__.'/cache/count_game_id_all.txt');
// Return value from cache only if available
if ($count !== false)
return (int) $count;
}
$db = getDatabase();
$ret = 0;
// Total game count (without network games)
$q_unique = mysqli_query($db, "SELECT count(*) AS `c`
FROM `game_list`
LEFT JOIN `game_id`
ON `game_id`.`key` = `game_list`.`key`
WHERE (`network` = 0
OR (`network` = 1 && `status` <= 2))
AND `type` = 'PS3 Game'; ");
if (!is_bool($q_unique) && mysqli_num_rows($q_unique) === 1)
{
$row = mysqli_fetch_object($q_unique);
// This should be unreachable unless the database structure is damaged
if (!$row || !property_exists($row, "c"))
{
return 0;
}
$ret = (int) $row->c;
}
mysqli_close($db);
return $ret;
}
// TODO: Cleanup
function getPagesCounter(int $pages, int $currentPage, string $extra) : string
{
global $c_pagelimit;
// Initialize string
$s_pagescounter = "";
if (!empty($extra))
$extra .= "&";
// IF no results are found then the amount of pages is 0
// Returns no results found message
if ($pages === 0)
return "No results found using the selected search criteria.";
// Shows current page and total pages
$s_pagescounter .= "Page {$currentPage} of {$pages} - ";
// If there's less pages to the left than current limit it loads the excess amount to the right for balance
if ($c_pagelimit > $currentPage)
$c_pagelimit += $c_pagelimit - $currentPage + 1;
// If there's less pages to the right than current limit it loads the excess amount to the left for balance
if ($c_pagelimit > $pages - $currentPage)
$c_pagelimit += $c_pagelimit - ($pages - $currentPage) + 1;
// Loop for each page link and make it properly clickable until there are no more pages left
for ($i = 1; $i <= $pages; $i++)
{
if ( ($i >= $currentPage-$c_pagelimit && $i <= $currentPage) || ($i+$c_pagelimit >= $currentPage && $i <= $currentPage+$c_pagelimit) )
{
// Highlights the page if it's the one we're currently in
$content = highlightText(str_pad((string) $i, 2, "0", STR_PAD_LEFT), $i === $currentPage);
$html_a = new HTMLA("?{$extra}p={$i}", "Page {$i}", $content);
$s_pagescounter .= $html_a->to_string();
$s_pagescounter .= "  ";
}
// First page
elseif ($i === 1)
{
$html_a = new HTMLA("?{$extra}p={$i}", "Page {$i}", "01");
$s_pagescounter .= $html_a->to_string();
$s_pagescounter .= "  ";
if ($currentPage != $c_pagelimit + 2)
{
$s_pagescounter .= "...  ";
}
}
// Last page
elseif ($pages === $i)
{
$s_pagescounter .= "...  ";
$html_a = new HTMLA("?{$extra}p={$i}", "Page {$i}", (string) $i);
$s_pagescounter .= $html_a->to_string();
}
}
return $s_pagescounter;
}
/**
* @param array<array<string, string>> $headers
*/
function getTableHeaders(array $headers, string $extra = "") : string
{
global $get;
if (!empty($extra))
$extra .= "&";
$html_div_ret = new HTMLDiv("compat-table-header");
foreach ($headers as $i => $header)
{
$html_div = new HTMLDiv($header["class"]);
if ($header['sort'] === '0')
{
$html_div->add_content($header["name"]);
}
else if (isset($get['o']) && $get['o'] === "{$header['sort']}a")
{
$html_a = new HTMLA("?{$extra}o={$header['sort']}d", $header["name"], "{$header['name']} ↑");
$html_div->add_content($html_a->to_string());
}
elseif (isset($get['o']) && $get['o'] === "{$header['sort']}d")
{
$html_a = new HTMLA("?{$extra}", $header["name"], "{$header['name']} ↓");
$html_div->add_content($html_a->to_string());
}
else
{
$html_a = new HTMLA("?{$extra}o={$header['sort']}a", $header["name"], $header["name"]);
$html_div->add_content($html_a->to_string());
}
$html_div_ret->add_content($html_div->to_string());
}
return $html_div_ret->to_string();
}
function getFooter() : string
{
global $c_maintenance, $get, $start_time;
// Total time in milliseconds
$total_time = round((microtime(true) - $start_time) * 1000, 2);
$html_a = new HTMLA("https://github.com/AniLeo", "AniLeo", "AniLeo");
$html_a->set_target("_blank");
$html_div = new HTMLDiv("compat-footer");
$html_div->add_content("<p>Compatibility list developed and maintained by {$html_a->to_string()} - Page loaded in {$total_time}ms</p>");
$s = $html_div->to_string();
// Debug output
if (!is_null($get['w']))
{
$html_div = new HTMLDiv("compat-profiler");
// Maintenance mode information
if ($c_maintenance)
{
$html_div->add_content("<p>Maintenance mode: <span class=\"color-green\"><b>ON</b></span></p>");
}
else
{
$html_div->add_content("<p>Maintenance mode: <span class=\"color-red\"><b>OFF</b></span></p>");
}
$html_div->add_content(Profiler::get_data_html());
$s .= $html_div->to_string();
}
return $s;
}
// File path where the menu was called from
function getMenu(string $file) : string
{
global $get;
$html_div = new HTMLDiv("compat-menu");
$file = basename($file, '.php');
if ($file !== "compat")
{
$html_a = new HTMLA("?", "Compatibility List", "Compatibility List");
$html_div->add_content($html_a->to_string());
}
if ($file !== "history")
{
$html_a = new HTMLA("?h", "Compatibility List History", "Compatibility List History");
$html_div->add_content($html_a->to_string());
}
if ($file !== "builds")
{
$html_a = new HTMLA("?b", "Builds History", "Builds History");
$html_div->add_content($html_a->to_string());
}
if (!is_null($get['w']) && $file !== "panel")
{
$html_a = new HTMLA("?a", "Debug Panel", "Debug Panel");
$html_div->add_content($html_a->to_string());
}
return $html_div->to_string();
}
// Get current page user is on
function getCurrentPage(int $pages) : int
{
global $get;
// No specific page set or page bigger or smaller than what's possible
if (!isset($get['p']) || $get['p'] > $pages || $get['p'] < 1)
return 1;
return $get['p'];
}
// Calculate the number of pages according selected status and results per page
function countPages(int $results, int $count) : int
{
return (int) ceil($count / $results);
}
/*****************
* Status Module *
*****************/
// TODO: Rework
function generateStatusModule(bool $getCount = true) : string
{
global $a_status;
$db = getDatabase();
// Get games count per status
$count = countGames($db)["status"];
mysqli_close($db);
// Initialize string
$output = "";
// Pretty output for readability
foreach ($a_status as $id => $status)
{
$percentage = "";
$output .= "<div class='compat-status-main'>\n";
$output .= "<div class='compat-status-icon background-status-{$id}'></div>\n";
$output .= "<div class='compat-status-text'>\n";
$output .= "<p style='color:#{$status['color']}'><strong>{$status['name']}";
if ($getCount)
{
$percentage = round(($count[$id]/$count[0]) * 100, 2, PHP_ROUND_HALF_UP);
$output .= " ({$percentage}%)";
}
$output .= ":</strong></p> {$status['desc']}\n</div>\n";
if ($getCount)
{
$output .= "<div class='compat-status-progress'>\n";
$output .= "<progress class='compat-status-progressbar' id='compat-progress{$id}' style=\"color:#{$status['color']}\" max=\"100\" value=\"{$percentage}\"></progress>\n";
$output .= "</div>\n";
}
$output .= "</div>\n";
}
return "<div class='compat-status-container'>\n{$output}</div>";
}
// Checks if user has debug permissions
/**
* @return array<string> $permissions
*/
function getDebugPermissions() : ?array
{
if (!isset($_COOKIE["debug"]) || !is_string($_COOKIE["debug"]) || !ctype_alnum($_COOKIE["debug"]))
return null;
$db = getDatabase();
$s_token = mysqli_real_escape_string($db, $_COOKIE["debug"]);
$q_debug = mysqli_query($db, "SELECT *
FROM `debug_whitelist`
WHERE `token` = '{$s_token}'
LIMIT 1; ");
if (is_bool($q_debug) || mysqli_num_rows($q_debug) === 0)
return null;
$row = mysqli_fetch_object($q_debug);
// This should be unreachable unless the database structure is damaged
if (!$row || !property_exists($row, "permissions"))
{
return null;
}
$permissions = array();
if (!str_contains($row->permissions, ','))
{
$permissions[0] = $row->permissions;
}
else
{
$permissions = explode(',', $row->permissions);
}
if (!is_array($permissions))
return null;
return $permissions;
}
function getDateDiff(string $datetime) : string
{
$diff = time() - strtotime($datetime);
$days = (int) floor($diff / 86400);
if ($days === 0)
{
$hours = (int) floor($diff / 3600);
if ($hours === 0)
{
$minutes = (int) floor($diff / 60);
$diff = $minutes === 1 ? "{$minutes} minute" : "{$minutes} minutes";
}
else
{
$diff = $hours === 1 ? "{$hours} hour" : "{$hours} hours";
}
}
else
{
$diff = $days === 1 ? "{$days} day" : "{$days} days";
}
return "{$diff} ago";
}
function monthNumberToName(int $month) : string
{
$datetime = DateTime::createFromFormat('!m', (string) $month);
return $datetime ? $datetime->format('F') : "";
}
function dumpVar(mixed $var) : void
{
echo "<br>";
highlight_string("<?php\n\$data =\n".var_export($var, true).";\n?>");
}
function resultsPerPage(string $combined_search) : string
{
global $a_pageresults, $get;
$s_pageresults = "";
if (!empty($combined_search))
$combined_search .= '&';
foreach ($a_pageresults as $pageresult)
{
// If it's the current selected item, highlight
$content = highlightText($pageresult, $get['r'] === $pageresult);
$html_a = new HTMLA("?{$combined_search}r={$pageresult}", $pageresult, $content);
$s_pageresults .= $html_a->to_string();
// If not the last value then add a separator for the next value
if ($pageresult !== end($a_pageresults))
{
$s_pageresults .= "• ";
}
}
return $s_pageresults;
}
// Checks whether indicated string is a Game ID or not
// Game ID validation: is alphanumeric, len = 9, last 5 characters are digits,
// 3rd character represents a valid region and 1st character represents a valid media
function isGameID(string $string) : bool
{
global $a_flags, $a_media;
return ctype_alnum($string) &&
strlen($string) == 9 &&
is_numeric(substr($string, 4, 5)) &&
array_key_exists(strtoupper(substr($string, 2, 1)), $a_flags) &&
array_key_exists(strtoupper(substr($string, 0, 1)), $a_media);
}
// Runs a function while keeping track of the time it takes to run
// Returns amount of time in seconds
function runFunctionWithCronometer(string $function) : float
{
if (!is_callable($function))
return -1.0;
$start = microtime(true);
$function();
$finish = microtime(true);
return round(($finish - $start), 4); // Seconds
}
// Gets status ID for a respective status title
function getStatusID(string $name) : ?int
{
global $a_status;
foreach ($a_status as $id => $status)
{
if ($name === $status['name'])
return $id;
}
return null;
}
// cURL JSON document and return the result as an object
function curl_json(string $url, CurlHandle &$cr = null) : ?object
{
if (!defined("gh_token"))
exit("[COMPAT] API: Missing connection data");
// Use existing cURL resource or create a temporary one
$ch = (!is_null($cr)) ? $cr : curl_init();
// Set the required cURL flags
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return result as raw output
curl_setopt($ch, CURLOPT_URL, $url);
if (strlen($url) >= 23 && substr($url, 0, 23) === "https://api.github.com/")
{
// We're cURLing the GitHub API, set GitHub Auth Token on headers
curl_setopt($ch, CURLOPT_USERAGENT, "RPCS3 - Compatibility");
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: token ".gh_token));
}
else
{
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0");
}
// Get the response and httpcode of that response
$result = curl_exec($ch);
// Close the temporary cURL resource or reset the given cURL resource
if (is_null($cr))
curl_close($ch);
else
curl_reset($cr);
if (is_bool($result))
return null;
// Decode JSON
$result = json_decode($result, false);
if (is_bool($result) || is_null($result) || !is_object($result))
return null;
return $result;
}
// Based on https://stackoverflow.com/a/9826656
function get_string_between(string $string, string $start, string $end) : ?string
{
// Return position of initial limit in our string
// If position doesn't exist, then return false as string doesn't contain our start limit
if (!($inipos = strpos($string, $start)))
return null;
// Add length of start limit, so our start position is the character AFTER the start limit
$inipos += strlen($start);
// Look for end string position starting on initial position (offset)
// If position doesn't exist, then return false as string doesn't contain our end limit
if (!($endpos = strpos($string, $end, $inipos)))
return null;
// Start on 'start limit position' and return string with substring length
return substr($string, $inipos, $endpos - $inipos /*substring length*/);
}