release 1.3.13

This commit is contained in:
Newcomer1989
2020-11-22 20:57:53 +01:00
parent 3316504336
commit e474b3feb8
74 changed files with 10142 additions and 8876 deletions

View File

@@ -13,57 +13,23 @@ if(ini_get('memory_limit') !== NULL) {
$memory_limit = "{none set}";
}
set_time_limit(0);
error_reporting(E_ALL);
ini_set("log_errors", 1);
function shutdown($mysqlcon = NULL,$cfg,$loglevel,$reason,$nodestroypid = TRUE) {
if($nodestroypid === TRUE) {
if (file_exists(substr(__DIR__,0,-4).'logs/pid')) {
unlink(substr(__DIR__,0,-4).'logs/pid');
}
}
enter_logfile($cfg,$loglevel,$reason." Shutting down!");
enter_logfile($cfg,9,"###################################################################");
if(isset($mysqlcon)) {
$mysqlcon = null;
}
exit;
}
function enter_logfile($cfg,$loglevel,$logtext,$norotate = false) {
if($loglevel!=9 && $loglevel > $cfg['logs_debug_level']) return;
$file = $cfg['logs_path'].'ranksystem.log';
switch ($loglevel) {
case 1: $loglevel = " CRITICAL "; break;
case 2: $loglevel = " ERROR "; break;
case 3: $loglevel = " WARNING "; break;
case 4: $loglevel = " NOTICE "; break;
case 5: $loglevel = " INFO "; break;
case 6: $loglevel = " DEBUG "; break;
default:$loglevel = " NONE ";
}
$loghandle = fopen($file, 'a');
fwrite($loghandle, DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''))->setTimeZone(new DateTimeZone($cfg['logs_timezone']))->format("Y-m-d H:i:s.u ").$loglevel.$logtext."\n");
fclose($loghandle);
if($norotate == false && filesize($file) > ($cfg['logs_rotation_size'] * 1048576)) {
$loghandle = fopen($file, 'a');
fwrite($loghandle, DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''))->setTimeZone(new DateTimeZone($cfg['logs_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($cfg['logs_timezone']))->format("Y-m-d H:i:s.u ")." NOTICE Rotated logfile...\n");
fclose($loghandle);
}
}
require_once(substr(__DIR__,0,-4).'other/_functions.php');
require_once(substr(__DIR__,0,-4).'other/config.php');
$lang = set_language(get_language($cfg));
set_error_handler("php_error_handling");
ini_set("error_log", $cfg['logs_path'].'ranksystem.log');
require_once(substr(__DIR__,0,-4).'other/phpcommand.php');
if(isset($_SERVER['HTTP_HOST']) || isset($_SERVER['REMOTE_ADDR'])) {
shutdown($mysqlcon,$cfg,1,"Request to start the Ranksystem from ".$_SERVER['REMOTE_ADDR'].". It seems the request came not from the command line!");
}
if(version_compare(phpversion(), '5.5.0', '<')) {
shutdown($mysqlcon,$cfg,1,"Your PHP version (".phpversion().") is below 5.5.0. Update of PHP is required!");
if(version_compare(PHP_VERSION, '5.5.0', '<')) {
shutdown($mysqlcon,$cfg,1,"Your PHP version (".PHP_VERSION.") is below 5.5.0. Update of PHP is required!");
}
if(!function_exists('simplexml_load_file')) {
shutdown($mysqlcon,$cfg,1,sprintf($lang['errphp'],'PHP SimpleXML'));
@@ -77,9 +43,7 @@ if(!in_array('zip', get_loaded_extensions())) {
if(!in_array('mbstring', get_loaded_extensions())) {
shutdown($mysqlcon,$cfg,1,sprintf($lang['errphp'],'PHP mbstring'));
}
if(!in_array('ssh2', get_loaded_extensions()) && $cfg['teamspeak_query_encrypt_switch'] == 1) {
shutdown($mysqlcon,$cfg,1,"PHP SSH2 is missed. Installation of PHP SSH2 is required, when using secured (SSH) connection to TeamSpeak! If you are not able to install PHP SSH2 (i.e. hosted webspace), you need to deactivate the TS3 Query encryption inside the Webinterface.");
}
enter_logfile($cfg,9,"");
enter_logfile($cfg,9,"###################################################################");
@@ -98,27 +62,25 @@ 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');
require_once(substr(__DIR__,0,-4).'jobs/reset_rs.php');
require_once(substr(__DIR__,0,-4).'jobs/db_ex_imp.php');
enter_logfile($cfg,9,"Running on OS: ".php_uname("s")." ".php_uname("r"));
enter_logfile($cfg,9,"Using PHP Version: ".phpversion());
enter_logfile($cfg,9,"Using PHP Version: ".PHP_VERSION);
if(version_compare(PHP_VERSION, '7.2.0', '<')) {
enter_logfile($cfg,3,"Your PHP Version: (".PHP_VERSION.") is outdated and no longer supported. Please update it!");
}
enter_logfile($cfg,9,"Database Version: ".$mysqlcon->getAttribute(PDO::ATTR_SERVER_VERSION));
$cfg = check_db($mysqlcon,$lang,$cfg,$dbname);
check_db($mysqlcon,$lang,$cfg,$dbname);
$cfg['temp_db_version'] = $mysqlcon->getAttribute(PDO::ATTR_SERVER_VERSION);
$cfg['temp_last_botstart'] = time();
$cfg['temp_reconnect_attempts'] = 0;
$cfg['temp_ts_no_reconnection'] = 0;
enter_logfile($cfg,4,"Check Ranksystem files for updates...");
if(isset($cfg['version_current_using']) && isset($cfg['version_latest_available']) && $cfg['version_latest_available'] != NULL && version_compare($cfg['version_latest_available'], $cfg['version_current_using'], '>')) {
update_rs($mysqlcon,$lang,$cfg,$dbname,$phpcommand);
}
enter_logfile($cfg,4,"Check Ranksystem files for updates [done]");
function check_shutdown($cfg) {
if(!file_exists(substr(__DIR__,0,-4).'logs/pid')) {
shutdown(NULL,$cfg,4,"Received signal to stop!");
}
}
enter_logfile($cfg,9,"Ranksystem Version: ".$cfg['version_current_using']." (on Update-Channel: ".$cfg['version_update_channel'].")");
enter_logfile($cfg,4,"Loading addons...");
require_once(substr(__DIR__,0,-4).'other/load_addons_config.php');
@@ -133,291 +95,228 @@ if($addons_config['assign_groups_active']['value'] == '1') {
}
enter_logfile($cfg,4,"Loading addons [done]");
function sendmessage($ts3, $cfg, $uuid, $targetmode, $targetid=NULL, $msg, $erromsg=NULL, $loglevel=NULL, $successmsg=NULL, $nolog=NULL) {
try {
if(strlen($msg) > 1024) {
$fragarr = explode("##*##", wordwrap($msg, 1022, "##*##", TRUE), 1022);
foreach($fragarr as $frag) {
usleep($cfg['teamspeak_query_command_delay']);
if ($targetmode==2 && $targetid!=NULL) {
$ts3->serverGetSelected()->channelGetById($targetid)->message("\n".$frag);
if($nolog==NULL) enter_logfile($cfg,6,"sendmessage fragment to channel (ID: $targetid): ".$frag);
} elseif ($targetmode==3) {
$ts3->serverGetSelected()->message("\n".$frag);
if($nolog==NULL) enter_logfile($cfg,6,"sendmessage fragment to server: ".$frag);
} elseif ($targetmode==1 && $targetid!=NULL) {
$ts3->serverGetSelected()->clientGetById($targetid)->message("\n".$frag);
if($nolog==NULL) enter_logfile($cfg,6,"sendmessage fragment to connectionID $targetid (uuid $uuid): ".$frag);
} else {
$ts3->serverGetSelected()->clientGetByUid($uuid)->message("\n".$frag);
if($nolog==NULL) enter_logfile($cfg,6,"sendmessage fragment to uuid $uuid (connectionID $targetid): ".$frag);
}
}
} else {
usleep($cfg['teamspeak_query_command_delay']);
if ($targetmode==2 && $targetid!=NULL) {
$ts3->serverGetSelected()->channelGetById($targetid)->message($msg);
if($nolog==NULL) enter_logfile($cfg,6,"sendmessage to channel (ID: $targetid): ".$msg);
} elseif ($targetmode==3) {
$ts3->serverGetSelected()->message($msg);
if($nolog==NULL) enter_logfile($cfg,6,"sendmessage to server: ".$msg);
} elseif ($targetmode==1 && $targetid!=NULL) {
$ts3->serverGetSelected()->clientGetById($targetid)->message($msg);
if($nolog==NULL) enter_logfile($cfg,6,"sendmessage to connectionID $targetid (uuid $uuid): ".$msg);
} else {
$ts3->serverGetSelected()->clientGetByUid($uuid)->message($msg);
if($nolog==NULL) enter_logfile($cfg,6,"sendmessage to uuid $uuid (connectionID $targetid): ".$msg);
}
}
if($successmsg!=NULL) {
enter_logfile($cfg,5,$successmsg);
}
} catch (Exception $e) {
if($loglevel!=NULL) {
enter_logfile($cfg,$loglevel,$erromsg." TS3: ".$e->getCode().': '.$e->getMessage());
} else {
enter_logfile($cfg,3,"sendmessage: ".$e->getCode().': '.$e->getMessage().", targetmode: $targetmode, targetid: $targetid");
}
}
}
function mime2extension($mimetype) {
$mimearr = [
'image/bmp' => 'bmp',
'image/x-bmp' => 'bmp',
'image/x-bitmap' => 'bmp',
'image/x-xbitmap' => 'bmp',
'image/x-win-bitmap' => 'bmp',
'image/x-windows-bmp' => 'bmp',
'image/ms-bmp' => 'bmp',
'image/x-ms-bmp' => 'bmp',
'image/gif' => 'gif',
'image/jpeg' => 'jpg',
'image/pjpeg' => 'jpg',
'image/x-portable-bitmap' => 'pbm',
'image/x-portable-graymap' => 'pgm',
'image/png' => 'png',
'image/x-png' => 'png',
'image/x-portable-pixmap' => 'ppm',
'image/svg+xml' => 'svg',
'image/x-xbitmap' => 'xbm',
'image/x-xpixmap' => 'xpm'
];
return isset($mimearr[$mimetype]) ? $mimearr[$mimetype] : FALSE;
}
function run_bot() {
global $cfg, $mysqlcon, $dbname, $dbtype, $lang, $phpcommand, $addons_config, $max_execution_time, $memory_limit;
function run_bot(&$cfg) {
global $mysqlcon, $db, $dbname, $dbtype, $lang, $phpcommand, $addons_config, $max_execution_time, $memory_limit, $ts3server;
enter_logfile($cfg,9,"Connect to TS3 Server (Address: \"".$cfg['teamspeak_host_address']."\" Voice-Port: \"".$cfg['teamspeak_voice_port']."\" Query-Port: \"".$cfg['teamspeak_query_port']."\" SSH: \"".$cfg['teamspeak_query_encrypt_switch']."\" Query-Slowmode: \"".number_format(($cfg['teamspeak_query_command_delay']/1000000),1)."\").");
try {
if($mysqlcon->exec("DROP INDEX `snapshot_id` ON `$dbname`.`user_snapshot` (`id`)") === false) { } else {
enter_logfile($cfg,4," [1.3.13] Dropped unneeded Index snapshot_id on table user_snapshot.");
}
if($mysqlcon->exec("DROP INDEX `snapshot_cldbid` ON `$dbname`.`user_snapshot` (`cldbid`)") === false) { } else {
enter_logfile($cfg,4," [1.3.13] Dropped unneeded Index snapshot_cldbid on table user_snapshot.");
}
} catch (Exception $e) { }
try {
if($cfg['teamspeak_query_encrypt_switch'] == 1) {
$ts3host = TeamSpeak3::factory("serverquery://".rawurlencode($cfg['teamspeak_query_user']).":".rawurlencode($cfg['teamspeak_query_pass'])."@".$cfg['teamspeak_host_address'].":".$cfg['teamspeak_query_port']."/?ssh=1");
} else {
$ts3host = TeamSpeak3::factory("serverquery://".rawurlencode($cfg['teamspeak_query_user']).":".rawurlencode($cfg['teamspeak_query_pass'])."@".$cfg['teamspeak_host_address'].":".$cfg['teamspeak_query_port']."/?blocking=0");
}
enter_logfile($cfg,9,"Connection to TS3 Server established.");
try{
$ts3version = $ts3host->version();
enter_logfile($cfg,5," TS3 Server version: ".$ts3version['version']." on ".$ts3version['platform']." [Build: ".$ts3version['build']." from ".date("Y-m-d H:i:s",$ts3version['build'])."]");
$cfg['temp_ts_version'] = $ts3version['version'];
} catch (Exception $e) {
enter_logfile($cfg,2," Error due getting TS3 server version - ".$e->getCode().': '.$e->getMessage());
}
if(version_compare($ts3version['version'],'3.11.9','<=')) {
enter_logfile($cfg,3," Your TS3 server is outdated, please update it!");
}
enter_logfile($cfg,9," Select virtual server...");
try {
if(version_compare($ts3version['version'],'3.4.0','>=')) {
usleep($cfg['teamspeak_query_command_delay']);
$ts3server = $ts3host->serverGetByPort($cfg['teamspeak_voice_port'], $cfg['teamspeak_query_nickname']);
if($cfg['temp_ts_no_reconnection'] != 1) {
if($cfg['teamspeak_query_encrypt_switch'] == 1) {
$ts3host = TeamSpeak3::factory("serverquery://".rawurlencode($cfg['teamspeak_query_user']).":".rawurlencode($cfg['teamspeak_query_pass'])."@".$cfg['teamspeak_host_address'].":".$cfg['teamspeak_query_port']."/?ssh=1");
} else {
usleep($cfg['teamspeak_query_command_delay']);
$ts3server = $ts3host->serverGetByPort($cfg['teamspeak_voice_port']);
for ($updcld = 0; $updcld < 10; $updcld++) {
try {
usleep($cfg['teamspeak_query_command_delay']);
if($updcld == 0) {
$ts3server->selfUpdate(array('client_nickname' => $cfg['teamspeak_query_nickname']));
} else {
$ts3server->selfUpdate(array('client_nickname' => $cfg['teamspeak_query_nickname'].$updcld));
$ts3host = TeamSpeak3::factory("serverquery://".rawurlencode($cfg['teamspeak_query_user']).":".rawurlencode($cfg['teamspeak_query_pass'])."@".$cfg['teamspeak_host_address'].":".$cfg['teamspeak_query_port']."/?blocking=0");
}
enter_logfile($cfg,9,"Connection to TS3 Server established.");
try{
$ts3version = $ts3host->version();
enter_logfile($cfg,5," TS3 Server version: ".$ts3version['version']." on ".$ts3version['platform']." [Build: ".$ts3version['build']." from ".date("Y-m-d H:i:s",$ts3version['build'])."]");
$cfg['temp_ts_version'] = $ts3version['version'];
} catch (Exception $e) {
enter_logfile($cfg,2," Error due getting TS3 server version - ".$e->getCode().': '.$e->getMessage());
}
if(version_compare($ts3version['version'],'3.12.9','<=') && version_compare($ts3version['version'],'3.0.0','>=')) {
enter_logfile($cfg,3," Your TS3 server is outdated, please update it!");
}
enter_logfile($cfg,9," Select virtual server...");
try {
if(version_compare($ts3version['version'],'3.4.0','>=')) {
usleep($cfg['teamspeak_query_command_delay']);
$ts3server = $ts3host->serverGetByPort($cfg['teamspeak_voice_port'], $cfg['teamspeak_query_nickname']);
} else {
usleep($cfg['teamspeak_query_command_delay']);
$ts3server = $ts3host->serverGetByPort($cfg['teamspeak_voice_port']);
for ($updcld = 0; $updcld < 10; $updcld++) {
try {
usleep($cfg['teamspeak_query_command_delay']);
if($updcld == 0) {
$ts3server->selfUpdate(array('client_nickname' => $cfg['teamspeak_query_nickname']));
} else {
$ts3server->selfUpdate(array('client_nickname' => $cfg['teamspeak_query_nickname'].$updcld));
}
break;
} catch (Exception $e) {
enter_logfile($cfg,3,' '.$lang['errorts3'].$e->getCode().': '.$e->getMessage());
shutdown($mysqlcon,$cfg,1,"Critical TS3 error on core function!");
}
break;
} catch (Exception $e) {
enter_logfile($cfg,3,' '.$lang['errorts3'].$e->getCode().': '.$e->getMessage());
shutdown($mysqlcon,$cfg,1,"Critical TS3 error on core function!");
}
}
enter_logfile($cfg,9," Select virtual server [done]");
$cfg['temp_reconnect_attempts'] = 0;
} catch (Exception $e) {
enter_logfile($cfg,2," Error due selecting virtual server - ".$e->getCode().': '.$e->getMessage()." (bad Voice-Port or Bot name?)");
}
enter_logfile($cfg,9," Select virtual server [done]");
$cfg['temp_reconnect_attempts'] = 0;
} catch (Exception $e) {
enter_logfile($cfg,2," Error due selecting virtual server - ".$e->getCode().': '.$e->getMessage()." (bad Voice-Port or Bot name?)");
}
try {
usleep($cfg['teamspeak_query_command_delay']);
$ts3server->notifyRegister("server");
$ts3server->notifyRegister("textprivate");
$ts3server->notifyRegister("textchannel");
$ts3server->notifyRegister("textserver");
TeamSpeak3_Helper_Signal::getInstance()->subscribe("notifyTextmessage", "handle_messages");
TeamSpeak3_Helper_Signal::getInstance()->subscribe("notifyCliententerview", "event_userenter");
} catch (Exception $e) {
enter_logfile($cfg,2," Error due notifyRegister on TS3 server - ".$e->getCode().': '.$e->getMessage());
}
$whoami = $ts3server->whoami();
if($cfg['teamspeak_default_channel_id'] != 0) {
try {
usleep($cfg['teamspeak_query_command_delay']);
$ts3server->clientMove($whoami['client_id'],$cfg['teamspeak_default_channel_id']);
enter_logfile($cfg,5," Joined to specified TS channel with channel-ID ".$cfg['teamspeak_default_channel_id'].".");
$ts3server->notifyRegister("server");
$ts3server->notifyRegister("textprivate");
$ts3server->notifyRegister("textchannel");
$ts3server->notifyRegister("textserver");
TeamSpeak3_Helper_Signal::getInstance()->subscribe("notifyTextmessage", "handle_messages");
TeamSpeak3_Helper_Signal::getInstance()->subscribe("notifyCliententerview", "event_userenter");
} catch (Exception $e) {
if($e->getCode() != 770) {
enter_logfile($cfg,2," Could not join specified TS channel (channel-ID: ".$cfg['teamspeak_default_channel_id'].") - ".$e->getCode().': '.$e->getMessage());
} else {
enter_logfile($cfg,5," Joined to specified TS channel with channel-ID ".$cfg['teamspeak_default_channel_id']." (already member of it).");
}
}
} else {
enter_logfile($cfg,5," No channel defined where the Ranksystem Bot should be entered.");
}
enter_logfile($cfg,9,"Config check started...");
switch ($cfg['logs_debug_level']) {
case 1:
$loglevel = "1 - CRITICAL";
break;
case 2:
$loglevel = "2 - ERROR";
break;
case 3:
$loglevel = "3 - WARNING";
break;
case 4:
$loglevel = "4 - NOTICE";
break;
case 5:
$loglevel = "5 - INFO";
break;
case 6:
$loglevel = "6 - DEBUG";
break;
default:
$loglevel = "UNKNOWN";
}
enter_logfile($cfg,9," Log Level: ".$loglevel);
enter_logfile($cfg,6," Serverside config 'max_execution_time' (PHP.ini): ".$max_execution_time." sec.");
enter_logfile($cfg,6," Serverside config 'memory_limit' (PHP.ini): ".$memory_limit);
krsort($cfg['rankup_definition']);
if(($groupslist = $mysqlcon->query("SELECT * FROM `$dbname`.`groups`")->fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC)) === false) {
enter_logfile($cfg,1," Select on DB failed for group check: ".print_r($mysqlcon->errorInfo(), true));
}
$checkgroups = 0;
if(isset($groupslist) && $groupslist != NULL) {
if(isset($cfg['rankup_definition']) && $cfg['rankup_definition'] != NULL) {
foreach($cfg['rankup_definition'] as $rank) {
if(!isset($groupslist[$rank['group']]) && $rank['group'] != NULL) {
$checkgroups++;
}
}
}
if(isset($cfg['rankup_boost_definition']) && $cfg['rankup_boost_definition'] != NULL) {
foreach($cfg['rankup_boost_definition'] as $groupid => $value) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
$checkgroups++;
}
}
}
if(isset($cfg['rankup_excepted_group_id_list']) && $cfg['rankup_excepted_group_id_list'] != NULL) {
foreach($cfg['rankup_excepted_group_id_list'] as $groupid => $value) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
$checkgroups++;
}
}
}
}
if($checkgroups > 0) {
enter_logfile($cfg,3," Found servergroups in config, which are unknown. Redownload all servergroups from TS3 server.");
if($mysqlcon->exec("DELETE FROM `$dbname`.`groups`;") === false) {
enter_logfile($cfg,2," Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
enter_logfile($cfg,2," Error due notifyRegister on TS3 server - ".$e->getCode().': '.$e->getMessage());
}
$serverinfo = $ts3server->serverInfo();
$select_arr = array();
$db_cache = array();
$sqlexec2 .= update_groups($ts3server,$mysqlcon,$lang,$cfg,$dbname,$serverinfo,$db_cache,1);
if($mysqlcon->exec($sqlexec2) === false) {
enter_logfile($cfg,2,"Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
$whoami = $ts3server->whoami();
if(isset($cfg['teamspeak_default_channel_id']) && $cfg['teamspeak_default_channel_id'] != 0 && $cfg['teamspeak_default_channel_id'] != '') {
try {
usleep($cfg['teamspeak_query_command_delay']);
$ts3server->clientMove($whoami['client_id'],$cfg['teamspeak_default_channel_id']);
enter_logfile($cfg,5," Joined to specified TS channel with channel-ID ".$cfg['teamspeak_default_channel_id'].".");
} catch (Exception $e) {
if($e->getCode() != 770) {
enter_logfile($cfg,2," Could not join specified TS channel (channel-ID: ".$cfg['teamspeak_default_channel_id'].") - ".$e->getCode().': '.$e->getMessage());
} else {
enter_logfile($cfg,5," Joined to specified TS channel with channel-ID ".$cfg['teamspeak_default_channel_id']." (already member of it).");
}
}
} else {
enter_logfile($cfg,5," No channel defined where the Ranksystem Bot should be entered.");
}
unset($sqlexec2,$select_arr,$db_cache,$groupslist,$serverinfo,$ts3version);
$errcnf = 0;
enter_logfile($cfg,4," Downloading of servergroups finished. Recheck the config.");
enter_logfile($cfg,9,"Config check started...");
switch ($cfg['logs_debug_level']) {
case 1:
$loglevel = "1 - CRITICAL";
break;
case 2:
$loglevel = "2 - ERROR";
break;
case 3:
$loglevel = "3 - WARNING";
break;
case 4:
$loglevel = "4 - NOTICE";
break;
case 5:
$loglevel = "5 - INFO";
break;
case 6:
$loglevel = "6 - DEBUG";
break;
default:
$loglevel = "UNKNOWN";
}
enter_logfile($cfg,9," Log Level: ".$loglevel);
enter_logfile($cfg,6," Serverside config 'max_execution_time' (PHP.ini): ".$max_execution_time." sec.");
enter_logfile($cfg,6," Serverside config 'memory_limit' (PHP.ini): ".$memory_limit);
krsort($cfg['rankup_definition']);
if(($groupslist = $mysqlcon->query("SELECT * FROM `$dbname`.`groups`")->fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC)) === false) {
enter_logfile($cfg,1," Select on DB failed for group check: ".print_r($mysqlcon->errorInfo(), true));
}
$checkgroups = 0;
if(isset($groupslist) && $groupslist != NULL) {
if(isset($cfg['rankup_definition']) && $cfg['rankup_definition'] != NULL) {
foreach($cfg['rankup_definition'] as $rank) {
if(!isset($groupslist[$rank['group']]) && $rank['group'] != NULL) {
enter_logfile($cfg,1,' '.sprintf($lang['upgrp0001'], $rank['group'], $lang['wigrptime']));
$errcnf++;
$checkgroups++;
}
}
}
if(isset($cfg['rankup_boost_definition']) && $cfg['rankup_boost_definition'] != NULL) {
foreach($cfg['rankup_boost_definition'] as $groupid => $value) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
enter_logfile($cfg,2,' '.sprintf($lang['upgrp0001'], $groupid, $lang['wiboost']));
$checkgroups++;
}
}
}
if(isset($cfg['rankup_excepted_group_id_list']) && $cfg['rankup_excepted_group_id_list'] != NULL) {
foreach($cfg['rankup_excepted_group_id_list'] as $groupid => $value) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
enter_logfile($cfg,2,' '.sprintf($lang['upgrp0001'], $groupid, $lang['wiexgrp']));
$checkgroups++;
}
}
}
}
if($errcnf > 0) {
shutdown($mysqlcon,$cfg,1,"Critical Config error!");
} else {
enter_logfile($cfg,4," No critical problems found! All seems to be fine...");
}
}
if($checkgroups > 0) {
enter_logfile($cfg,3," Found servergroups in config, which are unknown. Redownload all servergroups from TS3 server.");
if($mysqlcon->exec("DELETE FROM `$dbname`.`groups`;") === false) {
enter_logfile($cfg,2," Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
}
if(($lastupdate = $mysqlcon->query("SELECT `timestamp` FROM `$dbname`.`job_check` WHERE `job_name`='last_update'")->fetch()) === false) {
enter_logfile($cfg,1," Select on DB failed for job check: ".print_r($mysqlcon->errorInfo(), true));
} else {
if($lastupdate['timestamp'] != 0 && ($lastupdate['timestamp'] + 10) > time()) {
if(isset($cfg['webinterface_admin_client_unique_id_list']) && $cfg['webinterface_admin_client_unique_id_list'] != NULL) {
foreach(array_flip($cfg['webinterface_admin_client_unique_id_list']) as $clientuuid) {
sendmessage($ts3server, $cfg, $clientuuid, NULL, sprintf($lang['upmsg2'], $cfg['version_current_using'], 'https://ts-ranksystem.com/#changelog'), sprintf($lang['upusrerr'], $clientuuid), 6, sprintf($lang['upusrinf'], $clientuuid));
$serverinfo = $ts3server->serverInfo();
$select_arr = array();
$db_cache = array();
$sqlexec2 .= update_groups($ts3server,$mysqlcon,$lang,$cfg,$dbname,$serverinfo,$db_cache,1);
if($mysqlcon->exec($sqlexec2) === false) {
enter_logfile($cfg,2,"Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
}
unset($sqlexec2,$select_arr,$db_cache,$groupslist,$serverinfo,$ts3version);
$errcnf = 0;
enter_logfile($cfg,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($cfg,1," Select on DB failed for group check: ".print_r($mysqlcon->errorInfo(), true));
}
if(isset($groupslist) && $groupslist != NULL) {
if(isset($cfg['rankup_definition']) && $cfg['rankup_definition'] != NULL) {
foreach($cfg['rankup_definition'] as $rank) {
if(!isset($groupslist[$rank['group']]) && $rank['group'] != NULL) {
enter_logfile($cfg,1,' '.sprintf($lang['upgrp0001'], $rank['group'], $lang['wigrptime']));
$errcnf++;
}
}
}
if(isset($cfg['rankup_boost_definition']) && $cfg['rankup_boost_definition'] != NULL) {
foreach($cfg['rankup_boost_definition'] as $groupid => $value) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
enter_logfile($cfg,2,' '.sprintf($lang['upgrp0001'], $groupid, $lang['wiboost']));
}
}
}
if(isset($cfg['rankup_excepted_group_id_list']) && $cfg['rankup_excepted_group_id_list'] != NULL) {
foreach($cfg['rankup_excepted_group_id_list'] as $groupid => $value) {
if(!isset($groupslist[$groupid]) && $groupid != NULL) {
enter_logfile($cfg,2,' '.sprintf($lang['upgrp0001'], $groupid, $lang['wiexgrp']));
}
}
}
}
if($errcnf > 0) {
shutdown($mysqlcon,$cfg,1,"Critical Config error!");
} else {
enter_logfile($cfg,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($cfg,1," Select on DB failed for job check: ".print_r($mysqlcon->errorInfo(), true));
} else {
if($lastupdate['timestamp'] != 0 && ($lastupdate['timestamp'] + 10) > time()) {
if(isset($cfg['webinterface_admin_client_unique_id_list']) && $cfg['webinterface_admin_client_unique_id_list'] != NULL) {
foreach(array_flip($cfg['webinterface_admin_client_unique_id_list']) as $clientuuid) {
sendmessage($ts3server, $cfg, $clientuuid, sprintf($lang['upmsg2'], $cfg['version_current_using'], 'https://ts-ranksystem.com/#changelog'), 1, NULL, sprintf($lang['upusrerr'], $clientuuid), 6, sprintf($lang['upusrinf'], $clientuuid));
}
}
}
}
}
if($cfg['webinterface_fresh_installation'] == 1) {
if($mysqlcon->exec("UPDATE `$dbname`.`cfg_params` SET `value`=0 WHERE `param`='webinterface_fresh_installation'") === false) {
enter_logfile($cfg,2,"Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
if(isset($cfg['webinterface_fresh_installation']) && $cfg['webinterface_fresh_installation'] == 1) {
if($mysqlcon->exec("UPDATE `$dbname`.`cfg_params` SET `value`=0 WHERE `param`='webinterface_fresh_installation'") === false) {
enter_logfile($cfg,2,"Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
}
}
}
unset($groupslist,$errcnf,$checkgroups,$lastupdate,$updcld,$loglevel,$whoami,$ts3host,$max_execution_time,$memory_limit,$memory_limit);
enter_logfile($cfg,9,"Config check [done]");
unset($groupslist,$errcnf,$checkgroups,$lastupdate,$updcld,$loglevel,$whoami,$ts3host,$max_execution_time,$memory_limit,$memory_limit);
enter_logfile($cfg,9,"Config check [done]");
}
enter_logfile($cfg,9,"Bot starts now his work!");
$looptime = $cfg['temp_count_laps'] = $cfg['temp_whole_laptime'] = $cfg['temp_count_laptime'] = 0; $cfg['temp_last_laptime'] = '';
@@ -547,6 +446,7 @@ function run_bot() {
enter_logfile($cfg,6,"SQL executions needs: ".(number_format(round((microtime(true) - $startsql), 5),5)));
reset_rs($ts3server,$mysqlcon,$lang,$cfg,$dbname,$db_cache);
db_ex_imp($ts3server,$mysqlcon,$lang,$cfg,$dbname,$db_cache);
unset($sqlexec,$select_arr,$sqldump);
@@ -559,7 +459,7 @@ function run_bot() {
if($looptime < 1) {
$loopsleep = (1 - $looptime);
if($cfg['teamspeak_query_encrypt_switch'] == 1 || version_compare($ts3version['version'],'1.4.0','>=') && version_compare($ts3version['version'],'2.9.9','<=')) {
if($cfg['teamspeak_query_encrypt_switch'] == 1 || version_compare($cfg['temp_ts_version'],'1.4.0','>=') && version_compare($cfg['temp_ts_version'],'2.9.9','<=')) {
// no wait for data to become available on the stream on SSH due issues with non-blocking mode or TeaSpeak
usleep(round($loopsleep * 1000000));
} else {
@@ -568,13 +468,13 @@ function run_bot() {
}
}
} catch (Exception $e) {
enter_logfile($cfg,2,$lang['errorts3'].$e->getCode().': '.$e->getMessage());
enter_logfile($cfg,2,$lang['error'].': ['.$e->getCode().']: '.$e->getMessage());
if(in_array($e->getCode(), array(110,257,258,1024,1026,1031,1032,1033,1034,1280,1793))) {
if($mysqlcon->exec("UPDATE $dbname.stats_server SET server_status='0'") === false) {
enter_logfile($cfg,2,$lang['error'].print_r($mysqlcon->errorInfo(), true));
}
}
if($cfg['temp_last_botstart'] < (time() - 10)) {
if($cfg['temp_reconnect_attempts'] < 4) {
$wait_reconnect = 5;
@@ -597,8 +497,18 @@ function run_bot() {
check_shutdown($cfg);
}
if(in_array($e->getCode(), array('HY000','10054','70100','8'))) {
$cfg['temp_ts_no_reconnection'] = 1;
try {
$mysqlcon = db_connect($db['type'], $db['host'], $db['dbname'], $db['user'], $db['pass'], "no_exit");
enter_logfile($cfg,9,"Connection to database restored");
} catch (Exception $e) {
enter_logfile($cfg,2,$lang['error'].print_r($mysqlcon->errorInfo(), true));
}
}
$cfg['temp_reconnect_attempts'] = $cfg['temp_reconnect_attempts'] + 1;
return $cfg;
return $ts3server;
} else {
shutdown($mysqlcon,$cfg,1,"Critical TS3 error on core function!");
}
@@ -606,6 +516,6 @@ function run_bot() {
}
while(1) {
run_bot();
run_bot($cfg);
}
?>

View File

@@ -4,7 +4,7 @@ function calc_serverstats($ts3,$mysqlcon,&$cfg,$dbname,$dbtype,$serverinfo,&$db_
$nowtime = time();
$sqlexec = '';
if($db_cache['job_check']['calc_donut_chars']['timestamp'] < ($nowtime - 8)) {
if($db_cache['job_check']['calc_donut_chars']['timestamp'] < ($nowtime - 8) || $db_cache['job_check']['get_version']['timestamp'] < ($nowtime - 43199)) {
$db_cache['job_check']['calc_donut_chars']['timestamp'] = $nowtime;
$sqlexec .= "UPDATE `$dbname`.`job_check` SET `timestamp`={$nowtime} WHERE `job_name`='calc_donut_chars';\n";
@@ -12,6 +12,10 @@ function calc_serverstats($ts3,$mysqlcon,&$cfg,$dbname,$dbtype,$serverinfo,&$db_
$country_array = $platform_array = $count_version_user = array();
foreach($db_cache['all_user'] as $uuid) {
$nation = (string)$uuid['nation'];
$platform = (string)$uuid['platform'];
$version = (string)$uuid['version'];
if ($uuid['lastseen']>($nowtime-86400)) {
$user_quarter++; $user_month++; $user_week++; $user_today++;
} elseif ($uuid['lastseen']>($nowtime-604800)) {
@@ -22,22 +26,22 @@ function calc_serverstats($ts3,$mysqlcon,&$cfg,$dbname,$dbtype,$serverinfo,&$db_
$user_quarter++;
}
if(isset($country_array[$uuid['nation']])) {
$country_array[$uuid['nation']]++;
if(isset($country_array[$nation])) {
$country_array[$nation]++;
} else {
$country_array[$uuid['nation']] = 1;
$country_array[$nation] = 1;
}
if(isset($platform_array[$uuid['platform']])) {
$platform_array[$uuid['platform']]++;
if(isset($platform_array[$platform])) {
$platform_array[$platform]++;
} else {
$platform_array[$uuid['platform']] = 1;
$platform_array[$platform] = 1;
}
if(isset($count_version_user[$uuid['version']])) {
$count_version_user[$uuid['version']]++;
if(isset($count_version_user[$version])) {
$count_version_user[$version]++;
} else {
$count_version_user[$uuid['version']] = 1;
$count_version_user[$version] = 1;
}
$total_online_time = $total_online_time + $uuid['count'];
@@ -424,7 +428,7 @@ function calc_serverstats($ts3,$mysqlcon,&$cfg,$dbname,$dbtype,$serverinfo,&$db_
}
}
}
update_rs($mysqlcon,$lang,$cfg,$dbname,$phpcommand);
$sqlexec .= update_rs($mysqlcon,$lang,$cfg,$dbname,$phpcommand);
}
$sqlexec .= "UPDATE `$dbname`.`job_check` SET `timestamp`=$nowtime WHERE `job_name`='get_version';\nUPDATE `$dbname`.`cfg_params` SET `value`='{$cfg['version_latest_available']}' WHERE `param`='version_latest_available';\n";
}

View File

@@ -26,68 +26,45 @@ function calc_user($ts3,$mysqlcon,$lang,$cfg,$dbname,$allclients,$phpcommand,&$d
if(isset($db_cache['admin_addtime']) && count($db_cache['admin_addtime']) != 0) {
foreach($db_cache['admin_addtime'] as $uuid => $value) {
if(isset($db_cache['all_user'][$uuid])) {
$sqlexec2 = '';
$isonline = 0;
foreach($allclients as $client) {
if($client['client_unique_identifier'] == $uuid) {
$isonline = 1;
$temp_cldbid = $client['client_database_id'];
if($value['timecount'] < 0) {
$db_cache['all_user'][$uuid]['count'] += $value['timecount'];
if($db_cache['all_user'][$uuid]['count'] < 0) {
$db_cache['all_user'][$uuid]['count'] = 0;
$db_cache['all_user'][$uuid]['idle'] = 0;
} elseif ($db_cache['all_user'][$uuid]['idle'] > $db_cache['all_user'][$uuid]['count']) {
$db_cache['all_user'][$uuid]['idle'] = $db_cache['all_user'][$uuid]['count'];
}
} else {
$db_cache['all_user'][$uuid]['count'] += $value['timecount'];
}
}
}
$db_cache['all_user'][$uuid]['count'] += $value['timecount'];
if($db_cache['all_user'][$uuid]['count'] < 0) {
$db_cache['all_user'][$uuid]['count'] = $db_cache['all_user'][$uuid]['idle'] = 0;
} elseif ($db_cache['all_user'][$uuid]['idle'] > $db_cache['all_user'][$uuid]['count']) {
$db_cache['all_user'][$uuid]['idle'] = $db_cache['all_user'][$uuid]['count'];
}
if($isonline != 1) {
if(($user = $mysqlcon->query("SELECT `uuid`,`count`,`idle`,`cldbid` FROM `$dbname`.`user` WHERE `uuid`='{$uuid}'")->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE)) === false) {
if(($user = $mysqlcon->query("SELECT `uuid`,`cldbid` FROM `$dbname`.`user` WHERE `uuid`='{$uuid}'")->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE)) === false) {
enter_logfile($cfg,2,"Database error on selecting user (admin function remove/add time): ".print_r($mysqlcon->errorInfo(), true));
} else {
$temp_cldbid = $user[$uuid]['cldbid'];
if($value['timecount'] < 0) {
$user[$uuid]['count'] += $value['timecount'];
if($user[$uuid]['count'] < 0) {
$user[$uuid]['count'] = 0;
$user[$uuid]['idle'] = 0;
} elseif ($user[$uuid]['idle'] > $user[$uuid]['count']) {
$user[$uuid]['idle'] = $user[$uuid]['count'];
}
} else {
$user[$uuid]['count'] += $value['timecount'];
}
$sqlexec2 .= "UPDATE `$dbname`.`user` SET `count`='{$user[$uuid]['count']}', `idle`='{$user[$uuid]['idle']}' WHERE `uuid`='{$uuid}'; ";
$sqlexec .= "UPDATE `$dbname`.`user` SET `count`='{$db_cache['all_user'][$uuid]['count']}', `idle`='{$db_cache['all_user'][$uuid]['idle']}' WHERE `uuid`='{$uuid}';\n";
}
}
$sqlexec2 .= "DELETE FROM `$dbname`.`admin_addtime` WHERE `timestamp`=".$value['timestamp']." AND `uuid`='$uuid'; ";
if($mysqlcon->exec("DELETE FROM `$dbname`.`admin_addtime` WHERE `timestamp`=".$value['timestamp']." AND `uuid`='$uuid';") === false) {
enter_logfile($cfg,2,"Database error on updating user (admin function remove/add time): ".print_r($mysqlcon->errorInfo(), true));
}
if(($usersnap = $mysqlcon->query("SELECT `id`,`cldbid`,`count`,`idle` FROM `$dbname`.`user_snapshot` WHERE `cldbid`={$temp_cldbid}")->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE)) === false) {
enter_logfile($cfg,2,"Database error on selecting user (admin function remove/add time): ".print_r($mysqlcon->errorInfo(), true));
} else {
foreach($usersnap as $id => $valuesnap) {
if($value['timecount'] < 0) {
$valuesnap[$id]['count'] += $value['timecount'];
if($valuesnap[$id]['count'] < 0) {
$valuesnap[$id]['count'] = 0;
$valuesnap[$id]['idle'] = 0;
} elseif ($valuesnap[$id]['idle'] > $valuesnap[$id]['count']) {
$valuesnap[$id]['idle'] = $valuesnap[$id]['count'];
}
} else {
$valuesnap[$id]['count'] += $value['timecount'];
$valuesnap['count'] += $value['timecount'];
if($valuesnap['count'] < 0) {
$valuesnap['count'] = $valuesnap['idle'] = 0;
} elseif ($valuesnap['idle'] > $valuesnap['count']) {
$valuesnap['idle'] = $valuesnap['count'];
}
$sqlexec2 .= "UPDATE `$dbname`.`user_snapshot` SET `count`='{$valuesnap[$id]['count']}', `idle`='{$valuesnap[$id]['idle']}' WHERE `cldbid`='{$temp_cldbid}' AND `id`='{$id}'; ";
$sqlexec .= "UPDATE `$dbname`.`user_snapshot` SET `count`='{$valuesnap['count']}', `idle`='{$valuesnap['idle']}' WHERE `cldbid`='{$temp_cldbid}' AND `id`='{$id}';\n";
}
}
if($mysqlcon->exec($sqlexec2) === false) {
enter_logfile($cfg,2,"Database error on updating user (admin function remove/add time): ".print_r($mysqlcon->errorInfo(), true));
}
enter_logfile($cfg,4,sprintf($lang['sccupcount2'],$value['timecount'],$uuid));
unset($sqlexec2, $user, $usersnap);
unset($user, $usersnap);
}
}
unset($db_cache['admin_addtime']);
@@ -95,7 +72,7 @@ function calc_user($ts3,$mysqlcon,$lang,$cfg,$dbname,$allclients,$phpcommand,&$d
foreach ($allclients as $client) {
$client_groups_rankup = array();
$name = $mysqlcon->quote((mb_substr($client['client_nickname'],0,30)), ENT_QUOTES);
$name = $mysqlcon->quote((mb_substr(mb_convert_encoding($client['client_nickname'],'UTF-8','auto'),0,30)), ENT_QUOTES);
$uid = htmlspecialchars($client['client_unique_identifier'], ENT_QUOTES);
$sgroups = array_flip(explode(",", $client['client_servergroups']));
if(strlen($client['client_country']) > 2 || $client['client_country'] == '') $client['client_country'] = 'XX';
@@ -218,7 +195,7 @@ function calc_user($ts3,$mysqlcon,$lang,$cfg,$dbname,$allclients,$phpcommand,&$d
$hours = $dtF->diff($dtT)->format('%h');
$mins = $dtF->diff($dtT)->format('%i');
$secs = $dtF->diff($dtT)->format('%s');
sendmessage($ts3, $cfg, $uid, 1, NULL, sprintf($cfg['rankup_message_to_user'],$days,$hours,$mins,$secs,$db_cache['groups'][$rank['group']]['sgidname'],$client['client_nickname']), sprintf($lang['sgrprerr'], $name, $uid, $client['client_database_id'], $db_cache['groups'][$rank['group']]['sgidname'],$rank['group']), 2);
sendmessage($ts3, $cfg, $uid, sprintf($cfg['rankup_message_to_user'],$days,$hours,$mins,$secs,$db_cache['groups'][$rank['group']]['sgidname'],$client['client_nickname']), 1, NULL, sprintf($lang['sgrprerr'], $name, $uid, $client['client_database_id'], $db_cache['groups'][$rank['group']]['sgidname'],$rank['group']), 2);
}
} catch (Exception $e) {
enter_logfile($cfg,2,"TS3 error: ".$e->getCode().': '.$e->getMessage()." ; ".sprintf($lang['sgrprerr'], $name, $uid, $client['client_database_id'], $db_cache['groups'][$rank['group']]['sgidname'], $rank['group']));

View File

@@ -5,15 +5,18 @@ function calc_userstats($ts3,$mysqlcon,$cfg,$dbname,&$db_cache) {
$sqlexec = '';
$job_begin = $db_cache['job_check']['calc_user_limit']['timestamp'];
$job_end = ceil(count($db_cache['all_user']) / 10) * 10;
if ($job_begin >= $job_end) {
$limit_calc = ceil(count($db_cache['all_user']) / 600);
if($limit_calc < 5) $limit_calc = 5;
if ($job_begin >= (ceil(count($db_cache['all_user']) / $limit_calc) * $limit_calc)) {
$job_begin = 0;
$job_end = 10;
$job_end = $limit_calc;
} else {
$job_end = $job_begin + 10;
$job_end = $job_begin + $limit_calc;
}
$sqlhis = array_slice($db_cache['all_user'],$job_begin ,10);
$sqlhis = array_slice($db_cache['all_user'],$job_begin ,$limit_calc);
$cldbids = '';
foreach ($sqlhis as $uuid => $userstats) {
@@ -23,8 +26,8 @@ function calc_userstats($ts3,$mysqlcon,$cfg,$dbname,&$db_cache) {
$weekago = $db_cache['job_check']['last_snapshot_id']['timestamp'] - 28;
$monthago = $db_cache['job_check']['last_snapshot_id']['timestamp'] - 120;
if ($weekago < 1) $weekago = $weekago + 121;
if ($monthago < 1) $monthago = $monthago + 121;
if ($weekago < 1) $weekago += 121;
if ($monthago < 1) $monthago += 121;
if(isset($sqlhis) && $sqlhis != NULL) {
enter_logfile($cfg,6,"Update User Stats between ".$job_begin." and ".$job_end.":");
@@ -35,79 +38,90 @@ function calc_userstats($ts3,$mysqlcon,$cfg,$dbname,&$db_cache) {
$allupdateuuid = '';
foreach ($sqlhis as $uuid => $userstats) {
check_shutdown($cfg); usleep($cfg['teamspeak_query_command_delay']);
if($userstats['lastseen'] > ($nowtime - 2678400)) {
check_shutdown($cfg); usleep($cfg['teamspeak_query_command_delay']);
$keybase = array_search($db_cache['job_check']['last_snapshot_id']['timestamp'], array_column($userdata[$userstats['cldbid']], 'id'));
$keyweek = array_search($weekago, array_column($userdata[$userstats['cldbid']], 'id'));
$keymonth = array_search($monthago, array_column($userdata[$userstats['cldbid']], 'id'));
if(isset($userdata[$userstats['cldbid']]) && $userdata[$userstats['cldbid']] != NULL) {
$keybase = array_search($db_cache['job_check']['last_snapshot_id']['timestamp'], array_column($userdata[$userstats['cldbid']], 'id'));
$keyweek = array_search($weekago, array_column($userdata[$userstats['cldbid']], 'id'));
$keymonth = array_search($monthago, array_column($userdata[$userstats['cldbid']], 'id'));
if(isset($userdata[$userstats['cldbid']]) && isset($userdata[$userstats['cldbid']][$keyweek]) && $userdata[$userstats['cldbid']][$keyweek]['id'] == $weekago) {
$count_week = $userdata[$userstats['cldbid']][$keybase]['count'] - $userdata[$userstats['cldbid']][$keyweek]['count'];
$idle_week = $userdata[$userstats['cldbid']][$keybase]['idle'] - $userdata[$userstats['cldbid']][$keyweek]['idle'];
$active_week = $count_week - $idle_week;
} else {
$count_week = 0;
$idle_week = 0;
$active_week = 0;
}
if(isset($userdata[$userstats['cldbid']]) && isset($userdata[$userstats['cldbid']][$keymonth]) && $userdata[$userstats['cldbid']][$keymonth]['id'] == $monthago) {
$count_month = $userdata[$userstats['cldbid']][$keybase]['count'] - $userdata[$userstats['cldbid']][$keymonth]['count'];
$idle_month = $userdata[$userstats['cldbid']][$keybase]['idle'] - $userdata[$userstats['cldbid']][$keymonth]['idle'];
$active_month = $count_month - $idle_month;
} else {
$count_month = 0;
$idle_month = 0;
$active_month = 0;
}
try {
$clientinfo = $ts3->clientInfoDb($userstats['cldbid']);
$clientdesc = $mysqlcon->quote($clientinfo['client_description'], ENT_QUOTES);
if($clientinfo['client_totalconnections'] > 16777215) $clientinfo['client_totalconnections'] = 16777215;
} catch (Exception $e) {
if($e->getCode() == 512 || $e->getCode() == 1281) {
enter_logfile($cfg,6,"Client (uuid: ".$uuid." cldbid: ".$userstats['cldbid'].") known by Ranksystem is missing in TS database, perhaps its already deleted or cldbid changed. Try to search for client by uuid.");
try {
$getcldbid = $ts3->clientFindDb($uuid, TRUE);
if($getcldbid[0] != $userstats['cldbid']) {
enter_logfile($cfg,4," Client (uuid: ".$uuid." cldbid: ".$userstats['cldbid'].") known by the Ranksystem changed its cldbid. New cldbid is ".$getcldbid[0].".");
if($cfg['rankup_client_database_id_change_switch'] == 1) {
$db_cache['all_user'][$uuid]['cldbid'] = $getcldbid[0];
$sqlexec .= "UPDATE `$dbname`.`user` SET `count`=0,`idle`=0 WHERE `uuid`='$uuid';\nUPDATE `$dbname`.`stats_user` SET `count_week`=0,`count_month`=0,`idle_week`=0,`idle_month`=0,`active_week`=0,`active_month`=0 WHERE `uuid`='$uuid';\nDELETE FROM `$dbname`.`user_snapshot` WHERE `cldbid`='{$userstats['cldbid']}';\n";
enter_logfile($cfg,4," ".sprintf($lang['changedbid'], $userstats['name'], $uuid, $userstats['cldbid'], $getcldbid[0]));
} else {
$sqlexec .= "UPDATE `$dbname`.`user` SET `cldbid`={$getcldbid[0]} WHERE `uuid`='$uuid';\n";
// select current user_snapshot entries and insert this with the new database-ID
foreach($userdata[$userstats['cldbid']] as $id => $data) {
$allinsert .= "($id,'{$getcldbid[0]}',{$data['count']},{$data['idle']}),";
}
if ($allinsert != '') {
$allinsert = substr($allinsert, 0, -1);
$sqlexec .= "INSERT INTO `$dbname`.`user_snapshot` (`id`,`cldbid`,`count`,`idle`) VALUES $allinsert ON DUPLICATE KEY UPDATE `count`=VALUES(`count`),`idle`=VALUES(`idle`);\nDELETE FROM `$dbname`.`user_snapshot` WHERE `cldbid`='{$userstats['cldbid']}';\n";
}
unset($allinsert);
enter_logfile($cfg,4," Store new cldbid ".$getcldbid[0]." for client (uuid: ".$uuid." old cldbid: ".$userstats['cldbid'].")");
}
} else {
enter_logfile($cfg,3," Client (uuid: ".$uuid." cldbid: ".$userstats['cldbid'].") is missing in TS database, but TeamSpeak answers on question with the same cldbid (".$getcldbid[0].").. It's weird!");
}
} catch (Exception $e) {
if($e->getCode() == 2568) {
enter_logfile($cfg,4,$e->getCode() . ': ' . $e->getMessage()."; Error due command clientdbfind (permission: b_virtualserver_client_dbsearch needed).");
} else {
enter_logfile($cfg,6,$e->getCode() . ': ' . $e->getMessage()."; Client (uuid: ".$uuid." cldbid: ".$userstats['cldbid'].") is missing in TS database, it seems to be deleted. Run the !clean command to correct this.");
$sqlexec .= "UPDATE `$dbname`.`stats_user` SET `count_week`=0,`count_month`=0,`idle_week`=0,`idle_month`=0,`active_week`=0,`active_month`=0,`removed`=1 WHERE `uuid`='$uuid';\n";
}
if(isset($userdata[$userstats['cldbid']]) && isset($userdata[$userstats['cldbid']][$keyweek]) && $userdata[$userstats['cldbid']][$keyweek]['id'] == $weekago) {
$count_week = $userdata[$userstats['cldbid']][$keybase]['count'] - $userdata[$userstats['cldbid']][$keyweek]['count'];
$idle_week = $userdata[$userstats['cldbid']][$keybase]['idle'] - $userdata[$userstats['cldbid']][$keyweek]['idle'];
$active_week = $count_week - $idle_week;
if($count_week < 0 || $count_week < $idle_week) $count_week = 0;
if($idle_week < 0 || $count_week < $idle_week) $idle_week = 0;
if($active_week < 0 || $count_week < $idle_week) $active_week = 0;
} else {
$count_week = $idle_week = $active_week = 0;
}
if(isset($userdata[$userstats['cldbid']]) && isset($userdata[$userstats['cldbid']][$keymonth]) && $userdata[$userstats['cldbid']][$keymonth]['id'] == $monthago) {
$count_month = $userdata[$userstats['cldbid']][$keybase]['count'] - $userdata[$userstats['cldbid']][$keymonth]['count'];
$idle_month = $userdata[$userstats['cldbid']][$keybase]['idle'] - $userdata[$userstats['cldbid']][$keymonth]['idle'];
$active_month = $count_month - $idle_month;
if($idle_month < 0 || $count_month < $idle_month) $idle_month = 0;
if($count_month < 0 || $count_month < $idle_month) $count_month = 0;
if($active_month < 0 || $count_month < $idle_month) $active_month = 0;
} else {
$count_month = $idle_month = $active_month = 0;
}
} else {
enter_logfile($cfg,2,$lang['errorts3'].$e->getCode().': '.$e->getMessage()."; Error due command clientdbinfo for client-database-ID {$userstats['cldbid']} (permission: b_virtualserver_client_dbinfo needed).");
$count_week = $idle_week = $active_week = $count_month = $idle_month = $active_month = 0;
}
$clientdesc = $clientinfo['client_base64HashClientUID'] = $mysqlcon->quote('', ENT_QUOTES);
$clientinfo['client_totalconnections'] = $clientinfo['client_total_bytes_uploaded'] = $clientinfo['client_total_bytes_downloaded'] = 0;
}
try {
$clientinfo = $ts3->clientInfoDb($userstats['cldbid']);
$clientdesc = $mysqlcon->quote($clientinfo['client_description'], ENT_QUOTES);
if($clientinfo['client_totalconnections'] > 16777215) $clientinfo['client_totalconnections'] = 16777215;
} catch (Exception $e) {
if($e->getCode() == 512 || $e->getCode() == 1281) {
enter_logfile($cfg,6,"Client (uuid: ".$uuid." cldbid: ".$userstats['cldbid'].") known by Ranksystem is missing in TS database, perhaps its already deleted or cldbid changed. Try to search for client by uuid.");
try {
$getcldbid = $ts3->clientFindDb($uuid, TRUE);
if($getcldbid[0] != $userstats['cldbid']) {
enter_logfile($cfg,4," Client (uuid: ".$uuid." cldbid: ".$userstats['cldbid'].") known by the Ranksystem changed its cldbid. New cldbid is ".$getcldbid[0].".");
if($cfg['rankup_client_database_id_change_switch'] == 1) {
$db_cache['all_user'][$uuid]['cldbid'] = $getcldbid[0];
$sqlexec .= "UPDATE `$dbname`.`user` SET `count`=0,`idle`=0 WHERE `uuid`='$uuid';\nUPDATE `$dbname`.`stats_user` SET `count_week`=0,`count_month`=0,`idle_week`=0,`idle_month`=0,`active_week`=0,`active_month`=0 WHERE `uuid`='$uuid';\nDELETE FROM `$dbname`.`user_snapshot` WHERE `cldbid`='{$userstats['cldbid']}';\n";
enter_logfile($cfg,4," ".sprintf($lang['changedbid'], $userstats['name'], $uuid, $userstats['cldbid'], $getcldbid[0]));
} else {
$sqlexec .= "UPDATE `$dbname`.`user` SET `cldbid`={$getcldbid[0]} WHERE `uuid`='$uuid';\n";
// select current user_snapshot entries and insert this with the new database-ID
if(isset($userdata[$userstats['cldbid']])) {
$allinsert = '';
foreach($userdata[$userstats['cldbid']] as $id => $data) {
$allinsert .= "($id,'{$getcldbid[0]}',{$data['count']},{$data['idle']}),";
}
if ($allinsert != '') {
$allinsert = substr($allinsert, 0, -1);
$sqlexec .= "INSERT INTO `$dbname`.`user_snapshot` (`id`,`cldbid`,`count`,`idle`) VALUES $allinsert ON DUPLICATE KEY UPDATE `count`=VALUES(`count`),`idle`=VALUES(`idle`);\nDELETE FROM `$dbname`.`user_snapshot` WHERE `cldbid`='{$userstats['cldbid']}';\n";
}
unset($allinsert);
}
enter_logfile($cfg,4," Store new cldbid ".$getcldbid[0]." for client (uuid: ".$uuid." old cldbid: ".$userstats['cldbid'].")");
}
} else {
enter_logfile($cfg,3," Client (uuid: ".$uuid." cldbid: ".$userstats['cldbid'].") is missing in TS database, but TeamSpeak answers on question with the same cldbid (".$getcldbid[0].").. It's weird!");
}
} catch (Exception $e) {
if($e->getCode() == 2568) {
enter_logfile($cfg,4,$e->getCode() . ': ' . $e->getMessage()."; Error due command clientdbfind (permission: b_virtualserver_client_dbsearch needed).");
} else {
enter_logfile($cfg,6,$e->getCode() . ': ' . $e->getMessage()."; Client (uuid: ".$uuid." cldbid: ".$userstats['cldbid'].") is missing in TS database, it seems to be deleted. Run the !clean command to correct this.");
$sqlexec .= "UPDATE `$dbname`.`stats_user` SET `count_week`=0,`count_month`=0,`idle_week`=0,`idle_month`=0,`active_week`=0,`active_month`=0,`removed`=1 WHERE `uuid`='$uuid';\n";
}
}
} else {
enter_logfile($cfg,2,$lang['errorts3'].$e->getCode().': '.$e->getMessage()."; Error due command clientdbinfo for client-database-ID {$userstats['cldbid']} (permission: b_virtualserver_client_dbinfo needed).");
}
$allupdateuuid .= "('$uuid',$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,$nowtime),";
$clientdesc = $clientinfo['client_base64HashClientUID'] = $mysqlcon->quote('', ENT_QUOTES);
$clientinfo['client_totalconnections'] = $clientinfo['client_total_bytes_uploaded'] = $clientinfo['client_total_bytes_downloaded'] = 0;
}
$allupdateuuid .= "('$uuid',$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,$nowtime),";
}
}
unset($sqlhis,$userdataweekbegin,$userdataend,$userdatamonthbegin,$clientinfo,$count_week,$idle_week,$active_week,$count_month,$idle_month,$active_month,$clientdesc);

View File

@@ -1,6 +1,6 @@
<?PHP
function check_db($mysqlcon,$lang,$cfg,$dbname) {
$cfg['version_latest_available'] = '1.3.12';
function check_db($mysqlcon,$lang,&$cfg,$dbname) {
$cfg['version_latest_available'] = '1.3.13';
enter_logfile($cfg,5,"Check Ranksystem database for updates...");
function check_double_cldbid($mysqlcon,$cfg,$dbname) {
@@ -40,7 +40,7 @@ function check_db($mysqlcon,$lang,$cfg,$dbname) {
function old_files($cfg) {
$del_folder = array('icons/','libs/ts3_lib/Adapter/Blacklist/','libs/ts3_lib/Adapter/TSDNS/','libs/ts3_lib/Adapter/Update/','libs/fonts/');
$del_files = array('install.php','libs/combined_stats.css','libs/combined_stats.js','webinterface/admin.php','libs/ts3_lib/Adapter/Blacklist/Exception.php','libs/ts3_lib/Adapter/TSDNS/Exception.php','libs/ts3_lib/Adapter/Update/Exception.php','libs/ts3_lib/Adapter/Blacklist.php','libs/ts3_lib/Adapter/TSDNS.php','libs/ts3_lib/Adapter/Update.php','languages/core_ar.php','languages/core_cz.php','languages/core_de.php','languages/core_en.php','languages/core_es.php','languages/core_fr.php','languages/core_it.php','languages/core_nl.php','languages/core_pl.php','languages/core_pt.php','languages/core_ro.php','languages/core_ru.php','webinterface/nav.php','stats/nav.php');
$del_files = array('install.php','libs/combined_stats.css','libs/combined_stats.js','webinterface/admin.php','libs/ts3_lib/Adapter/Blacklist/Exception.php','libs/ts3_lib/Adapter/TSDNS/Exception.php','libs/ts3_lib/Adapter/Update/Exception.php','libs/ts3_lib/Adapter/Blacklist.php','libs/ts3_lib/Adapter/TSDNS.php','libs/ts3_lib/Adapter/Update.php','languages/core_ar.php','languages/core_cz.php','languages/core_de.php','languages/core_en.php','languages/core_es.php','languages/core_fr.php','languages/core_it.php','languages/core_nl.php','languages/core_pl.php','languages/core_pt.php','languages/core_ro.php','languages/core_ru.php','webinterface/nav.php','stats/nav.php','other/session.php');
function rmdir_recursive($folder,$cfg) {
foreach(scandir($folder) as $file) {
if ('.' === $file || '..' === $file) continue;
@@ -358,19 +358,47 @@ function check_db($mysqlcon,$lang,$cfg,$dbname) {
}
if(version_compare($cfg['version_current_using'], '1.3.12', '<')) {
if($mysqlcon->exec("DELETE FROM `$dbname`.`admin_addtime`;") === false) { }
if($mysqlcon->exec("DELETE FROM `$dbname`.`addon_assign_groups`;") === false) { }
if($mysqlcon->exec("INSERT INTO `$dbname`.`cfg_params` (`param`,`value`) VALUES ('stats_imprint_switch', '0'),('stats_imprint_address', 'Max Mustermann<br>Musterstraße 13<br>05172 Musterhausen<br>Germany'),('stats_imprint_address_url', 'https://site.url/imprint/'), ('stats_imprint_email', 'info@example.com'),('stats_imprint_phone', '+49 171 1234567'),('stats_imprint_notes', NULL),('stats_imprint_privacypolicy', 'Add your own privacy policy here. (editable in the webinterface)'),('stats_imprint_privacypolicy_url', 'https://site.url/privacy/');") === false) { } else {
enter_logfile($cfg,4," [1.3.12] Added new imprint values.");
}
}
if(version_compare($cfg['version_current_using'], '1.3.13', '<')) {
if($mysqlcon->exec("DELETE FROM `$dbname`.`admin_addtime`;") === false) { }
if($mysqlcon->exec("DELETE FROM `$dbname`.`addon_assign_groups`;") === false) { }
if($mysqlcon->exec("UPDATE `$dbname`.`user` SET `idle`=0 WHERE `idle`<0; UPDATE `$dbname`.`user` SET `count`=`idle` WHERE `count`<0; UPDATE `$dbname`.`user` SET `count`=`idle` WHERE `count`<`idle`;") === false) { }
if($mysqlcon->exec("UPDATE `$dbname`.`user_snapshot` SET `idle`=0 WHERE `idle`<0; UPDATE `$dbname`.`user_snapshot` SET `count`=`idle` WHERE `count`<0; UPDATE `$dbname`.`user_snapshot` SET `count`=`idle` WHERE `count`<`idle`;") === false) { }
if($mysqlcon->exec("CREATE INDEX `snapshot_id` ON `$dbname`.`user_snapshot` (`id`)") === false) { }
if($mysqlcon->exec("CREATE INDEX `snapshot_cldbid` ON `$dbname`.`user_snapshot` (`cldbid`)") === false) { }
if($mysqlcon->exec("CREATE INDEX `serverusage_timestamp` ON `$dbname`.`server_usage` (`timestamp`)") === false) { }
if($mysqlcon->exec("CREATE INDEX `user_version` ON `$dbname`.`user` (`version`)") === false) { }
if($mysqlcon->exec("CREATE INDEX `user_cldbid` ON `$dbname`.`user` (`cldbid` ASC,`uuid`,`rank`)") === false) { }
if($mysqlcon->exec("CREATE INDEX `user_online` ON `$dbname`.`user` (`online`,`lastseen`)") === false) { }
if($mysqlcon->exec("INSERT INTO `$dbname`.`job_check` (`job_name`,`timestamp`) VALUES ('database_export', '0'),('update_groups', '0') ON DUPLICATE KEY UPDATE `timestamp`=VALUES(`timestamp`);") === false) { } else {
enter_logfile($cfg,4," [1.3.13] Added new job_check values.");
}
try {
if($mysqlcon->exec("INSERT IGNORE INTO `$dbname`.`cfg_params` (`param`,`value`) VALUES ('webinterface_fresh_installation', '0'),('stats_column_nation_switch', '0'),('stats_column_version_switch', '0'),('stats_column_platform_switch', '0');") === false) { }
} catch (Exception $e) { }
if($mysqlcon->exec("INSERT INTO `$dbname`.`cfg_params` (`param`,`value`) VALUES ('default_session_sametime', 'Strict'),('default_header_origin', ''),('default_header_xss', '1; mode=block'),('default_header_contenttyp', '1'),('default_header_frame', '') ON DUPLICATE KEY UPDATE `value`=VALUES(`value`);") === false) { } else {
enter_logfile($cfg,4," [1.3.13] Added new cfg_params values.");
}
if($mysqlcon->exec("UPDATE `$dbname`.`user` SET `nation`='XX' WHERE `nation`='';") === false) { } else {
enter_logfile($cfg,4," [1.3.13] Updated table user.");
}
try {
if($mysqlcon->exec("DROP INDEX `snapshot_id` ON `$dbname`.`user_snapshot` (`id`)") === false) { } else {
enter_logfile($cfg,4," [1.3.13] Dropped unneeded Index snapshot_id on table user_snapshot.");
}
if($mysqlcon->exec("DROP INDEX `snapshot_cldbid` ON `$dbname`.`user_snapshot` (`cldbid`)") === false) { } else {
enter_logfile($cfg,4," [1.3.13] Dropped unneeded Index snapshot_cldbid on table user_snapshot.");
}
if($mysqlcon->exec("CREATE INDEX `serverusage_timestamp` ON `$dbname`.`server_usage` (`timestamp`)") === false) { }
if($mysqlcon->exec("CREATE INDEX `user_version` ON `$dbname`.`user` (`version`)") === false) { }
if($mysqlcon->exec("CREATE INDEX `user_cldbid` ON `$dbname`.`user` (`cldbid` ASC,`uuid`,`rank`)") === false) { }
if($mysqlcon->exec("CREATE INDEX `user_online` ON `$dbname`.`user` (`online`,`lastseen`)") === false) { }
} catch (Exception $e) { }
}
$cfg = set_new_version($mysqlcon,$cfg,$dbname);
}

139
jobs/db_ex_imp.php Normal file
View File

@@ -0,0 +1,139 @@
<?PHP
function db_ex_imp($ts3,$mysqlcon,$lang,$cfg,$dbname,&$db_cache) {
$starttime = microtime(true);
if (in_array($db_cache['job_check']['database_export']['timestamp'], ["1","2"], true)) {
enter_logfile($cfg,4,"DB Export job(s) started");
$err = 0;
if($mysqlcon->exec("UPDATE `$dbname`.`job_check` SET `timestamp`='2' WHERE `job_name`='database_export';") === false) {
$err++;
enter_logfile($cfg,2," Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
} else {
$db_cache['job_check']['database_export']['timestamp'] = 2;
enter_logfile($cfg,4," Started job '".$lang['wihladmex']."'");
}
$datetime = date("Y-m-d_H-i-s", time());
$filepath = $cfg['logs_path'].'db_export_'.$datetime;
$filename = 'db_export_'.$datetime;
$limit_entries = 10000;
if (($tables = $mysqlcon->query("SHOW TABLES")->fetchALL(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC)) === false) {
$err++;
enter_logfile($cfg,2," Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
} else {
$dump = fopen($filepath.".sql", 'a');
fwrite($dump, "-- Ranksystem SQL Export\n-- from $datetime\n");
fclose($dump);
foreach ($tables as $table => $value) {
$out = '';
if(substr($table, 0, 4) == 'bak_') continue;
#if($table == 'user_snapshot') continue;
if (($numColumns = $mysqlcon->query("SELECT * FROM `$dbname`.`$table` LIMIT 1")->columnCount()) === false) {
$err++;
enter_logfile($cfg,2," Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
}
$out .= 'DROP TABLE IF EXISTS `' . $table . '`;' . "\n\n";
if (($create_table = $mysqlcon->query("SHOW CREATE TABLE `$dbname`.`$table`")->fetch(PDO::FETCH_ASSOC)) === false) {
$err++;
enter_logfile($cfg,2," Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
}
$out .= $create_table['Create Table'] . ';' . "\n\n";
if (($maxvalues = $mysqlcon->query("SELECT COUNT(*) FROM `$dbname`.`$table`;")->fetch()) === false) {
$err++;
enter_logfile($cfg,2," Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
}
$dump = fopen($filepath.".sql", 'a');
fwrite($dump, $out);
fclose($dump);
unset($out);
$loops = $maxvalues[0] / $limit_entries;
for ($i = 0; $i <= $loops; $i++) {
$out = '';
$offset = $i * $limit_entries;
if (($sqldata = $mysqlcon->query("SELECT * FROM `$dbname`.`$table` LIMIT {$limit_entries} OFFSET {$offset}")->fetchALL(PDO::FETCH_NUM)) === false) {
$err++;
enter_logfile($cfg,2," Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
}
if(count($sqldata) != 0) {
$out .= "INSERT INTO `$table` VALUES";
foreach ($sqldata as $row) {
$out .= "(";
for ($j = 0; $j < $numColumns; $j++) {
if (isset($row[$j])) {
$out .= $mysqlcon->quote(($row[$j]), ENT_QUOTES);
} else {
$out .= '""';
}
if ($j < ($numColumns - 1)) {
$out .= ',';
}
}
$out .= '),';
}
$out = substr($out,0,-1);
$out .= ";";
}
$out .= "\n\n";
$dump = fopen($filepath.".sql", 'a');
fwrite($dump, $out);
fclose($dump);
unset($out, $sqldata);
}
}
$dump = fopen($filepath.".sql", 'a');
fwrite($dump, "-- Finished export");
fclose($dump);
$zip = new ZipArchive();
if ($zip->open($filepath.".sql.zip", ZipArchive::CREATE)!==TRUE) {
$err++;
enter_logfile($cfg,2," Cannot create $filepath.sql.zip!");
} else {
$zip->addFile($filepath.".sql",$filename.".sql");
if(version_compare(phpversion(), '7.2', '>=')) {
$zip->setEncryptionName($filename.".sql", ZipArchive::EM_AES_256, $cfg['teamspeak_query_pass']);
}
$zip->close();
if(!unlink($filepath.".sql")) {
$err++;
enter_logfile($cfg,2," Cannot remove SQL file $filepath.sql!");
}
}
}
if ($err == 0) {
if($mysqlcon->exec("UPDATE `$dbname`.`job_check` SET `timestamp`='4' WHERE `job_name`='database_export';") === false) {
enter_logfile($cfg,2," Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
} else {
$db_cache['job_check']['database_export']['timestamp'] = 4;
enter_logfile($cfg,4," Finished job '".$lang['wihladmex']."'");
}
} else {
if($mysqlcon->exec("UPDATE `$dbname`.`job_check` SET `timestamp`='3' WHERE `job_name`='database_export';") === false) {
enter_logfile($cfg,2," Executing SQL commands failed: ".print_r($mysqlcon->errorInfo(), true));
} else {
$db_cache['job_check']['database_export']['timestamp'] = 3;
}
}
enter_logfile($cfg,4,"DB Export job(s) finished");
}
enter_logfile($cfg,6,"db_ex_imp needs: ".(number_format(round((microtime(true) - $starttime), 5),5)));
}
?>

View File

@@ -30,7 +30,11 @@ function event_userenter(TeamSpeak3_Adapter_ServerQuery_Event $event, TeamSpeak3
$ip = '';
} elseif($cfg['rankup_hash_ip_addresses_mode'] == 2) {
$salt = md5(dechex(crc32(substr(__DIR__,0,-4))));
$hash = password_hash($ip, PASSWORD_DEFAULT, array("cost" => 10, "salt" => $salt));
if(version_compare(PHP_VERSION, '7.9.9', '>')) {
$hash = crypt($ip, '$2y$10$'.$salt.'$');
} else {
$hash = password_hash($ip, PASSWORD_DEFAULT, array("cost" => 10, "salt" => $salt));
}
$ip = '';
} else {
$hash = '';

View File

@@ -2,6 +2,7 @@
function get_avatars($ts3,$cfg,$dbname,&$db_cache) {
$starttime = microtime(true);
$nowtime = time();
$sqlexec = '';
if($db_cache['job_check']['get_avatars']['timestamp'] < ($nowtime - 32)) {
$db_cache['job_check']['get_avatars']['timestamp'] = $nowtime;

View File

@@ -60,7 +60,7 @@ function handle_messages(TeamSpeak3_Adapter_ServerQuery_Event $event, TeamSpeak3
$msg = sprintf($cfg['rankup_next_message_1'], $days, $hours, $mins, $secs, $sqlhisgroup[$rank['group']]['sgidname'], $name, $user['rank'], $sqlhisgroup[$user['grpid']]['sgidname'], date('Y-m-d H:i:s', $user['grpsince']));
}
$targetid = $event["invokerid"];
sendmessage($host, $cfg, $event["invokeruid"], 1, $targetid, $msg);
sendmessage($host, $cfg, $event["invokeruid"], $msg, 1, $targetid);
if($cfg['rankup_next_message_mode'] == 1) {
break;
}
@@ -72,39 +72,38 @@ function handle_messages(TeamSpeak3_Adapter_ServerQuery_Event $event, TeamSpeak3
if(strstr($event["msg"], '!version')) {
if(version_compare($cfg['version_latest_available'], $cfg['version_current_using'], '>') && $cfg['version_latest_available'] != '') {
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, sprintf($lang['upmsg'], $cfg['version_current_using'], $cfg['version_latest_available'], 'https://ts-ranksystem.com/#changelog'));
sendmessage($host, $cfg, $event["invokeruid"], sprintf($lang['upmsg'], $cfg['version_current_using'], $cfg['version_latest_available'], 'https://ts-ranksystem.com/#changelog'), $event["targetmode"], $targetid);
} else {
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, sprintf($lang['msg0001'], $cfg['version_current_using']));
sendmessage($host, $cfg, $event["invokeruid"], sprintf($lang['msg0001'], $cfg['version_current_using']), $event["targetmode"], $targetid);
}
return;
}
if(strstr($event["msg"], '!help') || strstr($event["msg"], '!info') || strstr($event["msg"], '!commands') || strstr($event["msg"], '!cmd')) {
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, $lang['msg0002']);
sendmessage($host, $cfg, $event["invokeruid"], $lang['msg0002'], $event["targetmode"], $targetid);
return;
}
if((strstr($event["msg"], '!shutdown') || strstr($event["msg"], '!quit') || strstr($event["msg"], '!stop')) && $admin == 1) {
enter_logfile($cfg,5,sprintf($lang['msg0004'], $event["invokername"], $event["invokeruid"]));
$path = substr(__DIR__, 0, -4);
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, $lang['msg0005']);
sendmessage($host, $cfg, $event["invokeruid"], $lang['msg0005'], $event["targetmode"], $targetid);
if (substr(php_uname(), 0, 7) == "Windows") {
exec("start ".$phpcommand." ".$path."worker.php stop");
file_put_contents(substr(__DIR__,0,-4).'logs\autostart_deactivated',"");
} else {
exec($phpcommand." ".$path."worker.php stop > /dev/null &");
file_put_contents(substr(__DIR__,0,-4).'logs/autostart_deactivated',"");
}
file_put_contents($cfg['logs_path'].'autostart_deactivated',"");
shutdown($mysql,$cfg,4,"Stop command received!");
} elseif (strstr($event["msg"], '!shutdown') || strstr($event["msg"], '!quit') || strstr($event["msg"], '!stop')) {
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, $lang['msg0003']);
sendmessage($host, $cfg, $event["invokeruid"], $lang['msg0003'], $event["targetmode"], $targetid);
return;
}
if((strstr($event["msg"], '!restart') || strstr($event["msg"], '!reboot')) && $admin == 1) {
enter_logfile($cfg,5,sprintf($lang['msg0007'], $event["invokername"], $event["invokeruid"], "restart"));
$path = substr(__DIR__, 0, -4);
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, $lang['msg0006']);
sendmessage($host, $cfg, $event["invokeruid"], $lang['msg0006'], $event["targetmode"], $targetid);
if (substr(php_uname(), 0, 7) == "Windows") {
exec("start ".$phpcommand." ".$path."worker.php restart");
} else {
@@ -112,18 +111,18 @@ function handle_messages(TeamSpeak3_Adapter_ServerQuery_Event $event, TeamSpeak3
}
return;
} elseif (strstr($event["msg"], '!restart') || strstr($event["msg"], '!reboot')) {
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, $lang['msg0003']);
sendmessage($host, $cfg, $event["invokeruid"], $lang['msg0003'], $event["targetmode"], $targetid);
return;
}
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) {
if($mysqlcon->exec("UPDATE `$dbname`.`job_check` SET `timestamp`='0' WHERE `job_name` IN ('check_update','get_version','calc_server_stats','calc_donut_chars')") === false) {
enter_logfile($cfg,4,"handle_messages 13:".print_r($mysqlcon->errorInfo(), true));
}
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, $lang['msg0008']);
sendmessage($host, $cfg, $event["invokeruid"], $lang['msg0008'], $event["targetmode"], $targetid);
return;
} elseif(strstr($event["msg"], '!checkupdate') || strstr($event["msg"], '!update')) {
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, $lang['msg0003']);
sendmessage($host, $cfg, $event["invokeruid"], $lang['msg0003'], $event["targetmode"], $targetid);
return;
}
@@ -132,10 +131,10 @@ function handle_messages(TeamSpeak3_Adapter_ServerQuery_Event $event, TeamSpeak3
if($mysqlcon->exec("UPDATE `$dbname`.`job_check` SET `timestamp`='0' WHERE `job_name` IN ('clean_db','clean_clients')") === false) {
enter_logfile($cfg,4,"handle_messages 13:".print_r($mysqlcon->errorInfo(), true));
}
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, $lang['msg0009'] ." ". $lang['msg0010']);
sendmessage($host, $cfg, $event["invokeruid"], $lang['msg0009'] ." ". $lang['msg0010'], $event["targetmode"], $targetid);
return;
} elseif(strstr($event["msg"], '!clean')) {
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, $lang['msg0003']);
sendmessage($host, $cfg, $event["invokeruid"], $lang['msg0003'], $event["targetmode"], $targetid);
return;
}
@@ -147,25 +146,25 @@ function handle_messages(TeamSpeak3_Adapter_ServerQuery_Event $event, TeamSpeak3
enter_logfile($cfg,4,"handle_messages 15:".print_r($mysqlcon->errorInfo(), true));
}
}
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, $lang['msg0011'] ." ". $lang['msg0010']);
sendmessage($host, $cfg, $event["invokeruid"], $lang['msg0011'] ." ". $lang['msg0010'], $event["targetmode"], $targetid);
return;
} elseif(strstr($event["msg"], '!reloadgroups')) {
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, $lang['msg0003']);
sendmessage($host, $cfg, $event["invokeruid"], $lang['msg0003'], $event["targetmode"], $targetid);
return;
}
if(strstr($event["msg"], '!online') || strstr($event["msg"], '!uptime')) {
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, sprintf("Bot is online since %s, now %s.", (DateTime::createFromFormat('U', $cfg['temp_last_botstart'])->setTimeZone(new DateTimeZone($cfg['logs_timezone']))->format("Y-m-d H:i:s")), (new DateTime("@0"))->diff(new DateTime("@".(time()-$cfg['temp_last_botstart'])))->format($cfg['default_date_format'])));
sendmessage($host, $cfg, $event["invokeruid"], sprintf("Bot is online since %s, now %s.", (DateTime::createFromFormat('U', $cfg['temp_last_botstart'])->setTimeZone(new DateTimeZone($cfg['logs_timezone']))->format("Y-m-d H:i:s")), (new DateTime("@0"))->diff(new DateTime("@".(time()-$cfg['temp_last_botstart'])))->format($cfg['default_date_format'])), $event["targetmode"], $targetid);
return;
}
if(strstr($event["msg"], '!runtime') || strstr($event["msg"], '!runtimes')) {
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, sprintf("Last 10 runtimes (in seconds):\n%s\n\nØ %s sec. (Σ %s)", str_replace(";","\n",$cfg['temp_last_laptime']), round(($cfg['temp_whole_laptime'] / $cfg['temp_count_laptime']),5), $cfg['temp_count_laptime']));
sendmessage($host, $cfg, $event["invokeruid"], sprintf("Last 10 runtimes (in seconds):\n%s\n\nØ %s sec. (Σ %s)", str_replace(";","\n",$cfg['temp_last_laptime']), round(($cfg['temp_whole_laptime'] / $cfg['temp_count_laptime']),5), $cfg['temp_count_laptime']), $event["targetmode"], $targetid);
return;
}
if(strstr($event["msg"], '!memory')) {
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, sprintf("Allocated memory of PHP for the Ranksystem Bot..\ncurrent using: %s KiB\npeak using: %s KiB", round((memory_get_usage()/1024),2), round((memory_get_peak_usage()/1024),2)));
sendmessage($host, $cfg, $event["invokeruid"], sprintf("Allocated memory of PHP for the Ranksystem Bot..\ncurrent using: %s KiB\npeak using: %s KiB", round((memory_get_usage()/1024),2), round((memory_get_peak_usage()/1024),2)), $event["targetmode"], $targetid);
return;
}
@@ -220,12 +219,12 @@ function handle_messages(TeamSpeak3_Adapter_ServerQuery_Event $event, TeamSpeak3
$message .= $line;
}
$targetid = $event["invokerid"];
sendmessage($host, $cfg, $event["invokeruid"], 1, $targetid, $message, NULL, NULL, NULL, $nolog=1);
sendmessage($host, $cfg, $event["invokeruid"], $message, 1, $targetid, NULL, NULL, NULL, $nolog=1);
} elseif(strstr($event["msg"], '!logs') || strstr($event["msg"], '!log')) {
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, $lang['msg0003']);
sendmessage($host, $cfg, $event["invokeruid"], $lang['msg0003'], $event["targetmode"], $targetid);
}
sendmessage($host, $cfg, $event["invokeruid"], $event["targetmode"], $targetid, $lang['msg0002']);
sendmessage($host, $cfg, $event["invokeruid"], $lang['msg0002'], $event["targetmode"], $targetid);
}
}
?>

View File

@@ -40,7 +40,11 @@ function update_groups($ts3,$mysqlcon,$lang,$cfg,$dbname,$serverinfo,&$db_cache,
$sIconFile = 0;
$extension = '';
if (!isset($db_cache['groups']['0']) || $db_cache['groups']['0']['iconid'] != $sIconId || (isset($iconarr["i".$sIconId]) && $iconarr["i".$sIconId] > $db_cache['groups']['0']['icondate'])) {
enter_logfile($cfg,6,"Servericon TSiconid:".$serverinfo['virtualserver_icon_id']."; powed TSiconid:".$sIconId."; DBiconid:".$db_cache['groups']['0']['iconid']."; TSicondate:".$iconarr["i".$sIconId]."; DBicondate:".$db_cache['groups']['0']['icondate'].";");
if(isset($db_cache['groups']['0']) && isset($iconarr["i".$sIconId])) {
enter_logfile($cfg,6,"Servericon TSiconid:".$serverinfo['virtualserver_icon_id']."; powed TSiconid:".$sIconId."; DBiconid:".$db_cache['groups']['0']['iconid']."; TSicondate:".$iconarr["i".$sIconId]."; DBicondate:".$db_cache['groups']['0']['icondate'].";");
} else {
enter_logfile($cfg,6,"Servericon TSiconid:".$serverinfo['virtualserver_icon_id']."; powed TSiconid:".$sIconId."; DBiconid: empty; TSicondate: empty; DBicondate: empty;");
}
if($sIconId > 600) {
try {
usleep($cfg['teamspeak_query_command_delay']);
@@ -62,7 +66,7 @@ function update_groups($ts3,$mysqlcon,$lang,$cfg,$dbname,$serverinfo,&$db_cache,
}
}
$iconarr["i".$sIconId] = $sIconId = 0;
} elseif($iconid < 601) {
} elseif($sIconId < 601) {
$extension = 'png';
} else {
$sIconId = 0;
@@ -90,7 +94,7 @@ function update_groups($ts3,$mysqlcon,$lang,$cfg,$dbname,$serverinfo,&$db_cache,
$tsgroupids[$servergroup['sgid']] = 0;
$sgid = $servergroup['sgid'];
$extension = '';
$sgname = $mysqlcon->quote((mb_substr($servergroup['name'],0,30)), ENT_QUOTES);
$sgname = $mysqlcon->quote((mb_substr(mb_convert_encoding($servergroup['name'],'UTF-8','auto'),0,30)), ENT_QUOTES);
$iconid = $servergroup['iconid'];
$iconid = ($iconid < 0) ? (pow(2, 32)) - ($iconid * -1) : $iconid;
$iconfile = 0;
@@ -128,7 +132,7 @@ function update_groups($ts3,$mysqlcon,$lang,$cfg,$dbname,$serverinfo,&$db_cache,
$iconarr["i".$iconid] = 0;
}
if(isset($db_cache['groups'][$servergroup['sgid']]) && $db_cache['groups'][$servergroup['sgid']]['sgidname'] == $servergroup['name'] && $db_cache['groups'][$servergroup['sgid']]['iconid'] == $iconid && $db_cache['groups'][$servergroup['sgid']]['icondate'] == $iconarr["i".$iconid] && $db_cache['groups'][$servergroup['sgid']]['sortid'] == $servergroup['sortid']) {
if(isset($db_cache['groups'][$servergroup['sgid']]) && $db_cache['groups'][$servergroup['sgid']]['sgidname'] == $sgname && $db_cache['groups'][$servergroup['sgid']]['iconid'] == $iconid && $db_cache['groups'][$servergroup['sgid']]['icondate'] == $iconarr["i".$iconid] && $db_cache['groups'][$servergroup['sgid']]['sortid'] == $servergroup['sortid']) {
enter_logfile($cfg,7,"Continue server group ".$sgname." (CID: ".$servergroup['sgid'].")");
continue;
} else {

View File

@@ -1,5 +1,7 @@
<?PHP
function update_rs($mysqlcon,$lang,$cfg,$dbname,$phpcommand,$norotate=NULL) {
$nowtime = time();
$sqlexec = '';
$norotate = true;
enter_logfile($cfg,4," Start updating the Ranksystem...",$norotate);
enter_logfile($cfg,4," Backup the database due cloning tables...",$norotate);
@@ -8,14 +10,16 @@ function update_rs($mysqlcon,$lang,$cfg,$dbname,$phpcommand,$norotate=NULL) {
$tables = array('addons_config','cfg_params','groups','job_check','server_usage','stats_server','stats_user','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($cfg,1," Error due deleting old backup table bak_".$table.".",$norotate);
$countbackuperr++;
} else {
enter_logfile($cfg,4," Old backup table bak_".$table." successfully removed.",$norotate);
try {
if($mysqlcon->query("SELECT 1 FROM `$dbname`.`bak_$table` LIMIT 1") !== false) {
if($mysqlcon->exec("DROP TABLE `$dbname`.`bak_$table`") === false) {
enter_logfile($cfg,1," Error due deleting old backup table bak_".$table.".",$norotate);
$countbackuperr++;
} else {
enter_logfile($cfg,4," Old backup table bak_".$table." successfully removed.",$norotate);
}
}
}
} catch (Exception $e) { }
}
foreach ($tables as $table) {
@@ -62,72 +66,81 @@ function update_rs($mysqlcon,$lang,$cfg,$dbname,$phpcommand,$norotate=NULL) {
} else {
enter_logfile($cfg,5," New update file (update/ranksystem_".$cfg['version_latest_available'].".zip) already here...",$norotate);
}
$zipHandle = zip_open(substr(__DIR__,0,-4).'update/ranksystem_'.$cfg['version_latest_available'].'.zip');
$countwrongfiles = 0;
$countchangedfiles = 0;
$zip = new ZipArchive;
while ($aF = zip_read($zipHandle)) {
$thisFileName = zip_entry_name($aF);
$thisFileDir = dirname($thisFileName);
enter_logfile($cfg,6," Parent directory: ".$thisFileDir,$norotate);
enter_logfile($cfg,6," File/Dir: ".$thisFileName,$norotate);
if(substr($thisFileName,-1,1) == '/' || substr($thisFileName,-1,1) == '\\') {
enter_logfile($cfg,6," Check folder is existing: ".$thisFileName,$norotate);
if(!is_dir(substr(__DIR__,0,-4).substr($thisFileName,0,-1))) {
enter_logfile($cfg,5," Create folder: ".substr(__DIR__,0,-4).substr($thisFileName,0,-1),$norotate);
if(mkdir((substr(__DIR__,0,-4).substr($thisFileName,0,-1)), 0755, true)) {
enter_logfile($cfg,4," Created new folder ".substr(__DIR__,0,-4).substr($thisFileName,0,-1),$norotate);
if($zip->open(substr(__DIR__,0,-4).'update/ranksystem_'.$cfg['version_latest_available'].'.zip')) {
for ($i = 0; $i < $zip->numFiles; $i++) {
$thisFileName = $zip->getNameIndex($i);
$thisFileDir = dirname($thisFileName);
enter_logfile($cfg,6," Parent directory: ".$thisFileDir,$norotate);
enter_logfile($cfg,6," File/Dir: ".$thisFileName,$norotate);
if(substr($thisFileName,-1,1) == '/' || substr($thisFileName,-1,1) == '\\') {
enter_logfile($cfg,6," Check folder is existing: ".$thisFileName,$norotate);
if(!is_dir(substr(__DIR__,0,-4).substr($thisFileName,0,-1))) {
enter_logfile($cfg,5," Create folder: ".substr(__DIR__,0,-4).substr($thisFileName,0,-1),$norotate);
if(mkdir((substr(__DIR__,0,-4).substr($thisFileName,0,-1)), 0740, true)) {
enter_logfile($cfg,4," Created new folder ".substr(__DIR__,0,-4).substr($thisFileName,0,-1),$norotate);
} else {
enter_logfile($cfg,2," Error by creating folder ".substr(__DIR__,0,-4).substr($thisFileName,0,-1).". Please check the permissions on the folder one level above.",$norotate);
$countwrongfiles++;
}
} else {
enter_logfile($cfg,2," Error by creating folder ".substr(__DIR__,0,-4).substr($thisFileName,0,-1).". Please check the permissions on the folder one level above.",$norotate);
$countwrongfiles++;
}
} else {
enter_logfile($cfg,6," Folder still existing.",$norotate);
enter_logfile($cfg,6," Folder still existing.",$norotate);
}
continue;
}
continue;
}
if(!is_dir(substr(__DIR__,0,-4).'/'.$thisFileDir)) {
enter_logfile($cfg,6," Check parent folder is existing: ".$thisFileDir,$norotate);
if(mkdir(substr(__DIR__,0,-4).$thisFileDir, 0755, true)) {
enter_logfile($cfg,4," Created new folder ".$thisFileDir,$norotate);
if(!is_dir(substr(__DIR__,0,-4).'/'.$thisFileDir)) {
enter_logfile($cfg,6," Check parent folder is existing: ".$thisFileDir,$norotate);
if(mkdir(substr(__DIR__,0,-4).$thisFileDir, 0740, true)) {
enter_logfile($cfg,4," Created new folder ".$thisFileDir,$norotate);
} else {
enter_logfile($cfg,2," Error by creating folder ".$thisFileDir.". Please check the permissions on your folder ".substr(__DIR__,0,-4),$norotate);
$countwrongfiles++;
}
} else {
enter_logfile($cfg,2," Error by creating folder ".$thisFileDir.". Please check the permissions on your folder ".substr(__DIR__,0,-4),$norotate);
enter_logfile($cfg,6," Parent folder still existing.",$norotate);
}
enter_logfile($cfg,6," Check file: ".substr(__DIR__,0,-4).$thisFileName,$norotate);
if(!is_dir(substr(__DIR__,0,-4).$thisFileName)) {
$contents = $zip->getFromName($thisFileName);
$updateThis = '';
if($thisFileName == 'other/dbconfig.php' || $thisFileName == 'install.php' || $thisFileName == 'other/phpcommand.php' || $thisFileName == 'logs/autostart_deactivated') {
enter_logfile($cfg,5," Did not touch ".$thisFileName,$norotate);
} else {
if(($updateThis = fopen(substr(__DIR__,0,-4).'/'.$thisFileName, 'w')) === false) {
enter_logfile($cfg,2," Failed to open file ".$thisFileName,$norotate);
$countwrongfiles++;
} elseif(!fwrite($updateThis, $contents)) {
enter_logfile($cfg,2," Failed to write file ".$thisFileName,$norotate);
$countwrongfiles++;
} else {
enter_logfile($cfg,4," Replaced file ".$thisFileName,$norotate);
$countchangedfiles++;
}
fclose($updateThis);
unset($contents);
}
} else {
enter_logfile($cfg,2," Unkown thing happened.. Is the parent directory existing? ".$thisFileDir." # ".$thisFileName,$norotate);
$countwrongfiles++;
}
} else {
enter_logfile($cfg,6," Parent folder still existing.",$norotate);
}
enter_logfile($cfg,6," Check file: ".substr(__DIR__,0,-4).$thisFileName,$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' || $thisFileName == 'logs/autostart_deactivated') {
enter_logfile($cfg,5," Did not touch ".$thisFileName,$norotate);
} else {
if(($updateThis = fopen(substr(__DIR__,0,-4).'/'.$thisFileName, 'w')) === false) {
enter_logfile($cfg,2," Failed to open file ".$thisFileName,$norotate);
$countwrongfiles++;
} elseif(!fwrite($updateThis, $contents)) {
enter_logfile($cfg,2," Failed to write file ".$thisFileName,$norotate);
$countwrongfiles++;
} else {
enter_logfile($cfg,4," Replaced file ".$thisFileName,$norotate);
$countchangedfiles++;
}
fclose($updateThis);
unset($contents);
}
} else {
enter_logfile($cfg,2," Unkown thing happened.. Is the parent directory existing? ".$thisFileDir." # ".$thisFileName,$norotate);
$countwrongfiles++;
}
$zip->close();
unset($zip);
sleep(1);
} else {
enter_logfile($cfg,2," Error with downloaded Zip file happened. Is the file inside the folder 'update' valid and readable?",$norotate);
$countwrongfiles++;
}
if(!unlink(substr(__DIR__,0,-4).'update/ranksystem_'.$cfg['version_latest_available'].'.zip')) {
enter_logfile($cfg,3," Could not clean update folder. Please remove the unneeded file ".substr(__DIR__,0,-4)."update/ranksystem_".$cfg['version_latest_available'].".zip",$norotate);
} else {
@@ -135,31 +148,30 @@ function update_rs($mysqlcon,$lang,$cfg,$dbname,$phpcommand,$norotate=NULL) {
}
if($countwrongfiles == 0 && $countchangedfiles != 0) {
$nowtime = time();
if($mysqlcon->exec("UPDATE `$dbname`.`job_check` SET `timestamp`='$nowtime' WHERE `job_name`='get_version'; UPDATE `$dbname`.`cfg_params` SET `value`='{$cfg['version_latest_available']}' WHERE `param`='version_latest_available';") === false) {
enter_logfile($cfg,1," Error due updating new version in database.",$norotate);
}
$sqlexec .= "UPDATE `$dbname`.`cfg_params` SET `value`='{$cfg['version_latest_available']}' WHERE `param`='version_latest_available';\n";
$path = substr(__DIR__, 0, -4);
if (file_exists(substr(__DIR__,0,-4).'logs/pid')) {
unlink(substr(__DIR__,0,-4).'logs/pid');
if (file_exists($cfg['logs_path'].'pid')) {
unlink($cfg['logs_path'].'pid');
}
sleep(2);
enter_logfile($cfg,4," Files updated successfully.",$norotate);
if (substr(php_uname(), 0, 7) == "Windows") {
exec("start ".$phpcommand." ".$path."worker.php start");
pclose(popen("start /B cmd /C ".$phpcommand." ".$path."worker.php start 1500000 >NUL 2>NUL", "r"));
} else {
exec($phpcommand." ".$path."worker.php start > /dev/null 2>/dev/null &");
exec($phpcommand." ".$path."worker.php start 2500000 > /dev/null 2>&1 &");
}
enter_logfile($cfg,4," Files updated successfully.",$norotate);
shutdown($mysqlcon,$cfg,4,"Update done. Wait for restart via cron/task.",TRUE);
shutdown($mysqlcon,$cfg,4,"Update done. Wait for restart via cron/task.",FALSE);
} else {
enter_logfile($cfg,1," Files updated with at least one error. Please check the log!",$norotate);
enter_logfile($cfg,2,"Update of the Ranksystem failed!",$norotate);
enter_logfile($cfg,4,"Continue with normal work on old version.",$norotate);
}
$sqlexec .= "UPDATE `$dbname`.`job_check` SET `timestamp`='$nowtime' WHERE `job_name`='get_version';\n";
return($sqlexec);
}