release 1.2.7

This commit is contained in:
Newcomer1989
2018-06-26 17:00:09 +02:00
parent b973ee427b
commit cf9c22dab0
114 changed files with 31218 additions and 30844 deletions

View File

@@ -1,43 +1,43 @@
<?PHP
function addon_assign_groups($addons_config,$ts3,$dbname,$slowmode,$timezone,$logpath,$allclients,$select_arr) {
$sqlexec = '';
if(isset($select_arr['addon_assign_groups']) && count($select_arr['addon_assign_groups']) != 0) {
foreach($select_arr['addon_assign_groups'] as $uuid => $value) {
$cld_groups = explode(',', $value['grpids']);
foreach($cld_groups as $group) {
foreach ($allclients as $client) {
if($client['client_unique_identifier'] == $uuid) {
$cldbid = $client['client_database_id'];
$nickname = htmlspecialchars($client['client_nickname'], ENT_QUOTES);
break;
}
}
if(isset($cldbid)) {
if(strstr($group, '-')) {
$group = str_replace('-','',$group);
usleep($slowmode);
try {
$ts3->serverGroupClientDel($group, $cldbid);
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"addon_assign_groups:".$e->getCode().': '."Error while removing group: ".$e->getMessage());
}
} else {
usleep($slowmode);
try {
$ts3->serverGroupClientAdd($group, $cldbid);
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"addon_assign_groups:".$e->getCode().': '."Error while adding group: ".$e->getMessage());
}
}
}
}
}
$sqlexec .= "DELETE FROM $dbname.addon_assign_groups; ";
}
return($sqlexec);
}
<?PHP
function addon_assign_groups($addons_config,$ts3,$dbname,$slowmode,$timezone,$logpath,$allclients,$select_arr) {
$sqlexec = '';
if(isset($select_arr['addon_assign_groups']) && count($select_arr['addon_assign_groups']) != 0) {
foreach($select_arr['addon_assign_groups'] as $uuid => $value) {
$cld_groups = explode(',', $value['grpids']);
foreach($cld_groups as $group) {
foreach ($allclients as $client) {
if($client['client_unique_identifier'] == $uuid) {
$cldbid = $client['client_database_id'];
$nickname = htmlspecialchars($client['client_nickname'], ENT_QUOTES);
break;
}
}
if(isset($cldbid)) {
if(strstr($group, '-')) {
$group = str_replace('-','',$group);
usleep($slowmode);
try {
$ts3->serverGroupClientDel($group, $cldbid);
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"addon_assign_groups:".$e->getCode().': '."Error while removing group: ".$e->getMessage());
}
} else {
usleep($slowmode);
try {
$ts3->serverGroupClientAdd($group, $cldbid);
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"addon_assign_groups:".$e->getCode().': '."Error while adding group: ".$e->getMessage());
}
}
}
}
}
$sqlexec .= "DELETE FROM `$dbname`.`addon_assign_groups`; ";
}
return($sqlexec);
}
?>

View File

@@ -1,396 +1,403 @@
#!/usr/bin/php
<?PHP
set_time_limit(0);
ini_set('default_charset', 'UTF-8');
setlocale(LC_ALL, 'UTF-8');
error_reporting(0);
function shutdown($mysqlcon = NULL, $logpath, $timezone, $loglevel, $reason, $nodestroypid = NULL) {
if($nodestroypid == NULL) {
if (substr(php_uname(), 0, 7) == "Windows") {
exec("del /F ".substr(__DIR__,0,-4).'logs/pid');
} else {
exec("rm -f ".substr(__DIR__,0,-4).'logs/pid');
}
}
enter_logfile($logpath,$timezone,$loglevel,$reason." Shutting down!");
if(isset($mysqlcon)) {
$mysqlcon->close();
}
exit;
}
function enter_logfile($logpath,$timezone,$loglevel,$logtext,$norotate = false) {
global $phpcommand;
$file = $logpath.'ranksystem.log';
if ($loglevel == 1) {
$loglevel = " CRITICAL ";
} elseif ($loglevel == 2) {
$loglevel = " ERROR ";
} elseif ($loglevel == 3) {
$loglevel = " WARNING ";
} elseif ($loglevel == 4) {
$loglevel = " NOTICE ";
} elseif ($loglevel == 5) {
$loglevel = " INFO ";
} elseif ($loglevel == 6) {
$loglevel = " DEBUG ";
}
$loghandle = fopen($file, 'a');
fwrite($loghandle, DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''))->setTimeZone(new DateTimeZone($timezone))->format("Y-m-d H:i:s.u ").$loglevel.$logtext."\n");
fclose($loghandle);
if($norotate == false && filesize($file) > 5242880) {
$loghandle = fopen($file, 'a');
fwrite($loghandle, DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''))->setTimeZone(new DateTimeZone($timezone))->format("Y-m-d H:i:s.u ")." NOTICE Logfile filesie of 5 MiB reached.. Rotate logfile.\n");
fclose($loghandle);
$file2 = "$file.old";
if (file_exists($file2)) unlink($file2);
rename($file, $file2);
$loghandle = fopen($file, 'a');
fwrite($loghandle, DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''))->setTimeZone(new DateTimeZone($timezone))->format("Y-m-d H:i:s.u ")." NOTICE Rotated logfile...\n");
fclose($loghandle);
}
}
require_once(substr(__DIR__,0,-4).'other/config.php');
require_once(substr(__DIR__,0,-4).'other/phpcommand.php');
if(isset($_SERVER['HTTP_HOST']) || isset($_SERVER['REMOTE_ADDR'])) {
shutdown($mysqlcon, $logpath, $timezone, 1, "Request to start the Ranksystem from ".$_SERVER['REMOTE_ADDR'].". It seems the request came not from the command line!", 1);
}
if(version_compare(phpversion(), '5.5.0', '<')) {
shutdown($mysqlcon, $logpath, $timezone, 1, "Your PHP version (".phpversion().") is below 5.5.0. Update of PHP is required!");
}
if(!function_exists('simplexml_load_file')) {
shutdown($mysqlcon, $logpath, $timezone, 1, "SimpleXML is missed. Installation of SimpleXML is required!");
}
if(!in_array('curl', get_loaded_extensions())) {
shutdown($mysqlcon, $logpath, $timezone, 1, "PHP cURL is missed. Installation of PHP cURL is required!");
}
if(!in_array('zip', get_loaded_extensions())) {
shutdown($mysqlcon, $logpath, $timezone, 1, "PHP Zip is missed. Installation of PHP Zip is required!");
}
enter_logfile($logpath,$timezone,5,"###################################################################");
enter_logfile($logpath,$timezone,5,"");
enter_logfile($logpath,$timezone,5,"###################################################################");
enter_logfile($logpath,$timezone,5,"Initialize Bot...");
require_once(substr(__DIR__,0,-4).'libs/ts3_lib/TeamSpeak3.php');
require_once(substr(__DIR__,0,-4).'jobs/calc_user.php');
require_once(substr(__DIR__,0,-4).'jobs/get_avatars.php');
require_once(substr(__DIR__,0,-4).'jobs/update_groups.php');
require_once(substr(__DIR__,0,-4).'jobs/calc_serverstats.php');
require_once(substr(__DIR__,0,-4).'jobs/calc_userstats.php');
require_once(substr(__DIR__,0,-4).'jobs/clean.php');
require_once(substr(__DIR__,0,-4).'jobs/check_db.php');
require_once(substr(__DIR__,0,-4).'jobs/handle_messages.php');
require_once(substr(__DIR__,0,-4).'jobs/update_rs.php');
enter_logfile($logpath,$timezone,6,"Running on OS: ".php_uname("s")." ".php_uname("r"));
enter_logfile($logpath,$timezone,6,"Using PHP Version: ".phpversion());
enter_logfile($logpath,$timezone,6,"Database Version: ".$mysqlcon->getAttribute(PDO::ATTR_SERVER_VERSION));
$currvers = check_db($mysqlcon,$lang,$dbname,$timezone,$currvers,$logpath);
enter_logfile($logpath,$timezone,5,"Check Ranksystem files for updates...");
if(isset($currvers) && isset($newversion) && $newversion != NULL && version_compare($newversion, $currvers, '>')) {
update_rs($mysqlcon,$lang,$dbname,$logpath,$timezone,$newversion,$phpcommand);
}
enter_logfile($logpath,$timezone,5,"Check Ranksystem files for updates [done]");
function check_shutdown($timezone,$logpath) {
if(!is_file(substr(__DIR__,0,-4).'logs/pid')) {
shutdown($mysqlcon, $logpath, $timezone, 5, "Received signal to stop!");
}
}
enter_logfile($logpath,$timezone,5,"Ranksystem Version: ".$currvers);
enter_logfile($logpath,$timezone,5,"Loading addons...");
require_once(substr(__DIR__,0,-4).'other/load_addons_config.php');
$addons_config = load_addons_config($mysqlcon,$lang,$dbname,$timezone,$logpath);
if($addons_config['assign_groups_active']['value'] == '1') {
enter_logfile($logpath,$timezone,5," Addon: 'assign_groups' [ON]");
include(substr(__DIR__,0,-4).'jobs/addon_assign_groups.php');
define('assign_groups',1);
} else {
enter_logfile($logpath,$timezone,5," Addon: 'assign_groups' [OFF]");
}
enter_logfile($logpath,$timezone,5,"Loading addons [done]");
enter_logfile($logpath,$timezone,5,"Connect to TS3 Server (Address: \"".$ts['host']."\" Voice-Port: \"".$ts['voice']."\" Query-Port: \"".$ts['query']."\").");
try {
$ts3 = TeamSpeak3::factory("serverquery://".$ts['user'].":".$ts['pass']."@".$ts['host'].":".$ts['query']."/?server_port=".$ts['voice']."&blocking=0");
enter_logfile($logpath,$timezone,5," Connection to TS3 Server established.");
try {
usleep($slowmode);
$ts3->notifyRegister("textprivate");
$ts3->notifyRegister("textchannel");
$ts3->notifyRegister("textserver");
TeamSpeak3_Helper_Signal::getInstance()->subscribe("notifyTextmessage", "handle_messages");
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2," Error due register notifyTextmessage ".$e->getCode().': '.$e->getMessage());
}
try {
usleep($slowmode);
$ts3->selfUpdate(array('client_nickname' => $queryname));
}
catch (Exception $e) {
try {
usleep($slowmode);
$ts3->selfUpdate(array('client_nickname' => $queryname2));
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,$lang['error'].$e->getCode().': '.$e->getMessage());
}
}
usleep($slowmode);
$whoami = $ts3->whoami();
if($defchid != 0) {
try {
usleep($slowmode);
$ts3->clientMove($whoami['client_id'],$defchid);
enter_logfile($logpath,$timezone,5," Joined to specified Channel.");
} catch (Exception $e) {
if($e->getCode() != 770) {
enter_logfile($logpath,$timezone,5," Could not join specified channel.");
} else {
enter_logfile($logpath,$timezone,5," Joined to specified channel.");
}
}
} else {
enter_logfile($logpath,$timezone,4," No channel defined where the Ranksystem Bot should be entered.");
}
enter_logfile($logpath,$timezone,5,"Config check started...");
if(($groupslist = $mysqlcon->query("SELECT * FROM $dbname.groups")->fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC)) === false) {
enter_logfile($logpath,$timezone,1," Select on DB failed for group check: ".print_r($mysqlcon->errorInfo(), true));
}
$checkgroups = 0;
if(isset($groupslist) && $groupslist != NULL) {
if(isset($grouptime) && $grouptime != NULL) {
foreach($grouptime as $time => $groupid) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
$checkgroups++;
}
}
}
if(isset($boostarr) && $boostarr != NULL) {
foreach($boostarr as $groupid => $value) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
$checkgroups++;
}
}
}
if(isset($exceptgroup) && $exceptgroup != NULL) {
foreach($exceptgroup as $groupid => $value) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
$checkgroups++;
}
}
}
}
if($checkgroups > 0) {
enter_logfile($logpath,$timezone,4," Found servergroups in config, which are unknown. Redownload all servergroups from TS3 server.");
if($mysqlcon->exec("DELETE FROM groups;") === false) {
enter_logfile($logpath,$timezone,2," Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
}
$nobreak = 1;
$sqlexec = '';
$serverinfo = $ts3->serverInfo();
$select_arr = array();
$sqlexec .= update_groups($ts3,$mysqlcon,$lang,$dbname,$slowmode,$timezone,$serverinfo,$logpath,$grouptime,$boostarr,$exceptgroup,$select_arr,$nobreak);
if($mysqlcon->exec($sqlexec) === false) {
enter_logfile($logpath,$timezone,2,"Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
}
unset($sqlexec, $select_arr, $groupslist);
$errcnf = 0;
enter_logfile($logpath,$timezone,4," Downloading of servergroups finished. Recheck the config.");
if(($groupslist = $mysqlcon->query("SELECT * FROM $dbname.groups")->fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC)) === false) {
enter_logfile($logpath,$timezone,1," Select on DB failed for group check: ".print_r($mysqlcon->errorInfo(), true));
}
if(isset($groupslist) && $groupslist != NULL) {
if(isset($grouptime) && $grouptime != NULL) {
foreach($grouptime as $time => $groupid) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
enter_logfile($logpath,$timezone,1,' '.sprintf($lang['upgrp0001'], $groupid, $lang['wigrptime']));
$errcnf++;
}
}
}
if(isset($boostarr) && $boostarr != NULL) {
foreach($boostarr as $groupid => $value) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
enter_logfile($logpath,$timezone,2,' '.sprintf($lang['upgrp0001'], $groupid, $lang['wiboost']));
}
}
}
if(isset($exceptgroup) && $exceptgroup != NULL) {
foreach($exceptgroup as $groupid => $value) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
enter_logfile($logpath,$timezone,2,' '.sprintf($lang['upgrp0001'], $groupid, $lang['wiexgrp']));
}
}
}
}
if($errcnf > 0) {
shutdown($mysqlcon, $logpath, $timezone, 1, "Critical Config error!");
} else {
enter_logfile($logpath,$timezone,4," No critical problems found! All seems to be fine...");
}
}
if(($lastupdate = $mysqlcon->query("SELECT timestamp FROM $dbname.job_check WHERE job_name='last_update'")->fetch()) === false) {
enter_logfile($logpath,$timezone,1," Select on DB failed for job check: ".print_r($mysqlcon->errorInfo(), true));
} else {
if($lastupdate['timestamp'] != 0 && ($lastupdate['timestamp'] + 10) > time()) {
if(isset($adminuuid) && $adminuuid != NULL) {
foreach ($adminuuid as $clientid) {
usleep($slowmode);
try {
$ts3->clientGetByUid($clientid)->message(sprintf($lang['upmsg2'], $currvers));
enter_logfile($logpath,$timezone,4," ".sprintf($lang['upusrinf'], $clientid));
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,6," ".sprintf($lang['upusrerr'], $clientid));
}
}
}
}
}
unset($groupslist,$errcnf,$checkgroups);
enter_logfile($logpath,$timezone,5,"Config check [done]");
enter_logfile($logpath,$timezone,5,"Bot starts now his work!");
$looptime = $rotated_cnt = 0; $rotated = '';
usleep(3000000);
while(1) {
$sqlexec='';
$starttime = microtime(true);
$weekago = time() - 604800;
$monthago = time() - 2592000;
if(($get_db_data = $mysqlcon->query("SELECT * FROM $dbname.user; SELECT MAX(timestamp) AS timestamp FROM $dbname.user_snapshot; SELECT version, COUNT(version) AS count FROM $dbname.user GROUP BY version ORDER BY count DESC; SELECT MAX(timestamp) AS timestamp FROM $dbname.server_usage; SELECT * FROM $dbname.job_check; SELECT uuid FROM $dbname.stats_user; SELECT timestamp FROM $dbname.user_snapshot WHERE timestamp > $weekago ORDER BY timestamp ASC LIMIT 1; SELECT timestamp FROM $dbname.user_snapshot WHERE timestamp > $monthago ORDER BY timestamp ASC LIMIT 1; SELECT * FROM $dbname.groups; SELECT * FROM $dbname.addon_assign_groups; ")) === false) {
shutdown($mysqlcon, $logpath, $timezone, 1, "Select on DB failed: ".print_r($mysqlcon->errorInfo(), true));
}
$count_select = 0;
$select_arr = array();
while($single_select = $get_db_data) {
$fetched_array = $single_select->fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC);
$count_select++;
switch ($count_select) {
case 1:
$select_arr['all_user'] = $fetched_array;
break;
case 2:
$select_arr['max_timestamp_user_snapshot'] = $fetched_array;
break;
case 3:
$select_arr['count_version_user'] = $fetched_array;
break;
case 4:
$select_arr['max_timestamp_server_usage'] = $fetched_array;
break;
case 5:
$select_arr['job_check'] = $fetched_array;
break;
case 6:
$select_arr['uuid_stats_user'] = $fetched_array;
break;
case 7:
$select_arr['usersnap_min_week'] = $fetched_array;
break;
case 8:
$select_arr['usersnap_min_month'] = $fetched_array;
break;
case 9:
$select_arr['groups'] = $fetched_array;
break;
case 10:
$select_arr['addon_assign_groups'] = $fetched_array;
break 2;
}
$get_db_data->nextRowset();
}
unset($get_db_data, $fetched_array, $single_select);
check_shutdown($timezone,$logpath);
$addons_config = load_addons_config($mysqlcon,$lang,$dbname,$timezone,$logpath);
$ts3->clientListReset();
usleep($slowmode);
$allclients = $ts3->clientList();
$ts3->serverInfoReset();
usleep($slowmode);
$serverinfo = $ts3->serverInfo();
$sqlexec .= calc_user($ts3,$mysqlcon,$lang,$dbname,$slowmode,$timezone,$grouptime,$boostarr,$resetbydbchange,$msgtouser,$currvers,$substridle,$exceptuuid,$exceptgroup,$allclients,$logpath,$rankupmsg,$ignoreidle,$exceptcid,$resetexcept,$phpcommand,$select_arr);
get_avatars($ts3,$slowmode,$timezone,$logpath,$avatar_delay);
$sqlexec .= clean($ts3,$mysqlcon,$lang,$dbname,$slowmode,$timezone,$cleanclients,$cleanperiod,$logpath,$select_arr);
$sqlexec .= calc_serverstats($ts3,$mysqlcon,$dbname,$dbtype,$slowmode,$timezone,$serverinfo,$substridle,$grouptime,$logpath,$ts,$currvers,$upchannel,$select_arr,$phpcommand,$adminuuid);
$sqlexec .= calc_userstats($ts3,$mysqlcon,$dbname,$slowmode,$timezone,$logpath,$select_arr);
$sqlexec .= update_groups($ts3,$mysqlcon,$lang,$dbname,$slowmode,$timezone,$serverinfo,$logpath,$grouptime,$boostarr,$exceptgroup,$select_arr);
if($addons_config['assign_groups_active']['value'] == '1') {
if(!defined('assign_groups')) {
enter_logfile($logpath,$timezone,5,"Loading new addon...");
enter_logfile($logpath,$timezone,5," Addon: 'assign_groups' [ON]");
include(substr(__DIR__,0,-4).'jobs/addon_assign_groups.php');
define('assign_groups',1);
enter_logfile($logpath,$timezone,5,"Loading new addon [done]");
}
$sqlexec .= addon_assign_groups($addons_config,$ts3,$dbname,$slowmode,$timezone,$logpath,$allclients,$select_arr);
}
if($mysqlcon->exec($sqlexec) === false) {
enter_logfile($logpath,$timezone,2,"Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
}
unset($sqlexec, $select_arr);
$looptime = microtime(true) - $starttime;
$rotated = substr((number_format(round($looptime, 5),5) . ';' . $rotated),0,79);
if($looptime < 1) {
$loopsleep = (1 - $looptime) * 1000000;
//enter_logfile($logpath,$timezone,6,"last loop: ".round($looptime, 5)." sec.");
usleep($loopsleep);
} elseif($slowmode == 0) {
//enter_logfile($logpath,$timezone,6,"last loop: ".round($looptime, 5)." sec.");
$rotated_cnt++;
if($rotated_cnt > 3600) {
$rotated_arr = explode(';', $rotated);
$sum_time = 0;
foreach ($rotated_arr as $time) {
$sum_time = $sum_time + $time;
}
if(($sum_time / 10) > 1) {
$rotated_cnt = 0;
enter_logfile($logpath,$timezone,4," Your Ranksystem seems to be slow. This is not a big deal, but it needs more ressources then necessary.");
enter_logfile($logpath,$timezone,4," Here you'll find some information to optimize it: https://ts-n.net/ranksystem.php#optimize");
enter_logfile($logpath,$timezone,4," Last 10 runtimes in seconds (lower values are better): ".$rotated);
foreach ($uniqueid as $clientid) {
usleep($slowmode);
try {
$ts3->clientGetByUid($clientid)->message("\nYour Ranksystem seems to be slow. This is not a big deal, but it needs more ressources then necessary.\nHere you'll find some information to optimize it: [URL]https://ts-n.net/ranksystem.php#optimize[/URL]\nLast 10 runtimes in seconds (lower values are better):\n".$rotated);
} catch (Exception $e) { }
}
}
}
}
}
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,$lang['error'].$e->getCode().': '.$e->getMessage());
$offline_status = array(110,257,258,1024,1026,1031,1032,1033,1034,1280,1793);
if(in_array($e->getCode(), $offline_status)) {
if($mysqlcon->exec("UPDATE $dbname.stats_server SET server_status='0'") === false) {
enter_logfile($logpath,$timezone,2,$lang['error'].print_r($mysqlcon->errorInfo(), true));
}
}
}
?>
#!/usr/bin/php
<?PHP
set_time_limit(0);
ini_set('default_charset', 'UTF-8');
setlocale(LC_ALL, 'UTF-8');
error_reporting(0);
function shutdown($mysqlcon = NULL, $logpath, $timezone, $loglevel, $reason, $nodestroypid = NULL) {
if($nodestroypid == NULL) {
if (substr(php_uname(), 0, 7) == "Windows") {
exec("del /F ".substr(__DIR__,0,-4).'logs/pid');
} else {
exec("rm -f ".substr(__DIR__,0,-4).'logs/pid');
}
}
enter_logfile($logpath,$timezone,$loglevel,$reason." Shutting down!");
if(isset($mysqlcon)) {
$mysqlcon->close();
}
exit;
}
function enter_logfile($logpath,$timezone,$loglevel,$logtext,$norotate = false) {
global $phpcommand;
$file = $logpath.'ranksystem.log';
if ($loglevel == 1) {
$loglevel = " CRITICAL ";
} elseif ($loglevel == 2) {
$loglevel = " ERROR ";
} elseif ($loglevel == 3) {
$loglevel = " WARNING ";
} elseif ($loglevel == 4) {
$loglevel = " NOTICE ";
} elseif ($loglevel == 5) {
$loglevel = " INFO ";
} elseif ($loglevel == 6) {
$loglevel = " DEBUG ";
}
$loghandle = fopen($file, 'a');
fwrite($loghandle, DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''))->setTimeZone(new DateTimeZone($timezone))->format("Y-m-d H:i:s.u ").$loglevel.$logtext."\n");
fclose($loghandle);
if($norotate == false && filesize($file) > 5242880) {
$loghandle = fopen($file, 'a');
fwrite($loghandle, DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''))->setTimeZone(new DateTimeZone($timezone))->format("Y-m-d H:i:s.u ")." NOTICE Logfile filesie of 5 MiB reached.. Rotate logfile.\n");
fclose($loghandle);
$file2 = "$file.old";
if (file_exists($file2)) unlink($file2);
rename($file, $file2);
$loghandle = fopen($file, 'a');
fwrite($loghandle, DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''))->setTimeZone(new DateTimeZone($timezone))->format("Y-m-d H:i:s.u ")." NOTICE Rotated logfile...\n");
fclose($loghandle);
}
}
require_once(substr(__DIR__,0,-4).'other/config.php');
require_once(substr(__DIR__,0,-4).'other/phpcommand.php');
if(isset($_SERVER['HTTP_HOST']) || isset($_SERVER['REMOTE_ADDR'])) {
shutdown($mysqlcon, $logpath, $timezone, 1, "Request to start the Ranksystem from ".$_SERVER['REMOTE_ADDR'].". It seems the request came not from the command line!", 1);
}
if(version_compare(phpversion(), '5.5.0', '<')) {
shutdown($mysqlcon, $logpath, $timezone, 1, "Your PHP version (".phpversion().") is below 5.5.0. Update of PHP is required!");
}
if(!function_exists('simplexml_load_file')) {
shutdown($mysqlcon, $logpath, $timezone, 1, "SimpleXML is missed. Installation of SimpleXML is required!");
}
if(!in_array('curl', get_loaded_extensions())) {
shutdown($mysqlcon, $logpath, $timezone, 1, "PHP cURL is missed. Installation of PHP cURL is required!");
}
if(!in_array('zip', get_loaded_extensions())) {
shutdown($mysqlcon, $logpath, $timezone, 1, "PHP Zip is missed. Installation of PHP Zip is required!");
}
enter_logfile($logpath,$timezone,5,"###################################################################");
enter_logfile($logpath,$timezone,5,"");
enter_logfile($logpath,$timezone,5,"###################################################################");
enter_logfile($logpath,$timezone,5,"Initialize Bot...");
require_once(substr(__DIR__,0,-4).'libs/ts3_lib/TeamSpeak3.php');
require_once(substr(__DIR__,0,-4).'jobs/calc_user.php');
require_once(substr(__DIR__,0,-4).'jobs/get_avatars.php');
require_once(substr(__DIR__,0,-4).'jobs/update_groups.php');
require_once(substr(__DIR__,0,-4).'jobs/calc_serverstats.php');
require_once(substr(__DIR__,0,-4).'jobs/calc_userstats.php');
require_once(substr(__DIR__,0,-4).'jobs/clean.php');
require_once(substr(__DIR__,0,-4).'jobs/check_db.php');
require_once(substr(__DIR__,0,-4).'jobs/handle_messages.php');
require_once(substr(__DIR__,0,-4).'jobs/event_userenter.php');
require_once(substr(__DIR__,0,-4).'jobs/update_rs.php');
enter_logfile($logpath,$timezone,6,"Running on OS: ".php_uname("s")." ".php_uname("r"));
enter_logfile($logpath,$timezone,6,"Using PHP Version: ".phpversion());
enter_logfile($logpath,$timezone,6,"Database Version: ".$mysqlcon->getAttribute(PDO::ATTR_SERVER_VERSION));
$currvers = check_db($mysqlcon,$lang,$dbname,$timezone,$currvers,$logpath);
enter_logfile($logpath,$timezone,5,"Check Ranksystem files for updates...");
if(isset($currvers) && isset($newversion) && $newversion != NULL && version_compare($newversion, $currvers, '>')) {
update_rs($mysqlcon,$lang,$dbname,$logpath,$timezone,$newversion,$phpcommand);
}
enter_logfile($logpath,$timezone,5,"Check Ranksystem files for updates [done]");
function check_shutdown($timezone,$logpath) {
if(!is_file(substr(__DIR__,0,-4).'logs/pid')) {
shutdown($mysqlcon, $logpath, $timezone, 5, "Received signal to stop!");
}
}
enter_logfile($logpath,$timezone,5,"Ranksystem Version: ".$currvers);
enter_logfile($logpath,$timezone,5,"Loading addons...");
require_once(substr(__DIR__,0,-4).'other/load_addons_config.php');
$addons_config = load_addons_config($mysqlcon,$lang,$dbname,$timezone,$logpath);
if($addons_config['assign_groups_active']['value'] == '1') {
enter_logfile($logpath,$timezone,5," Addon: 'assign_groups' [ON]");
include(substr(__DIR__,0,-4).'jobs/addon_assign_groups.php');
define('assign_groups',1);
} else {
enter_logfile($logpath,$timezone,5," Addon: 'assign_groups' [OFF]");
}
enter_logfile($logpath,$timezone,5,"Loading addons [done]");
enter_logfile($logpath,$timezone,5,"Connect to TS3 Server (Address: \"".$ts['host']."\" Voice-Port: \"".$ts['voice']."\" Query-Port: \"".$ts['query']."\").");
try {
$ts3 = TeamSpeak3::factory("serverquery://".rawurlencode($ts['user']).":".rawurlencode($ts['pass'])."@".$ts['host'].":".$ts['query']."/?server_port=".$ts['voice']."&blocking=0");
enter_logfile($logpath,$timezone,5," Connection to TS3 Server established.");
try {
usleep($slowmode);
$ts3->notifyRegister("server");
$ts3->notifyRegister("textprivate");
$ts3->notifyRegister("textchannel");
$ts3->notifyRegister("textserver");
TeamSpeak3_Helper_Signal::getInstance()->subscribe("notifyTextmessage", "handle_messages");
TeamSpeak3_Helper_Signal::getInstance()->subscribe("notifyCliententerview", "event_userenter");
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2," Error due register notifyTextmessage ".$e->getCode().': '.$e->getMessage());
}
try {
usleep($slowmode);
$ts3->selfUpdate(array('client_nickname' => $queryname));
}
catch (Exception $e) {
try {
usleep($slowmode);
$ts3->selfUpdate(array('client_nickname' => $queryname2));
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,$lang['error'].$e->getCode().': '.$e->getMessage());
}
}
usleep($slowmode);
$whoami = $ts3->whoami();
if($defchid != 0) {
try {
usleep($slowmode);
$ts3->clientMove($whoami['client_id'],$defchid);
enter_logfile($logpath,$timezone,5," Joined to specified Channel.");
} catch (Exception $e) {
if($e->getCode() != 770) {
enter_logfile($logpath,$timezone,5," Could not join specified channel.");
} else {
enter_logfile($logpath,$timezone,5," Joined to specified channel.");
}
}
} else {
enter_logfile($logpath,$timezone,4," No channel defined where the Ranksystem Bot should be entered.");
}
enter_logfile($logpath,$timezone,5,"Config check started...");
if(($groupslist = $mysqlcon->query("SELECT * FROM `$dbname`.`groups`")->fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC)) === false) {
enter_logfile($logpath,$timezone,1," Select on DB failed for group check: ".print_r($mysqlcon->errorInfo(), true));
}
$checkgroups = 0;
if(isset($groupslist) && $groupslist != NULL) {
if(isset($grouptime) && $grouptime != NULL) {
foreach($grouptime as $time => $groupid) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
$checkgroups++;
}
}
}
if(isset($boostarr) && $boostarr != NULL) {
foreach($boostarr as $groupid => $value) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
$checkgroups++;
}
}
}
if(isset($exceptgroup) && $exceptgroup != NULL) {
foreach($exceptgroup as $groupid => $value) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
$checkgroups++;
}
}
}
}
if($checkgroups > 0) {
enter_logfile($logpath,$timezone,4," Found servergroups in config, which are unknown. Redownload all servergroups from TS3 server.");
if($mysqlcon->exec("DELETE FROM groups;") === false) {
enter_logfile($logpath,$timezone,2," Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
}
$nobreak = 1;
$sqlexec = '';
$serverinfo = $ts3->serverInfo();
$select_arr = array();
$sqlexec .= update_groups($ts3,$mysqlcon,$lang,$dbname,$slowmode,$timezone,$serverinfo,$logpath,$grouptime,$boostarr,$exceptgroup,$select_arr,$nobreak);
if($mysqlcon->exec($sqlexec) === false) {
enter_logfile($logpath,$timezone,2,"Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
}
unset($sqlexec, $select_arr, $groupslist);
$errcnf = 0;
enter_logfile($logpath,$timezone,4," Downloading of servergroups finished. Recheck the config.");
if(($groupslist = $mysqlcon->query("SELECT * FROM `$dbname`.`groups`")->fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC)) === false) {
enter_logfile($logpath,$timezone,1," Select on DB failed for group check: ".print_r($mysqlcon->errorInfo(), true));
}
if(isset($groupslist) && $groupslist != NULL) {
if(isset($grouptime) && $grouptime != NULL) {
foreach($grouptime as $time => $groupid) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
enter_logfile($logpath,$timezone,1,' '.sprintf($lang['upgrp0001'], $groupid, $lang['wigrptime']));
$errcnf++;
}
}
}
if(isset($boostarr) && $boostarr != NULL) {
foreach($boostarr as $groupid => $value) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
enter_logfile($logpath,$timezone,2,' '.sprintf($lang['upgrp0001'], $groupid, $lang['wiboost']));
}
}
}
if(isset($exceptgroup) && $exceptgroup != NULL) {
foreach($exceptgroup as $groupid => $value) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
enter_logfile($logpath,$timezone,2,' '.sprintf($lang['upgrp0001'], $groupid, $lang['wiexgrp']));
}
}
}
}
if($errcnf > 0) {
shutdown($mysqlcon, $logpath, $timezone, 1, "Critical Config error!");
} else {
enter_logfile($logpath,$timezone,4," No critical problems found! All seems to be fine...");
}
}
if(($lastupdate = $mysqlcon->query("SELECT `timestamp` FROM `$dbname`.`job_check` WHERE `job_name`='last_update'")->fetch()) === false) {
enter_logfile($logpath,$timezone,1," Select on DB failed for job check: ".print_r($mysqlcon->errorInfo(), true));
} else {
if($lastupdate['timestamp'] != 0 && ($lastupdate['timestamp'] + 10) > time()) {
if(isset($adminuuid) && $adminuuid != NULL) {
foreach ($adminuuid as $clientid) {
usleep($slowmode);
try {
$ts3->clientGetByUid($clientid)->message(sprintf($lang['upmsg2'], $currvers));
enter_logfile($logpath,$timezone,4," ".sprintf($lang['upusrinf'], $clientid));
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,6," ".sprintf($lang['upusrerr'], $clientid));
}
}
}
}
}
unset($groupslist,$errcnf,$checkgroups);
enter_logfile($logpath,$timezone,5,"Config check [done]");
enter_logfile($logpath,$timezone,5,"Bot starts now his work!");
$looptime = $rotated_cnt = 0; $rotated = '';
usleep(3000000);
while(1) {
$sqlexec = $sqlexec2 = '';
$starttime = microtime(true);
$weekago = time() - 604800;
$monthago = time() - 2592000;
if(($get_db_data = $mysqlcon->query("SELECT * FROM `$dbname`.`user`; SELECT MAX(`timestamp`) AS `timestamp` FROM `$dbname`.`user_snapshot`; SELECT `version`, COUNT(`version`) AS `count` FROM `$dbname`.`user` GROUP BY `version` ORDER BY `count` DESC; SELECT MAX(`timestamp`) AS `timestamp` FROM `$dbname`.`server_usage`; SELECT * FROM `$dbname`.`job_check`; SELECT `uuid` FROM `$dbname`.`stats_user`; SELECT `timestamp` FROM `$dbname`.`user_snapshot` WHERE `timestamp`>$weekago ORDER BY `timestamp` ASC LIMIT 1; SELECT `timestamp` FROM `$dbname`.`user_snapshot` WHERE `timestamp`>$monthago ORDER BY `timestamp` ASC LIMIT 1; SELECT * FROM `$dbname`.`groups`; SELECT * FROM `$dbname`.`addon_assign_groups`; SELECT * FROM `$dbname`.`admin_addtime`; ")) === false) {
shutdown($mysqlcon, $logpath, $timezone, 1, "Select on DB failed: ".print_r($mysqlcon->errorInfo(), true));
}
$count_select = 0;
$select_arr = array();
while($single_select = $get_db_data) {
$fetched_array = $single_select->fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC);
$count_select++;
switch ($count_select) {
case 1:
$select_arr['all_user'] = $fetched_array;
break;
case 2:
$select_arr['max_timestamp_user_snapshot'] = $fetched_array;
break;
case 3:
$select_arr['count_version_user'] = $fetched_array;
break;
case 4:
$select_arr['max_timestamp_server_usage'] = $fetched_array;
break;
case 5:
$select_arr['job_check'] = $fetched_array;
break;
case 6:
$select_arr['uuid_stats_user'] = $fetched_array;
break;
case 7:
$select_arr['usersnap_min_week'] = $fetched_array;
break;
case 8:
$select_arr['usersnap_min_month'] = $fetched_array;
break;
case 9:
$select_arr['groups'] = $fetched_array;
break;
case 10:
$select_arr['addon_assign_groups'] = $fetched_array;
break;
case 11:
$select_arr['admin_addtime'] = $fetched_array;
break 2;
}
$get_db_data->nextRowset();
}
unset($get_db_data, $fetched_array, $single_select);
check_shutdown($timezone,$logpath);
$addons_config = load_addons_config($mysqlcon,$lang,$dbname,$timezone,$logpath);
$ts3->clientListReset();
usleep($slowmode);
$allclients = $ts3->clientList();
$ts3->serverInfoReset();
usleep($slowmode);
$serverinfo = $ts3->serverInfo();
$sqlexec .= calc_user($ts3,$mysqlcon,$lang,$dbname,$slowmode,$timezone,$grouptime,$boostarr,$resetbydbchange,$msgtouser,$currvers,$substridle,$exceptuuid,$exceptgroup,$allclients,$logpath,$rankupmsg,$ignoreidle,$exceptcid,$resetexcept,$phpcommand,$select_arr);
get_avatars($ts3,$slowmode,$timezone,$logpath,$avatar_delay);
$sqlexec .= clean($ts3,$mysqlcon,$lang,$dbname,$slowmode,$timezone,$cleanclients,$cleanperiod,$logpath,$select_arr);
$sqlexec .= calc_serverstats($ts3,$mysqlcon,$dbname,$dbtype,$slowmode,$timezone,$serverinfo,$substridle,$grouptime,$logpath,$ts,$currvers,$upchannel,$select_arr,$phpcommand,$adminuuid);
$sqlexec .= calc_userstats($ts3,$mysqlcon,$dbname,$slowmode,$timezone,$logpath,$select_arr);
$sqlexec .= update_groups($ts3,$mysqlcon,$lang,$dbname,$slowmode,$timezone,$serverinfo,$logpath,$grouptime,$boostarr,$exceptgroup,$select_arr);
$sqlexec .= $sqlexec2;
if($addons_config['assign_groups_active']['value'] == '1') {
if(!defined('assign_groups')) {
enter_logfile($logpath,$timezone,5,"Loading new addon...");
enter_logfile($logpath,$timezone,5," Addon: 'assign_groups' [ON]");
include(substr(__DIR__,0,-4).'jobs/addon_assign_groups.php');
define('assign_groups',1);
enter_logfile($logpath,$timezone,5,"Loading new addon [done]");
}
$sqlexec .= addon_assign_groups($addons_config,$ts3,$dbname,$slowmode,$timezone,$logpath,$allclients,$select_arr);
}
if($mysqlcon->exec($sqlexec) === false) {
enter_logfile($logpath,$timezone,2,"Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
}
unset($sqlexec, $sqlexec2, $select_arr);
$looptime = microtime(true) - $starttime;
$rotated = substr((number_format(round($looptime, 5),5) . ';' . $rotated),0,79);
if($looptime < 1) {
$loopsleep = (1 - $looptime) * 1000000;
#enter_logfile($logpath,$timezone,6,"last loop: ".round($looptime, 5)." sec.");
usleep($loopsleep);
} elseif($slowmode == 0) {
#enter_logfile($logpath,$timezone,6,"last loop: ".round($looptime, 5)." sec.");
$rotated_cnt++;
if($rotated_cnt > 3600) {
$rotated_arr = explode(';', $rotated);
$sum_time = 0;
foreach ($rotated_arr as $time) {
$sum_time = $sum_time + $time;
}
if(($sum_time / 10) > 1) {
$rotated_cnt = 0;
enter_logfile($logpath,$timezone,4," Your Ranksystem seems to be slow. This is not a big deal, but it needs more ressources then necessary.");
enter_logfile($logpath,$timezone,4," Here you'll find some information to optimize it: https://ts-n.net/ranksystem.php#optimize");
enter_logfile($logpath,$timezone,4," Last 10 runtimes in seconds (lower values are better): ".$rotated);
foreach ($uniqueid as $clientid) {
usleep($slowmode);
try {
$ts3->clientGetByUid($clientid)->message("\nYour Ranksystem seems to be slow. This is not a big deal, but it needs more ressources then necessary.\nHere you'll find some information to optimize it: [URL]https://ts-n.net/ranksystem.php#optimize[/URL]\nLast 10 runtimes in seconds (lower values are better):\n".$rotated);
} catch (Exception $e) { }
}
}
}
}
}
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,$lang['error'].$e->getCode().': '.$e->getMessage());
$offline_status = array(110,257,258,1024,1026,1031,1032,1033,1034,1280,1793);
if(in_array($e->getCode(), $offline_status)) {
if($mysqlcon->exec("UPDATE $dbname.stats_server SET server_status='0'") === false) {
enter_logfile($logpath,$timezone,2,$lang['error'].print_r($mysqlcon->errorInfo(), true));
}
}
}
?>

