forked from JimTR/PHPgsm
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ajaxv2.php
executable file
·1798 lines (1688 loc) · 58 KB
/
ajaxv2.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
/*
* ajaxv2t.php
*
* Copyright 2021 Jim Richardson <jim@noideersoftware.co.uk>
*
* 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.
*
* ajax v2 used for testing functions & modules
* requires PHP >= 7.4
*/
require_once 'includes/master.inc.php';
include 'functions.php';
require 'includes/class.emoji.php';
require DOC_ROOT. '/xpaw/SourceQuery/bootstrap.php'; // load xpaw
use xPaw\SourceQuery\SourceQuery;
define( 'SQ_TIMEOUT', $settings['SQ_TIMEOUT'] );
define( 'SQ_ENGINE', SourceQuery::SOURCE );
define( 'LOG', 'logs/ajaxv2.log');
define ('cr',PHP_EOL);
define ('CR',PHP_EOL);
define ('borders',array('horizontal' => '─', 'vertical' => '│', 'intersection' => '┼','left' =>'├','right' => '┤','left_top' => '┌','right_top'=>'┐','left_bottom'=>'└','right_bottom'=>'┘','top_intersection'=>'┬'));
$build = "54606-802951692";
$version = "2.078";
$time = "1644474313";
error_reporting (0);
$update_done= array();
$ip = $_SERVER['SERVER_ADDR']; // get calling IP
$sql = 'select * from base_servers where base_servers.ip ="'.$_SERVER['REMOTE_ADDR'].'"'; // do we know this ip ? mybb sets this at login
//echo $sql.'<br>';
$valid = $database->num_rows($sql); // get result if the ip can use the data the return value >0
$sql = 'select * from allowed users where `ip` = '.ip2long($_SERVER['REMOTE_ADDR']); // this should not happen but just incase some one tries it
//$valid += $database->num_rows($sql); // needs a minimum of 1
//if ($_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR'] ){$valid=1;} //dev code
if (isset($_SERVER['HTTP_PHPGSM_AUTH']) and $_SERVER['REMOTE_ADDR'] == $_SERVER['SERVER_ADDR']) {
// command has arrived via ajax-send so should be good
$HTTP_AUTH ='http_auth=>on ';
}
else{
$HTTP_AUTH = 'http_auth=>off ';
}
if(is_cli()) {
$valid = 1; // we trust the console
$sec = true;
$cmds =convert_to_argv($argv,"",true);
$method = 'ARGV';
$logline = date("d-m-Y H:i:s").' localhost accessed ajax with '.print_r($cmds,true).cr;
//file_put_contents(LOG,$logline,FILE_APPEND);
if ($cmds['debug'] == 'true') {
error_reporting( -1 );
echo 'Ajax v'.$version.' '.$build.' Copyright Noideer Software '.$settings['start_year'].' - '.date('Y').cr;
foreach ($cmds as $k => $v) {
if ($k == 'debug'){continue;}
print "[$k] => $v".cr;
}
if (empty($cmds['action'])) {exit;}
}
else {error_reporting( 0 );}
}
else {
error_reporting( 0 );
if (!empty($_POST)) {
$cmds = convert_to_argv($_POST,"",true);
$method = 'POST';
}
else {
if (isset($cmds)) {
$cmds = array_merge($cmds,convert_to_argv($_GET,"",true));
$method .='/GET ';
}
else {
$cmds = convert_to_argv($_GET,"",true);
$method = 'GET ';
}
}
}
if(!$valid) {
die( 'invalid request '.$_SERVER['REMOTE_ADDR'] .cr );
}
$entry ='';
foreach ($cmds as $k=>$v) {
//
$entry .="$k=>$v ";
}
$entry = rtrim($entry);
if(isset($_SERVER['REMOTE_ADDR'])) {
$rip = $_SERVER['REMOTE_ADDR'];
}
else {
$rip = "UnKnown \t";
}
$logline = date("d-m-Y H:i:s")." $rip valid = $valid method = $method cmds = $entry $HTTP_AUTH";
log_to(LOG,$logline);
// do what's needed
switch (strtolower($cmds['action'])) {
case "all" :
if($cmds['debug'] =='true' ) {
echo cr.print_r(all($cmds),true).cr;
}
else {
echo json_encode(all($cmds));
}
exit;
case "boottime" :
echo get_boot_time().cr;
exit;
case "check_services" :
if ($cmds['debug'] == true){
print_r(check_services($cmds));
}
else {
echo json_encode(check_services($cmds));
}
exit;
case "console":
$console_data['log'] = readlog($cmds);
$console_data = array_merge($console_data,viewserver($cmds));
if ($cmds['debug'] == true){
print_r($console_data);
//exit;
}
else {
echo json_encode($console_data);
}
exit;
case "exescreen" :
echo exescreen($cmds);
if (is_cli()) {
echo cr;
}
exit;
case "exetmux":
$output = exetmux($cmds);
if(is_array($output)) {
print_r($output);
}
else {
echo $output;
}
exit;
case "exe" :
echo exe($cmds);
exit;
case "get_file" :
if (isset($cmds['post'])) {
$logline = "POST";
foreach ($cmds as $k =>$v) {
//
$logline .= " $k => $v".cr;
}
//file_put_contents(LOG,$logline,FILE_APPEND);
file_put_contents($cmds['file'],$cmds['data']);
}
else {
$logline= "GET";
foreach ($cmds as $k => $v) {
$logline .= " $k => $v".cr;
}
//file_put_contents(LOG,$logline,FILE_APPEND);
echo file_get_contents($cmds['file']);
}
exit;
case "lgsm" :
lgsm($cmds);
exit;
case "ps_file" :
if (isset($cmds['filter'])) {
// add the grep filter
echo shell_exec ('ps -C srcds_linux -o pid,%cpu,%mem,cmd |grep '.$cmds['filter'].'.cfg');
}
else {
echo shell_exec ('ps -C srcds_linux -o pid,%cpu,%mem,cmd');
}
exit;
case "readlog":
if($cmds['debug'] =='true' ) {
echo print_r(readlog($cmds),true).cr;
}
else {
echo json_encode(readlog($cmds));
}
exit;
case "scanlog":
if (isset($cmds['email'])) {
echo 'email set'.cr;
}
$logline = "SCANLOG";
foreach ($cmds as $k => $v) {
$logline .= " $k => $v".cr;
}
log_to(LOG,trim($logline));
echo scanlog($cmds);
exit;
case "top" :
if (isset($cmds['filter'])) {
//do stuff
print_r($cmds);
echo shell_exec('top -b -n 1 -p '.$cmds['filter'].' | sed 1,7d');
}
exit;
case "lsof" :
lsof($cmds);
exit;
case "game_detail" :
$data = game_detail();
if($cmds['debug'] =='true' ) {
echo print_r($data,true).cr;
exit;
}
//print_r($cmds);
if (isset($cmds['output']) and $cmds['output'] == 'xml') {
$xml = array2xml($data, false);
//echo '<pre>';
//print_r($xml);
print($xml->asXML());
}
else {
//echo json_encode(utf8ize($data));
echo json_encode($data);
}
exit;
case "version":
echo 'Ajax v'.$version.' '.$build.' Copyright Noideer Software '.$settings['start_year'].' - '.date('Y').cr;
exit;
case "viewserver":
if($cmds['debug'] =='true' ) {
echo print_r(viewserver($cmds),true).cr;
}
else {
echo json_encode(viewserver($cmds));
}
exit;
}
function lsof($cmds) {
$cmd = 'ps a -o pid,%cpu,%mem,cmd | grep '.$cmds['filter'].'.cfg |grep srcds_linux | grep -v grep';
$tpid = shell_exec ('ps -C srcds_linux -o pid,%cpu,%mem,cmd |grep '.$cmds['filter'].'.cfg');
$get_pid = explode(' ',trim($tpid));
$pid= $get_pid[0];
$tmp = shell_exec('ls -l /proc/'.$pid.'/fd |grep '.$cmds['loc'].'/logs');
//echo $tmp.cr; // debug code
$x = explode(' ',$tmp);
foreach ($x as $k=>$v) {
if (empty(trim($v))) {
unset ($x[$k]);
}
else {
$x[$k]=trim($v);
}
}
$c = count($x); // need this to check file size
$x = array_values($x); // re-number array
//print_r($x);
// now do stuff return either the path or contents ?
// sending back the contents will save a call but maybe wrong
$filename = $x[10]; //got file name
if (!empty($cmds['return'])) {
//echo 'get contents of '.$filename.' '.filesize($filename).cr;
$return = file_get_contents($filename);
if (strlen($return) >0) {
echo $return;
}
else {
echo 'no data';
}
}
else {
echo $filename;
}
if (is_cli()) {echo cr;}
exit;
}
function game_detail() {
// get processes
include 'includes/vdfparser.php';
$gameq = new SourceQuery( );
$cpu_info = get_cpu_info();
global $cmds; // get options
$db = new db();
$mem =0;
$cpu = 0;
$total_players = 0;
$total_bots = 0;
$total_slots = 0;
if(isset($cmds['ip'])) {
$ip = $cmds['ip'];
}
else {
$host= gethostname();
$ip = gethostbyname($host);
$localIP = trim(shell_exec('hostname -I'));
$localIPs = explode(' ',$localIP);
//print_r($localIPs);
//$ip = geturl('https://api.ipify.org');
if (empty($ip)) { $ip = geturl('http://ipecho.net/plain');}
}
if(empty($ip)) {
$ip= trim(shell_exec("hostname -I | awk '{print $1}'"));
}
$checkip = $ip;
exec('ps -C srcds_linux -o pid,%cpu,%mem,cmd |sed 1,1d',$game_list,$val); // this gets running only needs rework may 2021 for sure jan 2022
foreach ($game_list as $game) {
$tmp = array_values(array_filter(explode (" ",$game)));
$result = find_string_in_array($tmp,'.cfg');
$tmp['host'] = pathinfo(implode('; ', $result), PATHINFO_FILENAME);
$output[] = $tmp;
}
$i=0;
$sql = "SELECT game as server,count(*) as today FROM player_history WHERE FROM_UNIXTIME(last_play,'%Y-%m-%d') = CURDATE() group by game";
$todays_players = $db->get_results($sql);
$sql ='select servers.location,count(*) as total,servers.host from servers where servers.fname like "'.$cmds['server'].'"'; //fname not ip
$server_no = $db->get_row($sql); // total servers
$server_count = $server_no['total'];
if ($cmds['debug'] == "true") { echo "\$server_count = $server_count".cr; }
if(empty($output)) {
// nothing running
if ($cmds['debug']) {
echo "IP to check is $ip".cr;
print_r($server_no);
}
if ($server_no['host'] <> $ip){
$return = $cmds['server'].' is not hosted here';
return $return;
}
$du = shell_exec('du -s '.dirname($server_no['location']));
list ($tsize,$location) = explode(" ",$du);
}
else{
if(isset($cmds['filter'])) {
//filtered output
$sql = 'select * from server1 where host_name = "'.$cmds['filter'].'"';
}
else{
$sql = 'select * from server1 where fname like "'.$cmds['server'].'" and enabled=1 order by server_name ASC';
}
$servers = $db->get_results($sql);
foreach ($servers as $server) {
unset ($server['id']);
$fname = trim($server['host_name']);
$key = searchforkey($fname, $todays_players,'server');
if ($key === false) {
$server['player_tot'] = 0;
}
else {
$server['player_tot'] = $todays_players[$key]['today'];
}
//$key = array_search('100', array_column($userdb, 'uid'));
$run_record = get_key($server['host_name'],$output) ;
if (get_key($server['host_name'],$output) >= 0) {
// running server add live data
$server['vdf_file'] = $server['location'].'/steamapps/appmanifest_'.$server['server_id'].'.acf';
$kv = VDFParse($server['vdf_file']);
$server['vdf_data'] =$kv['AppState'];
//https://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/api_id/<icon>.jpg
if ($server['running']) {
$server['online'] = 'Online';
try {
$gameq->Connect( $server['host'], $server['port'], SQ_TIMEOUT, SQ_ENGINE );
$sub_cmd = 'GetInfo';
$info1 = $gameq->GetInfo();
$server = array_merge($server ,$info1);
if ($info1['Players'] > 0) {
$sub_cmd = 'GetPlayers';
$total_players += ($info1['Players']-$info1['Bots']);
$total_bots += $info1['Bots'];
$server['players'] = $gameq->GetPlayers( ) ;
$server['players'] = add_steamid($server['players']);
}
}
catch( Exception $e ) {
$Exception = $e;
if (strpos($Exception,'Failed to read any data from socket')) {
$Exception = 'Failed to read any data from socket (Game Detail=>'.$sub_cmd.')';
}
$error = date("d-m-Y h:i:sa").' => '.$server['host_name'].'('.$server['host'].':'.$server['port'].') '.$Exception;
$mask = "%17.17s %-30.30s \n";
file_put_contents(LOG,$error.cr,FILE_APPEND);
}
}
if (isset($server['MaxPlayers'])) {$total_slots += $server['MaxPlayers'];}
$pid = $output[$run_record][0];
$server['mem'] = $output[$run_record][2];
$server['cpu'] = $output[$run_record][1];
$mem += $server['mem']; // memory %
$cpu += $server['cpu']; // cpu %
$du = trim(shell_exec('du -s '.$server['location'])); // get size of game
$size = str_replace($server['location'],'',$du);
$server['size'] = formatBytes(floatval($size)*1024,2);
if (empty($server['host_name'])) {
$logline =date("d-m-Y h:i:sa").' No Host_name !! '.$server1.PHP_EOL;
file_put_contents('logs/ajax.log',$logline,FILE_APPEND);
continue;
}
if (isset($cmds['filter'])) {
// run a different array
$return['server'] = $server;
}
else {
$return[$server['fname']][$server['host_name']] = $server;
}
if($server['running'] == '1') {
$i++;
}
}
else {
$du = trim(shell_exec('du -s '.$server['location'])); // get size of game
$size = str_replace($server['location'],'',$du);
$server['mem'] = 0;
$server['cpu'] = 0;
$server['online'] = 'Offline';
$server['size'] = formatBytes(floatval($size)*1024,2);
if (isset($cmds['filter'])) {
// run a different array
$return['server'] = $server;
}
else {
$return[$server['fname']][$server['host_name']] = $server;
}
}
}
$du = shell_exec('du -s '.dirname($server['location']));
$tsize = str_replace(dirname($server['location']),'',$du);
}
// add computed items
$sql = "SELECT `country`,country_code, count(*) as today FROM players WHERE FROM_UNIXTIME(last_log_on,\"%Y-%m-%d\") = CURDATE() group by country_code order by today desc;";
$return['general']['countries'] = $db->get_results($sql);
//$countries = $db->get_results($sql);
$sql = "SELECT * FROM `logins` LIMIT 10 ";
//$return['general']['countries'] = $db->get_results($sql);
$countries = $db->get_results($sql);
$sql = "SELECT sum(players) as player_tot, count(country) as countries, sum(logins) as tot_logins, (select count(*) from servers) as game_tot, (select count(*) from servers where running = 1) as run_tot FROM `logins` WHERE 1";
$return['general']['players'] = $db->get_row($sql);
$return['general']['countries'] = build_countrys($countries,$return['general']['countries'],$return);
$return['general']['server_id'] = $cmds['server'];
$return['general']['live_servers'] = $i;
$return['general']['total_players'] = $total_players;
$return['general']['total_bots'] = $total_bots;
$return['general']['used_slots'] = $total_players+$total_bots;
$return['general']['total_slots'] = $total_slots;
$return['general']['total_servers'] = $server_count;
$return['general']['total_mem'] = round($mem,2,PHP_ROUND_HALF_UP);
$return['general']['total_cpu'] = round($cpu,2,PHP_ROUND_HALF_UP);
$return['general']['game_cpu'] = number_format(($cpu/100) * (intval($cpu_info['load_1_min_pc']) /100)*100,1);
$return['general']['total_size'] = formatBytes(floatval($tsize)*1024,2);
$return['general']['total_size_raw'] = floatval($tsize);
$sql = "select players.name,players.country,players.country_code,players.log_ons,players.last_log_on,players.first_log_on from players ORDER BY `players`.`log_ons` DESC LIMIT 10";
//$return['general']['top_players']
$players = $db->get_results($sql);
foreach ($players as $k => $v) {
// top 10 players
$players[$k]['name'] = Emoji::Decode(trim($v['name']));
//$players[$k]['name'] = utf8_Encode($v['name']);
//echo mb_detect_encoding($$players[$k]['name']).cr;;
$players[$k]['last_log_on'] = time2str($v['last_log_on']);
$players[$k]['flag'] = 'https://ipdata.co/flags/'.trim(strtolower($v['country_code'])).'.png';
if ($players[$k]['last_log_on'] == "1 weeks ago") {$players[$k]['last_log_on'] = 'a week ago';}
//if ($player['log_ons'] < 100) {$player['log_ons'] =' '.$player['log_ons'];}
if ($players[$k]['first_log_on'] >0 ) {
$players[$k]['first_log_on'] = time2str($v['first_log_on']);
}
else {
$players[$k]['first_log_on'] = 'N/A';
}
}
$return['top_players']= $players;
//header('Content-Type:text/html; charset=gb2312');
return $return;
}
function all($cmds) {
//get the lot
global $database;
$return = get_cpu_info();
$return = array_merge($return,get_software_info($database));
$return = array_merge($return,get_disk_info());
$return = array_merge($return,get_mem_info());
$return = array_merge($return,get_user_info($return));
$tmp = game_detail();
$add = $tmp['general'];
unset($tmp['general']);
$games = $tmp[$cmds['server']];
if ($cmds['debug']) {
//print_r($games);
}
$x = floatval($return['quota_used']); // get size
$return['quota_pc'] = number_format( $x* (100/floatval($return['quota'])) ,2);
$return = array_merge($return,$add);
$return['servers'] = $games;
return $return;
}
function exescreen ($cmds) {
// start & stop etc
global $database;
$exe =$cmds['server'];
$localIP = getHostByName(getHostName()); // carefull if the hostname is set to 127.0.0.1
$localIP = trim(shell_exec('hostname -I'));
$localIPs = explode(' ',$localIP);
$key = array_search($exe, $localIPs);
$sql = 'select * from server1 where host_name like "'.trim($exe).'"';
$server = $database->get_row($sql); // pull results
$key = array_search($server['host'], $localIPs);
$localIP = $localIPs[$key];
if (empty($server['host'])) {
$return = "invalid server $exe"; // don't know this server
return $return;
}
if ($server['host'] <> $localIP) {
//$choices = print_r($localIPs,true);
//return "This Server is not hosted here $localip /".$server['host']." choices are $choices the key was $key"; // we know this one but it's elsewhere
}
switch ($server['binary_file']) {
case 'srcds_run':
$cmd = 'ps -C srcds_linux -o pid,%cpu,%mem,cmd |grep '.$exe.'.cfg';
break;
default:
$cmd = 'ps -C '.$server['binary_file'].' -o pid,%cpu,%mem,cmd |grep '.$server['binary_file'];
break;
}
$is_running = shell_exec ($cmd); // are we running ?
switch ($cmds['cmd']) {
case 's' :
if ($is_running) {
$return = $exe.' is already running';
break;
}
chdir($server['location']);
$logFile = $server['location'].'/log/console/'.$server['host_name'].'-console.log' ;
$savedLogfile = $server['location'].'/log/console/'.$server['host_name'].'-'.date("d-m-Y").'-console.log' ;
rename($logFile, $savedLogfile); // log rotate
if (strtolower($server['managed_by']) == 'phpgsm'){
$cmd = 'screen -L -Logfile '.$logFile.' -dmS '.$server['host_name'];
exec($cmd); // open session
$cmd = 'screen -S '.$server['host_name'].' -p 0 -X stuff "'.$server['startcmd'].'^M"'; //start server
exec($cmd);
}
else {
//lgsm ??
$cmd = $server['startcmd'].'?option=st';
$err = geturl("$cmd");
file_put_contents('lgsm.txt',$err,FILE_APPEND);
}
$sql = 'update servers set running = 1 where host_name = "'.$exe.'"';
$update['running'] = 1;
$update['starttime'] = time();
$where['host_name'] = $exe;
$database->update('servers',$update,$where);
$return = 'Starting Server '.$server['host_name'];
break;
case 'q':
if (!$is_running) {
$return = $exe.' is not running';
break;
}
if (strtolower($server['managed_by']) == 'phpgsm'){
switch ($server['binary_file']) {
case 'srcds_run':
//$cmd = 'screen -X -S '.$server['host_name'] .' quit';
$cmd = 'screen -S '.$exe.' -p 0 -X stuff "'.'quit'.'^M"';
break;
default:
$cmd = 'screen -XS '.$server['host_name'] .' quit';
break;
}
exec($cmd,$content,$ret_val);
if ($ret_val == 0) {
// tidy up screen
$cmd = 'screen -X -S '.$server['host_name'] .' quit';
exec($cmd);
}
}
else {
chdir($server['location']);
$cmd = $server['startcmd']. '?option=sp';
//echo "non phpgsm server stopping with $cmd";
geturl($cmd);
}
$return = 'Stopping Server '.$server['host_name'];
$update['running'] = 0;
$update['starttime'] = '';
$where['host_name'] = $exe;
$database->update('servers',$update,$where);
break;
case 'r':
if (!$is_running) {
$return = $exe.' is not running, starting instead';
// should we just start or quit ??
chdir($server['location']);
if (strtolower($server['managed_by']) == 'phpgsm'){
$logFile = $server['location'].'/log/console/'.$server['host_name'].'-console.log' ;
$savedLogfile = $server['location'].'/log/console/'.$server['host_name'].'-'.date("d-m-Y").'-console.log' ;
rename($logFile, $savedLogfile); // log rotate
$cmd = 'screen -L -Logfile '.$logFile.' -dmS '.$server['host_name'];
exec($cmd); // open session
$cmd = 'screen -S '.$server['host_name'].' -p 0 -X stuff "'.$server['startcmd'].'^M"'; //start server
exec($cmd);
}
else {
//lgsm
$cmd = $server['startcmd'].'?option=st';
geturl($cmd);
}
$sql = 'update servers set running = 1 where host_name = "'.$exe.'"';
$update['running'] = 1;
$update['starttime'] = time();
$where['host_name'] = $exe;
$database->update('servers',$update,$where);
//$return = 'Starting Server '.$server['host_name'];
break;
}
if (strtolower($server['managed_by']) == 'phpgsm'){
$cmd = 'screen -XS '.$server['host_name'] .' quit';
exec($cmd); // stop the server
chdir($server['location']);
$logFile = $server['location'].'/log/console/'.$server['host_name'].'-console.log' ;
$savedLogfile = $server['location'].'/log/console/'.$server['host_name'].'-'.date("d-m-Y").'-console.log' ;
rename($logFile, $savedLogfile); // log rotate
sleep(1); //slow the process up
$cmd = 'screen -L -Logfile '.$logFile.' -dmS '.$server['host_name'];
exec($cmd); // open session
$cmd = 'screen -S '.$server['host_name'].' -p 0 -X stuff "'.$server['startcmd'].'^M"';
exec($cmd); // restart the server
}
else {
//lgsm
$cmd = $server['startcmd'].'?option=r';
geturl($cmd);
}
$sql = 'update servers set running = 1 where host_name = "'.$exe.'"';
$update['running'] = 1;
$update['starttime'] = time();
$where['host_name'] = $exe;
$database->update('servers',$update,$where);
$return = 'Restarting Server '.$server['host_name'];
break;
case 'c':
if (!$is_running) {
$return ='start '.$exe.' before sending commands';
// should we just start or quit ??
break;
}
if (strtolower($server['managed_by']) == 'phpgsm'){
$cmd = 'screen -S '.$exe.' -p 0 -X stuff "'.trim($cmds['text']).'^M"';
$return = $cmd;
exec($cmd); // send console command
}
else {
$cmd = $server['startcmd']. '?option=sd&text='.urlencode($cmds['text']);
geturl($cmd); // send console command
}
$return = 'Command Sent';
break;
case 'u':
// do this to catch if the server is running or not
if($is_running) {
$return = 'Stop server before an update';
break;
}
chdir ($server['install_dir']);
//$steamcmd =shell_exec('which steamcmd');
//$cmds['cmd'] = $steamcmd.' +login anonymous +force_install_dir '.$server['install_dir'].'/'.$server['game'].' +app_update '.$server['server_id'].' +quit';
exe($cmds);
break;
}
return $return;
}
function exe($cmds) {
// run a command this array needs to be in a settings file
include 'includes/allowed_cmds.php';
//$allowed = array('scanlog.php','cron_u.php','cron_r.php','check_ud.php','steamcmd','tmpreaper', 'sudo','cron_scan.php');
foreach ($allowed as $find) {
if (strpos($cmds['cmd'], $find) !== FALSE ) {
$logline = date("d-m-Y h:i:s");
$logline .= " function exe => ".$cmds['cmd'];
log_to(LOG,$logline);
$can_do = true;
}
}
if(empty($can_do)) {
return 61912;
}
if($can_do == true) {
/*
* Exit codes
* 0 = ran correctly
* 127 = file not found
* 139 = segmentation
*/
$return ='';
$output = split_exec($cmds['cmd'],'');
$debug = explode(cr,$output['stdout']);
if (isset($cmds['debug'])) {
foreach ($debug as $line) {
$return .= $line.cr;
}
if(!empty($output['stderr'])) {
$logline = date("d-m-Y h:i:s").' exe had this error = '.$output['stderr'].' return error level was '.$output['return'].' when running '.$cmds['cmd'];
log_to(LOG,$logline);
}
return $return;
}
else {
// test if no debug needs to return somthing on success
foreach ($debug as $line) {
$return .= $line.cr;
}
return $return;
}
return false; // just in case anything slips through
}
}
function utf8ize($mixed) {
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = utf8ize($value);
}
} else if (is_string ($mixed)) {
return utf8_encode($mixed);
} else if (is_object($mixed)) {
$a = (array)$mixed; // from object to array
return utf8ize($a);
}
return $mixed;
}
function check_services($cmds) {
// run service check
exec('/usr/sbin/service --status-all 2>/dev/null',$services,$retVal);
//echo "return $retVal<br>";
//print_r ($services);
foreach ($services as $key=>$service) {
if (strpos($service,' + ')) {
$service = str_replace('[ + ]','',$service);
$id = trim($service);
if(isset($cmds['running']) and $cmds['running'] == 'true'){
$return[$id] = true;
}
elseif (!isset($cmds['running'])) {
$return[$id] = true;
}
}
elseif (strpos($service,'?')) {
echo 'not sure'.cr;
}
else {
$service = str_replace('[ - ]','',$service);
$id = trim($service);
if(isset($cmds['running']) and $cmds['running'] == 'false'){
$return[$id] = false;
}
elseif (!isset($cmds['running'])) {
$return[$id] = false;
}
}
//echo $key.' '.$service.cr;
}
//print_r($demo);
return $return;
}
function viewserver($cmds) {
// replace php file viewplayers.php
$database = new db();
$Query = new SourceQuery( );
$emoji = new Emoji;
$sql = 'select * from server1 where host_name like "'.$cmds['id'].'"';
file_put_contents('sql.txt',$sql);
$server =$database->get_row($sql);
try{
$Query->Connect( $server['host'], $server['port'], SQ_TIMEOUT, SQ_ENGINE );
$info = $Query->GetInfo();
$players = $Query->GetPlayers( ) ;
$rules = $Query->GetRules( );
}
catch( Exception $e ) {
$Exception = $e;
if (strpos($Exception,'Failed to read any data from socket')) {
$Exception = $Exception.' Failed to read any data from socket (Function viewplayers)';
}
$error = date("d-m-Y h:i:sa").' ('.$cmds['ip'].':'.$cmds['port'].') '.$Exception;
//sprintf("[%14.14s]",$str2)
$mask = "%17.17s %-30.30s \n";
file_put_contents('logs/xpaw.log',$error.CR,FILE_APPEND);
}
$Query->Disconnect( );
//we now have data
jump:
$sql = 'select * from players where name_c="';
if (count($players)) {
// we have players
orderBy($players,'Frags','d'); // score order
foreach ($players as $k=>$v) {
//loop add flag & country $v being the player array
// don't update player here let scanlog do it
$players[$k]['Name'] =$emoji->Encode($v['Name']);
$player_data = $database->get_results($sql.$database->escape($players[$k]['Name']).'"'); // player info from db
if (!empty($player_data)) {
// here we go
//echo 'Result '.print_r($player_data,true).cr;
$player_data= reset($player_data);
$players[$k]['Name'] = Emoji::Decode($players[$k]['Name']);
$players[$k]['flag'] = 'src ="https://ipdata.co/flags/'.trim(strtolower($player_data['country_code'])).'.png"'; // windows don't do emoji flags use image
$players[$k]['country'] = $player_data['country'];
$players[$k]['steam_id'] = $player_data['steam_id64']; // user steam_id
$players[$k]['ip'] = long2ip($player_data['ip']); // recorded ip address
}
else {
// no current flag or country
// add a default image for the flag
// random country
if(empty(trim($players[$k]['Name']))) { $players[$k]['Name'] = 'Spectator';}
$players[$k]['flag'] = 'src ="/img/'.'unknown.png"'; // windows don't do emoji flags use image
$players[$k]['country'] = 'unknown';
}
}
}
$return['info'] = $info;
$return['info']['real_players'] = $info['Players']-$info['Bots'];
$return['players'] = $players;
$return['rules'] = $rules;
return $return;
}
function readlog($cmds) {
if (!isset($cmds['rows'])) {
$cmds['rows']= 10;
}
//$table = new table(CONSOLE_TABLE_ALIGN_CENTER,borders,2,null,true,CONSOLE_TABLE_ALIGN_CENTER);
//$table->setHeaders(array("User ID/IP","Period"));
//convert readlog to ajax function
$ip = file_get_contents('https://api.ipify.org');// get ip
if (empty($ip)) { $ip = file_get_contents('http://ipecho.net/plain');}
$database = new db();
$sql = 'select * from server1 where host_name like "'.$cmds['id'].'"';
$server =$database->get_row($sql);
//echo $server['location'].cr;
$filename = $server['location'].'/log/console/'.$cmds['id'].'-console.log';
if ($ip <> $server['host']) {
$url = $server['url'].':'.$server['bport'].'/ajaxv2.php?action=get_file&file='.$filename;
if (isset($cmds['debug'])) {echo '[url] => '.$url.cr;}
$log_contents = geturl($url);
}
else {
$log_contents = file_get_contents($filename); // local file
}
$log_contents = array_reverse(explode(cr,trim($log_contents)));
//print_r($log_contents);
foreach($log_contents as $k=>$v) {
if ($k == $cmds['rows']) {break;}
$v = preg_replace('/<.*?>/', '', $v); //user number ?
$v = preg_replace('@\(.*?\)@','',$v); // bracket content
$v = preg_replace('/Console<0><Console><Console>/','Console',$v);
$v = preg_replace('/<[U:1:[0-9]+]>/', ' ', $v);
$v = preg_replace('/</',' ',$v);
$v = preg_replace('/>/',' ',$v);
if ($v == 'say admin') {
// show admin names
}
$date ='L '. date("m/d/Y");
if (is_cli()) {
$pattern = ' /L (\w+)\/(\d+)\/(\d+)/i';
$replacement = '${2}/$1/$3';
$v = preg_replace($pattern, $replacement, $v,-1,$count);
$replacement = '${1}:$2:$3';
$pattern = '/(\d+):(\d+):(\d+)/';
$v = preg_replace($pattern, $replacement, $v,-1,$count);
}
else {
// this code block needs to read a replacement array for str_replace rather than hard coding them !
$pattern = ' /L (\w+)\/(\d+)\/(\d+)/i';
$replacement = '<span style="color:yellow;"><b>${2}/$1/$3</b></span>';
//display the result returned by preg_replace
$v = preg_replace($pattern, $replacement, $v,-1,$count);
$replacement = '<span style="color:yellow;"><b>${1}:$2:$3</b></span>';
$pattern = '/(\d+):(\d+):(\d+)/';
$v = preg_replace($pattern, $replacement, $v,-1,$count);
$v = str_replace(' say ',' <span style="color:magenta;"><b> say </b></span>',$v);
$v = str_replace(' killed ',' <span style="color:red;"><b> killed </b></span>',$v);
$v = str_replace(' Console ',' <span style="color:#328ba8;"><b> Console </b></span>',$v);
$v = str_replace('committed suicide',' <span style="color:red;"><b> committed suicide </b></span>',$v);
$v = str_replace('This command can only be used in-game.','<span style="color:red;">This command can only be used in-game.</span>',$v);
$v = str_replace('Server logging enabled',' <span style="color:green;"><b>Server logging enabled</b></span> ',$v);
$v = str_replace('disconnected (reason "Kicked from server")','<span style="color:#ffbf00;"><b>disconnected (reason "Kicked from server")</b></span>',$v);
$v = str_replace('disconnected',' <span style="color:#ffbf00;"><b>dissconnected</b></span> ',$v);
$v = str_replace('Writing ','<span style="color:green"><b>Writing </b></span>',$v);
$v = str_replace('Unknown command','<span style="color:red"><b>Unknown command </b></span>',$v);
$v = str_replace('listip','<span style="color:blue"><b>List Banned IP\'s </b></span>',$v);
$v = str_replace('listid','<span style="color:green"><b>List Banned ID\'s </b></span>',$v);
if (strpos($v,' filter list:') == true) {
$data = explode(':',$v);
$v =trim($data[1]);
$count = intval($v);
$v=$count;
}
if (strpos($v,': permanent') or strpos($v,'.000 min')) {
// do ban lines
$data = explode(':',$v);
$v = "count = $count ".print_r($data,true);
}
$v = str_replace('"','',$v); // knock out "
}
if(!empty($v)) {
$return[] = $v;
}
}
return array_reverse($return); // send the data back in the right order !
}
function scanlog($cmds) {
// scanlog as a function
error_reporting(E_ALL); // set errors on for dev
global $settings,$database,$update_done;
$ip = geturl('https://api.ipify.org');// get ip
if (empty($ip)) { $ip = geturl('http://ipecho.net/plain');}
$localip = "ip = $ip";
if (empty( $settings['ip_key'] )) {
echo 'Fatal Error - api key missing'.cr;
exit(7);
}
else {
$key = $settings['ip_key'] ;
}
if(empty($cmds['server'])) {
return 'function not ran correctly';
}
$asql = 'select * from players where steam_id64="'; // sql stub for user updates
$display='';
if ($cmds['server'] == 'all') {
//$allsql = 'SELECT servers.* , base_servers.url, base_servers.port as bport, base_servers.fname,base_servers.ip as ipaddr FROM `servers` left join `base_servers` on servers.host = base_servers.ip where servers.id <>"" and servers.running="1" order by servers.host_name';
$allsql = "SELECT * FROM `server1`where running=1 order by host_name ASC";
$game_results = $database->get_results($allsql);
$display='';
foreach ($game_results as $run) {
//bulid path done this way so we can get the file back from a remote server
$path = $run['url'].':'.$run['bport'].'/ajaxv2.php?action=get_file&file='.$run['location'].'/log/console/'.$run['host_name'].'-console.log'; //used for screen log
//$path = $run['url'].':'.$run['bport'].'/ajaxv2.php?action=lsof&filter='.$run['host_name'].'&loc='.$run['location'].'/'.$run['game'].'&return=content'; //used for steam log
$tmp = geturl($path);
if (isset($cmds['debug'])) {
echo $run['host_name'].' '.$path.cr; // debug code