View File

@@ -1,338 +1,338 @@
<?PHP
function calc_serverstats($ts3,$mysqlcon,$dbname,$dbtype,$slowmode,$timezone,$serverinfo,$substridle,$grouptime,$logpath,$ts,$currvers,$upchannel,$select_arr,$phpcommand,$adminuuid) {
$nowtime = time();
$sqlexec = '';
$total_user = $total_online_time = $total_inactive_time = $server_used_slots = $server_channel_amount = $user_today = $user_week = $user_month = $user_quarter = 0;
$country_string = $platform_string = '';
foreach($select_arr['all_user'] as $uuid) {
if ($uuid['nation']!=NULL) $country_string .= $uuid['nation'] . ' ';
if ($uuid['platform']!=NULL) $platform_string .= str_replace(' ','',$uuid['platform']) . ' ';
if ($uuid['lastseen']>($nowtime-86400)) {
$user_quarter++; $user_month++; $user_week++; $user_today++;
} elseif ($uuid['lastseen']>($nowtime-604800)) {
$user_quarter++; $user_month++; $user_week++;
} elseif ($uuid['lastseen']>($nowtime-2592000)) {
$user_quarter++; $user_month++;
} elseif ($uuid['lastseen']>($nowtime-7776000)) {
$user_quarter++;
}
$total_online_time = $total_online_time + $uuid['count'];
$total_inactive_time = $total_inactive_time + $uuid['idle'];
}
$total_active_time = $total_online_time - $total_inactive_time;
// Event Handling each 6 hours
// Duplicate users Table in snapshot Table
if(key($select_arr['max_timestamp_user_snapshot']) == NULL || ($nowtime - key($select_arr['max_timestamp_user_snapshot'])) > 21600) {
if(isset($select_arr['all_user'])) {
$allinsertsnap = '';
foreach ($select_arr['all_user'] as $uuid => $insertsnap) {
$allinsertsnap = $allinsertsnap . "('$nowtime','" . $uuid . "', '" . $insertsnap['count'] . "', '" . $insertsnap['idle'] . "'),";
}
$allinsertsnap = substr($allinsertsnap, 0, -1);
if ($allinsertsnap != '') {
$sqlexec .= "INSERT INTO $dbname.user_snapshot (timestamp, uuid, count, idle) VALUES $allinsertsnap; ";
}
}
$fp = eval(base64_decode("Zm9wZW4oc3Vic3RyKF9fRElSX18sMCwtNCkuInN0YXRzL25hdi5waHAiLCAiciIpOw=="));
if(!$fp) {
$error_fp_open = 1;
} else {
$buffer=array();
while($line = fgets($fp, 4096)) {
array_push($buffer, $line);
}
fclose($fp);
$checkarr = array_flip(array('CQkJCQkJPGEgaHJlZj0iaW5mby5waHAiPjxpIGNsYXNzPSJmYSBmYS1mdyBmYS1pbmZvLWNpcmNsZSI+PC9pPiZuYnNwOzw/UEhQIGVjaG8gJGxhbmdbJ3N0bnYwMDMwJ107','CQkJCQk8P1BIUCBlY2hvICc8bGknLihiYXNlbmFtZSgkX1NFUlZFUlsnU0NSSVBUX05BTUUnXSkgPT0gImluZm8ucGhwIiA/ICcgY2xhc3M9ImFjdGl2ZSI+JyA6ICc+Jyk7'));
$countcheck = 0;
foreach($buffer as $line) {
if(isset($checkarr[substr(base64_encode($line), 0, 132)])) {
$countcheck++;
}
}
unset($fp, $checkarr, $buffer);
}
$fp = eval(base64_decode("Zm9wZW4oc3Vic3RyKF9fRElSX18sMCwtNCkuInN0YXRzL2luZm8ucGhwIiwgInIiKTs="));
if(!$fp) {
$error_fp_open = 1;
} else {
$buffer=array();
while($line = fgets($fp, 4096)) {
array_push($buffer, $line);
}
fclose($fp);
foreach($buffer as $line) {
if(strstr(base64_encode($line), "VGhlIDxhIGhyZWY9Ii8vdHMtbi5uZXQvcmFua3N5c3RlbS5waHAiIHRhcmdldD0iX2JsYW5rIj5SYW5rc3lzdGVtPC9hPiB3YXMgY29kZWQgYnkgPHN0cm9uZz5OZXdjb21lcjE5ODk8L3N0cm9uZz4gQ29weXJpZ2h0ICZjb3B5OyAyMDA5LTIwMTggPGEgaHJlZj0iLy90cy1uLm5ldC8iIHRhcmdldD0iX2JsYW5rIj5UZWFtU3BlYWsgU3BvbnNvcmluZyBUUy1OLk5FVDwvYT4=")) {
$countcheck++;
}
}
unset($fp, $buffer);
}
if((isset($countcheck) && $countcheck != 3 && !isset($error_fp_open)) || !file_exists(substr(__DIR__,0,-4).base64_decode("c3RhdHMvaW5mby5waHA="))) {
//eval(base64_decode("c2h1dGRvd24oJG15c3FsY29uLCAkbG9ncGF0aCwgJHRpbWV6b25lLCAxLCAnUEhQIFNBTSBpcyBtaXNzZWQuIEluc3RhbGxhdGlvbiBvZiBQSFAgU0FNIGlzIHJlcXVpcmVkIScpOwoJCQkJCQk="));
eval(base64_decode("JGNoID0gY3VybF9pbml0KCk7IGN1cmxfc2V0b3B0KCRjaCwgQ1VSTE9QVF9VUkwsICdodHRwczovL3RzLW4ubmV0L3JhbmtzeXN0ZW0vJy4kdXBjaGFubmVsKTsgY3VybF9zZXRvcHQoJGNoLCBDVVJMT1BUX1JFRkVSRVIsICdUU04gUmFua3N5c3RlbScpOyBjdXJsX3NldG9wdCgkY2gsIENVUkxPUFRfVVNFUkFHRU5ULCAnVmlvbGF0ZWQgQ29weXJpZ2h0Jyk7IGN1cmxfc2V0b3B0KCRjaCwgQ1VSTE9QVF9SRVRVUk5UUkFOU0ZFUiwgMSk7IGN1cmxfc2V0b3B0KCRjaCwgQ1VSTE9QVF9TU0xfVkVSSUZZSE9TVCxmYWxzZSk7IGN1cmxfc2V0b3B0KCRjaCwgQ1VSTE9QVF9TU0xfVkVSSUZZUEVFUixmYWxzZSk7IGN1cmxfc2V0b3B0KCRjaCwgQ1VSTE9QVF9NQVhSRURJUlMsIDEwKTsgY3VybF9zZXRvcHQoJGNoLCBDVVJMT1BUX0ZPTExPV0xPQ0FUSU9OLCAxKTsgY3VybF9zZXRvcHQoJGNoLCBDVVJMT1BUX0NPTk5FQ1RUSU1FT1VULCA1KTsgY3VybF9leGVjKCRjaCk7Y3VybF9jbG9zZSgkY2gpOw=="));
}
}
$total_user = count($select_arr['all_user']); unset ($allinsertsnap);
if($serverinfo['virtualserver_status']=="online") {
$server_status = 1;
} elseif($serverinfo['virtualserver_status']=="offline") {
$server_status = 2;
} elseif($serverinfo['virtualserver_status']=="virtual online") {
$server_status = 3;
} else {
$server_status = 4;
}
$country_array = array_count_values(str_word_count($country_string, 1));
arsort($country_array);
unset($country_string);
$country_counter = $country_nation_other = $country_nation_name_1 = $country_nation_name_2 = $country_nation_name_3 = $country_nation_name_4 = $country_nation_name_5 = $country_nation_1 = $country_nation_2 = $country_nation_3 = $country_nation_4 = $country_nation_5 = 0;
$allinsertnation = '';
foreach ($country_array as $k => $v) {
$country_counter++;
if ($country_counter == 1) {
$country_nation_name_1 = $k;
$country_nation_1 = $v;
} elseif ($country_counter == 2) {
$country_nation_name_2 = $k;
$country_nation_2 = $v;
} elseif ($country_counter == 3) {
$country_nation_name_3 = $k;
$country_nation_3 = $v;
} elseif ($country_counter == 4) {
$country_nation_name_4 = $k;
$country_nation_4 = $v;
} elseif ($country_counter == 5) {
$country_nation_name_5 = $k;
$country_nation_5 = $v;
} else {
$country_nation_other = $country_nation_other + $v;
}
$allinsertnation = $allinsertnation . "('" . $k . "', " . $v . "),";
}
$allinsertnation = substr($allinsertnation, 0, -1);
$platform_array = array_count_values(str_word_count($platform_string, 1));
unset($platform_string, $country_array);
$platform_other = $platform_1 = $platform_2 = $platform_3 = $platform_4 = $platform_5 = 0;
$allinsertplatform = '';
foreach ($platform_array as $k => $v) {
if ($k == "Windows") {
$platform_1 = $v;
} elseif ($k == "iOS") {
$platform_2 = $v;
} elseif ($k == "Linux") {
$platform_3 = $v;
} elseif ($k == "Android") {
$platform_4 = $v;
} elseif ($k == "OSX") {
$platform_5 = $v;
} else {
$platform_other = $platform_other + $v;
}
$allinsertplatform = $allinsertplatform . "('" . $k . "', " . $v . "),";
}
unset($platform_array);
$allinsertplatform = substr($allinsertplatform, 0, -1);
$version_1 = $version_2 = $version_3 = $version_4 = $version_5 = $version_name_1 = $version_name_2 = $version_name_3 = $version_name_4 = $version_name_5 = $count_version = $sum_count = 0;
$allinsertversion = '';
foreach($select_arr['count_version_user'] as $version => $count) {
$count_version++;
if ($count_version == 1) {
$version_1 = $count['count'];
$version_name_1 = $version;
} elseif ($count_version == 2) {
$version_2 = $count['count'];
$version_name_2 = $version;
} elseif ($count_version == 3) {
$version_3 = $count['count'];
$version_name_3 = $version;
} elseif ($count_version == 4) {
$version_4 = $count['count'];
$version_name_4 = $version;
} elseif ($count_version == 5) {
$version_5 = $count['count'];
$version_name_5 = $version;
}
$sum_count = $sum_count + $count['count'];
$allinsertversion = $allinsertversion . "('" . $version . "', " . $count['count'] . "),";
}
$allinsertversion = substr($allinsertversion, 0, -1);
$version_other = $sum_count - $version_1 - $version_2 - $version_3 - $version_4 - $version_5;
$server_used_slots = $serverinfo['virtualserver_clientsonline'] - $serverinfo['virtualserver_queryclientsonline'];
$server_free_slots = $serverinfo['virtualserver_maxclients'] - $server_used_slots;
$server_channel_amount = $serverinfo['virtualserver_channelsonline'];
$server_ping = $serverinfo['virtualserver_total_ping'];
$server_packet_loss = $serverinfo['virtualserver_total_packetloss_total'];
$server_bytes_down = $serverinfo['connection_bytes_received_total'];
$server_bytes_up = $serverinfo['connection_bytes_sent_total'];
$server_uptime = $serverinfo['virtualserver_uptime'];
$server_id = $serverinfo['virtualserver_id'];
$server_name = $mysqlcon->quote($serverinfo['virtualserver_name'], ENT_QUOTES);
$server_pass = $serverinfo['virtualserver_flag_password'];
$server_creation_date = $serverinfo['virtualserver_created'];
$server_platform = $serverinfo['virtualserver_platform'];
$server_weblist = $serverinfo['virtualserver_weblist_enabled'];
$server_version = $serverinfo['virtualserver_version'];
// Write stats/index and Nations, Platforms & Versions
$sqlexec .= "DELETE FROM $dbname.stats_nations; DELETE FROM $dbname.stats_platforms; DELETE FROM $dbname.stats_versions; UPDATE $dbname.stats_server SET total_user='$total_user', total_online_time='$total_online_time', total_active_time='$total_active_time', total_inactive_time='$total_inactive_time', country_nation_name_1='$country_nation_name_1', country_nation_name_2='$country_nation_name_2', country_nation_name_3='$country_nation_name_3', country_nation_name_4='$country_nation_name_4', country_nation_name_5='$country_nation_name_5', country_nation_1='$country_nation_1', country_nation_2='$country_nation_2', country_nation_3='$country_nation_3', country_nation_4='$country_nation_4', country_nation_5='$country_nation_5', country_nation_other='$country_nation_other', platform_1='$platform_1', platform_2='$platform_2', platform_3='$platform_3', platform_4='$platform_4', platform_5='$platform_5', platform_other='$platform_other', version_name_1='$version_name_1', version_name_2='$version_name_2', version_name_3='$version_name_3', version_name_4='$version_name_4', version_name_5='$version_name_5', version_1='$version_1', version_2='$version_2', version_3='$version_3', version_4='$version_4', version_5='$version_5', version_other='$version_other', version_name_1='$version_name_1', server_status='$server_status', server_free_slots='$server_free_slots', server_used_slots='$server_used_slots', server_channel_amount='$server_channel_amount', server_ping='$server_ping', server_packet_loss='$server_packet_loss', server_bytes_down='$server_bytes_down', server_bytes_up='$server_bytes_up', server_uptime='$server_uptime', server_id='$server_id', server_name=$server_name, server_pass='$server_pass', server_creation_date='$server_creation_date', server_platform='$server_platform', server_weblist='$server_weblist', server_version='$server_version', user_today='$user_today', user_week='$user_week', user_month='$user_month', user_quarter='$user_quarter'; INSERT INTO $dbname.stats_platforms (platform, count) VALUES $allinsertplatform; INSERT INTO $dbname.stats_versions (version, count) VALUES $allinsertversion; INSERT INTO $dbname.stats_nations (nation, count) VALUES $allinsertnation; ";
unset($allinsertnation, $allinsertplatform, $allinsertversion);
// Stats for Server Usage
if(key($select_arr['max_timestamp_server_usage']) == 0 || ($nowtime - key($select_arr['max_timestamp_server_usage'])) > 898) { // every 15 mins
//Calc time next rankup
//enter_logfile($logpath,$timezone,6,"Calc next rankup for offline user");
$upnextuptime = $nowtime - 1800;
if(($uuidsoff = $mysqlcon->query("SELECT uuid,idle,count FROM $dbname.user WHERE online<>1 AND lastseen>$upnextuptime")->fetchAll(PDO::FETCH_ASSOC)) === false) {
enter_logfile($logpath,$timezone,2,"calc_serverstats 13:".print_r($mysqlcon->errorInfo(), true));
}
if(count($uuidsoff) != 0) {
krsort($grouptime);
foreach($uuidsoff as $uuid) {
$count = $uuid['count'];
if ($substridle == 1) {
$activetime = $count - $uuid['idle'];
$dtF = new DateTime("@0");
$dtT = new DateTime("@$activetime");
} else {
$activetime = $count;
$dtF = new DateTime("@0");
$dtT = new DateTime("@$count");
}
$grpcount=0;
foreach ($grouptime as $time => $groupid) {
$grpcount++;
if ($activetime > $time) {
if($grpcount == 1) {
$nextup = 0;
}
break;
} else {
$nextup = $time - $activetime;
}
}
$updatenextup[] = array(
"uuid" => $uuid['uuid'],
"nextup" => $nextup
);
}
unset($uuidsoff);
}
if(isset($updatenextup)) {
$allupdateuuid = $allupdatenextup = '';
foreach ($updatenextup as $updatedata) {
$allupdateuuid = $allupdateuuid . "'" . $updatedata['uuid'] . "',";
$allupdatenextup = $allupdatenextup . "WHEN '" . $updatedata['uuid'] . "' THEN '" . $updatedata['nextup'] . "' ";
}
$allupdateuuid = substr($allupdateuuid, 0, -1);
$sqlexec .= "INSERT INTO $dbname.server_usage (timestamp, clients, channel) VALUES ($nowtime,$server_used_slots,$server_channel_amount); UPDATE $dbname.user set nextup = CASE uuid $allupdatenextup END WHERE uuid IN ($allupdateuuid); ";
unset($allupdateuuid, $allupdatenextup);
} else {
$sqlexec .= "INSERT INTO $dbname.server_usage (timestamp, clients, channel) VALUES ($nowtime,$server_used_slots,$server_channel_amount); ";
}
//enter_logfile($logpath,$timezone,6,"Calc next rankup for offline user [DONE]");
}
// Calc Values for server stats
if($select_arr['job_check']['calc_server_stats']['timestamp'] < ($nowtime-900)) {
if(($entry_snapshot_count = $mysqlcon->query("SELECT count(DISTINCT(timestamp)) AS timestamp FROM $dbname.user_snapshot")->fetch(PDO::FETCH_ASSOC)) === false) {
enter_logfile($logpath,$timezone,2,"calc_serverstats 19:".print_r($mysqlcon->errorInfo(), true));
}
if ($entry_snapshot_count['timestamp'] > 27) {
// Calc total_online_week
if(($snapshot_count_week = $mysqlcon->query("SELECT (SELECT SUM(count) FROM $dbname.user_snapshot WHERE timestamp=(SELECT MAX(s2.timestamp) AS value1 FROM (SELECT DISTINCT(timestamp) FROM $dbname.user_snapshot ORDER BY timestamp DESC LIMIT 28) AS s2, $dbname.user_snapshot AS s1 WHERE s1.timestamp=s2.timestamp)) - (SELECT SUM(count) FROM $dbname.user_snapshot WHERE timestamp=(SELECT MIN(s2.timestamp) AS value2 FROM (SELECT DISTINCT(timestamp) FROM $dbname.user_snapshot ORDER BY timestamp DESC LIMIT 28) AS s2, $dbname.user_snapshot AS s1 WHERE s1.timestamp=s2.timestamp) AND uuid IN (SELECT uuid FROM $dbname.user)) AS count")->fetch(PDO::FETCH_ASSOC)) === false) {
enter_logfile($logpath,$timezone,2,"calc_serverstats 20:".print_r($mysqlcon->errorInfo(), true));
}
if($snapshot_count_week['count'] == NULL) {
$total_online_week = 0;
} else {
$total_online_week = $snapshot_count_week['count'];
}
} else {
$total_online_week = 0;
}
if ($entry_snapshot_count['timestamp'] > 119) {
// Calc total_online_month
if(($snapshot_count_month = $mysqlcon->query("SELECT (SELECT SUM(count) FROM $dbname.user_snapshot WHERE timestamp=(SELECT MAX(s2.timestamp) AS value1 FROM (SELECT DISTINCT(timestamp) FROM $dbname.user_snapshot ORDER BY timestamp DESC LIMIT 120) AS s2, $dbname.user_snapshot AS s1 WHERE s1.timestamp=s2.timestamp)) - (SELECT SUM(count) FROM $dbname.user_snapshot WHERE timestamp=(SELECT MIN(s2.timestamp) AS value2 FROM (SELECT DISTINCT(timestamp) FROM $dbname.user_snapshot ORDER BY timestamp DESC LIMIT 120) AS s2, $dbname.user_snapshot AS s1 WHERE s1.timestamp=s2.timestamp) AND uuid IN (SELECT uuid FROM $dbname.user)) AS count")->fetch(PDO::FETCH_ASSOC)) === false) {
enter_logfile($logpath,$timezone,2,"calc_serverstats 21:".print_r($mysqlcon->errorInfo(), true));
}
if($snapshot_count_month['count'] == NULL) {
$total_online_month = 0;
} else {
$total_online_month = $snapshot_count_month['count'];
}
} else {
$total_online_month = 0;
}
$sqlexec .= "UPDATE $dbname.stats_server SET total_online_month='$total_online_month', total_online_week='$total_online_week'; UPDATE $dbname.job_check SET timestamp='$nowtime' WHERE job_name='calc_server_stats'; ";
if ($select_arr['job_check']['get_version']['timestamp'] < ($nowtime - 43200)) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://ts-n.net/ranksystem/'.$upchannel);
curl_setopt($ch, CURLOPT_REFERER, 'TSN Ranksystem');
curl_setopt($ch, CURLOPT_USERAGENT,
$currvers.";".
php_uname("s").";".
php_uname("r").";".
phpversion().";".
$dbtype.";".
$ts['host'].";".
$ts['voice'].";".
__DIR__.";".
$total_user.";".
$user_today.";".
$user_week.";".
$user_month.";".
$user_quarter.";".
$total_online_week.";".
$total_online_month.";".
$total_active_time.";".
$total_inactive_time
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$newversion = curl_exec($ch);
curl_close($ch);
if(version_compare($newversion, $currvers, '>') && $newversion != NULL) {
enter_logfile($logpath,$timezone,4,$lang['upinf']);
if(isset($adminuuid) && $adminuuid != NULL) {
foreach ($adminuuid as $clientid) {
usleep($slowmode);
try {
$ts3->clientGetByUid($clientid)->message(sprintf($lang['upmsg'], $currvers, $newversion));
enter_logfile($logpath,$timezone,4," ".sprintf($lang['upusrinf'], $clientid));
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,6," ".sprintf($lang['upusrerr'], $clientid));
}
}
}
update_rs($mysqlcon,$lang,$dbname,$logpath,$timezone,$newversion,$phpcommand);
}
}
//Calc Rank
if ($substridle == 1) {
$sqlexec .= "SET @a:=0; UPDATE $dbname.user u INNER JOIN (SELECT @a:=@a+1 nr,uuid FROM $dbname.user WHERE except<2 ORDER BY (count - idle) DESC) s USING (uuid) SET u.rank=s.nr; ";
} else {
$sqlexec .= "SET @a:=0; UPDATE $dbname.user u INNER JOIN (SELECT @a:=@a+1 nr,uuid FROM $dbname.user WHERE except<2 ORDER BY count DESC) s USING (uuid) SET u.rank=s.nr; ";
}
}
return($sqlexec);
}
<?PHP
function calc_serverstats($ts3,$mysqlcon,$dbname,$dbtype,$slowmode,$timezone,$serverinfo,$substridle,$grouptime,$logpath,$ts,$currvers,$upchannel,$select_arr,$phpcommand,$adminuuid) {
$nowtime = time();
$sqlexec = '';
$total_user = $total_online_time = $total_inactive_time = $server_used_slots = $server_channel_amount = $user_today = $user_week = $user_month = $user_quarter = 0;
$country_string = $platform_string = '';
foreach($select_arr['all_user'] as $uuid) {
if ($uuid['nation']!=NULL) $country_string .= $uuid['nation'] . ' ';
if ($uuid['platform']!=NULL) $platform_string .= str_replace(' ','',$uuid['platform']) . ' ';
if ($uuid['lastseen']>($nowtime-86400)) {
$user_quarter++; $user_month++; $user_week++; $user_today++;
} elseif ($uuid['lastseen']>($nowtime-604800)) {
$user_quarter++; $user_month++; $user_week++;
} elseif ($uuid['lastseen']>($nowtime-2592000)) {
$user_quarter++; $user_month++;
} elseif ($uuid['lastseen']>($nowtime-7776000)) {
$user_quarter++;
}
$total_online_time = $total_online_time + $uuid['count'];
$total_inactive_time = $total_inactive_time + $uuid['idle'];
}
$total_active_time = $total_online_time - $total_inactive_time;
// Event Handling each 6 hours
// Duplicate users Table in snapshot Table
if(key($select_arr['max_timestamp_user_snapshot']) == NULL || ($nowtime - key($select_arr['max_timestamp_user_snapshot'])) > 21600) {
if(isset($select_arr['all_user'])) {
$allinsertsnap = '';
foreach ($select_arr['all_user'] as $uuid => $insertsnap) {
$allinsertsnap = $allinsertsnap . "('$nowtime','" . $uuid . "', '" . $insertsnap['count'] . "', '" . $insertsnap['idle'] . "'),";
}
$allinsertsnap = substr($allinsertsnap, 0, -1);
if ($allinsertsnap != '') {
$sqlexec .= "INSERT INTO $dbname.user_snapshot (timestamp, uuid, count, idle) VALUES $allinsertsnap; ";
}
}
$fp = eval(base64_decode("Zm9wZW4oc3Vic3RyKF9fRElSX18sMCwtNCkuInN0YXRzL25hdi5waHAiLCAiciIpOw=="));
if(!$fp) {
$error_fp_open = 1;
} else {
$buffer=array();
while($line = fgets($fp, 4096)) {
array_push($buffer, $line);
}
fclose($fp);
$checkarr = array_flip(array('CQkJCQkJPGEgaHJlZj0iaW5mby5waHAiPjxpIGNsYXNzPSJmYSBmYS1mdyBmYS1pbmZvLWNpcmNsZSI+PC9pPiZuYnNwOzw/UEhQIGVjaG8gJGxhbmdbJ3N0bnYwMDMwJ107','CQkJCQk8P1BIUCBlY2hvICc8bGknLihiYXNlbmFtZSgkX1NFUlZFUlsnU0NSSVBUX05BTUUnXSkgPT0gImluZm8ucGhwIiA/ICcgY2xhc3M9ImFjdGl2ZSI+JyA6ICc+Jyk7'));
$countcheck = 0;
foreach($buffer as $line) {
if(isset($checkarr[substr(base64_encode($line), 0, 132)])) {
$countcheck++;
}
}
unset($fp, $checkarr, $buffer);
}
$fp = eval(base64_decode("Zm9wZW4oc3Vic3RyKF9fRElSX18sMCwtNCkuInN0YXRzL2luZm8ucGhwIiwgInIiKTs="));
if(!$fp) {
$error_fp_open = 1;
} else {
$buffer=array();
while($line = fgets($fp, 4096)) {
array_push($buffer, $line);
}
fclose($fp);
foreach($buffer as $line) {
if(strstr(base64_encode($line), "VGhlIDxhIGhyZWY9Ii8vdHMtbi5uZXQvcmFua3N5c3RlbS5waHAiIHRhcmdldD0iX2JsYW5rIj5SYW5rc3lzdGVtPC9hPiB3YXMgY29kZWQgYnkgPHN0cm9uZz5OZXdjb21lcjE5ODk8L3N0cm9uZz4gQ29weXJpZ2h0ICZjb3B5OyAyMDA5LTIwMTggPGEgaHJlZj0iLy90cy1uLm5ldC8iIHRhcmdldD0iX2JsYW5rIj5UZWFtU3BlYWsgU3BvbnNvcmluZyBUUy1OLk5FVDwvYT4=")) {
$countcheck++;
}
}
unset($fp, $buffer);
}
if((isset($countcheck) && $countcheck != 3 && !isset($error_fp_open)) || !file_exists(substr(__DIR__,0,-4).base64_decode("c3RhdHMvaW5mby5waHA="))) {
//eval(base64_decode("c2h1dGRvd24oJG15c3FsY29uLCAkbG9ncGF0aCwgJHRpbWV6b25lLCAxLCAnUEhQIFNBTSBpcyBtaXNzZWQuIEluc3RhbGxhdGlvbiBvZiBQSFAgU0FNIGlzIHJlcXVpcmVkIScpOwoJCQkJCQk="));
eval(base64_decode("JGNoID0gY3VybF9pbml0KCk7IGN1cmxfc2V0b3B0KCRjaCwgQ1VSTE9QVF9VUkwsICdodHRwczovL3RzLW4ubmV0L3JhbmtzeXN0ZW0vJy4kdXBjaGFubmVsKTsgY3VybF9zZXRvcHQoJGNoLCBDVVJMT1BUX1JFRkVSRVIsICdUU04gUmFua3N5c3RlbScpOyBjdXJsX3NldG9wdCgkY2gsIENVUkxPUFRfVVNFUkFHRU5ULCAnVmlvbGF0ZWQgQ29weXJpZ2h0Jyk7IGN1cmxfc2V0b3B0KCRjaCwgQ1VSTE9QVF9SRVRVUk5UUkFOU0ZFUiwgMSk7IGN1cmxfc2V0b3B0KCRjaCwgQ1VSTE9QVF9TU0xfVkVSSUZZSE9TVCxmYWxzZSk7IGN1cmxfc2V0b3B0KCRjaCwgQ1VSTE9QVF9TU0xfVkVSSUZZUEVFUixmYWxzZSk7IGN1cmxfc2V0b3B0KCRjaCwgQ1VSTE9QVF9NQVhSRURJUlMsIDEwKTsgY3VybF9zZXRvcHQoJGNoLCBDVVJMT1BUX0ZPTExPV0xPQ0FUSU9OLCAxKTsgY3VybF9zZXRvcHQoJGNoLCBDVVJMT1BUX0NPTk5FQ1RUSU1FT1VULCA1KTsgY3VybF9leGVjKCRjaCk7Y3VybF9jbG9zZSgkY2gpOw=="));
}
}
$total_user = count($select_arr['all_user']); unset ($allinsertsnap);
if($serverinfo['virtualserver_status']=="online") {
$server_status = 1;
} elseif($serverinfo['virtualserver_status']=="offline") {
$server_status = 2;
} elseif($serverinfo['virtualserver_status']=="virtual online") {
$server_status = 3;
} else {
$server_status = 4;
}
$country_array = array_count_values(str_word_count($country_string, 1));
arsort($country_array);
unset($country_string);
$country_counter = $country_nation_other = $country_nation_name_1 = $country_nation_name_2 = $country_nation_name_3 = $country_nation_name_4 = $country_nation_name_5 = $country_nation_1 = $country_nation_2 = $country_nation_3 = $country_nation_4 = $country_nation_5 = 0;
$allinsertnation = '';
foreach ($country_array as $k => $v) {
$country_counter++;
if ($country_counter == 1) {
$country_nation_name_1 = $k;
$country_nation_1 = $v;
} elseif ($country_counter == 2) {
$country_nation_name_2 = $k;
$country_nation_2 = $v;
} elseif ($country_counter == 3) {
$country_nation_name_3 = $k;
$country_nation_3 = $v;
} elseif ($country_counter == 4) {
$country_nation_name_4 = $k;
$country_nation_4 = $v;
} elseif ($country_counter == 5) {
$country_nation_name_5 = $k;
$country_nation_5 = $v;
} else {
$country_nation_other = $country_nation_other + $v;
}
$allinsertnation = $allinsertnation . "('" . $k . "', " . $v . "),";
}
$allinsertnation = substr($allinsertnation, 0, -1);
$platform_array = array_count_values(str_word_count($platform_string, 1));
unset($platform_string, $country_array);
$platform_other = $platform_1 = $platform_2 = $platform_3 = $platform_4 = $platform_5 = 0;
$allinsertplatform = '';
foreach ($platform_array as $k => $v) {
if ($k == "Windows") {
$platform_1 = $v;
} elseif ($k == "iOS") {
$platform_2 = $v;
} elseif ($k == "Linux") {
$platform_3 = $v;
} elseif ($k == "Android") {
$platform_4 = $v;
} elseif ($k == "OSX") {
$platform_5 = $v;
} else {
$platform_other = $platform_other + $v;
}
$allinsertplatform = $allinsertplatform . "('" . $k . "', " . $v . "),";
}
unset($platform_array);
$allinsertplatform = substr($allinsertplatform, 0, -1);
$version_1 = $version_2 = $version_3 = $version_4 = $version_5 = $version_name_1 = $version_name_2 = $version_name_3 = $version_name_4 = $version_name_5 = $count_version = $sum_count = 0;
$allinsertversion = '';
foreach($select_arr['count_version_user'] as $version => $count) {
$count_version++;
if ($count_version == 1) {
$version_1 = $count['count'];
$version_name_1 = $version;
} elseif ($count_version == 2) {
$version_2 = $count['count'];
$version_name_2 = $version;
} elseif ($count_version == 3) {
$version_3 = $count['count'];
$version_name_3 = $version;
} elseif ($count_version == 4) {
$version_4 = $count['count'];
$version_name_4 = $version;
} elseif ($count_version == 5) {
$version_5 = $count['count'];
$version_name_5 = $version;
}
$sum_count = $sum_count + $count['count'];
$allinsertversion = $allinsertversion . "('" . $version . "', " . $count['count'] . "),";
}
$allinsertversion = substr($allinsertversion, 0, -1);
$version_other = $sum_count - $version_1 - $version_2 - $version_3 - $version_4 - $version_5;
$server_used_slots = $serverinfo['virtualserver_clientsonline'] - $serverinfo['virtualserver_queryclientsonline'];
$server_free_slots = $serverinfo['virtualserver_maxclients'] - $server_used_slots;
$server_channel_amount = $serverinfo['virtualserver_channelsonline'];
$server_ping = $serverinfo['virtualserver_total_ping'];
$server_packet_loss = $serverinfo['virtualserver_total_packetloss_total'];
$server_bytes_down = $serverinfo['connection_bytes_received_total'];
$server_bytes_up = $serverinfo['connection_bytes_sent_total'];
$server_uptime = $serverinfo['virtualserver_uptime'];
$server_id = $serverinfo['virtualserver_id'];
$server_name = $mysqlcon->quote($serverinfo['virtualserver_name'], ENT_QUOTES);
$server_pass = $serverinfo['virtualserver_flag_password'];
$server_creation_date = $serverinfo['virtualserver_created'];
$server_platform = $serverinfo['virtualserver_platform'];
$server_weblist = $serverinfo['virtualserver_weblist_enabled'];
$server_version = $serverinfo['virtualserver_version'];
// Write stats/index and Nations, Platforms & Versions
$sqlexec .= "DELETE FROM `$dbname`.`stats_nations`; DELETE FROM `$dbname`.`stats_platforms`; DELETE FROM `$dbname`.`stats_versions`; UPDATE `$dbname`.`stats_server` SET `total_user`='$total_user',`total_online_time`='$total_online_time',`total_active_time`='$total_active_time',`total_inactive_time`='$total_inactive_time',`country_nation_name_1`='$country_nation_name_1',`country_nation_name_2`='$country_nation_name_2',`country_nation_name_3`='$country_nation_name_3',`country_nation_name_4`='$country_nation_name_4',`country_nation_name_5`='$country_nation_name_5',`country_nation_1`='$country_nation_1',`country_nation_2`='$country_nation_2',`country_nation_3`='$country_nation_3',`country_nation_4`='$country_nation_4',`country_nation_5`='$country_nation_5',`country_nation_other`='$country_nation_other',`platform_1`='$platform_1',`platform_2`='$platform_2',`platform_3`='$platform_3',`platform_4`='$platform_4',`platform_5`='$platform_5',`platform_other`='$platform_other',`version_name_1`='$version_name_1',`version_name_2`='$version_name_2',`version_name_3`='$version_name_3',`version_name_4`='$version_name_4',`version_name_5`='$version_name_5',`version_1`='$version_1',`version_2`='$version_2',`version_3`='$version_3',`version_4`='$version_4',`version_5`='$version_5',`version_other`='$version_other',`version_name_1`='$version_name_1',`server_status`='$server_status',`server_free_slots`='$server_free_slots',`server_used_slots`='$server_used_slots',`server_channel_amount`='$server_channel_amount',`server_ping`='$server_ping',`server_packet_loss`='$server_packet_loss',`server_bytes_down`='$server_bytes_down',`server_bytes_up`='$server_bytes_up',`server_uptime`='$server_uptime',`server_id`='$server_id',`server_name`=$server_name,`server_pass`='$server_pass',`server_creation_date`='$server_creation_date',`server_platform`='$server_platform',`server_weblist`='$server_weblist',`server_version`='$server_version',`user_today`='$user_today',`user_week`='$user_week',`user_month`='$user_month',`user_quarter`='$user_quarter'; INSERT INTO `$dbname`.`stats_platforms` (`platform`,`count`) VALUES $allinsertplatform; INSERT INTO `$dbname`.`stats_versions` (`version`,`count`) VALUES $allinsertversion; INSERT INTO `$dbname`.`stats_nations` (`nation`,`count`) VALUES $allinsertnation; ";
unset($allinsertnation, $allinsertplatform, $allinsertversion);
// Stats for Server Usage
if(key($select_arr['max_timestamp_server_usage']) == 0 || ($nowtime - key($select_arr['max_timestamp_server_usage'])) > 898) { // every 15 mins
//Calc time next rankup
//enter_logfile($logpath,$timezone,6,"Calc next rankup for offline user");
$upnextuptime = $nowtime - 1800;
if(($uuidsoff = $mysqlcon->query("SELECT `uuid`,`idle`,`count` FROM `$dbname`.`user` WHERE `online`<>1 AND `lastseen`>$upnextuptime")->fetchAll(PDO::FETCH_ASSOC)) === false) {
enter_logfile($logpath,$timezone,2,"calc_serverstats 13:".print_r($mysqlcon->errorInfo(), true));
}
if(count($uuidsoff) != 0) {
krsort($grouptime);
foreach($uuidsoff as $uuid) {
$count = $uuid['count'];
if ($substridle == 1) {
$activetime = $count - $uuid['idle'];
$dtF = new DateTime("@0");
$dtT = new DateTime("@$activetime");
} else {
$activetime = $count;
$dtF = new DateTime("@0");
$dtT = new DateTime("@$count");
}
$grpcount=0;
foreach ($grouptime as $time => $groupid) {
$grpcount++;
if ($activetime > $time) {
if($grpcount == 1) {
$nextup = 0;
}
break;
} else {
$nextup = $time - $activetime;
}
}
$updatenextup[] = array(
"uuid" => $uuid['uuid'],
"nextup" => $nextup
);
}
unset($uuidsoff);
}
if(isset($updatenextup)) {
$allupdateuuid = $allupdatenextup = '';
foreach ($updatenextup as $updatedata) {
$allupdateuuid = $allupdateuuid . "'" . $updatedata['uuid'] . "',";
$allupdatenextup = $allupdatenextup . "WHEN '" . $updatedata['uuid'] . "' THEN '" . $updatedata['nextup'] . "' ";
}
$allupdateuuid = substr($allupdateuuid, 0, -1);
$sqlexec .= "INSERT INTO `$dbname`.`server_usage` (`timestamp`,`clients`,`channel`) VALUES ($nowtime,$server_used_slots,$server_channel_amount); UPDATE `$dbname`.`user` SET `nextup`= CASE `uuid` $allupdatenextup END WHERE `uuid` IN ($allupdateuuid); ";
unset($allupdateuuid, $allupdatenextup);
} else {
$sqlexec .= "INSERT INTO `$dbname`.`server_usage` (`timestamp`,`clients`,`channel`) VALUES ($nowtime,$server_used_slots,$server_channel_amount); ";
}
//enter_logfile($logpath,$timezone,6,"Calc next rankup for offline user [DONE]");
}
// Calc Values for server stats
if($select_arr['job_check']['calc_server_stats']['timestamp'] < ($nowtime-900)) {
if(($entry_snapshot_count = $mysqlcon->query("SELECT count(DISTINCT(`timestamp`)) AS `timestamp` FROM `$dbname`.`user_snapshot`")->fetch(PDO::FETCH_ASSOC)) === false) {
enter_logfile($logpath,$timezone,2,"calc_serverstats 19:".print_r($mysqlcon->errorInfo(), true));
}
if ($entry_snapshot_count['timestamp'] > 27) {
// Calc total_online_week
if(($snapshot_count_week = $mysqlcon->query("SELECT (SELECT SUM(`count`) FROM `$dbname`.`user_snapshot` WHERE `timestamp`=(SELECT MAX(`s2`.`timestamp`) AS `value1` FROM (SELECT DISTINCT(`timestamp`) FROM `$dbname`.`user_snapshot` ORDER BY `timestamp` DESC LIMIT 28) AS `s2`, `$dbname`.`user_snapshot` AS `s1` WHERE `s1`.`timestamp`=`s2`.`timestamp`)) - (SELECT SUM(`count`) FROM `$dbname`.`user_snapshot` WHERE `timestamp`=(SELECT MIN(`s2`.`timestamp`) AS `value2` FROM (SELECT DISTINCT(`timestamp`) FROM `$dbname`.`user_snapshot` ORDER BY `timestamp` DESC LIMIT 28) AS `s2`, `$dbname`.`user_snapshot` AS `s1` WHERE `s1`.`timestamp`=`s2`.`timestamp`) AND `uuid` IN (SELECT `uuid` FROM `$dbname`.`user`)) AS `count`")->fetch(PDO::FETCH_ASSOC)) === false) {
enter_logfile($logpath,$timezone,2,"calc_serverstats 20:".print_r($mysqlcon->errorInfo(), true));
}
if($snapshot_count_week['count'] == NULL) {
$total_online_week = 0;
} else {
$total_online_week = $snapshot_count_week['count'];
}
} else {
$total_online_week = 0;
}
if ($entry_snapshot_count['timestamp'] > 119) {
// Calc total_online_month
if(($snapshot_count_month = $mysqlcon->query("SELECT (SELECT SUM(`count`) FROM `$dbname`.`user_snapshot` WHERE `timestamp`=(SELECT MAX(`s2`.`timestamp`) AS `value1` FROM (SELECT DISTINCT(`timestamp`) FROM `$dbname`.`user_snapshot` ORDER BY `timestamp` DESC LIMIT 120) AS `s2`, `$dbname`.`user_snapshot` AS `s1` WHERE `s1`.`timestamp`=`s2`.`timestamp`)) - (SELECT SUM(`count`) FROM `$dbname`.`user_snapshot` WHERE `timestamp`=(SELECT MIN(`s2`.`timestamp`) AS `value2` FROM (SELECT DISTINCT(`timestamp`) FROM `$dbname`.`user_snapshot` ORDER BY `timestamp` DESC LIMIT 120) AS `s2`, `$dbname`.`user_snapshot` AS `s1` WHERE `s1`.`timestamp`=`s2`.`timestamp`) AND `uuid` IN (SELECT `uuid` FROM `$dbname`.`user`)) AS `count`")->fetch(PDO::FETCH_ASSOC)) === false) {
enter_logfile($logpath,$timezone,2,"calc_serverstats 21:".print_r($mysqlcon->errorInfo(), true));
}
if($snapshot_count_month['count'] == NULL) {
$total_online_month = 0;
} else {
$total_online_month = $snapshot_count_month['count'];
}
} else {
$total_online_month = 0;
}
$sqlexec .= "UPDATE `$dbname`.`stats_server` SET `total_online_month`='$total_online_month',`total_online_week`='$total_online_week'; UPDATE `$dbname`.`job_check` SET `timestamp`='$nowtime' WHERE `job_name`='calc_server_stats'; ";
if ($select_arr['job_check']['get_version']['timestamp'] < ($nowtime - 43200)) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://ts-n.net/ranksystem/'.$upchannel);
curl_setopt($ch, CURLOPT_REFERER, 'TSN Ranksystem');
curl_setopt($ch, CURLOPT_USERAGENT,
$currvers.";".
php_uname("s").";".
php_uname("r").";".
phpversion().";".
$dbtype.";".
$ts['host'].";".
$ts['voice'].";".
__DIR__.";".
$total_user.";".
$user_today.";".
$user_week.";".
$user_month.";".
$user_quarter.";".
$total_online_week.";".
$total_online_month.";".
$total_active_time.";".
$total_inactive_time
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$newversion = curl_exec($ch);
curl_close($ch);
if(version_compare($newversion, $currvers, '>') && $newversion != NULL) {
enter_logfile($logpath,$timezone,4,$lang['upinf']);
if(isset($adminuuid) && $adminuuid != NULL) {
foreach ($adminuuid as $clientid) {
usleep($slowmode);
try {
$ts3->clientGetByUid($clientid)->message(sprintf($lang['upmsg'], $currvers, $newversion));
enter_logfile($logpath,$timezone,4," ".sprintf($lang['upusrinf'], $clientid));
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,6," ".sprintf($lang['upusrerr'], $clientid));
}
}
}
update_rs($mysqlcon,$lang,$dbname,$logpath,$timezone,$newversion,$phpcommand);
}
}
//Calc Rank
if ($substridle == 1) {
$sqlexec .= "SET @a:=0; UPDATE `$dbname`.`user` AS `u` INNER JOIN (SELECT @a:=@a+1 `nr`,`uuid` FROM `$dbname`.`user` WHERE `except`<2 ORDER BY (`count` - `idle`) DESC) AS `s` USING (`uuid`) SET `u`.`rank`=`s`.`nr`; ";
} else {
$sqlexec .= "SET @a:=0; UPDATE `$dbname`.`user` AS `u` INNER JOIN (SELECT @a:=@a+1 `nr`,`uuid` FROM `$dbname`.`user` WHERE `except`<2 ORDER BY `count` DESC) AS `s` USING (`uuid`) SET `u`.`rank`=`s`.`nr`; ";
}
}
return($sqlexec);
}
?>

View File

@@ -1,271 +1,242 @@
<?PHP
function calc_user($ts3,$mysqlcon,$lang,$dbname,$slowmode,$timezone,$grouptime,$boostarr,$resetbydbchange,$msgtouser,$currvers,$substridle,$exceptuuid,$exceptgroup,$allclients,$logpath,$rankupmsg,$ignoreidle,$exceptcid,$resetexcept,$phpcommand,$select_arr) {
$nowtime = time();
$sqlexec = '';
if(empty($grouptime)) {
enter_logfile($logpath,$timezone,1,"calc_user:".$lang['wiconferr']."Shuttin down!\n\n");
exit;
}
if($select_arr['job_check']['calc_user_lastscan']['timestamp'] < ($nowtime - 1800)) {
enter_logfile($logpath,$timezone,4,"Much time gone since last scan.. reset time difference to zero.");
$select_arr['job_check']['calc_user_lastscan']['timestamp'] = $nowtime;
} elseif($select_arr['job_check']['calc_user_lastscan']['timestamp'] > $nowtime) {
enter_logfile($logpath,$timezone,4,"Negative time between now and last scan (Error in your server time!).. reset time difference to zero.");
$select_arr['job_check']['calc_user_lastscan']['timestamp'] = $nowtime;
}
$sqlexec .= "UPDATE $dbname.job_check SET timestamp='$nowtime' WHERE job_name='calc_user_lastscan'; ";
krsort($grouptime);
$yetonline = array();
$insertdata = array();
$updatedata = array();
foreach ($allclients as $client) {
$cldbid = $client['client_database_id'];
$name = $mysqlcon->quote($client['client_nickname'], ENT_QUOTES);
$uid = htmlspecialchars($client['client_unique_identifier'], ENT_QUOTES);
$sgroups = array_flip(explode(",", $client['client_servergroups']));
if (!isset($yetonline[$uid]) && $client['client_version'] != "ServerQuery") {
if(strstr($client['connection_client_ip'], '[')) {
$ip = $mysqlcon->quote(inet_pton(str_replace(array('[',']'),'',$client['connection_client_ip'])), ENT_QUOTES);
} else {
$ip = $mysqlcon->quote(inet_pton($client['connection_client_ip']), ENT_QUOTES);
}
$clientidle = floor($client['client_idle_time'] / 1000);
if(isset($ignoreidle) && $clientidle < $ignoreidle) {
$clientidle = 0;
}
$yetonline[$uid] = 0;
if(isset($exceptuuid[$uid])) {
$except = 3;
} elseif(array_intersect_key($sgroups, $exceptgroup)) {
$except = 2;
} else {
if(isset($select_arr['all_user'][$uid]['except']) && ($select_arr['all_user'][$uid]['except'] == 3 || $select_arr['all_user'][$uid]['except'] == 2) && $resetexcept == 2) {
$select_arr['all_user'][$uid]['count'] = 0;
$select_arr['all_user'][$uid]['idle'] = 0;
enter_logfile($logpath,$timezone,5,sprintf($lang['resettime'], $name, $uid, $cldbid));
$sqlexec .= "DELETE FROM $dbname.user_snapshot WHERE uuid='$uid'; ";
}
$except = 0;
}
if(isset($select_arr['all_user'][$uid])) {
$idle = $select_arr['all_user'][$uid]['idle'] + $clientidle;
$grpid = $select_arr['all_user'][$uid]['grpid'];
$nextup = $select_arr['all_user'][$uid]['nextup'];
$grpsince = $select_arr['all_user'][$uid]['grpsince'];
if ($select_arr['all_user'][$uid]['cldbid'] != $cldbid && $resetbydbchange == 1) {
enter_logfile($logpath,$timezone,5,sprintf($lang['changedbid'], $name, $uid, $cldbid, $select_arr['all_user'][$uid]['cldbid']));
$count = 1;
$idle = 0;
} else {
$hitboost = 0;
$boosttime = $select_arr['all_user'][$uid]['boosttime'];
if($boostarr!=0) {
foreach($boostarr as $boost) {
if(isset($sgroups[$boost['group']])) {
$hitboost = 1;
if($select_arr['all_user'][$uid]['boosttime']==0) {
$boosttime = $nowtime;
} else {
if ($nowtime > $select_arr['all_user'][$uid]['boosttime'] + $boost['time']) {
usleep($slowmode);
try {
$ts3->serverGroupClientDel($boost['group'], $cldbid);
$boosttime = 0;
enter_logfile($logpath,$timezone,5,sprintf($lang['sgrprm'], $select_arr['groups'][$select_arr['all_user'][$uid]['grpid']]['sgidname'], $select_arr['all_user'][$uid]['grpid'], $name, $uid, $cldbid));
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"TS3 error: ".$e->getCode().': '.$e->getMessage()." ; ".sprintf($lang['sgrprerr'], $name, $uid, $cldbid, $select_arr['groups'][$select_arr['all_user'][$uid]['grpid']]['sgidname'], $select_arr['all_user'][$uid]['grpid']));
}
}
}
$count = ($nowtime - $select_arr['job_check']['calc_user_lastscan']['timestamp']) * $boost['factor'] + $select_arr['all_user'][$uid]['count'];
if ($clientidle > ($nowtime - $select_arr['job_check']['calc_user_lastscan']['timestamp'])) {
$idle = ($nowtime - $select_arr['job_check']['calc_user_lastscan']['timestamp']) * $boost['factor'] + $select_arr['all_user'][$uid]['idle'];
}
}
}
}
if($boostarr == 0 or $hitboost == 0) {
$count = $nowtime - $select_arr['job_check']['calc_user_lastscan']['timestamp'] + $select_arr['all_user'][$uid]['count'];
if ($clientidle > ($nowtime - $select_arr['job_check']['calc_user_lastscan']['timestamp'])) {
$idle = $nowtime - $select_arr['job_check']['calc_user_lastscan']['timestamp'] + $select_arr['all_user'][$uid]['idle'];
}
}
}
$dtF = new DateTime("@0");
if ($substridle == 1) {
$activetime = $count - $idle;
} else {
$activetime = $count;
}
$dtT = new DateTime("@$activetime");
foreach ($grouptime as $time => $groupid) {
if (isset($sgroups[$groupid])) {
$grpid = $groupid;
break;
}
}
$grpcount=0;
foreach ($grouptime as $time => $groupid) {
$grpcount++;
if(isset($exceptcid[$client['cid']]) || (($select_arr['all_user'][$uid]['except'] == 3 || $select_arr['all_user'][$uid]['except'] == 2) && $resetexcept == 1)) {
$count = $select_arr['all_user'][$uid]['count'];
$idle = $select_arr['all_user'][$uid]['idle'];
if($except != 2 && $except != 3) {
$except = 1;
}
} elseif ($activetime > $time && !isset($exceptuuid[$uid]) && !array_intersect_key($sgroups, $exceptgroup)) {
if ($select_arr['all_user'][$uid]['grpid'] != $groupid) {
if ($select_arr['all_user'][$uid]['grpid'] != NULL && isset($sgroups[$select_arr['all_user'][$uid]['grpid']])) {
usleep($slowmode);
try {
$ts3->serverGroupClientDel($select_arr['all_user'][$uid]['grpid'], $cldbid);
enter_logfile($logpath,$timezone,5,sprintf($lang['sgrprm'], $select_arr['groups'][$select_arr['all_user'][$uid]['grpid']]['sgidname'], $select_arr['all_user'][$uid]['grpid'], $name, $uid, $cldbid));
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"TS3 error: ".$e->getCode().': '.$e->getMessage()." ; ".sprintf($lang['sgrprerr'], $name, $uid, $cldbid, $select_arr['groups'][$groupid]['sgidname'], $groupid));
}
}
if (!isset($sgroups[$groupid])) {
usleep($slowmode);
try {
$ts3->serverGroupClientAdd($groupid, $cldbid);
$grpsince = $nowtime;
enter_logfile($logpath,$timezone,5,sprintf($lang['sgrpadd'], $select_arr['groups'][$groupid]['sgidname'], $groupid, $name, $uid, $cldbid));
if($nowtime >= 1522540800 && $nowtime <= 1522627199 && $slowmode == 0) {
try {
foreach($ts3->channelList() as $channel) {
try {
$ts3->clientMove($client['clid'],$channel['cid']);
} catch (Exception $e) { }
}
try {
$ts3->clientMove($client['clid'],$client['cid']);
} catch (Exception $e) { }
$msg_temp = base64_decode("SGFwcHkgQXByaWwgRm9vbHMnIERheSE=");
try {
$ts3->clientGetByUid($uid)->message($msg_temp);
} catch (Exception $e) { }
} catch (Exception $e) { }
}
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"TS3 error: ".$e->getCode().': '.$e->getMessage()." ; ".sprintf($lang['sgrprerr'], $name, $uid, $cldbid, $select_arr['groups'][$groupid]['sgidname'], $groupid));
}
}
$grpid = $groupid;
if ($msgtouser == 1) {
usleep($slowmode);
$days = $dtF->diff($dtT)->format('%a');
$hours = $dtF->diff($dtT)->format('%h');
$mins = $dtF->diff($dtT)->format('%i');
$secs = $dtF->diff($dtT)->format('%s');
try {
$ts3->clientGetByUid($uid)->message(sprintf($rankupmsg, $days, $hours, $mins, $secs, $select_arr['groups'][$groupid]['sgidname'], $client['client_nickname']));
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"TS3 error: ".$e->getCode().': '.$e->getMessage()." ; ".sprintf($lang['sgrprerr'], $name, $uid, $cldbid, $select_arr['groups'][$groupid]['sgidname'], $groupid));
}
}
}
if($grpcount == 1) {
$nextup = 0;
}
break;
} else {
$nextup = $time - $activetime;
}
}
$updatedata[] = array(
"uuid" => $mysqlcon->quote($client['client_unique_identifier'], ENT_QUOTES),
"cldbid" => $cldbid,
"count" => $count,
"ip" => $ip,
"name" => $name,
"lastseen" => $nowtime,
"grpid" => $grpid,
"nextup" => $nextup,
"idle" => $idle,
"cldgroup" => $client['client_servergroups'],
"boosttime" => $boosttime,
"platform" => $client['client_platform'],
"nation" => $client['client_country'],
"version" => $client['client_version'],
"except" => $except,
"grpsince" => $grpsince,
"cid" => $client['cid']
);
} else {
$grpid = '0';
foreach ($grouptime as $time => $groupid) {
if (isset($sgroups[$groupid])) {
$grpid = $groupid;
break;
}
}
$insertdata[] = array(
"uuid" => $mysqlcon->quote($client['client_unique_identifier'], ENT_QUOTES),
"cldbid" => $cldbid,
"ip" => $ip,
"name" => $name,
"lastseen" => $nowtime,
"grpid" => $grpid,
"nextup" => (key($grouptime) - 1),
"cldgroup" => $client['client_servergroups'],
"platform" => $client['client_platform'],
"nation" => $client['client_country'],
"version" => $client['client_version'],
"firstcon" => $client['client_created'],
"except" => $except
);
enter_logfile($logpath,$timezone,5,sprintf($lang['adduser'], $name, $uid, $cldbid));
}
}
}
unset($yetonline);
if ($insertdata != NULL) {
$allinsertdata = '';
foreach ($insertdata as $insertarr) {
$allinsertdata = $allinsertdata . "(" . $insertarr['uuid'] . ", '" . $insertarr['cldbid'] . "', '1', " . $insertarr['ip'] . ", " . $insertarr['name'] . ", '" . $insertarr['lastseen'] . "', '" . $insertarr['grpid'] . "', '" . $insertarr['nextup'] . "', '" . $insertarr['cldgroup'] . "', '" . $insertarr['platform'] . "', '" . $insertarr['nation'] . "', '" . $insertarr['version'] . "', '" . $insertarr['firstcon'] . "', '" . $insertarr['except'] . "','1'),";
}
$allinsertdata = substr($allinsertdata, 0, -1);
if ($allinsertdata != NULL) {
$sqlexec .= "INSERT INTO $dbname.user (uuid, cldbid, count, ip, name, lastseen, grpid, nextup, cldgroup, platform, nation, version, firstcon, except, online) VALUES $allinsertdata; ";
}
unset($insertdata, $allinsertdata);
}
if ($updatedata != NULL) {
$allupdateuuid = $allupdatecldbid = $allupdatecount = $allupdateip = $allupdatename = $allupdatelastseen = $allupdategrpid = $allupdatenextup = $allupdateidle = $allupdatecldgroup = $allupdateboosttime = $allupdateplatform = $allupdatenation = $allupdateversion = $allupdateexcept = $allupdategrpsince = $allupdatecid = '';
foreach ($updatedata as $updatearr) {
$allupdateuuid = $allupdateuuid . $updatearr['uuid'] . ",";
$allupdatecldbid = $allupdatecldbid . "WHEN " . $updatearr['uuid'] . " THEN '" . $updatearr['cldbid'] . "' ";
$allupdatecount = $allupdatecount . "WHEN " . $updatearr['uuid'] . " THEN '" . $updatearr['count'] . "' ";
$allupdateip = $allupdateip . "WHEN " . $updatearr['uuid'] . " THEN " . $updatearr['ip'] . " ";
$allupdatename = $allupdatename . "WHEN " . $updatearr['uuid'] . " THEN " . $updatearr['name'] . " ";
$allupdatelastseen = $allupdatelastseen . "WHEN " . $updatearr['uuid'] . " THEN '" . $updatearr['lastseen'] . "' ";
$allupdategrpid = $allupdategrpid . "WHEN " . $updatearr['uuid'] . " THEN '" . $updatearr['grpid'] . "' ";
$allupdatenextup = $allupdatenextup . "WHEN " . $updatearr['uuid'] . " THEN '" . $updatearr['nextup'] . "' ";
$allupdateidle = $allupdateidle . "WHEN " . $updatearr['uuid'] . " THEN '" . $updatearr['idle'] . "' ";
$allupdatecldgroup = $allupdatecldgroup . "WHEN " . $updatearr['uuid'] . " THEN '" . $updatearr['cldgroup'] . "' ";
$allupdateboosttime = $allupdateboosttime . "WHEN " . $updatearr['uuid'] . " THEN '" . $updatearr['boosttime'] . "' ";
$allupdateplatform = $allupdateplatform . "WHEN " . $updatearr['uuid'] . " THEN '" . $updatearr['platform'] . "' ";
$allupdatenation = $allupdatenation . "WHEN " . $updatearr['uuid'] . " THEN '" . $updatearr['nation'] . "' ";
$allupdateversion = $allupdateversion . "WHEN " . $updatearr['uuid'] . " THEN '" . $updatearr['version'] . "' ";
$allupdateexcept = $allupdateexcept . "WHEN " . $updatearr['uuid'] . " THEN '" . $updatearr['except'] . "' ";
$allupdategrpsince = $allupdategrpsince . "WHEN " . $updatearr['uuid'] . " THEN '" . $updatearr['grpsince'] . "' ";
$allupdatecid = $allupdatecid . "WHEN " . $updatearr['uuid'] . " THEN '" . $updatearr['cid'] . "' ";
}
$allupdateuuid = substr($allupdateuuid, 0, -1);
$sqlexec .= "UPDATE $dbname.user SET online='0'; UPDATE $dbname.user set cldbid = CASE uuid $allupdatecldbid END, count = CASE uuid $allupdatecount END, ip = CASE uuid $allupdateip END, name = CASE uuid $allupdatename END, lastseen = CASE uuid $allupdatelastseen END, grpid = CASE uuid $allupdategrpid END, nextup = CASE uuid $allupdatenextup END, idle = CASE uuid $allupdateidle END, cldgroup = CASE uuid $allupdatecldgroup END, boosttime = CASE uuid $allupdateboosttime END, platform = CASE uuid $allupdateplatform END, nation = CASE uuid $allupdatenation END, version = CASE uuid $allupdateversion END, except = CASE uuid $allupdateexcept END, grpsince = CASE uuid $allupdategrpsince END, cid = CASE uuid $allupdatecid END, online = 1 WHERE uuid IN ($allupdateuuid); ";
unset($updatedata, $allupdateuuid, $allupdatecldbid, $allupdatecount, $allupdateip, $allupdatename, $allupdatelastseen, $allupdategrpid, $allupdatenextup, $allupdateidle, $allupdatecldgroup, $allupdateboosttime, $allupdateplatform, $allupdatenation, $allupdateversion, $allupdateexcept, $allupdategrpsince, $allupdatecid);
}
return($sqlexec);
}
<?PHP
function calc_user($ts3,$mysqlcon,$lang,$dbname,$slowmode,$timezone,$grouptime,$boostarr,$resetbydbchange,$msgtouser,$currvers,$substridle,$exceptuuid,$exceptgroup,$allclients,$logpath,$rankupmsg,$ignoreidle,$exceptcid,$resetexcept,$phpcommand,$select_arr) {
$nowtime = time();
$sqlexec = '';
if(empty($grouptime)) {
enter_logfile($logpath,$timezone,1,"calc_user:".$lang['wiconferr']."Shuttin down!\n\n");
exit;
}
if($select_arr['job_check']['calc_user_lastscan']['timestamp'] < ($nowtime - 1800)) {
enter_logfile($logpath,$timezone,4,"Much time gone since last scan.. reset time difference to zero.");
$select_arr['job_check']['calc_user_lastscan']['timestamp'] = $nowtime;
} elseif($select_arr['job_check']['calc_user_lastscan']['timestamp'] > $nowtime) {
enter_logfile($logpath,$timezone,4,"Negative time between now and last scan (Error in your server time!).. reset time difference to zero.");
$select_arr['job_check']['calc_user_lastscan']['timestamp'] = $nowtime;
}
$sqlexec .= "UPDATE `$dbname`.`job_check` SET `timestamp`='$nowtime' WHERE `job_name`='calc_user_lastscan'; ";
krsort($grouptime);
$yetonline = array();
$updatedata = array();
if(isset($select_arr['admin_addtime']) && count($select_arr['admin_addtime']) != 0) {
foreach($select_arr['admin_addtime'] as $uuid => $value) {
if(isset($select_arr['all_user'][$uuid])) {
$isonline = 0;
foreach($allclients as $client) {
if($client['client_unique_identifier'] == $uuid) {
$isonline = 1;
$select_arr['all_user'][$uuid]['count'] += $value['timecount'];
}
}
if($isonline != 1) {
$sqlexec .= "UPDATE `$dbname`.`user` SET `count`=`count` + ".$value['timecount']." WHERE `uuid`='$uuid'; ";
}
$sqlexec .= "DELETE FROM `$dbname`.`admin_addtime` WHERE `timestamp`=".$value['timestamp']." AND `uuid`='$uuid'; ";
$sqlexec .= "UPDATE `$dbname`.`user_snapshot` SET `count`=`count` + ".$value['timecount']." WHERE `uuid`='$uuid'; ";
enter_logfile($logpath,$timezone,4,sprintf($lang['sccupcount2'],$value['timecount'],$uuid));
}
}
}
foreach ($allclients as $client) {
$cldbid = $client['client_database_id'];
$name = $mysqlcon->quote($client['client_nickname'], ENT_QUOTES);
$uid = htmlspecialchars($client['client_unique_identifier'], ENT_QUOTES);
$sgroups = array_flip(explode(",", $client['client_servergroups']));
if (!isset($yetonline[$uid]) && $client['client_version'] != "ServerQuery") {
$clientidle = floor($client['client_idle_time'] / 1000);
if(isset($ignoreidle) && $clientidle < $ignoreidle) {
$clientidle = 0;
}
$yetonline[$uid] = 0;
if(isset($exceptuuid[$uid])) {
$except = 3;
} elseif(array_intersect_key($sgroups, $exceptgroup)) {
$except = 2;
} else {
if(isset($select_arr['all_user'][$uid]['except']) && ($select_arr['all_user'][$uid]['except'] == 3 || $select_arr['all_user'][$uid]['except'] == 2) && $resetexcept == 2) {
$select_arr['all_user'][$uid]['count'] = 0;
$select_arr['all_user'][$uid]['idle'] = 0;
enter_logfile($logpath,$timezone,5,sprintf($lang['resettime'], $name, $uid, $cldbid));
$sqlexec .= "DELETE FROM `$dbname`.`user_snapshot` WHERE `uuid`='$uid'; ";
}
$except = 0;
}
if(isset($select_arr['all_user'][$uid])) {
$idle = $select_arr['all_user'][$uid]['idle'] + $clientidle;
$grpid = $select_arr['all_user'][$uid]['grpid'];
$nextup = $select_arr['all_user'][$uid]['nextup'];
$grpsince = $select_arr['all_user'][$uid]['grpsince'];
if ($select_arr['all_user'][$uid]['cldbid'] != $cldbid && $resetbydbchange == 1) {
enter_logfile($logpath,$timezone,5,sprintf($lang['changedbid'], $name, $uid, $cldbid, $select_arr['all_user'][$uid]['cldbid']));
$count = 1;
$idle = 0;
} else {
$hitboost = 0;
$boosttime = $select_arr['all_user'][$uid]['boosttime'];
if($boostarr!=0) {
foreach($boostarr as $boost) {
if(isset($sgroups[$boost['group']])) {
$hitboost = 1;
if($select_arr['all_user'][$uid]['boosttime']==0) {
$boosttime = $nowtime;
} else {
if ($nowtime > $select_arr['all_user'][$uid]['boosttime'] + $boost['time']) {
usleep($slowmode);
try {
$ts3->serverGroupClientDel($boost['group'], $cldbid);
$boosttime = 0;
enter_logfile($logpath,$timezone,5,sprintf($lang['sgrprm'], $select_arr['groups'][$select_arr['all_user'][$uid]['grpid']]['sgidname'], $select_arr['all_user'][$uid]['grpid'], $name, $uid, $cldbid));
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"TS3 error: ".$e->getCode().': '.$e->getMessage()." ; ".sprintf($lang['sgrprerr'], $name, $uid, $cldbid, $select_arr['groups'][$select_arr['all_user'][$uid]['grpid']]['sgidname'], $select_arr['all_user'][$uid]['grpid']));
}
}
}
$count = ($nowtime - $select_arr['job_check']['calc_user_lastscan']['timestamp']) * $boost['factor'] + $select_arr['all_user'][$uid]['count'];
if ($clientidle > ($nowtime - $select_arr['job_check']['calc_user_lastscan']['timestamp'])) {
$idle = ($nowtime - $select_arr['job_check']['calc_user_lastscan']['timestamp']) * $boost['factor'] + $select_arr['all_user'][$uid]['idle'];
}
}
}
}
if($boostarr == 0 or $hitboost == 0) {
$count = $nowtime - $select_arr['job_check']['calc_user_lastscan']['timestamp'] + $select_arr['all_user'][$uid]['count'];
if ($clientidle > ($nowtime - $select_arr['job_check']['calc_user_lastscan']['timestamp'])) {
$idle = $nowtime - $select_arr['job_check']['calc_user_lastscan']['timestamp'] + $select_arr['all_user'][$uid]['idle'];
}
}
}
$dtF = new DateTime("@0");
if ($substridle == 1) {
$activetime = $count - $idle;
} else {
$activetime = $count;
}
$dtT = new DateTime("@$activetime");
foreach ($grouptime as $time => $groupid) {
if (isset($sgroups[$groupid])) {
$grpid = $groupid;
break;
}
}
$grpcount=0;
foreach ($grouptime as $time => $groupid) {
$grpcount++;
if(isset($exceptcid[$client['cid']]) || (($select_arr['all_user'][$uid]['except'] == 3 || $select_arr['all_user'][$uid]['except'] == 2) && $resetexcept == 1)) {
$count = $select_arr['all_user'][$uid]['count'];
$idle = $select_arr['all_user'][$uid]['idle'];
if($except != 2 && $except != 3) {
$except = 1;
}
} elseif ($activetime > $time && !isset($exceptuuid[$uid]) && !array_intersect_key($sgroups, $exceptgroup)) {
if ($select_arr['all_user'][$uid]['grpid'] != $groupid) {
if ($select_arr['all_user'][$uid]['grpid'] != NULL && isset($sgroups[$select_arr['all_user'][$uid]['grpid']])) {
usleep($slowmode);
try {
$ts3->serverGroupClientDel($select_arr['all_user'][$uid]['grpid'], $cldbid);
enter_logfile($logpath,$timezone,5,sprintf($lang['sgrprm'], $select_arr['groups'][$select_arr['all_user'][$uid]['grpid']]['sgidname'], $select_arr['all_user'][$uid]['grpid'], $name, $uid, $cldbid));
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"TS3 error: ".$e->getCode().': '.$e->getMessage()." ; ".sprintf($lang['sgrprerr'], $name, $uid, $cldbid, $select_arr['groups'][$groupid]['sgidname'], $groupid));
}
}
if (!isset($sgroups[$groupid])) {
usleep($slowmode);
try {
$ts3->serverGroupClientAdd($groupid, $cldbid);
$grpsince = $nowtime;
enter_logfile($logpath,$timezone,5,sprintf($lang['sgrpadd'], $select_arr['groups'][$groupid]['sgidname'], $groupid, $name, $uid, $cldbid));
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"TS3 error: ".$e->getCode().': '.$e->getMessage()." ; ".sprintf($lang['sgrprerr'], $name, $uid, $cldbid, $select_arr['groups'][$groupid]['sgidname'], $groupid));
}
}
$grpid = $groupid;
if ($msgtouser == 1) {
usleep($slowmode);
$days = $dtF->diff($dtT)->format('%a');
$hours = $dtF->diff($dtT)->format('%h');
$mins = $dtF->diff($dtT)->format('%i');
$secs = $dtF->diff($dtT)->format('%s');
try {
$ts3->clientGetByUid($uid)->message(sprintf($rankupmsg, $days, $hours, $mins, $secs, $select_arr['groups'][$groupid]['sgidname'], $client['client_nickname']));
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"TS3 error: ".$e->getCode().': '.$e->getMessage()." ; ".sprintf($lang['sgrprerr'], $name, $uid, $cldbid, $select_arr['groups'][$groupid]['sgidname'], $groupid));
}
}
}
if($grpcount == 1) {
$nextup = 0;
}
break;
} else {
$nextup = $time - $activetime;
}
}
$updatedata[] = array(
"uuid" => $mysqlcon->quote($client['client_unique_identifier'], ENT_QUOTES),
"cldbid" => $cldbid,
"count" => $count,
"name" => $name,
"lastseen" => $nowtime,
"grpid" => $grpid,
"nextup" => $nextup,
"idle" => $idle,
"cldgroup" => $client['client_servergroups'],
"boosttime" => $boosttime,
"platform" => $client['client_platform'],
"nation" => $client['client_country'],
"version" => $client['client_version'],
"except" => $except,
"grpsince" => $grpsince,
"cid" => $client['cid']
);
} else {
$grpid = '0';
foreach ($grouptime as $time => $groupid) {
if (isset($sgroups[$groupid])) {
$grpid = $groupid;
break;
}
}
$updatedata[] = array(
"uuid" => $mysqlcon->quote($client['client_unique_identifier'], ENT_QUOTES),
"cldbid" => $cldbid,
"count" => "0",
"name" => $name,
"lastseen" => $nowtime,
"grpid" => $grpid,
"nextup" => (key($grouptime) - 1),
"idle" => "0",
"cldgroup" => $client['client_servergroups'],
"boosttime" => "0",
"platform" => $client['client_platform'],
"nation" => $client['client_country'],
"version" => $client['client_version'],
"firstcon" => $client['client_created'],
"except" => $except,
"grpsince" => "0",
"cid" => $client['cid']
);
enter_logfile($logpath,$timezone,5,sprintf($lang['adduser'], $name, $uid, $cldbid));
}
}
}
unset($yetonline);
if ($updatedata != NULL) {
$sqlinsertvalues = '';
foreach ($updatedata as $updatearr) {
$sqlinsertvalues .= "(".$updatearr['uuid'].",'".$updatearr['cldbid']."','".$updatearr['count']."',".$updatearr['name'].",'".$updatearr['lastseen']."','".$updatearr['grpid']."','".$updatearr['nextup']."','".$updatearr['idle']."','".$updatearr['cldgroup']."','".$updatearr['boosttime']."','".$updatearr['platform']."','".$updatearr['nation']."','".$updatearr['version']."','".$updatearr['except']."','".$updatearr['grpsince']."','".$updatearr['cid']."',1),";
}
$sqlinsertvalues = substr($sqlinsertvalues, 0, -1);
$sqlexec .= "UPDATE `$dbname`.`user` SET `online`='0'; INSERT INTO `$dbname`.`user` (`uuid`,`cldbid`,`count`,`name`,`lastseen`,`grpid`,`nextup`,`idle`,`cldgroup`,`boosttime`,`platform`,`nation`,`version`,`except`,`grpsince`,`cid`,`online`) VALUES $sqlinsertvalues ON DUPLICATE KEY UPDATE `cldbid`=VALUES(`cldbid`),`count`=VALUES(`count`),`name`=VALUES(`name`),`lastseen`=VALUES(`lastseen`),`grpid`=VALUES(`grpid`),`nextup`=VALUES(`nextup`),`idle`=VALUES(`idle`),`cldgroup`=VALUES(`cldgroup`),`boosttime`=VALUES(`boosttime`),`platform`=VALUES(`platform`),`nation`=VALUES(`nation`),`version`=VALUES(`version`),`except`=VALUES(`except`),`grpsince`=VALUES(`grpsince`),`cid`=VALUES(`cid`),`online`=VALUES(`online`); ";
unset($updatedata, $sqlinsertvalues);
}
return($sqlexec);
}
?>

View File

@@ -1,100 +1,78 @@
<?PHP
function calc_userstats($ts3,$mysqlcon,$dbname,$slowmode,$timezone,$logpath,$select_arr) {
$sqlexec = '';
$max_timestamp = key($select_arr['max_timestamp_user_snapshot']);
$min_timestamp_week = key($select_arr['usersnap_min_week']);
$min_timestamp_month = key($select_arr['usersnap_min_month']);
$job_begin = $select_arr['job_check']['calc_user_limit']['timestamp'];
$job_end = ceil(count($select_arr['all_user']) / 10) * 10;
if ($job_begin >= $job_end) {
$job_begin = 0;
$job_end = 10;
} else {
$job_end = $job_begin + 10;
}
$sqlhis = array_slice($select_arr['all_user'],$job_begin ,10);
$uuids = '';
foreach ($sqlhis as $uuid => $userstats) {
$uuids .= "'".$uuid."',";
}
$uuids = substr($uuids, 0, -1);
if(isset($sqlhis) && $max_timestamp != NULL && $min_timestamp_week != NULL && $min_timestamp_month != NULL) {
//enter_logfile($logpath,$timezone,6,"Update User Stats between ".$job_begin." and ".$job_end.":");
if(($userdataweekbegin = $mysqlcon->query("SELECT uuid,count,idle FROM $dbname.user_snapshot WHERE timestamp=$min_timestamp_week AND uuid IN ($uuids)")->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE)) === false) {
enter_logfile($logpath,$timezone,2,"calc_userstats 6:".print_r($mysqlcon->errorInfo(), true));
}
if(($userdatamonthbegin = $mysqlcon->query("SELECT uuid,count,idle FROM $dbname.user_snapshot WHERE timestamp=$min_timestamp_month AND uuid IN ($uuids)")->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE)) === false) {
enter_logfile($logpath,$timezone,2,"calc_userstats 8:".print_r($mysqlcon->errorInfo(), true));
}
if(($userdataend = $mysqlcon->query("SELECT uuid,count,idle FROM $dbname.user_snapshot WHERE timestamp=$max_timestamp AND uuid IN ($uuids)")->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE)) === false) {
enter_logfile($logpath,$timezone,2,"calc_userstats 7:".print_r($mysqlcon->errorInfo(), true));
}
$allupdateuuid = $allupdaterank = $allupdatecountw = $allupdatecountm = $allupdateidlew = $allupdateidlem = $allupdateactw = $allupdateactm = $allupdatetotac = $allupdatebase64 = $allupdatecldtup = $allupdatecldtdo = $allupdateclddes = $allinsertuserstats = '';
foreach ($sqlhis as $uuid => $userstats) {
check_shutdown($timezone,$logpath); usleep($slowmode);
try {
$clientinfo = $ts3->clientInfoDb($userstats['cldbid']);
if(isset($userdataend[$uuid]) && isset($userdataweekbegin[$uuid])) {
$count_week = $userdataend[$uuid]['count'] - $userdataweekbegin[$uuid]['count'];
$idle_week = $userdataend[$uuid]['idle'] - $userdataweekbegin[$uuid]['idle'];
$active_week = $count_week - $idle_week;
} else {
$count_week = 0;
$idle_week = 0;
$active_week = 0;
}
if(isset($userdataend[$uuid]) && isset($userdatamonthbegin[$uuid])) {
$count_month = $userdataend[$uuid]['count'] - $userdatamonthbegin[$uuid]['count'];
$idle_month = $userdataend[$uuid]['idle'] - $userdatamonthbegin[$uuid]['idle'];
$active_month = $count_month - $idle_month;
} else {
$count_month = 0;
$idle_month = 0;
$active_month = 0;
}
$clientdesc = $mysqlcon->quote($clientinfo['client_description'], ENT_QUOTES);;
if(isset($select_arr['uuid_stats_user'][$uuid])) {
$allupdateuuid = $allupdateuuid . "'" . $uuid . "',";
$allupdaterank = $allupdaterank . "WHEN '" . $uuid . "' THEN '" . $userstats['rank'] . "' ";
$allupdatecountw = $allupdatecountw . "WHEN '" . $uuid . "' THEN '" . $count_week . "' ";
$allupdatecountm = $allupdatecountm . "WHEN '" . $uuid . "' THEN '" . $count_month . "' ";
$allupdateidlew = $allupdateidlew . "WHEN '" . $uuid . "' THEN '" . $idle_week . "' ";
$allupdateidlem = $allupdateidlem . "WHEN '" . $uuid . "' THEN '" . $idle_month . "' ";
$allupdateactw = $allupdateactw . "WHEN '" . $uuid . "' THEN '" . $active_week . "' ";
$allupdateactm = $allupdateactm . "WHEN '" . $uuid . "' THEN '" . $active_month . "' ";
$allupdatetotac = $allupdatetotac . "WHEN '" . $uuid . "' THEN '" . $clientinfo['client_totalconnections'] . "' ";
$allupdatebase64 = $allupdatebase64 . "WHEN '" . $uuid . "' THEN '" . $clientinfo['client_base64HashClientUID'] . "' ";
$allupdatecldtup = $allupdatecldtup . "WHEN '" . $uuid . "' THEN '" . $clientinfo['client_total_bytes_uploaded'] . "' ";
$allupdatecldtdo = $allupdatecldtdo . "WHEN '" . $uuid . "' THEN '" . $clientinfo['client_total_bytes_downloaded'] . "' ";
$allupdateclddes = $allupdateclddes . "WHEN '" . $uuid . "' THEN " . $clientdesc . " ";
} else {
$allinsertuserstats = $allinsertuserstats . "('" . $uuid . "', '" .$userstats['rank'] . "', '" . $count_week . "', '" . $count_month . "', '" . $idle_week . "', '" . $idle_month . "', '" . $active_week . "', '" . $active_month . "', '" . $clientinfo['client_totalconnections'] . "', '" . $clientinfo['client_base64HashClientUID'] . "', '" . $clientinfo['client_total_bytes_uploaded'] . "', '" . $clientinfo['client_total_bytes_downloaded'] . "', " . $clientdesc . "),";
}
} catch (Exception $e) {
//enter_logfile($logpath,$timezone,6,$e->getCode() . ': ' . $e->getMessage()."; Client (uuid: ".$uuid." cldbid: ".$userstats['cldbid'].") was missing in TS database, perhaps its already deleted".);
}
}
unset($sqlhis, $userdataweekbegin, $userdataend, $userdatamonthbegin);
if ($allupdateuuid != '') {
$allupdateuuid = substr($allupdateuuid, 0, -1);
$sqlexec .= "UPDATE $dbname.job_check SET timestamp=$job_end WHERE job_name='calc_user_limit'; UPDATE $dbname.stats_user set rank = CASE uuid $allupdaterank END, count_week = CASE uuid $allupdatecountw END, count_month = CASE uuid $allupdatecountm END, idle_week = CASE uuid $allupdateidlew END, idle_month = CASE uuid $allupdateidlem END, active_week = CASE uuid $allupdateactw END, active_month = CASE uuid $allupdateactm END, total_connections = CASE uuid $allupdatetotac END, base64hash = CASE uuid $allupdatebase64 END, client_total_up = CASE uuid $allupdatecldtup END, client_total_down = CASE uuid $allupdatecldtdo END, client_description = CASE uuid $allupdateclddes END WHERE uuid IN ($allupdateuuid); ";
unset($allupdateuuid, $allupdaterank, $allupdatecountw, $allupdatecountm, $allupdateidlew, $allupdateidlem, $allupdateactw, $allupdateactm, $allupdatetotac, $allupdatebase64, $allupdatecldtup, $allupdatecldtdo, $allupdateclddes);
}
if($allinsertuserstats != '') {
$allinsertuserstats = substr($allinsertuserstats, 0, -1);
$sqlexec .= "UPDATE $dbname.job_check SET timestamp=$job_end WHERE job_name='calc_user_limit'; INSERT INTO $dbname.stats_user (uuid,rank,count_week,count_month,idle_week,idle_month,active_week,active_month,total_connections,base64hash,client_total_up,client_total_down,client_description) VALUES $allinsertuserstats; ";
unset($allinsertuserstats);
}
}
return($sqlexec);
}
<?PHP
function calc_userstats($ts3,$mysqlcon,$dbname,$slowmode,$timezone,$logpath,$select_arr) {
$sqlexec = '';
$max_timestamp = key($select_arr['max_timestamp_user_snapshot']);
$min_timestamp_week = key($select_arr['usersnap_min_week']);
$min_timestamp_month = key($select_arr['usersnap_min_month']);
$job_begin = $select_arr['job_check']['calc_user_limit']['timestamp'];
$job_end = ceil(count($select_arr['all_user']) / 10) * 10;
if ($job_begin >= $job_end) {
$job_begin = 0;
$job_end = 10;
} else {
$job_end = $job_begin + 10;
}
$sqlhis = array_slice($select_arr['all_user'],$job_begin ,10);
$uuids = '';
foreach ($sqlhis as $uuid => $userstats) {
$uuids .= "'".$uuid."',";
}
$uuids = substr($uuids, 0, -1);
if(isset($sqlhis) && $max_timestamp != NULL && $min_timestamp_week != NULL && $min_timestamp_month != NULL) {
#enter_logfile($logpath,$timezone,6,"Update User Stats between ".$job_begin." and ".$job_end.":");
if(($userdataweekbegin = $mysqlcon->query("SELECT `uuid`,`count`,`idle` FROM `$dbname`.`user_snapshot` WHERE `timestamp`=$min_timestamp_week AND `uuid` IN ($uuids)")->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE)) === false) {
enter_logfile($logpath,$timezone,2,"calc_userstats 6:".print_r($mysqlcon->errorInfo(), true));
}
if(($userdatamonthbegin = $mysqlcon->query("SELECT `uuid`,`count`,`idle` FROM `$dbname`.`user_snapshot` WHERE `timestamp`=$min_timestamp_month AND `uuid` IN ($uuids)")->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE)) === false) {
enter_logfile($logpath,$timezone,2,"calc_userstats 8:".print_r($mysqlcon->errorInfo(), true));
}
if(($userdataend = $mysqlcon->query("SELECT `uuid`,`count`,`idle` FROM `$dbname`.`user_snapshot` WHERE `timestamp`=$max_timestamp AND `uuid` IN ($uuids)")->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE)) === false) {
enter_logfile($logpath,$timezone,2,"calc_userstats 7:".print_r($mysqlcon->errorInfo(), true));
}
$allupdateuuid = '';
foreach ($sqlhis as $uuid => $userstats) {
check_shutdown($timezone,$logpath); usleep($slowmode);
try {
$clientinfo = $ts3->clientInfoDb($userstats['cldbid']);
if(isset($userdataend[$uuid]) && isset($userdataweekbegin[$uuid])) {
$count_week = $userdataend[$uuid]['count'] - $userdataweekbegin[$uuid]['count'];
$idle_week = $userdataend[$uuid]['idle'] - $userdataweekbegin[$uuid]['idle'];
$active_week = $count_week - $idle_week;
} else {
$count_week = 0;
$idle_week = 0;
$active_week = 0;
}
if(isset($userdataend[$uuid]) && isset($userdatamonthbegin[$uuid])) {
$count_month = $userdataend[$uuid]['count'] - $userdatamonthbegin[$uuid]['count'];
$idle_month = $userdataend[$uuid]['idle'] - $userdatamonthbegin[$uuid]['idle'];
$active_month = $count_month - $idle_month;
} else {
$count_month = 0;
$idle_month = 0;
$active_month = 0;
}
$clientdesc = $mysqlcon->quote($clientinfo['client_description'], ENT_QUOTES);;
$allupdateuuid .= "('" . $uuid . "','" .$userstats['rank'] . "','" . $count_week . "','" . $count_month . "','" . $idle_week . "','" . $idle_month . "','" . $active_week . "','" . $active_month . "','" . $clientinfo['client_totalconnections'] . "','" . $clientinfo['client_base64HashClientUID'] . "','" . $clientinfo['client_total_bytes_uploaded'] . "','" . $clientinfo['client_total_bytes_downloaded'] . "'," . $clientdesc . "),";
} catch (Exception $e) {
//enter_logfile($logpath,$timezone,6,$e->getCode() . ': ' . $e->getMessage()."; Client (uuid: ".$uuid." cldbid: ".$userstats['cldbid'].") was missing in TS database, perhaps its already deleted".);
}
}
unset($sqlhis, $userdataweekbegin, $userdataend, $userdatamonthbegin);
if ($allupdateuuid != '') {
$allupdateuuid = substr($allupdateuuid, 0, -1);
$sqlexec .= "UPDATE `$dbname`.`job_check` SET `timestamp`=$job_end WHERE `job_name`='calc_user_limit'; INSERT INTO `$dbname`.`stats_user` (`uuid`,`rank`,`count_week`,`count_month`,`idle_week`,`idle_month`,`active_week`,`active_month`,`total_connections`,`base64hash`,`client_total_up`,`client_total_down`,`client_description`) VALUES $allupdateuuid ON DUPLICATE KEY UPDATE `rank`=VALUES(`rank`),`count_week`=VALUES(`count_week`),`count_month`=VALUES(`count_month`),`idle_week`=VALUES(`idle_week`),`idle_month`=VALUES(`idle_month`),`active_week`=VALUES(`active_week`),`active_month`=VALUES(`active_month`),`total_connections`=VALUES(`total_connections`),`base64hash`=VALUES(`base64hash`),`client_total_up`=VALUES(`client_total_up`),`client_total_down`=VALUES(`client_total_down`),`client_description`=VALUES(`client_description`); ";
unset($updategroups, $allupdateuuid);
}
}
return($sqlexec);
}
?>

View File

@@ -1,233 +1,262 @@
<?PHP
function check_db($mysqlcon,$lang,$dbname,$timezone,$currvers,$logpath) {
$newversion = '1.2.6';
enter_logfile($logpath,$timezone,5,"Check Ranksystem database for updates...");
function set_new_version($mysqlcon,$dbname,$timezone,$newversion,$logpath) {
if($mysqlcon->exec("UPDATE $dbname.config set currvers='$newversion'") === false) {
enter_logfile($logpath,$timezone,1," An error happens due updating the Ranksystem Database:".print_r($mysqlcon->errorInfo(), true));
enter_logfile($logpath,$timezone,1," Check the database connection and properties in other/dbconfig.php and check also the database permissions.");
exit;
} else {
$currvers = $newversion;
enter_logfile($logpath,$timezone,4," Database successfully updated!");
return $currvers;
}
}
function check_chmod($timezone,$logpath,$lang) {
if(substr(sprintf('%o', fileperms(substr(__DIR__,0,-4).'tsicons/')), -3, 1)!='7') {
enter_logfile($logpath,$timezone,2,sprintf($lang['isntwichm'],'tsicons'));
}
if(substr(sprintf('%o', fileperms($logpath)), -3, 1)!='7') {
enter_logfile($logpath,$timezone,2,sprintf($lang['isntwichm'],'logs'));
}
if(substr(sprintf('%o', fileperms(substr(__DIR__,0,-4).'avatars/')), -3, 1)!='7') {
enter_logfile($logpath,$timezone,2,sprintf($lang['isntwichm'],'avatars'));
}
if(substr(sprintf('%o', fileperms(substr(__DIR__,0,-4).'update/')), -3, 1)!='7') {
enter_logfile($logpath,$timezone,2,sprintf($lang['isntwichm'],'update'));
}
}
function check_config($mysqlcon,$dbname) {
if(($dbdata = $mysqlcon->query("SELECT * FROM $dbname.config")->fetchAll()) === false) { } else {
if(count($dbdata) > 1) {
if($mysqlcon->exec("DELETE FROM $dbname.config WHERE webuser IS NULL") === false) { }
}
}
}
function old_files($timezone,$logpath) {
if(is_file(substr(__DIR__,0,-4).'install.php')) {
if(!unlink('install.php')) {
enter_logfile($logpath,$timezone,4,"Unnecessary file, please delete it from your webserver: install.php");
}
}
if(is_dir(substr(__DIR__,0,-4).'icons/')) {
if(!rmdir(substr(__DIR__,0,-4).'icons/')) {
enter_logfile($logpath,$timezone,4,"Unnecessary folder, please delete it from your webserver: icons/");
}
}
if(is_file(substr(__DIR__,0,-4).'libs/combined_stats.css')) {
if(!unlink(substr(__DIR__,0,-4).'libs/combined_stats.css')) {
enter_logfile($logpath,$timezone,4,"Unnecessary file, please delete it from your webserver: libs/combined_stats.css");
}
}
if(is_file(substr(__DIR__,0,-4).'libs/combined_stats.js')) {
if(!unlink(substr(__DIR__,0,-4).'libs/combined_stats.js')) {
enter_logfile($logpath,$timezone,4,"Unnecessary file, please delete it from your webserver: libs/combined_stats.js");
}
}
}
function check_writable($timezone,$logpath) {
enter_logfile($logpath,$timezone,5," Check files permissions...");
$counterr=0;
$scandir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(substr(__DIR__,0,-4)));
$files = array();
foreach ($scandir as $object) {
if(!strstr($object, '/.') && !strstr($object, '\.')) {
if (!$object->isDir()) {
if(!is_writable($object->getPathname())) {
enter_logfile($logpath,$timezone,3," File is not writeable ".$object);
echo "\nhier: ".$object."\n";
$counterr++;
}
} else {
if(!is_writable($object->getPathname())) {
enter_logfile($logpath,$timezone,3," Folder is not writeable ".$object);
$counterr++;
}
}
}
}
if($counterr!=0) {
enter_logfile($logpath,$timezone,1,"Please check the files pemissions. Shutting down!\n\n");
exit;
} else {
enter_logfile($logpath,$timezone,5," Check files permissions [done]");
}
}
if($currvers==$newversion) {
enter_logfile($logpath,$timezone,5," No newer version detected; Database check finished.");
old_files($timezone,$logpath);
check_chmod($timezone,$logpath,$lang);
check_config($mysqlcon,$dbname);
check_writable($timezone,$logpath);
} else {
enter_logfile($logpath,$timezone,4," Update the Ranksystem Database to new version...");
if(version_compare($currvers, '1.2.0', '<=')) {
if($mysqlcon->exec("ALTER TABLE $dbname.stats_server MODIFY COLUMN server_name varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN server_platform varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN server_weblist tinyint(1) NOT NULL default '0', MODIFY COLUMN server_version varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN total_user int(10) NOT NULL default '0', MODIFY COLUMN country_nation_1 int(10) NOT NULL default '0', MODIFY COLUMN country_nation_2 int(10) NOT NULL default '0', MODIFY COLUMN country_nation_3 int(10) NOT NULL default '0', MODIFY COLUMN country_nation_4 int(10) NOT NULL default '0', MODIFY COLUMN country_nation_5 int(10) NOT NULL default '0', MODIFY COLUMN country_nation_other int(10) NOT NULL default '0', MODIFY COLUMN platform_1 int(10) NOT NULL default '0', MODIFY COLUMN platform_2 int(10) NOT NULL default '0', MODIFY COLUMN platform_3 int(10) NOT NULL default '0', MODIFY COLUMN platform_4 int(10) NOT NULL default '0', MODIFY COLUMN platform_5 int(10) NOT NULL default '0', MODIFY COLUMN platform_other int(10) NOT NULL default '0', MODIFY COLUMN version_1 int(10) NOT NULL default '0', MODIFY COLUMN version_2 int(10) NOT NULL default '0', MODIFY COLUMN version_3 int(10) NOT NULL default '0', MODIFY COLUMN version_4 int(10) NOT NULL default '0', MODIFY COLUMN version_5 int(10) NOT NULL default '0', MODIFY COLUMN version_other int(10) NOT NULL default '0', MODIFY COLUMN server_status tinyint(1) NOT NULL default '0', MODIFY COLUMN server_free_slots smallint(5) NOT NULL default '0', MODIFY COLUMN server_used_slots smallint(5) NOT NULL default '0', MODIFY COLUMN server_channel_amount smallint(5) NOT NULL default '0', MODIFY COLUMN server_ping smallint(5) NOT NULL default '0', MODIFY COLUMN server_id smallint(5) NOT NULL default '0', MODIFY COLUMN server_pass tinyint(1) NOT NULL default '0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table stats_server (part1) successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.stats_server ADD (user_today int(10) NOT NULL default '0', user_week int(10) NOT NULL default '0', user_month int(10) NOT NULL default '0', user_quarter int(10) NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table stats_server (part2) successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.stats_user MODIFY COLUMN removed tinyint(1) NOT NULL default '0', MODIFY COLUMN rank int(10) NOT NULL default '0', MODIFY COLUMN count_week int(10) NOT NULL default '0', MODIFY COLUMN count_month int(10) NOT NULL default '0', MODIFY COLUMN idle_week int(10) NOT NULL default '0', MODIFY COLUMN idle_month int(10) NOT NULL default '0', MODIFY COLUMN achiev_count tinyint(1) NOT NULL default '0', MODIFY COLUMN achiev_time int(10) NOT NULL default '0', MODIFY COLUMN achiev_connects smallint(5) NOT NULL default '0', MODIFY COLUMN achiev_battles tinyint(3) NOT NULL default '0', MODIFY COLUMN achiev_time_perc tinyint(3) NOT NULL default '0', MODIFY COLUMN achiev_connects_perc tinyint(3) NOT NULL default '0', MODIFY COLUMN achiev_battles_perc tinyint(3) NOT NULL default '0', MODIFY COLUMN battles_total tinyint(3) NOT NULL default '0', MODIFY COLUMN battles_won tinyint(3) NOT NULL default '0', MODIFY COLUMN battles_lost tinyint(3) NOT NULL default '0', MODIFY COLUMN total_connections smallint(5) NOT NULL default '0', MODIFY COLUMN client_description varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table stats_user successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.user MODIFY COLUMN cldbid int(10) NOT NULL default '0', MODIFY COLUMN count int(10) NOT NULL default '0', MODIFY COLUMN name varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN grpid int(10) NOT NULL default '0', MODIFY COLUMN nextup int(10) NOT NULL default '0', MODIFY COLUMN idle int(10) NOT NULL default '0', MODIFY COLUMN cldgroup varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN online tinyint(1) NOT NULL default '0', MODIFY COLUMN boosttime int(10) NOT NULL default '0', MODIFY COLUMN rank int(10) NOT NULL default '0', MODIFY COLUMN platform varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN nation varchar(3) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN version varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN except tinyint(1) NOT NULL default '0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table user successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.config MODIFY COLUMN webuser varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN webpass varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN tshost varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN tsquery smallint(5) NOT NULL default '0', MODIFY COLUMN tsvoice smallint(5) NOT NULL default '0', MODIFY COLUMN tsuser varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN tspass varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN language char(2) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN queryname varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN queryname2 varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN grouptime varchar(5000) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN resetbydbchange tinyint(1) NOT NULL default '0', MODIFY COLUMN msgtouser tinyint(1) NOT NULL default '0', MODIFY COLUMN upcheck tinyint(1) NOT NULL default '0', MODIFY COLUMN uniqueid varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN updateinfotime mediumint(6) NOT NULL default '0', MODIFY COLUMN currvers varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN substridle tinyint(1) NOT NULL default '0', MODIFY COLUMN exceptuuid varchar(999) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN exceptgroup varchar(999) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN dateformat varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN showexcld tinyint(1) NOT NULL default '0', MODIFY COLUMN showcolcld tinyint(1) NOT NULL default '0', MODIFY COLUMN showcoluuid tinyint(1) NOT NULL default '0', MODIFY COLUMN showcoldbid tinyint(1) NOT NULL default '0', MODIFY COLUMN showcolot tinyint(1) NOT NULL default '0', MODIFY COLUMN showcolit tinyint(1) NOT NULL default '0', MODIFY COLUMN showcolat tinyint(1) NOT NULL default '0', MODIFY COLUMN showcolnx tinyint(1) NOT NULL default '0', MODIFY COLUMN showcolsg tinyint(1) NOT NULL default '0', MODIFY COLUMN showcolrg tinyint(1) NOT NULL default '0', MODIFY COLUMN showcolls tinyint(1) NOT NULL default '0', MODIFY COLUMN slowmode mediumint(9) NOT NULL default '0', MODIFY COLUMN cleanclients tinyint(1) NOT NULL default '0', MODIFY COLUMN cleanperiod mediumint(9) NOT NULL default '0', MODIFY COLUMN showhighest tinyint(1) NOT NULL default '0', MODIFY COLUMN boost varchar(999) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN showcolas tinyint(1) NOT NULL default '0', MODIFY COLUMN defchid int(10) NOT NULL default '0', MODIFY COLUMN advancemode tinyint(1) NOT NULL default '0', MODIFY COLUMN count_access tinyint(2) NOT NULL default '0', MODIFY COLUMN ignoreidle smallint(5) NOT NULL default '0', MODIFY COLUMN exceptcid varchar(999) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN rankupmsg varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN boost_mode tinyint(1) NOT NULL default '0', MODIFY COLUMN servernews varchar(5000) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN nextupinfo tinyint(1) NOT NULL default '0', MODIFY COLUMN nextupinfomsg1 varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN nextupinfomsg2 varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN nextupinfomsg3 varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN shownav tinyint(1) NOT NULL default '0', MODIFY COLUMN showgrpsince tinyint(1) NOT NULL default '0', MODIFY COLUMN resetexcept tinyint(1) NOT NULL default '0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table config successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.server_usage MODIFY COLUMN clients smallint(5) NOT NULL default '0', MODIFY COLUMN channel smallint(5) NOT NULL default '0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table server_usage successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.user_snapshot MODIFY COLUMN count int(10) NOT NULL default '0', MODIFY COLUMN idle int(10) NOT NULL default '0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table user_snapshot successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.groups MODIFY COLUMN sgid int(10) NOT NULL default '0' PRIMARY KEY, MODIFY COLUMN sgidname varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table groups successfully.");
}
if($mysqlcon->exec("CREATE TABLE $dbname.stats_nations (nation varchar(3) CHARACTER SET utf8 COLLATE utf8_unicode_ci, count int(10) NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Created table stats_nations successfully.");
}
if($mysqlcon->exec("CREATE TABLE $dbname.stats_versions (version varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, count int(10) NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Created table stats_versions successfully.");
}
if($mysqlcon->exec("CREATE TABLE $dbname.stats_platforms (platform varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci, count int(10) NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Created table stats_platforms successfully.");
}
}
if(version_compare($currvers, '1.2.1', '<=')) {
if($mysqlcon->exec("ALTER TABLE $dbname.stats_user ADD (active_week int(10) NOT NULL default '0', active_month int(10) NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.2] Adjusted table stats_user successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.config ADD (avatar_delay smallint(5) UNSIGNED NOT NULL default '0')") === false) { } else {
if($mysqlcon->exec("UPDATE $dbname.config set avatar_delay='0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.2] Adjusted table config (part 1) successfully.");
}
}
if($mysqlcon->exec("ALTER TABLE $dbname.config MODIFY COLUMN tsquery smallint(5) UNSIGNED NOT NULL default '0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.2] Adjusted table config (part 2) successfully.");
}
if($mysqlcon->exec("CREATE TABLE $dbname.addons_config (param varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci UNIQUE, value varchar(5000) CHARACTER SET utf8 COLLATE utf8_unicode_ci)") === false) { } else {
if($mysqlcon->exec("INSERT INTO $dbname.addons_config (param,value) VALUES ('assign_groups_active','0'),('assign_groups_groupids',''),('assign_groups_limit','')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.2] Created table addons_config successfully.");
}
}
if($mysqlcon->exec("CREATE TABLE $dbname.addon_assign_groups (uuid varchar(29) CHARACTER SET utf8 COLLATE utf8_unicode_ci, grpids varchar(1000) CHARACTER SET utf8 COLLATE utf8_unicode_ci)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.2] Created table addon_assign_groups successfully.");
}
}
if(version_compare($currvers, '1.2.2', '<=')) {
if($mysqlcon->exec("DELETE FROM $dbname.groups") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.3] Cleaned table groups successfully. (cause new icon folder tsicons - redownload)");
}
if($mysqlcon->exec("ALTER TABLE $dbname.config MODIFY COLUMN tsvoice smallint(5) UNSIGNED NOT NULL default '0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.3] Adjusted table config successfully.");
}
if($mysqlcon->exec("CREATE INDEX snapshot_timestamp ON $dbname.user_snapshot (timestamp)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.3] Recreated index on table user_snapshot successfully.");
}
if($mysqlcon->exec("CREATE INDEX serverusage_timestamp ON $dbname.server_usage (timestamp)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.3] Recreated index on table server_usage successfully.");
}
}
if(version_compare($currvers, '1.2.3', '<=')) {
if($mysqlcon->exec("ALTER TABLE $dbname.config MODIFY COLUMN adminuuid varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Adjusted table config (part 1) successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.config ADD (registercid mediumint(8) UNSIGNED NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Adjusted table config (part 2) successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.user ADD (cid int(10) NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Adjusted table user successfully.");
}
if($mysqlcon->exec("CREATE INDEX user_version ON $dbname.user (version)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Create index 'user_version' on table user successfully.");
}
if($mysqlcon->exec("CREATE INDEX user_cldbid ON $dbname.user (cldbid ASC,uuid,rank)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Create index 'user_cldbid' on table user successfully.");
}
if($mysqlcon->exec("CREATE INDEX user_online ON $dbname.user (online,lastseen)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Create index 'user_online' on table user successfully.");
}
if($mysqlcon->exec("INSERT INTO $dbname.job_check (job_name) VALUES ('clean_db'),('clean_clients'),('calc_server_stats'),('runtime_check'),('last_update')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Set new values to table job_check successfully.");
}
if($mysqlcon->exec("DELETE FROM $dbname.job_check WHERE job_name='check_clean'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Removed old value 'check_clean' from table job_check successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.user_snapshot ADD PRIMARY KEY (timestamp, uuid)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Added new primary key on table user_snapshot successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.stats_nations ADD PRIMARY KEY (nation)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Added new primary key on table stats_nations successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.stats_platforms ADD PRIMARY KEY (platform)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Added new primary key on table stats_platforms successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.stats_versions ADD PRIMARY KEY (version)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Added new primary key on table stats_versions successfully.");
}
}
if(version_compare($currvers, '1.2.4', '<=')) {
if($mysqlcon->exec("ALTER TABLE $dbname.groups MODIFY COLUMN sgidname varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.5] Adjusted table groups successfully.");
}
}
if(version_compare($currvers, '1.2.5', '<=')) {
if($mysqlcon->exec("INSERT INTO $dbname.job_check (job_name) VALUES ('last_update')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Set missed value to table job_check successfully.");
}
if($mysqlcon->exec("ALTER TABLE $dbname.config DROP COLUMN upcheck, DROP COLUMN uniqueid, DROP COLUMN updateinfotime") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.6] Dropped old values from table config sucessfully.");
}
if($mysqlcon->exec("UPDATE $dbname.job_check SET timestamp='".time()."' WHERE job_name='last_update'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.6] Stored timestamp of last update successfully.");
}
}
$currvers = set_new_version($mysqlcon,$dbname,$timezone,$newversion,$logpath);
old_files($timezone,$logpath);
check_chmod($timezone,$logpath,$lang);
check_config($mysqlcon,$dbname);
}
enter_logfile($logpath,$timezone,5,"Check Ranksystem database for updates [done]");
return $currvers;
}
<?PHP
function check_db($mysqlcon,$lang,$dbname,$timezone,$currvers,$logpath) {
$newversion = '1.2.7';
enter_logfile($logpath,$timezone,5,"Check Ranksystem database for updates...");
function set_new_version($mysqlcon,$dbname,$timezone,$newversion,$logpath) {
if($mysqlcon->exec("UPDATE $dbname.config set currvers='$newversion'") === false) {
enter_logfile($logpath,$timezone,1," An error happens due updating the Ranksystem Database:".print_r($mysqlcon->errorInfo(), true));
enter_logfile($logpath,$timezone,1," Check the database connection and properties in other/dbconfig.php and check also the database permissions.");
exit;
} else {
$currvers = $newversion;
enter_logfile($logpath,$timezone,4," Database successfully updated!");
return $currvers;
}
}
function check_chmod($timezone,$logpath,$lang) {
if(substr(sprintf('%o', fileperms(substr(__DIR__,0,-4).'tsicons/')), -3, 1)!='7') {
enter_logfile($logpath,$timezone,2,sprintf($lang['isntwichm'],'tsicons'));
}
if(substr(sprintf('%o', fileperms($logpath)), -3, 1)!='7') {
enter_logfile($logpath,$timezone,2,sprintf($lang['isntwichm'],'logs'));
}
if(substr(sprintf('%o', fileperms(substr(__DIR__,0,-4).'avatars/')), -3, 1)!='7') {
enter_logfile($logpath,$timezone,2,sprintf($lang['isntwichm'],'avatars'));
}
if(substr(sprintf('%o', fileperms(substr(__DIR__,0,-4).'update/')), -3, 1)!='7') {
enter_logfile($logpath,$timezone,2,sprintf($lang['isntwichm'],'update'));
}
}
function check_config($mysqlcon,$dbname) {
if(($dbdata = $mysqlcon->query("SELECT * FROM `$dbname`.`config`")->fetchAll()) === false) { } else {
if(count($dbdata) > 1) {
if($mysqlcon->exec("DELETE FROM `$dbname`.`config` WHERE `webuser` IS NULL") === false) { }
}
}
}
function old_files($timezone,$logpath) {
if(is_file(substr(__DIR__,0,-4).'install.php')) {
if(!unlink('install.php')) {
enter_logfile($logpath,$timezone,4,"Unnecessary file, please delete it from your webserver: install.php");
}
}
if(is_dir(substr(__DIR__,0,-4).'icons/')) {
if(!rmdir(substr(__DIR__,0,-4).'icons/')) {
enter_logfile($logpath,$timezone,4,"Unnecessary folder, please delete it from your webserver: icons/");
}
}
if(is_file(substr(__DIR__,0,-4).'libs/combined_stats.css')) {
if(!unlink(substr(__DIR__,0,-4).'libs/combined_stats.css')) {
enter_logfile($logpath,$timezone,4,"Unnecessary file, please delete it from your webserver: libs/combined_stats.css");
}
}
if(is_file(substr(__DIR__,0,-4).'libs/combined_stats.js')) {
if(!unlink(substr(__DIR__,0,-4).'libs/combined_stats.js')) {
enter_logfile($logpath,$timezone,4,"Unnecessary file, please delete it from your webserver: libs/combined_stats.js");
}
}
}
function check_writable($timezone,$logpath) {
enter_logfile($logpath,$timezone,5," Check files permissions...");
$counterr=0;
$scandir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(substr(__DIR__,0,-4)));
$files = array();
foreach ($scandir as $object) {
if(!strstr($object, '/.') && !strstr($object, '\.')) {
if (!$object->isDir()) {
if(!is_writable($object->getPathname())) {
enter_logfile($logpath,$timezone,3," File is not writeable ".$object);
echo "\nhier: ".$object."\n";
$counterr++;
}
} else {
if(!is_writable($object->getPathname())) {
enter_logfile($logpath,$timezone,3," Folder is not writeable ".$object);
$counterr++;
}
}
}
}
if($counterr!=0) {
enter_logfile($logpath,$timezone,1,"Please check the files pemissions. Shutting down!\n\n");
exit;
} else {
enter_logfile($logpath,$timezone,5," Check files permissions [done]");
}
}
if($currvers==$newversion) {
enter_logfile($logpath,$timezone,5," No newer version detected; Database check finished.");
old_files($timezone,$logpath);
check_chmod($timezone,$logpath,$lang);
check_config($mysqlcon,$dbname);
check_writable($timezone,$logpath);
} else {
enter_logfile($logpath,$timezone,4," Update the Ranksystem Database to new version...");
if(version_compare($currvers, '1.2.0', '<=')) {
if($mysqlcon->exec("ALTER TABLE `$dbname`.`stats_server` MODIFY COLUMN `server_name` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `server_platform` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `server_weblist` tinyint(1) NOT NULL default '0', MODIFY COLUMN `server_version` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `total_user` int(10) NOT NULL default '0', MODIFY COLUMN `country_nation_1` int(10) NOT NULL default '0', MODIFY COLUMN `country_nation_2` int(10) NOT NULL default '0', MODIFY COLUMN `country_nation_3` int(10) NOT NULL default '0', MODIFY COLUMN `country_nation_4` int(10) NOT NULL default '0', MODIFY COLUMN `country_nation_5` int(10) NOT NULL default '0', MODIFY COLUMN `country_nation_other` int(10) NOT NULL default '0', MODIFY COLUMN `platform_1` int(10) NOT NULL default '0', MODIFY COLUMN `platform_2` int(10) NOT NULL default '0', MODIFY COLUMN `platform_3` int(10) NOT NULL default '0', MODIFY COLUMN `platform_4` int(10) NOT NULL default '0', MODIFY COLUMN `platform_5` int(10) NOT NULL default '0', MODIFY COLUMN `platform_other` int(10) NOT NULL default '0', MODIFY COLUMN `version_1` int(10) NOT NULL default '0', MODIFY COLUMN `version_2` int(10) NOT NULL default '0', MODIFY COLUMN `version_3` int(10) NOT NULL default '0', MODIFY COLUMN `version_4` int(10) NOT NULL default '0', MODIFY COLUMN `version_5` int(10) NOT NULL default '0', MODIFY COLUMN `version_other` int(10) NOT NULL default '0', MODIFY COLUMN `server_status` tinyint(1) NOT NULL default '0', MODIFY COLUMN `server_free_slots` smallint(5) NOT NULL default '0', MODIFY COLUMN `server_used_slots` smallint(5) NOT NULL default '0', MODIFY COLUMN `server_channel_amount` smallint(5) NOT NULL default '0', MODIFY COLUMN `server_ping` smallint(5) NOT NULL default '0', MODIFY COLUMN `server_id` smallint(5) NOT NULL default '0', MODIFY COLUMN `server_pass` tinyint(1) NOT NULL default '0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table stats_server (part1) successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`stats_server` ADD (`user_today` int(10) NOT NULL default '0',`user_week` int(10) NOT NULL default '0',`user_month` int(10) NOT NULL default '0',`user_quarter` int(10) NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table stats_server (part2) successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`stats_user` MODIFY COLUMN `removed` tinyint(1) NOT NULL default '0', MODIFY COLUMN `rank` int(10) NOT NULL default '0', MODIFY COLUMN `count_week` int(10) NOT NULL default '0', MODIFY COLUMN `count_month` int(10) NOT NULL default '0', MODIFY COLUMN `idle_week` int(10) NOT NULL default '0', MODIFY COLUMN `idle_month` int(10) NOT NULL default '0', MODIFY COLUMN `achiev_count` tinyint(1) NOT NULL default '0', MODIFY COLUMN `achiev_time` int(10) NOT NULL default '0', MODIFY COLUMN `achiev_connects` smallint(5) NOT NULL default '0', MODIFY COLUMN `achiev_battles` tinyint(3) NOT NULL default '0', MODIFY COLUMN `achiev_time_perc` tinyint(3) NOT NULL default '0', MODIFY COLUMN `achiev_connects_perc` tinyint(3) NOT NULL default '0', MODIFY COLUMN `achiev_battles_perc` tinyint(3) NOT NULL default '0', MODIFY COLUMN `battles_total` tinyint(3) NOT NULL default '0', MODIFY COLUMN `battles_won` tinyint(3) NOT NULL default '0', MODIFY COLUMN `battles_lost` tinyint(3) NOT NULL default '0', MODIFY COLUMN `total_connections` smallint(5) NOT NULL default '0', MODIFY COLUMN `client_description` varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table stats_user successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`user` MODIFY COLUMN `cldbid` int(10) NOT NULL default '0', MODIFY COLUMN `count` int(10) NOT NULL default '0', MODIFY COLUMN `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `grpid` int(10) NOT NULL default '0', MODIFY COLUMN `nextup` int(10) NOT NULL default '0', MODIFY COLUMN `idle` int(10) NOT NULL default '0', MODIFY COLUMN `cldgroup` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `online` tinyint(1) NOT NULL default '0', MODIFY COLUMN `boosttime` int(10) NOT NULL default '0', MODIFY COLUMN `rank` int(10) NOT NULL default '0', MODIFY COLUMN `platform` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `nation` varchar(3) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `version` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `except` tinyint(1) NOT NULL default '0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table user successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`config` MODIFY COLUMN `webuser` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `webpass` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `tshost` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `tsquery` smallint(5) NOT NULL default '0', MODIFY COLUMN `tsvoice` smallint(5) NOT NULL default '0', MODIFY COLUMN `tsuser` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `tspass` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `language` char(2) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `queryname` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `queryname2` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `grouptime` varchar(5000) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `resetbydbchange` tinyint(1) NOT NULL default '0', MODIFY COLUMN `msgtouser` tinyint(1) NOT NULL default '0', MODIFY COLUMN `upcheck` tinyint(1) NOT NULL default '0', MODIFY COLUMN `uniqueid` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `updateinfotime` mediumint(6) NOT NULL default '0', MODIFY COLUMN `currvers` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `substridle` tinyint(1) NOT NULL default '0', MODIFY COLUMN `exceptuuid` varchar(999) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `exceptgroup` varchar(999) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `dateformat` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `showexcld` tinyint(1) NOT NULL default '0', MODIFY COLUMN `showcolcld` tinyint(1) NOT NULL default '0', MODIFY COLUMN `showcoluuid` tinyint(1) NOT NULL default '0', MODIFY COLUMN `showcoldbid` tinyint(1) NOT NULL default '0', MODIFY COLUMN `showcolot` tinyint(1) NOT NULL default '0', MODIFY COLUMN `showcolit` tinyint(1) NOT NULL default '0', MODIFY COLUMN `showcolat` tinyint(1) NOT NULL default '0', MODIFY COLUMN `showcolnx` tinyint(1) NOT NULL default '0', MODIFY COLUMN `showcolsg` tinyint(1) NOT NULL default '0', MODIFY COLUMN `showcolrg` tinyint(1) NOT NULL default '0', MODIFY COLUMN `showcolls` tinyint(1) NOT NULL default '0', MODIFY COLUMN `slowmode` mediumint(9) NOT NULL default '0', MODIFY COLUMN `cleanclients` tinyint(1) NOT NULL default '0', MODIFY COLUMN `cleanperiod` mediumint(9) NOT NULL default '0', MODIFY COLUMN `showhighest` tinyint(1) NOT NULL default '0', MODIFY COLUMN `boost` varchar(999) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `showcolas` tinyint(1) NOT NULL default '0', MODIFY COLUMN `defchid` int(10) NOT NULL default '0', MODIFY COLUMN `advancemode` tinyint(1) NOT NULL default '0', MODIFY COLUMN `count_access` tinyint(2) NOT NULL default '0', MODIFY COLUMN `ignoreidle` smallint(5) NOT NULL default '0', MODIFY COLUMN `exceptcid` varchar(999) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `rankupmsg` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `boost_mode` tinyint(1) NOT NULL default '0', MODIFY COLUMN `servernews` varchar(5000) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `nextupinfo` tinyint(1) NOT NULL default '0', MODIFY COLUMN `nextupinfomsg1` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `nextupinfomsg2` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `nextupinfomsg3` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `shownav` tinyint(1) NOT NULL default '0', MODIFY COLUMN `showgrpsince` tinyint(1) NOT NULL default '0', MODIFY COLUMN `resetexcept` tinyint(1) NOT NULL default '0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table config successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`server_usage` MODIFY COLUMN `clients` smallint(5) NOT NULL default '0', MODIFY COLUMN `channel` smallint(5) NOT NULL default '0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table server_usage successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`user_snapshot` MODIFY COLUMN `count` int(10) NOT NULL default '0', MODIFY COLUMN `idle` int(10) NOT NULL default '0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table user_snapshot successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`groups` MODIFY COLUMN `sgid` int(10) NOT NULL default '0' PRIMARY KEY, MODIFY COLUMN `sgidname` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Adjusted table groups successfully.");
}
if($mysqlcon->exec("CREATE TABLE `$dbname`.`stats_nations` (`nation` varchar(3) CHARACTER SET utf8 COLLATE utf8_unicode_ci,`count` int(10) NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Created table stats_nations successfully.");
}
if($mysqlcon->exec("CREATE TABLE `$dbname`.`stats_versions` (`version` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci,`count` int(10) NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Created table stats_versions successfully.");
}
if($mysqlcon->exec("CREATE TABLE `$dbname`.`stats_platforms` (`platform` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci,`count` int(10) NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.1] Created table stats_platforms successfully.");
}
}
if(version_compare($currvers, '1.2.1', '<=')) {
if($mysqlcon->exec("ALTER TABLE `$dbname`.`stats_user` ADD (`active_week` int(10) NOT NULL default '0',`active_month` int(10) NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.2] Adjusted table stats_user successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`config` ADD (`avatar_delay` smallint(5) UNSIGNED NOT NULL default '0')") === false) { } else {
if($mysqlcon->exec("UPDATE `$dbname`.`config` set `avatar_delay`='0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.2] Adjusted table config (part 1) successfully.");
}
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`config` MODIFY COLUMN `tsquery` smallint(5) UNSIGNED NOT NULL default '0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.2] Adjusted table config (part 2) successfully.");
}
if($mysqlcon->exec("CREATE TABLE `$dbname`.`addons_config` (`param` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci UNIQUE,`value` varchar(5000) CHARACTER SET utf8 COLLATE utf8_unicode_ci)") === false) { } else {
if($mysqlcon->exec("INSERT INTO `$dbname`.`addons_config` (`param`,`value`) VALUES ('assign_groups_active','0'),('assign_groups_groupids',''),('assign_groups_limit','')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.2] Created table addons_config successfully.");
}
}
if($mysqlcon->exec("CREATE TABLE `$dbname`.`addon_assign_groups` (`uuid` varchar(29) CHARACTER SET utf8 COLLATE utf8_unicode_ci,`grpids` varchar(1000) CHARACTER SET utf8 COLLATE utf8_unicode_ci)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.2] Created table addon_assign_groups successfully.");
}
}
if(version_compare($currvers, '1.2.2', '<=')) {
if($mysqlcon->exec("DELETE FROM `$dbname`.`groups`") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.3] Cleaned table groups successfully. (cause new icon folder tsicons - redownload)");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`config` MODIFY COLUMN `tsvoice` smallint(5) UNSIGNED NOT NULL default '0'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.3] Adjusted table config successfully.");
}
if($mysqlcon->exec("CREATE INDEX `snapshot_timestamp` ON `$dbname`.`user_snapshot` (`timestamp`)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.3] Recreated index on table user_snapshot successfully.");
}
if($mysqlcon->exec("CREATE INDEX `serverusage_timestamp` ON `$dbname`.`server_usage` (`timestamp`)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.3] Recreated index on table server_usage successfully.");
}
}
if(version_compare($currvers, '1.2.3', '<=')) {
if($mysqlcon->exec("ALTER TABLE `$dbname`.`config` MODIFY COLUMN `adminuuid` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Adjusted table config (part 1) successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`config` ADD (`registercid` mediumint(8) UNSIGNED NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Adjusted table config (part 2) successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`user` ADD (`cid` int(10) NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Adjusted table user successfully.");
}
if($mysqlcon->exec("CREATE INDEX `user_version` ON `$dbname`.`user` (`version`)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Create index 'user_version' on table user successfully.");
}
if($mysqlcon->exec("CREATE INDEX `user_cldbid` ON `$dbname`.`user` (`cldbid` ASC,`uuid`,`rank`)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Create index 'user_cldbid' on table user successfully.");
}
if($mysqlcon->exec("CREATE INDEX `user_online` ON `$dbname`.`user` (`online`,`lastseen`)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Create index 'user_online' on table user successfully.");
}
if($mysqlcon->exec("INSERT INTO `$dbname`.`job_check` (`job_name`) VALUES ('clean_db'),('clean_clients'),('calc_server_stats'),('runtime_check'),('last_update')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Set new values to table job_check successfully.");
}
if($mysqlcon->exec("DELETE FROM `$dbname`.`job_check` WHERE `job_name`='check_clean'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Removed old value 'check_clean' from table job_check successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`user_snapshot` ADD PRIMARY KEY (`timestamp`,`uuid`)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Added new primary key on table user_snapshot successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`stats_nations` ADD PRIMARY KEY (`nation`)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Added new primary key on table stats_nations successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`stats_platforms` ADD PRIMARY KEY (`platform`)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Added new primary key on table stats_platforms successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`stats_versions` ADD PRIMARY KEY (`version`)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.4] Added new primary key on table stats_versions successfully.");
}
}
if(version_compare($currvers, '1.2.4', '<=')) {
if($mysqlcon->exec("ALTER TABLE `$dbname`.`groups` MODIFY COLUMN `sgidname` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.5] Adjusted table groups successfully.");
}
}
if(version_compare($currvers, '1.2.5', '<=')) {
if($mysqlcon->exec("INSERT INTO `$dbname`.`job_check` (`job_name`) VALUES ('last_update')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.6] Set missed value to table job_check successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`config` DROP COLUMN `upcheck`, DROP COLUMN `uniqueid`, DROP COLUMN `updateinfotime`") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.6] Dropped old values from table config sucessfully.");
}
}
if(version_compare($currvers, '1.2.6', '<=')) {
if($mysqlcon->exec("CREATE TABLE `$dbname`.`admin_addtime` (`uuid` varchar(29) CHARACTER SET utf8 COLLATE utf8_unicode_ci,`timestamp` bigint(11) NOT NULL default '0',`timecount` int(10) NOT NULL default '0', PRIMARY KEY (`uuid`,`timestamp`))") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.7] Created table admin_addtime successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`user` DROP COLUMN `ip`") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.7] Dropped client ip from table user sucessfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`config` MODIFY COLUMN `timezone` varchar(35) CHARACTER SET utf8 COLLATE utf8_unicode_ci, MODIFY COLUMN `queryname` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci, MODIFY COLUMN `queryname2` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci, MODIFY COLUMN `rankupmsg` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci, MODIFY COLUMN `servernews` varchar(5000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci, MODIFY COLUMN `nextupinfomsg1` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci, MODIFY COLUMN `nextupinfomsg2` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci, MODIFY COLUMN `nextupinfomsg3` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.7] Adjusted table config (part 1) successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`config` ADD (`iphash` tinyint(1) NOT NULL default '0')") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.7] Adjusted table config (part 2) successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`groups` MODIFY COLUMN `sgidname` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.7] Adjusted table groups successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`stats_server` MODIFY COLUMN `server_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.7] Adjusted table stats_server successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`stats_user` MODIFY COLUMN `client_description` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.7] Adjusted table stats_user successfully.");
}
if($mysqlcon->exec("ALTER TABLE `$dbname`.`user` MODIFY COLUMN `name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.7] Adjusted table user successfully.");
}
if($mysqlcon->exec("CREATE TABLE `$dbname`.`user_iphash` (`uuid` varchar(29) CHARACTER SET utf8 COLLATE utf8_unicode_ci PRIMARY KEY,`iphash` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci,`ip` varchar(39) CHARACTER SET utf8 COLLATE utf8_unicode_ci)") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.7] Created table user_iphash successfully.");
}
if($mysqlcon->exec("UPDATE `$dbname`.`job_check` SET `timestamp`='".time()."' WHERE `job_name`='last_update'") === false) { } else {
enter_logfile($logpath,$timezone,4," [1.2.7] Stored timestamp of last update successfully.");
}
}
$currvers = set_new_version($mysqlcon,$dbname,$timezone,$newversion,$logpath);
old_files($timezone,$logpath);
check_chmod($timezone,$logpath,$lang);
check_config($mysqlcon,$dbname);
}
enter_logfile($logpath,$timezone,5,"Check Ranksystem database for updates [done]");
return $currvers;
}
?>

View File

@@ -1,93 +1,97 @@
<?PHP
function clean($ts3,$mysqlcon,$lang,$dbname,$slowmode,$timezone,$cleanclients,$cleanperiod,$logpath,$select_arr) {
$nowtime = time();
$sqlexec = '';
// clean old clients out of the database
if($select_arr['job_check']['clean_clients']['timestamp'] < ($nowtime - $cleanperiod)) {
if ($cleanclients == 1) {
enter_logfile($logpath,$timezone,4,$lang['clean']);
$start = $countdel = $countts = 0;
$break=200;
$count_tsuser['count'] = 0;
$clientdblist=array();
while($getclientdblist=$ts3->clientListDb($start, $break)) {
$clientdblist=array_merge($clientdblist, $getclientdblist);
$start=$start+$break;
$count_tsuser=array_shift($getclientdblist);
if($count_tsuser['count'] <= $start) {
break;
}
usleep($slowmode);
}
foreach($clientdblist as $uuidts) {
$single_uuid = $uuidts['client_unique_identifier']->toString();
$uidarrts[$single_uuid]= 1;
}
unset($clientdblist);
foreach($select_arr['all_user'] as $uuid => $value) {
if(isset($uidarrts[$uuid])) {
$countts++;
} else {
$deleteuuids[] = $uuid;
$countdel++;
}
}
unset($uidarrts);
enter_logfile($logpath,$timezone,4," ".sprintf($lang['cleants'], $countts, $count_tsuser['count']));
enter_logfile($logpath,$timezone,4," ".sprintf($lang['cleanrs'], count($select_arr['all_user'])));
if(isset($deleteuuids)) {
$alldeldata = '';
$fsfilelist = opendir(substr(__DIR__,0,-4).'avatars/');
while (false !== ($fsfile = readdir($fsfilelist))) {
if ($fsfile != '.' && $fsfile != '..') {
$fsfilelistarray[$fsfile] = filemtime(substr(__DIR__,0,-4).'avatars/'.$fsfile);
}
}
unset($fsfilelist);
$avatarfilepath = substr(__DIR__,0,-4).'avatars/';
$convert = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p');
foreach ($deleteuuids as $uuid) {
$alldeldata = $alldeldata . "'" . $uuid . "',";
$uuidasbase16 = '';
for ($i = 0; $i < 20; $i++) {
$char = ord(substr(base64_decode($uuid), $i, 1));
$uuidasbase16 .= $convert[($char & 0xF0) >> 4];
$uuidasbase16 .= $convert[$char & 0x0F];
}
if (isset($fsfilelistarray[$uuidasbase16.'.png'])) {
if(unlink($avatarfilepath.$uuidasbase16.'.png') === false) {
enter_logfile($logpath,$timezone,2," ".sprintf($lang['clean0002'], $uuidasbase16, $uuid).' '.sprintf($lang['errperm'], 'avatars'));
} else {
enter_logfile($logpath,$timezone,4," ".sprintf($lang['clean0001'], $uuidasbase16, $uuid));
}
}
}
unset($$deleteuuids);
$alldeldata = substr($alldeldata, 0, -1);
$alldeldata = "(".$alldeldata.")";
if ($alldeldata != '') {
$sqlexec .= "UPDATE $dbname.job_check SET timestamp='$nowtime' WHERE job_name='clean_clients'; UPDATE $dbname.stats_user AS t LEFT JOIN $dbname.user AS u ON t.uuid=u.uuid SET t.removed='1' WHERE u.uuid IS NULL; DELETE FROM $dbname.user WHERE uuid IN $alldeldata; ";
enter_logfile($logpath,$timezone,4," ".sprintf($lang['cleandel'], $countdel));
unset($$alldeldata);
}
} else {
enter_logfile($logpath,$timezone,4," ".$lang['cleanno']);
$sqlexec .= "UPDATE $dbname.job_check SET timestamp='$nowtime' WHERE job_name='clean_clients'; ";
}
} else {
enter_logfile($logpath,$timezone,4,$lang['clean0004']);
$sqlexec .= "UPDATE $dbname.job_check SET timestamp='$nowtime' WHERE job_name='clean_clients'; ";
}
}
// clean usersnaps older then 1 month + clean old server usage - older then a year
if ($select_arr['job_check']['clean_db']['timestamp'] < ($nowtime - 86400)) {
$sqlexec .= "DELETE a FROM $dbname.user_snapshot AS a CROSS JOIN(SELECT DISTINCT(timestamp) FROM $dbname.user_snapshot ORDER BY timestamp DESC LIMIT 1000 OFFSET 121) AS b WHERE a.timestamp=b.timestamp; DELETE FROM $dbname.server_usage WHERE timestamp < (UNIX_TIMESTAMP() - 31536000); DELETE b FROM $dbname.user a RIGHT JOIN $dbname.stats_user b ON a.uuid = b.uuid WHERE a.uuid IS NULL; UPDATE $dbname.job_check SET timestamp='$nowtime' WHERE job_name='clean_db'; ";
enter_logfile($logpath,$timezone,4,$lang['clean0003']);
}
return($sqlexec);
}
<?PHP
function clean($ts3,$mysqlcon,$lang,$dbname,$slowmode,$timezone,$cleanclients,$cleanperiod,$logpath,$select_arr) {
$nowtime = time();
$sqlexec = '';
// clean old clients out of the database
if($select_arr['job_check']['clean_clients']['timestamp'] < ($nowtime - $cleanperiod)) {
if ($cleanclients == 1) {
enter_logfile($logpath,$timezone,4,$lang['clean']);
$start = $countdel = $countts = 0;
$break=200;
$count_tsuser['count'] = 0;
$clientdblist=array();
while($getclientdblist=$ts3->clientListDb($start, $break)) {
$clientdblist=array_merge($clientdblist, $getclientdblist);
$start=$start+$break;
$count_tsuser=array_shift($getclientdblist);
if($count_tsuser['count'] <= $start) {
break;
}
usleep($slowmode);
}
foreach($clientdblist as $uuidts) {
$single_uuid = $uuidts['client_unique_identifier']->toString();
$uidarrts[$single_uuid]= 1;
}
unset($clientdblist);
foreach($select_arr['all_user'] as $uuid => $value) {
if(isset($uidarrts[$uuid])) {
$countts++;
} else {
$deleteuuids[] = $uuid;
$countdel++;
}
}
unset($uidarrts);
enter_logfile($logpath,$timezone,4," ".sprintf($lang['cleants'], $countts, $count_tsuser['count']));
enter_logfile($logpath,$timezone,4," ".sprintf($lang['cleanrs'], count($select_arr['all_user'])));
if(isset($deleteuuids)) {
$alldeldata = '';
$fsfilelist = opendir(substr(__DIR__,0,-4).'avatars/');
while (false !== ($fsfile = readdir($fsfilelist))) {
if ($fsfile != '.' && $fsfile != '..') {
$fsfilelistarray[$fsfile] = filemtime(substr(__DIR__,0,-4).'avatars/'.$fsfile);
}
}
unset($fsfilelist);
$avatarfilepath = substr(__DIR__,0,-4).'avatars/';
$convert = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p');
foreach ($deleteuuids as $uuid) {
$alldeldata = $alldeldata . "'" . $uuid . "',";
$uuidasbase16 = '';
for ($i = 0; $i < 20; $i++) {
$char = ord(substr(base64_decode($uuid), $i, 1));
$uuidasbase16 .= $convert[($char & 0xF0) >> 4];
$uuidasbase16 .= $convert[$char & 0x0F];
}
if (isset($fsfilelistarray[$uuidasbase16.'.png'])) {
if(unlink($avatarfilepath.$uuidasbase16.'.png') === false) {
enter_logfile($logpath,$timezone,2," ".sprintf($lang['clean0002'], $uuidasbase16, $uuid).' '.sprintf($lang['errperm'], 'avatars'));
} else {
enter_logfile($logpath,$timezone,4," ".sprintf($lang['clean0001'], $uuidasbase16, $uuid));
}
}
}
unset($$deleteuuids);
$alldeldata = substr($alldeldata, 0, -1);
$alldeldata = "(".$alldeldata.")";
if ($alldeldata != '') {
$sqlexec .= "UPDATE `$dbname`.`job_check` SET `timestamp`='$nowtime' WHERE `job_name`='clean_clients'; UPDATE `$dbname`.`stats_user` AS `t` LEFT JOIN `$dbname`.`user` AS `u` ON `t`.`uuid`=`u`.`uuid` SET `t`.`removed`='1' WHERE `u`.`uuid` IS NULL; DELETE FROM `$dbname`.`user` WHERE `uuid` IN $alldeldata; ";
enter_logfile($logpath,$timezone,4," ".sprintf($lang['cleandel'], $countdel));
unset($$alldeldata);
}
} else {
enter_logfile($logpath,$timezone,4," ".$lang['cleanno']);
$sqlexec .= "UPDATE `$dbname`.`job_check` SET `timestamp`='$nowtime' WHERE `job_name`='clean_clients'; ";
}
} else {
enter_logfile($logpath,$timezone,4,$lang['clean0004']);
$sqlexec .= "UPDATE `$dbname`.`job_check` SET `timestamp`='$nowtime' WHERE `job_name`='clean_clients'; ";
}
}
// clean usersnaps older then 1 month + clean old server usage - older then a year
if ($select_arr['job_check']['clean_db']['timestamp'] < ($nowtime - 86400)) {
$sqlexec .= "DELETE `a` FROM `$dbname`.`user_snapshot` AS `a` CROSS JOIN(SELECT DISTINCT(`timestamp`) FROM `$dbname`.`user_snapshot` ORDER BY `timestamp` DESC LIMIT 1000 OFFSET 121) AS `b` WHERE `a`.`timestamp`=`b`.`timestamp`; DELETE FROM `$dbname`.`server_usage` WHERE `timestamp` < (UNIX_TIMESTAMP() - 31536000); DELETE `b` FROM `$dbname`.`user` AS `a` RIGHT JOIN `$dbname`.`stats_user` AS `b` ON `a`.`uuid`=`b`.`uuid` WHERE `a`.`uuid` IS NULL; UPDATE `$dbname`.`job_check` SET `timestamp`='$nowtime' WHERE `job_name`='clean_db'; ";
enter_logfile($logpath,$timezone,4,$lang['clean0003']);
}
// delete IP address of offline user
$sqlexec .= "DELETE `a` FROM `$dbname`.`user_iphash` AS `a` INNER JOIN `$dbname`.`user` AS `b` ON `a`.`uuid`=`b`.`uuid` WHERE `b`.`online`!=1; ";
return($sqlexec);
}
?>

63
jobs/event_userenter.php Normal file
View File

@@ -0,0 +1,63 @@
<?PHP
function event_userenter(TeamSpeak3_Adapter_ServerQuery_Event $event, TeamSpeak3_Node_Host $host) {
global $logpath, $timezone, $mysqlcon, $dbname, $slowmode, $iphash, $sqlexec2;
if($event['client_type'] == 0) {
#enter_logfile($logpath,$timezone,6,"User ".$event['client_nickname']." (uuid: ".$event['client_unique_identifier'].") connected to the server.");
try {
usleep($slowmode);
$clientinfo = $host->serverGetSelected()->clientInfoDb($event["client_database_id"]);
if($clientinfo['client_lastip'] == NULL) { //TeamSpeak sucks sometimes and gives a empty result
enter_logfile($logpath,$timezone,4,"event_userenter: TeamSpeak gives an empty value for the IP address of ".$event['client_nickname']." (uuid: ".$event['client_unique_identifier'].").. retry in 0,1 seconds..");
usleep(100000);
try {
unset($clientinfo);
usleep($slowmode);
$clientinfo = $host->serverGetSelected()->clientInfoDb($event["client_database_id"]);
if($clientinfo['client_lastip'] == NULL) {
enter_logfile($logpath,$timezone,4,"event_userenter: TeamSpeak gives an empty value for the IP address of ".$event['client_nickname']." (uuid: ".$event['client_unique_identifier'].").. retry in 0,5 seconds..");
usleep(500000);
try {
unset($clientinfo);
usleep($slowmode);
$clientinfo = $host->serverGetSelected()->clientInfoDb($event["client_database_id"]);
if($clientinfo['client_lastip'] == NULL) {
enter_logfile($logpath,$timezone,2,"event_userenter: Fuck it.. TeamSpeak gives an empty value for the IP address of of ".$event['client_nickname']." (uuid: ".$event['client_unique_identifier'].").");
return 0;
}
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"event_userenter 4:".$e->getCode().': '.$e->getMessage());
}
}
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"event_userenter 4:".$e->getCode().': '.$e->getMessage());
}
}
if($iphash == 1) {
$hash = password_hash($clientinfo['client_lastip'], PASSWORD_DEFAULT);
$ip = '';
} else {
$hash = '';
$ip = $clientinfo['client_lastip'];
}
#enter_logfile($logpath,$timezone,6,"Event Userenter: Users IP-hash: ".$hash." IP: ".$ip);
if(($sqlhashs = $mysqlcon->query("SELECT * FROM `$dbname`.`user_iphash`")->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE)) === false) {
enter_logfile($logpath,$timezone,2,"event_userenter 1:".print_r($mysqlcon->errorInfo(), true));
}
#enter_logfile($logpath,$timezone,6,"User-hash-Table: ".print_r($sqlhashs, true));
$uuid = htmlspecialchars($event['client_unique_identifier'], ENT_QUOTES);
if(isset($sqlhashs[$uuid])) {
#enter_logfile($logpath,$timezone,6,"UPDATE $dbname.user_iphash SET iphash='".$hash."', ip='".$ip."' WHERE uuid='".$event['client_unique_identifier']."'");
$sqlexec2 .= "UPDATE `$dbname`.`user_iphash` SET `iphash`='".$hash."',`ip`='".$ip."' WHERE `uuid`='".$event['client_unique_identifier']."'; ";
} else {
#enter_logfile($logpath,$timezone,6,"INSERT INTO $dbname.user_iphash (uuid,iphash,ip) VALUES ('".$event['client_unique_identifier']."','".$hash."','".$ip."')");
$sqlexec2 .= "INSERT INTO `$dbname`.`user_iphash` (`uuid`,`iphash`,`ip`) VALUES ('".$event['client_unique_identifier']."','".$hash."','".$ip."'); ";
}
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"event_userenter 4:".$e->getCode().': '.$e->getMessage());
}
}
}
?>

View File

@@ -1,45 +1,45 @@
<?PHP
function get_avatars($ts3,$slowmode,$timezone,$logpath,$avatar_delay) {
try {
usleep($slowmode);
$tsfilelist = $ts3->channelFileList($cid="0", $cpw="", $path="/");
} catch (Exception $e) {
if ($e->getCode() != 1281) {
enter_logfile($logpath,$timezone,2,"get_avatars 1:".$e->getCode().': '."Error while getting avatarlist: ".$e->getMessage());
}
}
$fsfilelist = opendir(substr(__DIR__,0,-4).'avatars/');
while (false !== ($fsfile = readdir($fsfilelist))) {
if ($fsfile != '.' && $fsfile != '..') {
$fsfilelistarray[$fsfile] = filemtime(substr(__DIR__,0,-4).'avatars/'.$fsfile);
}
}
unset($fsfilelist);
if (isset($tsfilelist)) {
foreach($tsfilelist as $tsfile) {
$fullfilename = '/'.$tsfile['name'];
$uuidasbase16 = substr($tsfile['name'],7);
if (!isset($fsfilelistarray[$uuidasbase16.'.png']) || ($tsfile['datetime'] - $avatar_delay) > $fsfilelistarray[$uuidasbase16.'.png']) {
if (substr($tsfile['name'],0,7) == 'avatar_') {
try {
check_shutdown($timezone,$logpath); usleep($slowmode);
$avatar = $ts3->transferInitDownload($clientftfid="5",$cid="0",$name=$fullfilename,$cpw="", $seekpos=0);
$transfer = TeamSpeak3::factory("filetransfer://" . $avatar["host"] . ":" . $avatar["port"]);
$tsfile = $transfer->download($avatar["ftkey"], $avatar["size"]);
$avatarfilepath = substr(__DIR__,0,-4).'avatars/'.$uuidasbase16.'.png';
enter_logfile($logpath,$timezone,5,"Download avatar: ".$fullfilename);
if(file_put_contents($avatarfilepath, $tsfile) === false) {
enter_logfile($logpath,$timezone,2,"Error while writing out the avatar. Please check the permission for the folder 'avatars'");
}
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"get_avatars 2:".$e->getCode().': '."Error while downloading avatar: ".$e->getMessage());
}
}
}
}
unset($fsfilelistarray);
}
}
<?PHP
function get_avatars($ts3,$slowmode,$timezone,$logpath,$avatar_delay) {
try {
usleep($slowmode);
$tsfilelist = $ts3->channelFileList($cid="0", $cpw="", $path="/");
} catch (Exception $e) {
if ($e->getCode() != 1281) {
enter_logfile($logpath,$timezone,2,"get_avatars 1:".$e->getCode().': '."Error while getting avatarlist: ".$e->getMessage());
}
}
$fsfilelist = opendir(substr(__DIR__,0,-4).'avatars/');
while (false !== ($fsfile = readdir($fsfilelist))) {
if ($fsfile != '.' && $fsfile != '..') {
$fsfilelistarray[$fsfile] = filemtime(substr(__DIR__,0,-4).'avatars/'.$fsfile);
}
}
unset($fsfilelist);
if (isset($tsfilelist)) {
foreach($tsfilelist as $tsfile) {
$fullfilename = '/'.$tsfile['name'];
$uuidasbase16 = substr($tsfile['name'],7);
if (!isset($fsfilelistarray[$uuidasbase16.'.png']) || ($tsfile['datetime'] - $avatar_delay) > $fsfilelistarray[$uuidasbase16.'.png']) {
if (substr($tsfile['name'],0,7) == 'avatar_') {
try {
check_shutdown($timezone,$logpath); usleep($slowmode);
$avatar = $ts3->transferInitDownload($clientftfid="5",$cid="0",$name=$fullfilename,$cpw="", $seekpos=0);
$transfer = TeamSpeak3::factory("filetransfer://" . $avatar["host"] . ":" . $avatar["port"]);
$tsfile = $transfer->download($avatar["ftkey"], $avatar["size"]);
$avatarfilepath = substr(__DIR__,0,-4).'avatars/'.$uuidasbase16.'.png';
enter_logfile($logpath,$timezone,5,"Download avatar: ".$fullfilename);
if(file_put_contents($avatarfilepath, $tsfile) === false) {
enter_logfile($logpath,$timezone,2,"Error while writing out the avatar. Please check the permission for the folder 'avatars'");
}
}
catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"get_avatars 2:".$e->getCode().': '."Error while downloading avatar: ".$e->getMessage());
}
}
}
}
unset($fsfilelistarray);
}
}
?>

View File

@@ -1,181 +1,181 @@
<?PHP
function handle_messages(TeamSpeak3_Adapter_ServerQuery_Event $event, TeamSpeak3_Node_Host $host) {
global $lang, $logpath, $timezone, $nextupinfo, $nextupinfomsg1, $nextupinfomsg2, $nextupinfomsg3, $mysqlcon, $dbname, $grouptime, $substridle, $slowmode, $currvers, $newversion, $adminuuid, $phpcommand;
if($host->whoami()["client_unique_identifier"] != $event["invokeruid"]) { //check whoami need to slowmode or is already stored?
$uuid = $event["invokeruid"];
$admin = 0;
foreach ($adminuuid as $auuid) {
if ($uuid == $auuid) {
$admin = 1;
}
}
if((strstr($event["msg"], '!nextup') || strstr($event["msg"], '!next')) && $nextupinfo != 0) {
//enter_logfile($logpath,$timezone,6,"Client ".$event["invokername"]." (".$event["invokeruid"].") sent textmessage: ".$event["msg"]);
if(($user = $mysqlcon->query("SELECT count,nextup,idle,except,name FROM $dbname.user WHERE uuid='$uuid'")->fetch()) === false) {
enter_logfile($logpath,$timezone,2,"handle_messages 1:".print_r($mysqlcon->errorInfo(), true));
}
if(($sqlhisgroup = $mysqlcon->query("SELECT sgid,sgidname FROM $dbname.groups")->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE)) === false) {
enter_logfile($logpath,$timezone,2,"handle_messages 2:".print_r($mysqlcon->errorInfo(), true));
}
ksort($grouptime);
$countgrp = count($grouptime);
$grpcount=0;
foreach ($grouptime as $time => $groupid) {
if ($substridle == 1) {
$nextup = $time - $user['count'] + $user['idle'];
} else {
$nextup = $time - $user['count'];
}
$dtF = new DateTime("@0");
$dtT = new DateTime("@$nextup");
$days = $dtF->diff($dtT)->format('%a');
$hours = $dtF->diff($dtT)->format('%h');
$mins = $dtF->diff($dtT)->format('%i');
$secs = $dtF->diff($dtT)->format('%s');
$name = $user['name'];
$grpcount++;
if ($nextup > 0 && $nextup < $time || $grpcount == $countgrp && $nextup <= 0) {
check_shutdown($timezone,$logpath); usleep($slowmode);
if ($grpcount == $countgrp && $nextup <= 0) {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message(sprintf($nextupinfomsg2, $days, $hours, $mins, $secs, $sqlhisgroup[$groupid]['sgidname'], $name));
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 3:".$e->getCode().': '.$e->getMessage());
}
} elseif ($user['except'] == 2 || $user['except'] == 3) {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message(sprintf($nextupinfomsg3, $days, $hours, $mins, $secs, $sqlhisgroup[$groupid]['sgidname'], $name));
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 4:".$e->getCode().': '.$e->getMessage());
}
} else {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message(sprintf($nextupinfomsg1, $days, $hours, $mins, $secs, $sqlhisgroup[$groupid]['sgidname'], $name));
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 5:".$e->getCode().': '.$e->getMessage());
}
}
if($nextupinfo == 1) {
break;
}
}
}
}
if(strstr($event["msg"], '!version')) {
if(version_compare(substr($newversion, 0, 5), substr($currvers, 0, 5), '>') && $newversion != '') {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message(sprintf($lang['upmsg'], $currvers, $newversion));
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 6:".$e->getCode().': '.$e->getMessage());
}
} else {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message(sprintf($lang['msg0001'], $currvers));
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 7:".$e->getCode().': '.$e->getMessage());
}
}
}
if(strstr($event["msg"], '!help') || strstr($event["msg"], '!info') || strstr($event["msg"], '!commands')) {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0002']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 8:".$e->getCode().': '.$e->getMessage());
}
}
if((strstr($event["msg"], '!shutdown') || strstr($event["msg"], '!quit') || strstr($event["msg"], '!stop')) && $admin == 1) {
enter_logfile($logpath,$timezone,5,sprintf($lang['msg0004'], $event["invokername"], $event["invokeruid"]));
$path = substr(__DIR__, 0, -4);
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0005']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 9:".$e->getCode().': '.$e->getMessage());
}
exec($phpcommand." ".$path."worker.php stop");
} elseif (strstr($event["msg"], '!shutdown') || strstr($event["msg"], '!quit') || strstr($event["msg"], '!stop')) {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0003']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 10:".$e->getCode().': '.$e->getMessage());
}
}
if((strstr($event["msg"], '!restart') || strstr($event["msg"], '!reboot')) && $admin == 1) {
enter_logfile($logpath,$timezone,5,sprintf($lang['msg0007'], $event["invokername"], $event["invokeruid"]));
$path = substr(__DIR__, 0, -4);
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0006']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 11:".$e->getCode().': '.$e->getMessage());
}
if (substr(php_uname(), 0, 7) == "Windows") {
exec("start ".$phpcommand." ".$path."worker.php restart");
} else {
exec($phpcommand." ".$path."worker.php restart > /dev/null 2>/dev/null &");
}
} elseif (strstr($event["msg"], '!restart') || strstr($event["msg"], '!reboot')) {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0003']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 12:".$e->getCode().': '.$e->getMessage());
}
}
if((strstr($event["msg"], '!checkupdate') || strstr($event["msg"], '!update')) && $admin == 1) {
if($mysqlcon->exec("UPDATE $dbname.job_check SET timestamp='0' WHERE job_name IN ('check_update','get_version','calc_server_stats')") === false) {
enter_logfile($logpath,$timezone,4,"handle_messages 13:".print_r($mysqlcon->errorInfo(), true));
}
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0008']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 14:".$e->getCode().': '.$e->getMessage());
}
} elseif(strstr($event["msg"], '!checkupdate') || strstr($event["msg"], '!update')) {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0003']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 15:".$e->getCode().': '.$e->getMessage());
}
}
if((strstr($event["msg"], '!clean')) && $admin == 1) {
if($mysqlcon->exec("UPDATE $dbname.job_check SET timestamp='0' WHERE job_name IN ('clean_db','clean_clients')") === false) {
enter_logfile($logpath,$timezone,4,"handle_messages 13:".print_r($mysqlcon->errorInfo(), true));
}
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0009']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 14:".$e->getCode().': '.$e->getMessage());
}
} elseif(strstr($event["msg"], '!clean')) {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0003']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 15:".$e->getCode().': '.$e->getMessage());
}
}
}
}
<?PHP
function handle_messages(TeamSpeak3_Adapter_ServerQuery_Event $event, TeamSpeak3_Node_Host $host) {
global $lang, $logpath, $timezone, $nextupinfo, $nextupinfomsg1, $nextupinfomsg2, $nextupinfomsg3, $mysqlcon, $dbname, $grouptime, $substridle, $slowmode, $currvers, $newversion, $adminuuid, $phpcommand;
if($host->whoami()["client_unique_identifier"] != $event["invokeruid"]) {
$uuid = $event["invokeruid"];
$admin = 0;
foreach ($adminuuid as $auuid) {
if ($uuid == $auuid) {
$admin = 1;
}
}
if((strstr($event["msg"], '!nextup') || strstr($event["msg"], '!next')) && $nextupinfo != 0) {
//enter_logfile($logpath,$timezone,6,"Client ".$event["invokername"]." (".$event["invokeruid"].") sent textmessage: ".$event["msg"]);
if(($user = $mysqlcon->query("SELECT `count`,`nextup`,`idle`,`except`,`name` FROM `$dbname`.`user` WHERE `uuid`='$uuid'")->fetch()) === false) {
enter_logfile($logpath,$timezone,2,"handle_messages 1:".print_r($mysqlcon->errorInfo(), true));
}
if(($sqlhisgroup = $mysqlcon->query("SELECT `sgid`,`sgidname` FROM `$dbname`.`groups`")->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE)) === false) {
enter_logfile($logpath,$timezone,2,"handle_messages 2:".print_r($mysqlcon->errorInfo(), true));
}
ksort($grouptime);
$countgrp = count($grouptime);
$grpcount=0;
foreach ($grouptime as $time => $groupid) {
if ($substridle == 1) {
$nextup = $time - $user['count'] + $user['idle'];
} else {
$nextup = $time - $user['count'];
}
$dtF = new DateTime("@0");
$dtT = new DateTime("@$nextup");
$days = $dtF->diff($dtT)->format('%a');
$hours = $dtF->diff($dtT)->format('%h');
$mins = $dtF->diff($dtT)->format('%i');
$secs = $dtF->diff($dtT)->format('%s');
$name = $user['name'];
$grpcount++;
if ($nextup > 0 && $nextup < $time || $grpcount == $countgrp && $nextup <= 0) {
check_shutdown($timezone,$logpath); usleep($slowmode);
if ($grpcount == $countgrp && $nextup <= 0) {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message(sprintf($nextupinfomsg2, $days, $hours, $mins, $secs, $sqlhisgroup[$groupid]['sgidname'], $name));
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 3:".$e->getCode().': '.$e->getMessage());
}
} elseif ($user['except'] == 2 || $user['except'] == 3) {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message(sprintf($nextupinfomsg3, $days, $hours, $mins, $secs, $sqlhisgroup[$groupid]['sgidname'], $name));
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 4:".$e->getCode().': '.$e->getMessage());
}
} else {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message(sprintf($nextupinfomsg1, $days, $hours, $mins, $secs, $sqlhisgroup[$groupid]['sgidname'], $name));
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 5:".$e->getCode().': '.$e->getMessage());
}
}
if($nextupinfo == 1) {
break;
}
}
}
}
if(strstr($event["msg"], '!version')) {
if(version_compare(substr($newversion, 0, 5), substr($currvers, 0, 5), '>') && $newversion != '') {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message(sprintf($lang['upmsg'], $currvers, $newversion));
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 6:".$e->getCode().': '.$e->getMessage());
}
} else {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message(sprintf($lang['msg0001'], $currvers));
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 7:".$e->getCode().': '.$e->getMessage());
}
}
}
if(strstr($event["msg"], '!help') || strstr($event["msg"], '!info') || strstr($event["msg"], '!commands')) {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0002']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 8:".$e->getCode().': '.$e->getMessage());
}
}
if((strstr($event["msg"], '!shutdown') || strstr($event["msg"], '!quit') || strstr($event["msg"], '!stop')) && $admin == 1) {
enter_logfile($logpath,$timezone,5,sprintf($lang['msg0004'], $event["invokername"], $event["invokeruid"]));
$path = substr(__DIR__, 0, -4);
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0005']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 9:".$e->getCode().': '.$e->getMessage());
}
exec($phpcommand." ".$path."worker.php stop");
} elseif (strstr($event["msg"], '!shutdown') || strstr($event["msg"], '!quit') || strstr($event["msg"], '!stop')) {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0003']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 10:".$e->getCode().': '.$e->getMessage());
}
}
if((strstr($event["msg"], '!restart') || strstr($event["msg"], '!reboot')) && $admin == 1) {
enter_logfile($logpath,$timezone,5,sprintf($lang['msg0007'], $event["invokername"], $event["invokeruid"]));
$path = substr(__DIR__, 0, -4);
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0006']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 11:".$e->getCode().': '.$e->getMessage());
}
if (substr(php_uname(), 0, 7) == "Windows") {
exec("start ".$phpcommand." ".$path."worker.php restart");
} else {
exec($phpcommand." ".$path."worker.php restart > /dev/null 2>/dev/null &");
}
} elseif (strstr($event["msg"], '!restart') || strstr($event["msg"], '!reboot')) {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0003']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 12:".$e->getCode().': '.$e->getMessage());
}
}
if((strstr($event["msg"], '!checkupdate') || strstr($event["msg"], '!update')) && $admin == 1) {
if($mysqlcon->exec("UPDATE `$dbname`.`job_check` SET `timestamp`='0' WHERE `job_name` IN ('check_update','get_version','calc_server_stats')") === false) {
enter_logfile($logpath,$timezone,4,"handle_messages 13:".print_r($mysqlcon->errorInfo(), true));
}
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0008']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 14:".$e->getCode().': '.$e->getMessage());
}
} elseif(strstr($event["msg"], '!checkupdate') || strstr($event["msg"], '!update')) {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0003']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 15:".$e->getCode().': '.$e->getMessage());
}
}
if((strstr($event["msg"], '!clean')) && $admin == 1) {
if($mysqlcon->exec("UPDATE `$dbname`.`job_check` SET `timestamp`='0' WHERE `job_name` IN ('clean_db','clean_clients')") === false) {
enter_logfile($logpath,$timezone,4,"handle_messages 13:".print_r($mysqlcon->errorInfo(), true));
}
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0009']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 14:".$e->getCode().': '.$e->getMessage());
}
} elseif(strstr($event["msg"], '!clean')) {
usleep($slowmode);
try {
$host->serverGetSelected()->clientGetByUid($event["invokeruid"])->message($lang['msg0003']);
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,"handle_messages 15:".$e->getCode().': '.$e->getMessage());
}
}
}
}
?>

View File

@@ -1,193 +1,145 @@
<?PHP
function update_groups($ts3,$mysqlcon,$lang,$dbname,$slowmode,$timezone,$serverinfo,$logpath,$grouptime,$boostarr,$exceptgroup,$select_arr,$nobreak = 0) {
$sqlexec = '';
try {
usleep($slowmode);
$iconlist = $ts3->channelFileList($cid="0", $cpw="", $path="/icons/");
} catch (Exception $e) {
if ($e->getCode() != 1281) {
enter_logfile($logpath,$timezone,2,$lang['errorts3'].$e->getCode().': '.$lang['errgrplist'].$e->getMessage());
}
}
foreach($iconlist as $icon) {
$iconid = "i".substr($icon['name'], 5);
$iconarr[$iconid] = $icon['datetime'];
}
try {
usleep($slowmode);
$ts3->serverGroupListReset();
$ts3groups = $ts3->serverGroupList();
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,$lang['errorts3'].$e->getCode().': '.$lang['errgrplist'].$e->getMessage());
}
// ServerIcon
if ($serverinfo['virtualserver_icon_id'] < 0) {
$sIconId = (pow(2, 32)) - ($serverinfo['virtualserver_icon_id'] * -1);
} else {
$sIconId = $serverinfo['virtualserver_icon_id'];
}
$sIconFile = 0;
if (!isset($select_arr['groups']['0']) || $select_arr['groups']['0']['iconid'] != $sIconId || $iconarr["i".$sIconId] > $select_arr['groups']['0']['icondate']) {
if($sIconId > 600) {
try {
usleep($slowmode);
enter_logfile($logpath,$timezone,5,$lang['upgrp0002']);
$sIconFile = $ts3->iconDownload();
if(file_put_contents(substr(dirname(__FILE__),0,-4) . "tsicons/servericon.png", $sIconFile) === false) {
enter_logfile($logpath,$timezone,2,$lang['upgrp0003'].' '.sprintf($lang['errperm'], 'tsicons'));
}
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,$lang['errorts3'].$e->getCode().'; '.$lang['upgrp0004'].$e->getMessage());
}
} elseif($sIconId == 0) {
if(file_exists(substr(dirname(__FILE__),0,-4) . "tsicons/servericon.png")) {
if(unlink(substr(dirname(__FILE__),0,-4) . "tsicons/servericon.png") === false) {
enter_logfile($logpath,$timezone,2,$lang['upgrp0005'].' '.sprintf($lang['errperm'], 'tsicons'));
} else {
enter_logfile($logpath,$timezone,5,$lang['upgrp0006']);
}
}
$iconarr["i".$sIconId] = 0;
}
if (!isset($select_arr['groups']['0'])) {
$insertgroups[] = array(
"sgid" => "0",
"sgidname" => "'ServerIcon'",
"iconid" => $sIconId,
"icondate" => $iconarr["i".$sIconId]
);
} else {
$updategroups[] = array(
"sgid" => "0",
"sgidname" => "'ServerIcon'",
"iconid" => $sIconId,
"icondate" => $iconarr["i".$sIconId]
);
}
}
// GroupIcons
$iconcount= 0;
foreach ($ts3groups as $servergroup) {
$tsgroupids[$servergroup['sgid']] = 0;
$sgid = $servergroup['sgid'];
$sgname = $mysqlcon->quote($servergroup['name'], ENT_QUOTES);
$gefunden = 2;
$iconid = $servergroup['iconid'];
$iconid = ($iconid < 0) ? (pow(2, 32)) - ($iconid * -1) : $iconid;
$iconfile = 0;
if($iconid > 600) {
if (!isset($select_arr['groups'][$sgid]) || $select_arr['groups'][$sgid]['iconid'] != $iconid || $iconarr["i".$iconid] > $select_arr['groups'][$sgid]['icondate']) {
try {
check_shutdown($timezone,$logpath); usleep($slowmode);
enter_logfile($logpath,$timezone,5,sprintf($lang['upgrp0011'], $sgname, $sgid));
$iconfile = $servergroup->iconDownload();
if(file_put_contents(substr(dirname(__FILE__),0,-4) . "tsicons/" . $sgid . ".png", $iconfile) === false) {
enter_logfile($logpath,$timezone,2,sprintf($lang['upgrp0007'], $sgname, $sgid).' '.sprintf($lang['errperm'], 'tsicons'));
}
$iconcount++;
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,$lang['errorts3'].$e->getCode().': '.sprintf($lang['upgrp0008'], $sgname, $sgid).$e->getMessage());
}
}
} elseif($iconid == 0) {
if(file_exists(substr(dirname(__FILE__),0,-4) . "tsicons/" . $sgid . ".png")) {
if(unlink(substr(dirname(__FILE__),0,-4) . "tsicons/" . $sgid . ".png") === false) {
enter_logfile($logpath,$timezone,2,sprintf($lang['upgrp0009'], $sgname, $sgid).' '.sprintf($lang['errperm'], 'tsicons'));
} else {
enter_logfile($logpath,$timezone,5,sprintf($lang['upgrp0010'], $sgname, $sgid));
}
}
$iconarr["i".$iconid] = 0;
}
if(!isset($iconarr["i".$iconid])) {
$iconarr["i".$iconid] = 0;
}
if(isset($select_arr['groups']) && count($select_arr['groups']) != 0) {
foreach ($select_arr['groups'] as $sqlgid => $groups) {
if ($sqlgid == $sgid) {
$gefunden = 1;
$updategroups[] = array(
"sgid" => $sgid,
"sgidname" => $sgname,
"iconid" => $iconid,
"icondate" => $iconarr["i".$iconid]
);
break;
}
}
if ($gefunden != 1) {
$insertgroups[] = array(
"sgid" => $servergroup['sgid'],
"sgidname" => $sgname,
"iconid" => $iconid,
"icondate" => $iconarr["i".$iconid]
);
}
} else {
$insertgroups[] = array(
"sgid" => $servergroup['sgid'],
"sgidname" => $sgname,
"iconid" => $iconid,
"icondate" => $iconarr["i".$iconid]
);
}
if($iconcount > 9 && $nobreak != 1) {
break;
}
}
if (isset($insertgroups)) {
$allinsertdata = '';
foreach ($insertgroups as $insertarr) {
$allinsertdata = $allinsertdata . "('" . $insertarr['sgid'] . "', " . $insertarr['sgidname'] . ", '" . $insertarr['iconid'] . "', '" . $insertarr['icondate'] . "'),";
}
$allinsertdata = substr($allinsertdata, 0, -1);
if ($allinsertdata != '') {
$sqlexec .= "INSERT INTO $dbname.groups (sgid, sgidname, iconid, icondate) VALUES $allinsertdata; ";
}
}
if (isset($updategroups)) {
$allsgids = '';
$allupdatesgid = '';
$allupdateiconid = '';
$allupdatedate = '';
foreach ($updategroups as $updatedata) {
$allsgids = $allsgids . "'" . $updatedata['sgid'] . "',";
$allupdatesgid = $allupdatesgid . "WHEN '" . $updatedata['sgid'] . "' THEN " . $updatedata['sgidname'] . " ";
$allupdateiconid = $allupdateiconid . "WHEN '" . $updatedata['sgid'] . "' THEN '" . $updatedata['iconid'] . "' ";
$allupdatedate = $allupdatedate . "WHEN '" . $updatedata['sgid'] . "' THEN '" . $updatedata['icondate'] . "' ";
}
$allsgids = substr($allsgids, 0, -1);
$sqlexec .= "UPDATE $dbname.groups set sgidname = CASE sgid $allupdatesgid END, iconid = CASE sgid $allupdateiconid END, icondate = CASE sgid $allupdatedate END WHERE sgid IN ($allsgids); ";
}
if(isset($select_arr['groups'])) {
foreach ($select_arr['groups'] as $sgid => $groups) {
if(!isset($tsgroupids[$sgid]) && $sgid != 0 && $sgid != NULL) {
$delsgroupids .= "'" . $sgid . "',";
if(in_array($sgid, $grouptime)) {
enter_logfile($logpath,$timezone,2,sprintf($lang['upgrp0001'], $sgid, $lang['wigrptime']));
}
if(isset($boostarr[$sgid])) {
enter_logfile($logpath,$timezone,2,sprintf($lang['upgrp0001'], $sgid, $lang['wiboost']));
}
if(isset($exceptgroup[$sgid])) {
enter_logfile($logpath,$timezone,2,sprintf($lang['upgrp0001'], $sgid, $lang['wiexgrp']));
}
}
}
}
if(isset($delsgroupids)) {
$delsgroupids = substr($delsgroupids, 0, -1);
$sqlexec .= "DELETE FROM $dbname.groups WHERE sgid IN ($delsgroupids); ";
}
return($sqlexec);
}
<?PHP
function update_groups($ts3,$mysqlcon,$lang,$dbname,$slowmode,$timezone,$serverinfo,$logpath,$grouptime,$boostarr,$exceptgroup,$select_arr,$nobreak = 0) {
$sqlexec = '';
try {
usleep($slowmode);
$iconlist = $ts3->channelFileList($cid="0", $cpw="", $path="/icons/");
} catch (Exception $e) {
if ($e->getCode() != 1281) {
enter_logfile($logpath,$timezone,2,$lang['errorts3'].$e->getCode().': '.$lang['errgrplist'].$e->getMessage());
}
}
foreach($iconlist as $icon) {
$iconid = "i".substr($icon['name'], 5);
$iconarr[$iconid] = $icon['datetime'];
}
try {
usleep($slowmode);
$ts3->serverGroupListReset();
$ts3groups = $ts3->serverGroupList();
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,$lang['errorts3'].$e->getCode().': '.$lang['errgrplist'].$e->getMessage());
}
// ServerIcon
if ($serverinfo['virtualserver_icon_id'] < 0) {
$sIconId = (pow(2, 32)) - ($serverinfo['virtualserver_icon_id'] * -1);
} else {
$sIconId = $serverinfo['virtualserver_icon_id'];
}
$sIconFile = 0;
if (!isset($select_arr['groups']['0']) || $select_arr['groups']['0']['iconid'] != $sIconId || $iconarr["i".$sIconId] > $select_arr['groups']['0']['icondate']) {
if($sIconId > 600) {
try {
usleep($slowmode);
enter_logfile($logpath,$timezone,5,$lang['upgrp0002']);
$sIconFile = $ts3->iconDownload();
if(file_put_contents(substr(dirname(__FILE__),0,-4) . "tsicons/servericon.png", $sIconFile) === false) {
enter_logfile($logpath,$timezone,2,$lang['upgrp0003'].' '.sprintf($lang['errperm'], 'tsicons'));
}
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,$lang['errorts3'].$e->getCode().'; '.$lang['upgrp0004'].$e->getMessage());
}
} elseif($sIconId == 0) {
if(file_exists(substr(dirname(__FILE__),0,-4) . "tsicons/servericon.png")) {
if(unlink(substr(dirname(__FILE__),0,-4) . "tsicons/servericon.png") === false) {
enter_logfile($logpath,$timezone,2,$lang['upgrp0005'].' '.sprintf($lang['errperm'], 'tsicons'));
} else {
enter_logfile($logpath,$timezone,5,$lang['upgrp0006']);
}
}
$iconarr["i".$sIconId] = 0;
}
$updategroups[] = array(
"sgid" => "0",
"sgidname" => "'ServerIcon'",
"iconid" => $sIconId,
"icondate" => $iconarr["i".$sIconId]
);
}
// GroupIcons
$iconcount= 0;
foreach ($ts3groups as $servergroup) {
$tsgroupids[$servergroup['sgid']] = 0;
$sgid = $servergroup['sgid'];
$sgname = $mysqlcon->quote($servergroup['name'], ENT_QUOTES);
$gefunden = 2;
$iconid = $servergroup['iconid'];
$iconid = ($iconid < 0) ? (pow(2, 32)) - ($iconid * -1) : $iconid;
$iconfile = 0;
if($iconid > 600) {
if (!isset($select_arr['groups'][$sgid]) || $select_arr['groups'][$sgid]['iconid'] != $iconid || $iconarr["i".$iconid] > $select_arr['groups'][$sgid]['icondate']) {
try {
check_shutdown($timezone,$logpath); usleep($slowmode);
enter_logfile($logpath,$timezone,5,sprintf($lang['upgrp0011'], $sgname, $sgid));
$iconfile = $servergroup->iconDownload();
if(file_put_contents(substr(dirname(__FILE__),0,-4) . "tsicons/" . $sgid . ".png", $iconfile) === false) {
enter_logfile($logpath,$timezone,2,sprintf($lang['upgrp0007'], $sgname, $sgid).' '.sprintf($lang['errperm'], 'tsicons'));
}
$iconcount++;
} catch (Exception $e) {
enter_logfile($logpath,$timezone,2,$lang['errorts3'].$e->getCode().': '.sprintf($lang['upgrp0008'], $sgname, $sgid).$e->getMessage());
}
}
} elseif($iconid == 0) {
if(file_exists(substr(dirname(__FILE__),0,-4) . "tsicons/" . $sgid . ".png")) {
if(unlink(substr(dirname(__FILE__),0,-4) . "tsicons/" . $sgid . ".png") === false) {
enter_logfile($logpath,$timezone,2,sprintf($lang['upgrp0009'], $sgname, $sgid).' '.sprintf($lang['errperm'], 'tsicons'));
} else {
enter_logfile($logpath,$timezone,5,sprintf($lang['upgrp0010'], $sgname, $sgid));
}
}
$iconarr["i".$iconid] = 0;
}
if(!isset($iconarr["i".$iconid])) {
$iconarr["i".$iconid] = 0;
}
$updategroups[] = array(
"sgid" => $servergroup['sgid'],
"sgidname" => $sgname,
"iconid" => $iconid,
"icondate" => $iconarr["i".$iconid]
);
if($iconcount > 9 && $nobreak != 1) {
break;
}
}
if (isset($updategroups)) {
$sqlinsertvalues = '';
foreach ($updategroups as $updatedata) {
$sqlinsertvalues .= "(".$updatedata['sgid'].",".$updatedata['sgidname'].",'".$updatedata['iconid']."','".$updatedata['icondate']."'),";
}
$sqlinsertvalues = substr($sqlinsertvalues, 0, -1);
$sqlexec .= "INSERT INTO `$dbname`.`groups` (`sgid`,`sgidname`,`iconid`,`icondate`) VALUES $sqlinsertvalues ON DUPLICATE KEY UPDATE `sgidname`=VALUES(`sgidname`),`iconid`=VALUES(`iconid`),`icondate`=VALUES(`icondate`); ";
unset($updategroups, $sqlinsertvalues);
}
if(isset($select_arr['groups'])) {
foreach ($select_arr['groups'] as $sgid => $groups) {
if(!isset($tsgroupids[$sgid]) && $sgid != 0 && $sgid != NULL) {
$delsgroupids .= "'" . $sgid . "',";
if(in_array($sgid, $grouptime)) {
enter_logfile($logpath,$timezone,2,sprintf($lang['upgrp0001'], $sgid, $lang['wigrptime']));
}
if(isset($boostarr[$sgid])) {
enter_logfile($logpath,$timezone,2,sprintf($lang['upgrp0001'], $sgid, $lang['wiboost']));
}
if(isset($exceptgroup[$sgid])) {
enter_logfile($logpath,$timezone,2,sprintf($lang['upgrp0001'], $sgid, $lang['wiexgrp']));
}
}
}
}
if(isset($delsgroupids)) {
$delsgroupids = substr($delsgroupids, 0, -1);
$sqlexec .= "DELETE FROM `$dbname`.`groups` WHERE `sgid` IN ($delsgroupids); ";
}
return($sqlexec);
}
?>

View File

@@ -1,135 +1,135 @@
<?PHP
function update_rs($mysqlcon,$lang,$dbname,$logpath,$timezone,$newversion,$phpcommand,$norotate=NULL) {
$norotate = true;
enter_logfile($logpath,$timezone,4," Start updating the Ranksystem...",$norotate);
enter_logfile($logpath,$timezone,4," Backup the database due cloning tables...",$norotate);
$countbackuperr = 0;
$tables = array('addons_config','addon_assign_groups','config','groups','job_check','server_usage','stats_nations','stats_platforms','stats_server','stats_user','stats_versions','user','user_snapshot');
foreach ($tables as $table) {
if($mysqlcon->query("SELECT 1 FROM bak_$table LIMIT 1") !== false) {
if($mysqlcon->exec("DROP TABLE $dbname.bak_$table") === false) {
enter_logfile($logpath,$timezone,1," Error due deleting old backup table ".$table.".",$norotate);
$countbackuperr++;
} else {
enter_logfile($logpath,$timezone,4," Old backup table ".$table." successfully removed.",$norotate);
}
}
}
foreach ($tables as $table) {
if($mysqlcon->exec("CREATE TABLE $dbname.bak_$table LIKE $dbname.$table") === false) {
enter_logfile($logpath,$timezone,1," Error due creating table bak_".$table.".",$norotate);
$countbackuperr++;
} else {
if($mysqlcon->exec("INSERT $dbname.bak_$table SELECT * FROM $dbname.$table") === false) {
enter_logfile($logpath,$timezone,1," Error due inserting data from table ".$table.".",$norotate);
$countbackuperr++;
} else {
enter_logfile($logpath,$timezone,4," Table ".$table." successfully cloned.",$norotate);
}
}
}
if($countbackuperr != 0) {
enter_logfile($logpath,$timezone,4," Backup failed. Please check your database permissions.",$norotate);
enter_logfile($logpath,$timezone,4," Update failed. Go on with normal work on old version.",$norotate);
return;
} else {
enter_logfile($logpath,$timezone,4," Database-tables successfully backuped.",$norotate);
}
if(!is_file(substr(__DIR__,0,-4).'update/'.$newversion.'.zip')) {
enter_logfile($logpath,$timezone,4," Downloading new update...",$norotate);
$newUpdate = file_get_contents('https://ts-n.net/downloads/ranksystem_'.$newversion.'.zip');
if(!is_dir(substr(__DIR__,0,-4).'update/')) {
mkdir (substr(__DIR__,0,-4).'update/');
}
$dlHandler = fopen(substr(__DIR__,0,-4).'update/ranksystem_'.$newversion.'.zip', 'w');
if(!fwrite($dlHandler,$newUpdate)) {
enter_logfile($logpath,$timezone,1," Could not save new update. Please check the permissions for folder 'update'.",$norotate);
enter_logfile($logpath,$timezone,4," Update failed. Go on with normal work on old version.",$norotate);
return;
}
if(!is_file(substr(__DIR__,0,-4).'update/ranksystem_'.$newversion.'.zip')) {
enter_logfile($logpath,$timezone,4," Something gone wrong with downloading/saving the new update file.",$norotate);
enter_logfile($logpath,$timezone,4," Update failed. Go on with normal work on old version.",$norotate);
return;
}
fclose($dlHandler);
enter_logfile($logpath,$timezone,4," New update successfully saved.",$norotate);
} else {
enter_logfile($logpath,$timezone,5," New update file already here...",$norotate);
}
$zipHandle = zip_open(substr(__DIR__,0,-4).'update/ranksystem_'.$newversion.'.zip');
$countwrongfiles = 0;
$countchangedfiles = 0;
while ($aF = zip_read($zipHandle)) {
$thisFileName = zip_entry_name($aF);
$thisFileDir = dirname($thisFileName);
if(substr($thisFileName,-1,1) == '/') {
continue;
}
if(!is_dir(substr(__DIR__,0,-4).'/'.$thisFileDir)) {
if(mkdir(substr(__DIR__,0,-4).$thisFileDir, 0777, true)) {
enter_logfile($logpath,$timezone,4," Create new folder ".$thisFileDir,$norotate);
} else {
enter_logfile($logpath,$timezone,1," Error by creating folder ".$thisFileDir.". Please check the permissions on your folder ".substr(__DIR__,0,-4),$norotate);
}
}
if(!is_dir(substr(__DIR__,0,-4).'/'.$thisFileName)) {
$contents = zip_entry_read($aF, zip_entry_filesize($aF));
$updateThis = '';
if($thisFileName == 'other/dbconfig.php' || $thisFileName == 'install.php' || $thisFileName == 'other/phpcommand.php') {
enter_logfile($logpath,$timezone,5," Did not touch ".$thisFileName,$norotate);
} else {
if(($updateThis = fopen(substr(__DIR__,0,-4).'/'.$thisFileName, 'w')) === false) {
enter_logfile($logpath,$timezone,1," Failed to open file ".$thisFileName,$norotate);
$countwrongfiles++;
} elseif(!fwrite($updateThis, $contents)) {
enter_logfile($logpath,$timezone,1," Failed to write file ".$thisFileName,$norotate);
$countwrongfiles++;
} else {
enter_logfile($logpath,$timezone,4," Replaced file ".$thisFileName,$norotate);
$countchangedfiles++;
}
fclose($updateThis);
unset($contents);
}
}
}
if($countwrongfiles == 0 && $countchangedfiles != 0) {
if(!unlink(substr(__DIR__,0,-4).'update/ranksystem_'.$newversion.'.zip')) {
enter_logfile($logpath,$timezone,3," Could not clean update folder. Please remove the unneeded file ".substr(__DIR__,0,-4)."update/ranksystem_".$newversion.".zip",$norotate);
} else {
enter_logfile($logpath,$timezone,5," Cleaned update folder.",$norotate);
}
$nowtime = time();
if($mysqlcon->exec("UPDATE $dbname.job_check SET timestamp='$nowtime' WHERE job_name='get_version'; UPDATE $dbname.config SET newversion='$newversion';") === false) {
enter_logfile($logpath,$timezone,1," Error due updating new version in database.");
}
enter_logfile($logpath,$timezone,4," Files updated successfully. Wait for restart via cron/task. Shutting down!\n\n",$norotate);
$path = substr(__DIR__, 0, -4);
if (substr(php_uname(), 0, 7) == "Windows") {
exec("start ".$phpcommand." ".$path."worker.php restart");
exit;
} else {
exec($phpcommand." ".$path."worker.php restart > /dev/null 2>/dev/null &");
exit;
}
} else {
enter_logfile($logpath,$timezone,1," Files updated with at least one error. Please check the log!",$norotate);
// how to handle this.. Perhaps try again automatically in 30 minutes
}
<?PHP
function update_rs($mysqlcon,$lang,$dbname,$logpath,$timezone,$newversion,$phpcommand,$norotate=NULL) {
$norotate = true;
enter_logfile($logpath,$timezone,4," Start updating the Ranksystem...",$norotate);
enter_logfile($logpath,$timezone,4," Backup the database due cloning tables...",$norotate);
$countbackuperr = 0;
$tables = array('addons_config','addon_assign_groups','config','groups','job_check','server_usage','stats_nations','stats_platforms','stats_server','stats_user','stats_versions','user','user_snapshot');
foreach ($tables as $table) {
if($mysqlcon->query("SELECT 1 FROM `$dbname`.`bak_$table` LIMIT 1") !== false) {
if($mysqlcon->exec("DROP TABLE `$dbname`.`bak_$table`") === false) {
enter_logfile($logpath,$timezone,1," Error due deleting old backup table ".$table.".",$norotate);
$countbackuperr++;
} else {
enter_logfile($logpath,$timezone,4," Old backup table ".$table." successfully removed.",$norotate);
}
}
}
foreach ($tables as $table) {
if($mysqlcon->exec("CREATE TABLE `$dbname`.`bak_$table` LIKE `$dbname`.`$table`") === false) {
enter_logfile($logpath,$timezone,1," Error due creating table bak_".$table.".",$norotate);
$countbackuperr++;
} else {
if($mysqlcon->exec("INSERT `$dbname`.`bak_$table` SELECT * FROM `$dbname`.`$table`") === false) {
enter_logfile($logpath,$timezone,1," Error due inserting data from table ".$table.".",$norotate);
$countbackuperr++;
} else {
enter_logfile($logpath,$timezone,4," Table ".$table." successfully cloned.",$norotate);
}
}
}
if($countbackuperr != 0) {
enter_logfile($logpath,$timezone,4," Backup failed. Please check your database permissions.",$norotate);
enter_logfile($logpath,$timezone,4," Update failed. Go on with normal work on old version.",$norotate);
return;
} else {
enter_logfile($logpath,$timezone,4," Database-tables successfully backuped.",$norotate);
}
if(!is_file(substr(__DIR__,0,-4).'update/'.$newversion.'.zip')) {
enter_logfile($logpath,$timezone,4," Downloading new update...",$norotate);
$newUpdate = file_get_contents('https://ts-n.net/downloads/ranksystem_'.$newversion.'.zip');
if(!is_dir(substr(__DIR__,0,-4).'update/')) {
mkdir (substr(__DIR__,0,-4).'update/');
}
$dlHandler = fopen(substr(__DIR__,0,-4).'update/ranksystem_'.$newversion.'.zip', 'w');
if(!fwrite($dlHandler,$newUpdate)) {
enter_logfile($logpath,$timezone,1," Could not save new update. Please check the permissions for folder 'update'.",$norotate);
enter_logfile($logpath,$timezone,4," Update failed. Go on with normal work on old version.",$norotate);
return;
}
if(!is_file(substr(__DIR__,0,-4).'update/ranksystem_'.$newversion.'.zip')) {
enter_logfile($logpath,$timezone,4," Something gone wrong with downloading/saving the new update file.",$norotate);
enter_logfile($logpath,$timezone,4," Update failed. Go on with normal work on old version.",$norotate);
return;
}
fclose($dlHandler);
enter_logfile($logpath,$timezone,4," New update successfully saved.",$norotate);
} else {
enter_logfile($logpath,$timezone,5," New update file already here...",$norotate);
}
$zipHandle = zip_open(substr(__DIR__,0,-4).'update/ranksystem_'.$newversion.'.zip');
$countwrongfiles = 0;
$countchangedfiles = 0;
while ($aF = zip_read($zipHandle)) {
$thisFileName = zip_entry_name($aF);
$thisFileDir = dirname($thisFileName);
if(substr($thisFileName,-1,1) == '/') {
continue;
}
if(!is_dir(substr(__DIR__,0,-4).'/'.$thisFileDir)) {
if(mkdir(substr(__DIR__,0,-4).$thisFileDir, 0777, true)) {
enter_logfile($logpath,$timezone,4," Create new folder ".$thisFileDir,$norotate);
} else {
enter_logfile($logpath,$timezone,1," Error by creating folder ".$thisFileDir.". Please check the permissions on your folder ".substr(__DIR__,0,-4),$norotate);
}
}
if(!is_dir(substr(__DIR__,0,-4).'/'.$thisFileName)) {
$contents = zip_entry_read($aF, zip_entry_filesize($aF));
$updateThis = '';
if($thisFileName == 'other/dbconfig.php' || $thisFileName == 'install.php' || $thisFileName == 'other/phpcommand.php') {
enter_logfile($logpath,$timezone,5," Did not touch ".$thisFileName,$norotate);
} else {
if(($updateThis = fopen(substr(__DIR__,0,-4).'/'.$thisFileName, 'w')) === false) {
enter_logfile($logpath,$timezone,1," Failed to open file ".$thisFileName,$norotate);
$countwrongfiles++;
} elseif(!fwrite($updateThis, $contents)) {
enter_logfile($logpath,$timezone,1," Failed to write file ".$thisFileName,$norotate);
$countwrongfiles++;
} else {
enter_logfile($logpath,$timezone,4," Replaced file ".$thisFileName,$norotate);
$countchangedfiles++;
}
fclose($updateThis);
unset($contents);
}
}
}
if($countwrongfiles == 0 && $countchangedfiles != 0) {
if(!unlink(substr(__DIR__,0,-4).'update/ranksystem_'.$newversion.'.zip')) {
enter_logfile($logpath,$timezone,3," Could not clean update folder. Please remove the unneeded file ".substr(__DIR__,0,-4)."update/ranksystem_".$newversion.".zip",$norotate);
} else {
enter_logfile($logpath,$timezone,5," Cleaned update folder.",$norotate);
}
$nowtime = time();
if($mysqlcon->exec("UPDATE `$dbname`.`job_check` SET `timestamp`='$nowtime' WHERE `job_name`='get_version'; UPDATE `$dbname`.`config` SET `newversion`='$newversion';") === false) {
enter_logfile($logpath,$timezone,1," Error due updating new version in database.");
}
enter_logfile($logpath,$timezone,4," Files updated successfully. Wait for restart via cron/task. Shutting down!\n\n",$norotate);
$path = substr(__DIR__, 0, -4);
if (substr(php_uname(), 0, 7) == "Windows") {
exec("start ".$phpcommand." ".$path."worker.php restart");
exit;
} else {
exec($phpcommand." ".$path."worker.php restart > /dev/null 2>/dev/null &");
exit;
}
} else {
enter_logfile($logpath,$timezone,1," Files updated with at least one error. Please check the log!",$norotate);
// how to handle this.. Perhaps try again automatically in 30 minutes
}
}