<?PHP

if(function_exists('mysqli_report')) mysqli_report(MYSQLI_REPORT_OFF);

require_once('php/lib/functions_brand.php');
require_once('php/lib/functions_open.php');
if(file_exists('config/bin_utils_configuration.php')) {
	require_once('config/bin_utils_configuration.php');
}

ini_set('session.cookie_httponly', 1);
if(!empty($_SERVER["HTTPS"])) ini_set('session.cookie_secure', 1);

define('MINIMAL_IONCUBE_VERSION', 110000);
define('MINIMAL_IONCUBE_VERSION_PHP7', 110000);
define('EXTJS_VERSION', '8.0');


$APP_NAME = Get_brand_name();
$APP_URL = Get_brand_url();
$BASENAME = Get_brand_base();
$DBNAME = Get_brand_dbname();
$LOGO = Get_brand_logo();
$SNIFFERNAME = Get_brand_sniffername();
$SITE = Get_brand_sitename();


function loadConfiguration__index($enablePasswords = true) {
	$configurationItems = getConfigurationItems__index();
	foreach($configurationItems as $name => &$configuration) {
		if(!$enablePasswords && 
		   isset($configuration['type']) && $configuration['type'] == 'password') {
			continue;
		}
		$value = getConfigurationNameValueExists__index($name, $value_exists);
		if($value_exists) {
			$configuration['value'] = $value;
			$configuration['value_exists'] = $value_exists;
		}
	}
	return($configurationItems);
}

function applyConfiguration__index($values) {
	$configurationItems = getConfigurationItems__index();
	foreach($configurationItems as $name => &$configuration) {
		if(is_object($values) ?
		    isset($values->{$name}) :
		    isset($values[$name])) {
			$configuration['value'] = is_object($values) ?
						   $values->{$name} :
						   $values[$name];
			$configuration['value_exists'] = true;
		}
	}
	return($configurationItems);
}

function craeteNewConfiguration__index($values) {
	$configurationItems = getConfigurationItems__index();
	if($values) {
		foreach($configurationItems as $name => &$configuration) {
			if(is_object($values) ?
			    isset($values->{$name}) :
			    isset($values[$name])) {
				$configuration['value'] = is_object($values) ?
							   $values->{$name} :
							   $values[$name];
			}
		}
	}
	$newConfiguration = '<?PHP' . "\n";
	foreach($configurationItems as $name => &$configuration) {
		$value = isset($configuration['value']) ? 
			  $configuration['value'] :
			  $configuration['default_value'];
		$nameValue = prepareNameValueForSave__index($name, $value);
		$disable = !isset($configuration['value']) && !empty($configuration['default_disable']);
		if(empty($configuration['no_separator'])) {
			$newConfiguration .= "\n";
		}
		if(!empty($configuration['description'])) {
			$newConfiguration .= '// ' . $configuration['description'] . "\n";
		}
		$newConfiguration .= ($disable ? '#' : '') . $nameValue . "\n";
	}
	$newConfiguration .= "\n" . '?>';
	return($newConfiguration);
}

function getConfigurationValue__index($configurationItems, $name) {
	if(isset($configurationItems[$name])) {
		return(isset($configurationItems[$name]['value']) ?
			$configurationItems[$name]['value'] :
			$configurationItems[$name]['default_value']);
	}
	return(NULL);
}

function getConfigurationItems__index() {
	global $APP_NAME;
	global $DBNAME;
	global $SNIFFERNAME;
	global $BASENAME;
	return(array(
		'SPOOLDIR' => array('default_value' => '/var/spool/' . escapeConfigurationValue__index($SNIFFERNAME) . '/',
			'label' => 'Pcap spool directory'),
		'DISABLE_CHECK_SPOOLDIR' => array('default_value' => false,
			'label' => 'Disable check spool directory',
			'no_separator' => true),
		'MYSQL_HOST' => array('default_value' => '127.0.0.1',
			'label' => 'MySQL host'),
		'MYSQL_DB' => array('default_value' => escapeConfigurationValue__index($DBNAME),
			'label' => 'MySQL database',
			'no_separator' => true),
		'MYSQL_USER' => array('default_value' => 'root',
			'label' => 'MySQL user',
			'no_separator' => true),
		'MYSQL_PASS' => array('default_value' => NULL,
			'label' => 'MySQL password',
			'type' => 'password',
			'no_separator' => true),
		'MYSQL_KEY' => array('default_value' => NULL,
			'label' => 'MySQL key for SSL/TLS',
			'no_separator' => true),
		'MYSQL_CERT' => array('default_value' => NULL,
			'label' => 'MySQL certificate for SSL/TLS',
			'no_separator' => true),
		'MYSQL_CACERT' => array('default_value' => NULL,
			'label' => 'MySQL ca certificate for SSL/TLS',
			'no_separator' => true),
		'MYSQL_CAPATH' => array('default_value' => NULL,
			'label' => 'MySQL ca path for SSL/TLS',
			'no_separator' => true),
		'MYSQL_CIPHERS' => array('default_value' => NULL,
			'label' => 'MySQL ciphers for SSL/TLS',
			'no_separator' => true),
		'VPMANAGERHOST' => array('default_value' => '127.0.0.1',
			'label' => 'Sniffer manager host'),
		'VPMANAGERPORT' => array('default_value' => 5029,
			'label' => 'Sniffer manager port',
			'no_separator' => true),
		'ENABLE_IP_REVERSE_LOOKUP' => array('default_value' => true,
			'label' => 'DNS reverse lookup'),
		'DEFAULT_CDR_INTERVAL' => array('default_value' => '0',
			'label' => 'Default CDR date interval'),
		'SNIFFER_NAME' => array('default_value' => escapeConfigurationValue__index($SNIFFERNAME)),
		'TIMEZONE' => array('default_value' => get_system_timezone__index() ? 'system default' : 'Etc/UTC',
			'form' => false),
		'DATE_FORMAT' => array('default_value' => 'Y-m-d',
			'form' => false),
		'TIME_FORMAT' => array('default_value' => 'G:i:s',
			'form' => false),
		'ENABLE_GROUPS_CDR' => array('default_value' => true,
			'form' => false),
		'ENABLE_FILTER_CDR_BY_IP_GROUPS' => array('default_value' => true,
			'form' => false),
		'ENABLE_SQL_IP_REVERSE_LOOKUP' => array('default_value' => true,
			'form' => false),
		'ENABLE_DIG_REVERSE_RESOLVE' => array('default_value' => false,
			'form' => false),
		'ENABLE_SQL_CUSTOMER_PREFIX_LOOKUP' => array('default_value' => false,
			'form' => false),
		'NORTPFIRSTLEG' => array('default_value' => true,
			'description' => 'this is for rare cases when wav cannot be decoded',
			'form' => false),
		'ENABLE_TEST_SIP_USERS' => array('default_value' => false,
			'form' => false),
		'DISABLE_WAV_SECURITY' => array('default_value' => false,
			'description' => 'If true  https://' . escapeConfigurationValue__index($BASENAME) . '/php/2909.wav will not require user to be logged. If true, user is not checked against valid session when downloading WAV. Suitable for downloading WAV outside ' . escapeConfigurationValue__index($APP_NAME) . ' GUI. If you need to secure it, you can set WAV_API_KEY below.',
			'form' => false),
		'WAV_API_KEY' => array('default_value' => 'puthereSomeKey',
			'default_disable' => true,
			'description' => 'If you set DISABLE_WAV_SECURITY and set WAV_API_KEY, you have to pass &key=puthereSomeKey to WAV /php/wav.php?id=226587&key=puthereSomeKey. If you do not set WAV_API_KEY you do not need to pass that key (but still have to set true to DISABLE_WAV_SECURITY.',
			'form' => false),
		'DISABLE_SHOW_DOMAIN' => array('default_value' => false,
			'description' => 'disable showing domains in CDR',
			'form' => false),
		'DISABLE_LIVEPLAY' => array('default_value' =>false,
			'description' => 'disable play in live view globally',
			'form' => false),
		'DISABLE_CDRPLAY' => array('default_value' => false,
			'description' => 'disable play in CDR globally',
			'form' => false),
		'UPLOADPCAP_SNIFFERCONF' => array('default_value' => '/etc/' . escapeConfigurationValue__index($SNIFFERNAME) . '.conf',
			'description' => 'define configuration file used for uploading files',
			'form' => false),
		'EULA_AGREE' => array('default_value' => true,
			'form' => false,
			'type' => 'eula')
	));
}

function getConfigurationItems_forForm__index() {
	$configurationItems = getConfigurationItems__index();
	$rslt = array();
	foreach($configurationItems as $name => $item) {
		if(isset($item['label'])) {
			$rslt[$name] = $item;
		}
	}
	return($rslt);
}

function getConfigurationNameValueExists__index($name, &$exists) {
	$exists = false;
	if(!existsConfigurationFile__index()) {
		return(NULL);
	}
	$content = file_get_contents(getConfigurationFile__index());
	$contentE = explode("\n", $content);
	foreach($contentE as $contentI) {
		$contentI = trim($contentI);
		if(strlen($contentI) &&
		   $contentI[0] != '/' && $contentI[0] != '#' &&
		   (($pos = strpos($contentI, "'" . $name . "'")) !== false ||
		    ($pos = strpos($contentI, '"' . $name . '"')) !== false)) {
			$posBegin = $pos + strlen($name) + 2;
			while($contentI[$posBegin] == ',' || $contentI[$posBegin] == ' ') {
				++$posBegin;
			}
			$quotation = $contentI[$posBegin] == "'" || $contentI[$posBegin] == '"' ? $contentI[$posBegin] : false;
			if($quotation) {
				++$posBegin;
			}
			$posEnd = $posBegin;
			while($posEnd < strlen($contentI) &&
			      ($quotation ? !($contentI[$posEnd] == $quotation && $contentI[$posEnd - 1] != '\\') : $contentI[$posEnd] != ')')) {
				++$posEnd;
			}
			if($posEnd > $posBegin) {
				$exists = true;
				$rslt = substr($contentI, $posBegin, $posEnd - $posBegin);
				if(!$quotation) {
					if(strtolower($rslt) == 'true') {
						return(true);
					} else if(strtolower($rslt) == 'false') {
						return(false);
					}
				}
				if($quotation) {
					$rslt = unescapeConfigurationValue__index($rslt, $quotation);
				}
				return($rslt);
			}
		}
	}
	return(NULL);
}

function getConfigurationNameValue__index($name) {
	return(getConfigurationNameValueExists__index($name, $exists));
}

function setConfigurationNameValue__index($name, $value) {
	$content = file_get_contents(getConfigurationFile__index());
	$contentE = explode("\n", $content);
	$contentNewE = array();
	$existsName = false;
	$nameValueOk = false;
	$newNameValue = prepareNameValueForSave__index($name, $value);
	foreach($contentE as $contentI) {
		if(strpos($contentI, "'" . $name . "'") !== false ||
		   strpos($contentI, '"' . $name . '"') !== false) {
			if($contentI != $newNameValue) {
				$contentNewE[] = $newNameValue;
				$existsName = true;
			} else {
				$nameValueOk = true;
			}
		} else {
			$contentNewE[] = $contentI;
		}
	}
	global $setConfigurationTypeValue_rslt;
	if($nameValueOk) {
		$setConfigurationTypeValue_rslt[$name] = true;
	} else {
		if(!$existsName) {
			$contentNewE[] = $newNameValue;
		}
		$setConfigurationTypeValue_rslt[$name] = file_put_contents(getConfigurationFile__index(), implode("\n", $contentNewE));
	}
}

function prepareNameValueForSave__index($name, $value) {
	if($value === NULL) {
		$value = 'NULL';
	} else if(is_bool($value)) {
		$value = $value ? 'true' : 'false';
	} else if(is_string($value)) {
		$value = '\'' . escapeConfigurationValue__index($value) . '\'';
	}
	return('define(\'' . $name . '\', ' . $value . ');');
}

function check_all__index($configuration = NULL, $useSessionsInCheckKey = true) {
	if(!isset($configuration)) {
		$configuration = loadConfiguration__index();
	}
	$system = checkSystem__index();
	if(!check_group__index($system)) {
		return(false);
	}
	$binUtils = checkBinUtils__index();
	if(!check_group__index($binUtils)) {
		return(false);
	}
	$config = checkConfiguration__index($configuration);
	if(!check_group__index($config)) {
		return(false);
	}
	$license = checkLicense__index($useSessionsInCheckKey);
	if(!check_group__index($license)) {
		return(false);
	}
	return(true);
}

function check_group__index(&$group) {
	foreach($group as &$item) {
		if(empty($item['ok'])) {
			return(false);
		}
	}
	return(true);
}

function fix_group__index(&$group) {
	foreach($group as &$item) {
		if(!empty($item['ok'])) {
			if(isset($item['error'])) {
				unset($item['error']);
			}
			if(isset($item['instructions'])) {
				unset($item['instructions']);
			}
		} else {
			if(isset($item['error'])) {
				$item['error'] = htmlspecialchars_with_exceptions__index($item['error']);
			}
			if(isset($item['instructions'])) {
				if(is_string($item['instructions'])) {
					$item['instructions'] = htmlspecialchars_with_exceptions__index($item['instructions']);
				} else {
					if(is_string($item['instructions']['deb'])) {
						$item['instructions']['deb'] = htmlspecialchars_with_exceptions__index($item['instructions']['deb']);
					}
					if(is_string($item['instructions']['rh'])) {
						$item['instructions']['rh'] = htmlspecialchars_with_exceptions__index($item['instructions']['rh']);
					}
				}
			}
		}
	}
}

function checkSystem__index() {
	$arch = php_uname('m');
	$phpver_dec = getPhpVersion__index();
	$phpver_major = floor($phpver_dec / 100);
	$phpver_minor = $phpver_dec % 100;
	$phpver_dot = $phpver_major . '.' . $phpver_minor;
	$rslt = array();
	$binUtils = checkBinUtils__index();
	if(!getConfigurationNameValue__index('DISABLE_WWW_WRITEABLE_CHECK') &&
	   (!existsConfigurationFile__index() || 
	    !existsKeyFile__index() || 
	    !check_group__index($binUtils))) {
		$rslt[] = array(
			'type' => 'chown',
			'name' => 'Access for apache/httpd',
			'ok' => checkApacheAccess__index(),
			'error' => 'GUI folder is not writable by PHP',
			'instructions' => chownInstruction__index());
	}
	if(!extension_loaded('ionCube Loader') || !check_ioncube_version__index()) {
		$path_extension = ini_get('extension_dir');
		$ts = isThreadSafe__index() ? "_ts" : "";
		$loader_file = "ioncube_loader_lin_".$phpver_major.".".$phpver_minor.$ts.".so";
		if($arch == 'x86_64') {
			$loader_path = "x86_64/$loader_file";
		} else {
			$loader_path = "i686/$loader_file";
		}
		$error = NULL;
		$instructions_deb = NULL;
		$instructions_rh = NULL;
		$upgradeIoncube = false;
		if(!extension_loaded('ionCube Loader')) {
			$error = 'ionCube is missing';
		} else {
			$error = 'ionCube needs to be upgraded. SSH to your server and run these commands:';
			$upgradeIoncube = true;
		}
		global $APP_URL;
		if(!$upgradeIoncube) {
			$instructions_deb .= 'apt-get install wget' . eol_instructions__index();
			$instructions_rh .= 'yum install wget' . eol_instructions__index();
		}
		$instructions_deb .= "wget --no-continue $APP_URL/ioncube/$loader_path -O $path_extension/$loader_file" . eol_instructions__index();
		$instructions_rh .= "wget --no-continue $APP_URL/ioncube/$loader_path -O $path_extension/$loader_file" .eol_instructions__index();
		$apache_restart = NULL;
		if(!$upgradeIoncube) {
			if ($phpver_dot == "8.0") {
				$apache_restart = false;
				$instructions_deb = $instructions_rh = "The ionCube doesn't support PHP 8.0. Please use another PHP version!";
			} else {
				$apache_restart = true;
				$instructions_deb .= "echo \"zend_extension = $path_extension/$loader_file\" > " .
						     ($phpver_major >= 7 ?
						       "/etc/php/{$phpver_dot}/apache2/conf.d/01-ioncube.ini" :
						       '/etc/php5/apache2/conf.d/01-ioncube.ini') .
						     eol_instructions__index();
				$instructions_deb .= "echo \"zend_extension = $path_extension/$loader_file\" > " .
						     ($phpver_major >= 7 ?
						       "/etc/php/{$phpver_dot}/cli/conf.d/01-ioncube.ini" :
						       '/etc/php5/cli/conf.d/01-ioncube.ini') .
						     eol_instructions__index();
				$instructions_deb .= "In case of PHP-fpm: echo \"zend_extension = $path_extension/$loader_file\" > " .
						     ($phpver_major >= 7 ?
						       "/etc/php/{$phpver_dot}/fpm/conf.d/01-ioncube.ini" :
						       '/etc/php5/fpm/conf.d/01-ioncube.ini') .
						     eol_instructions__index();
				$instructions_rh .= "echo \"zend_extension = $path_extension/$loader_file\" > /etc/php.d/ioncube.ini" . eol_instructions__index();
			}
		}
		$rslt[] = array(
			'type' => 'ioncube_loader',
			'name' => 'Ioncube.com PHP Loader',
			'ok' => false,
			'error' => $error,
			'instructions' => array(
				'deb' => $instructions_deb,
				'rh' => $instructions_rh,
				'need_restart_apache' => $apache_restart));
	} else if(!check_ioncube_php_version__index($error, $instructions)) {
		$rslt[] = array(
			'type' => 'ioncube_version',
			'name' => 'Ioncube.com PHP Loader',
			'ok' => false,
			'error' => $error,
			'instructions' => $instructions);
	} else if(!check_ioncube_loader_phpcli__index($error)) {
		$rslt[] = array(
			'type' => 'ioncube_phpcli',
			'name' => 'Ioncube.com PHP Loader for php cli',
			'ok' => false,
			'error' => 'Failed check Ioncube.com PHP Loader for php cli ' . $error,
			'instructions' => 'contact support');
	}
	$rslt = array_merge($rslt, array(
		array(
			'type' => 'mysql',
			'name' => 'PHP MySQL module',
			'ok' => function_exists('mysql_connect') || function_exists('mysqli_connect'),
			'error' => 'module missing',
			'instructions' => array(
				'deb' => $phpver_major >= 7 ? 
					  "apt-get install php{$phpver_dot}-mysql" : 
					  'apt-get install php5-mysql',
				'rh' => 'yum install php-mysql',
				'need_restart_apache' => true)),
		array(
			'type' => 'json',
			'name' => 'PHP JSON module',
			'ok' => $phpver_dec < 502 || function_exists('json_encode'),
			'error' => 'module missing',
			'instructions' => array(
				'deb' => $phpver_major >= 7 ? 
					  "apt-get install php{$phpver_dot}-json" : 
					  'apt-get install php5-json',
				'rh' => 'yum install php-json',
				'need_restart_apache' => true)),
		array(
			'type' => 'zip',
			'name' => 'PHP ZIP module',
			'ok' => exists_unzip__index() || function_exists('zip_open'),
			'error' => 'module missing',
			'instructions' => array(
				'deb' => $phpver_major >= 7 ? 
					  "apt-get install php{$phpver_dot}-zip or apt-get install unzip" : 
					  'apt-get install php5-zip or apt-get install unzip',
				'rh' => 'yum install php-zip or yum install unzip',
				'need_restart_apache' => true)),
		array(
			'type' => 'gd',
			'name' => 'PHP GD module',
			'ok' => function_exists('gd_info'),
			'error' => 'module missing',
			'instructions' => array(
				'deb' => $phpver_major >= 7 ? 
					  "apt-get install php{$phpver_dot}-gd" : 
					  'apt-get install php5-gd',
				'rh' => 'yum install php-gd',
				'need_restart_apache' => true)),
		array(
			'type' => 'mbstring',
			'name' => 'PHP MBSTRING module',
			'ok' => function_exists('mb_strlen'),
			'error' => 'module missing',
			'instructions' => array(
				'deb' => $phpver_major >= 7 ? 
					  "apt-get install php{$phpver_dot}-mbstring" : 
					  NULL,
				'rh' => 'yum install php-mbstring',
				'need_restart_apache' => true)),
		array(
			'type' => 'posix_getpwuid',
			'name' => 'PHP posix_getpwuid function',
			'ok' => function_exists('posix_getpwuid'),
			'error' => 'module missing',
			'instructions' => array(
				'deb' => 'Install php support for function posix_getpwuid!',
				'rh' => 'yum install php-process',
				'need_restart_apache' => true)),
		array(
			'type' => 'gz',
			'name' => 'PHP gzdecode/gzinflate function',
			'ok' => function_exists('gzdecode') || function_exists('gzinflate'),
			'error' => 'module missing',
			'instructions' => array(
				'all' => 'Install php support for function gzdecode/gzinflate!',
				'need_restart_apache' => true)),
		array(
			'type' => 'tmp',
			'name' => 'Check if system temp directory is writable',
			'ok' => check_temp__index(),
			'error' => 'temp directory is not writable',
			'instructions' => array(
				'all' => 'chmod 777 \'' . sys_get_temp_dir() . '\'')),
		array(
			'type' => 'fonts',
			'name' => 'Postscript fonts',
			'ok' => check_fonts__index(),
			'error' => 'fonts missing',
			'instructions' => array(
				'deb' => 'apt-get install gsfonts',
				'rh' => 'yum install urw-fonts'))
	));
	fix_group__index($rslt);
	return($rslt);
};

function checkBinUtils__index() {
	$arch = php_uname('m');
	$bindir = get_dirname__index() . '/bin/';
	$rslt = array();
	$binUtilsForDownload = array(
		'phantomjs',
		'sox',
		'tshark',
		'mergecap',
		't38_decode');
	foreach($binUtilsForDownload as $binUtil) {
		$exists = exists_bin_util($binUtil);
		$executable = $exists && is_set_executable_bin_util($binUtil);
		$confBinUtil = get_configuration_bin_util($binUtil);
		$rslt[] = array(
			'type' => $binUtil,
			'name' => $confBinUtil['name'] . ' binary',
			'ok' => $exists && $executable,
			'downloadable' => true,
			'missing' => !$exists,
			'error' => ($exists && $executable ?
				     NULL :
				   (!$exists ?
				     'binary missing' :
				     'binary is not executable')),
			'instructions' => ($exists && $executable ?
					    NULL :
					  (!$exists ?
					    ($confBinUtil['zip'] ?
					      (!checkApacheAccess__index(get_dirname__index() . '/bin') ?
						 chownInstruction__index(get_dirname__index() . '/bin') . eol_instructions__index() : 
						 NULL) .
					      "wget {$confBinUtil['url']} -O '{$bindir}{$confBinUtil['bin']}.gz'" . eol_instructions__index().
					      "gunzip '{$bindir}{$confBinUtil['bin']}.gz'" . eol_instructions__index().
					      "chmod +x '{$bindir}{$confBinUtil['bin']}'" :
					      "wget {$confBinUtil['url']} -O '{$bindir}{$confBinUtil['bin']}'" . eol_instructions__index().
					      "chmod +x '{$bindir}{$confBinUtil['bin']}'") :
					    "chmod +x '{$bindir}{$confBinUtil['bin']}'")));
	}
	$binUtilsInPackage = array(
		'mscgen' => array(
			'name' => 'MSCGEN',
			'arch' => true,
			'need' => true),
		'charts' => array(
			'name' => 'CHARTS',
			'arch' => true,
			'try_without_arch' => true,
			'need' => true),
		'vm' => array(
			'name' => 'VM',
			'arch' => true,
			'need' => true),
		'vmcodecs' => array(
			'name' => 'VMCODECS',
			'arch' => false,
			'need' => true));
	foreach($binUtilsInPackage as $binUtil => $binUtilConfig) {
		$binFile = $bindir . $binUtil . ($binUtilConfig['arch'] ? '-' . $arch : '');
		$exists = file_exists($binFile);
		$executable = $exists && is_set_executable__index($binFile, true);
		if(!$exists && !empty($binUtilConfig['try_without_arch'])) {
			$alterBinFile = $bindir . $binUtil;
			if(file_exists($alterBinFile) && is_set_executable__index($alterBinFile)) {
				$exists = true;
				$executable = true;
			}
		}
		$rslt[] = array(
			'type' => $binUtil,
			'name' => $binUtilConfig['name'] . ' binary',
			'ok' => $exists && $executable,
			'error' => ($exists && $executable ?
				     NULL :
				   (!$exists ?
				     'binary missing' :
				     'binary is not executable')),
			'instructions' => ($exists && $executable ?
					    NULL :
					  (!$exists ?
					    'contact support' :
					    "chmod +x '{$binFile}'")));
	}
	fix_group__index($rslt);
	return($rslt);
}

function checkConfiguration__index($configurationItems, $checkExistsConfiguration = true) {
	$rslt = array();
	$config_missing_error = NULL;
	$config_missing_instruction = NULL;
	$missingConfigurationFile = false;
	if($checkExistsConfiguration) {
		$missingConfigurationFile = !existsConfigurationFile__index();
		$config_missing_error = $missingConfigurationFile ? 'configuration file not saved' : NULL;
		$config_missing_instruction = $missingConfigurationFile ? 'fill configuration items and continue with the next / finish buttons' : NULL;
	}
	$mysql_ok = checkConfiguration_mysql__index($configurationItems, $mysql_error);
	$rslt[] = array(
		'type' => 'mysql',
		'name' => 'MySQL configuration',
		'ok' => $mysql_ok && !$missingConfigurationFile,
		'error' => $mysql_ok ? 
			    $config_missing_error :
			    $mysql_error,
		'instructions' => $config_missing_instruction);
	$spooldir_ok = checkConfiguration_spooldir__index($configurationItems, $spooldir_error);
	$rslt[] = array(
		'type' => 'spooldir',
		'name' => 'SPOOLDIR setting',
		'ok' => $spooldir_ok,
		'error' => $spooldir_error);
	fix_group__index($rslt);
	return($rslt);
}

function checkLicense__index($useSessionsInCheckKey = true) {
	if(!existsKeyFile__index()) {
		$ok = false;
		$error = 'license file key.php is missing';
	} else if(isEmptyKeyFileContent__index()) {
		$ok = false;
		$error = 'license file key.php is empty';
	} else {
		$key_rslt = checkKey__index($useSessionsInCheckKey);
		if($key_rslt === true) {
			$ok = true;
			$error = NULL;
		} else {
			$ok = false;
			$error = $key_rslt;
		}
	}
	$rslt = array(
		array(
			'type' => 'license',
			'name' => 'GUI license',
			'ok' => $ok,
			'error' => $error));
	fix_group__index($rslt);
	return($rslt);
}

function getErrorFromCheckLicenseRslt__index($checkLicenseRslt) {
	return(isset($checkLicenseRslt) && isset($checkLicenseRslt[0]) &&
	       $checkLicenseRslt[0]['type'] == 'license' &&
	       empty($checkLicenseRslt[0]['ok']) ?
		$checkLicenseRslt[0]['error'] :
		NULL);
}

$__checkKey__counter = 0;
$__checkKey__keys = array();
function checkKey__index($useSessions = true) {
	if(!check_ioncube_version__index()) {
		return(false);
	}
	global $__checkKey__counter;
	global $__checkKey__keys;
	require_once('php/lib/functions_enc.php');
	$hwid = getHwid();
	$key_md5 = md5(getKeyFileContent__index() . ($hwid ? '/' . $hwid : NULL));
	$key_md5_session = '__io_key_' . $key_md5;
	if(isset($__checkKey__keys[$key_md5])) {
		return($__checkKey__keys[$key_md5]);
	} else if($useSessions && isset($_SESSION[$key_md5_session])) {
		$__checkKey__keys[$key_md5] = $_SESSION[$key_md5_session];
		return($_SESSION[$key_md5_session]);
	}
	++$__checkKey__counter;
	if($__checkKey__counter == 1) {
		require_once('ioncubetest.php');
		if(key_check2i()) {
			$__checkKey__keys[$key_md5] = true;
			_session_set_value__index($key_md5_session, true);
			return(true);
		} else {
			$error = key_check2e();
		}
	} else {
		$uri = $_SERVER['REQUEST_URI'];
		if(($last_sep = strrpos($uri, '/')) !== false) {
			$uri = substr($uri, 0, $last_sep);
		}
		$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . 
		       '://' . 
		       $_SERVER['HTTP_HOST'] .
		       (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 443 : 80) ? ':' . $_SERVER['SERVER_PORT'] : NULL) .
		       $uri .
		       '/ioncubetest_simple.php';
		$rslt = request__index(array(
				'url' => $url,
				'verify_peer' => false,
				'verify_peer_name' => false),
				$req_error);
		if($rslt !== false) {
			list($rslt) = explode("\n", $rslt);
			$rslt = trim($rslt);
			$error = NULL;
			if($rslt === 'ok') {
				$__checkKey__keys[$key_md5] = true;
				_session_set_value__index($key_md5_session, true);
				return(true);
			} else if(substr($rslt, 0, 6) === 'error:' && strlen($rslt) > 6) {
				$error = substr($rslt, 6);
			}
		} else {
			$error = $req_error;
		}
	}
	if(!$error || $error === '_invalid_') {
		$error = 'license file key.php is invalid or corrupted<br>make sure you are pasting the key including "<?php...."';
	}
	$__checkKey__keys[$key_md5] = $error;
	_session_set_value__index($key_md5_session, $error);
	return($error);
}

function checkConfiguration_mysql__index($configurationItems, &$error) {
	return(getDbLink__index($configurationItems, $error) !== false);
}

function checkConfiguration_spooldir__index($configurationItems, &$error) {
	$disable_check = getConfigurationValue__index($configurationItems, 'DISABLE_CHECK_SPOOLDIR');
	if(!empty($disable_check)) {
		return(true);
	}
	$spooldir = getConfigurationValue__index($configurationItems, 'SPOOLDIR');
	if(!file_exists($spooldir)) {
		$error = 'Spooldir ' . $spooldir . ' not exists';
		return(false);
	}
	if(@touch($spooldir . '/testwrite')) {
		@unlink($spooldir . '/testwrite');
		return(true);
	} else {
		$error = 'Spooldir ' . $spooldir . ' is unaccessible';
		return(false);
	}
}

function getDbLink__index($configurationItems, &$error) {
	if(!function_exists('mysql_connect') && !function_exists('mysqli_connect')) {
		return(false);
	}
	$host = getConfigurationValue__index($configurationItems, 'MYSQL_HOST');
	$db = getConfigurationValue__index($configurationItems, 'MYSQL_DB');
	$user = getConfigurationValue__index($configurationItems, 'MYSQL_USER');
	$pass = getConfigurationValue__index($configurationItems, 'MYSQL_PASS');
	$key = getConfigurationValue__index($configurationItems, 'MYSQL_KEY');
	$cert = getConfigurationValue__index($configurationItems, 'MYSQL_CERT');
	$cacert = getConfigurationValue__index($configurationItems, 'MYSQL_CACERT');
	$capath = getConfigurationValue__index($configurationItems, 'MYSQL_CAPATH');
	$ciphers = getConfigurationValue__index($configurationItems, 'MYSQL_CIPHERS');
	$link = vm_mysql_connect__index($host, $user, $pass,
					$key, $cert, $cacert, $capath, $ciphers);
	if($link) {
		if(!vm_mysql_select_db__index($db, $link)) {
			$error = vm_mysql_error__index($link);
			return(false);
		}
	} else {
		$error = vm_mysql_error__index();
		return(false);
	}
	return($link);
}

function check_temp__index() {
	$tempFile = tempnam(sys_get_temp_dir(), 'VM');
	if($tempFile) {
		@unlink($tempFile);
		return(true);
	}
	return(false);
}

function check_fonts__index() {
	return(file_exists('/usr/share/fonts/default/Type1') ||
	       file_exists('/usr/share/fonts/ghostscript') ||
	       file_exists('/usr/share/fonts/type1/gsfonts') ||
	       file_exists('/usr/share/fonts/type1/urw-base35') ||
	       file_exists('/usr/share/fonts/urw-fonts') ||
	       file_exists('/usr/share/fonts/urw-base35'));
}

function getConfigurationFile__index() {
	return(get_dirname__index() . '/config/configuration.php');
}

function existsConfigurationFile__index() {
	return(file_exists(getConfigurationFile__index()));
}

function writeConfigurationFile__index($values, &$error) {
	$configurationContent = craeteNewConfiguration__index($values);
	if(file_put_contents(getConfigurationFile__index(), $configurationContent) !== false) {
		return(true);
	} else {
		$error = 'there are no write permissions on the ' . getConfigurationFile__index() . ' file';
		return(false);
	}
}

function getKeyFile__index() {
	return(get_dirname__index() . '/key.php');
}

function existsKeyFile__index() {
	return(file_exists(getKeyFile__index()));
}

function getKeyFileContent__index() {
	if(file_exists(getKeyFile__index())) {
		return(normalizeKey__index(file_get_contents(getKeyFile__index())));
	}
	return(NULL);
}

function isEmptyKeyFileContent__index() {
	$key_content = getKeyFileContent__index();
	return(empty($key_content));
}

function normalizeKey__index($key) {
	$trimChars = array(' ', "\t", "\n", "\r");
	while(strlen($key) && in_array($key[0], $trimChars)) {
		$key = substr($key, 1);
	}
	while(strlen($key) && in_array($key[strlen($key) - 1], $trimChars)) {
		$key = substr($key, 0, strlen($key) - 1);
	}
	$key = str_replace("\r\n", "\n", $key);
	$key = str_replace("\r", "\n", $key);
	return($key);
}

function writeKeyFile__index($key, &$error, &$instructions, $restoreOldIfFailed = false) {
	$key = normalizeKey__index($key);
	if(!strlen($key)) {
		$error = 'key is empty';
		return(false);
	}
	if(!check_key_content_before_save($key)) {
		$error = 'bad key content';
		return(false);
	}
	if($restoreOldIfFailed) {
		$old_key_exists = existsKeyFile__index();
		$old_key_content = $old_key_exists ? file_get_contents(getKeyFile__index()) : NULL;
	}
	if(file_put_contents(getKeyFile__index(), $key) !== false) {
		$license = checkLicense__index();
		$license_ok = check_group__index($license);
		if($restoreOldIfFailed === 'force' ||
		   (!$license_ok && $restoreOldIfFailed)) {
			if($old_key_exists) {
				file_put_contents(getKeyFile__index(), $old_key_content);
			} else {
				unlink(getKeyFile__index());
			}
		}
		if($license_ok) {
			return($license);
		} else {
			$error = getErrorFromCheckLicenseRslt__index($license);
			return(false);
		}
	} else {
		$error = 'there are no write permissions on the key.php file';
		$instructions = chownInstruction__index();
		return(false);
	}
}


function escapeConfigurationValue__index($value) {
	if(is_string($value)) {
		$value = str_replace("'", "\\'",
			 str_replace('\\', '\\\\', $value));
	}
	return($value);
}

function unescapeConfigurationValue__index($value, $quotation = "'") {
	if(is_string($value)) {
		$value = str_replace('\\\\', '\\',
			 str_replace($quotation == "'" ? "\\'" : '\\"', $quotation == "'" ? "'" : '"', $value));
	}
	return($value);
}

function get_system_timezone__index() {
	if(function_exists('timezone_name_from_abbr')) {
		return(timezone_name_from_abbr(exec('date +%Z')));
	} else {
		return(false);
	}
}

function getLicenseKey__index($licenseToken, $hwid, &$key, &$error) {
	if(empty($licenseToken)) {
		$error = 'license token muset be set';
		return(false);
	}
	$licensekeyUrl = Get_brand_get_licensekey_url();
	if(!$licensekeyUrl) {
		$error = 'empty licensekey url';
		return(false);
	}
	$rslt = request__index(array(
		'url' => $licensekeyUrl,
		'post' => true,
		'params' => array(
			'licensetoken' => trim($licenseToken),
			'hwid' => trim($hwid)),
		'ignore_errors' => false,
		'verify_peer' => false,
		'verify_peer_name' => false),
		$error);
	if($rslt !== false) {
		$rslt = json_decode($rslt);
		if(!$rslt) {
			$error = 'unknown response';
			return(false);
		}
		if(!empty($rslt->success)) {
			$key = $rslt->key;
			$error = false;
			return(true);
		} else {
			$error = $rslt->error;
			return(false);
		}
	}
	return(false);
}

function getLicenseToken__index($configuration = NULL) {
	if(!isset($configuration)) {
		$configuration = loadConfiguration__index();
	}
	$link = getDbLink__index($configuration, $error);
	if($link === false) {
		return(false);
	}
	$result = vm_mysql_query__index(
		"select content from `system` where type = 'license_token'",
		$link);
	if($result) {
		if($row = vm_mysql_fetch_array__index($result)) {
			return($row['content']);
		}
	}
	return(false);
}

function saveLicenseToken__index($licenseToken, $configuration = NULL) {
	if(!isset($configuration)) {
		$configuration = loadConfiguration__index();
	}
	$link = getDbLink__index($configuration, $error);
	if($link === false) {
		return(false);
	}
	vm_mysql_query__index(
		"CREATE TABLE IF NOT EXISTS `system` (
			`id` int NOT NULL auto_increment,
			`type` text default NULL,
			`cdate` date default NULL,
			`cdatetime` datetime default NULL,
			`content` text default NULL,
			PRIMARY KEY  (`id`),
			UNIQUE `type_cdate` (type(100), cdate)
		) ENGINE=InnoDB DEFAULT CHARSET=latin1;",
		$link);
	$result = vm_mysql_query__index(
		"select id from `system` where type = 'license_token'",
		$link);
	if(!$result) {
		return(false);
	}
	$licenseToken = vm_mysql_real_escape_string__index(trim($licenseToken));
	if($row = vm_mysql_fetch_array__index($result)) {
		return(vm_mysql_query__index("update `system` set content = '{$licenseToken}' where id = {$row['id']}",
					     $link));
	} else {
		return(vm_mysql_query__index("insert into `system` (type, content) values('license_token', '{$licenseToken}')",
					     $link));
	}
}

function check_exists_local_admin__index($configuration = NULL) {
	if(!isset($configuration)) {
		$configuration = loadConfiguration__index();
	}
	$link = getDbLink__index($configuration, $error);
	if($link === false) {
		return(false);
	}
	if(!($queryRslt = vm_mysql_query__index('show tables like \'users\'', $link))) {
		return(false);
	}
	if(!vm_mysql_fetch_array__index($queryRslt)) {
		return(false);
	}
	if(!($queryRslt = vm_mysql_query__index('select * from users', $link))) {
		return(false);
	}
	if(!vm_mysql_fetch_array__index($queryRslt)) {
		return(false);
	}
	return(true);
}

function get_apache_restart_command__index() {
	$cmds = array('/etc/init.d/apache' => '/etc/init.d/apache restart',
		      '/etc/init.d/apache2' => '/etc/init.d/apache2 restart',
		      '/etc/init.d/http' => '/etc/init.d/http restart',
		      '/etc/init.d/httpd' => '/etc/init.d/httpd restart',
		      '/lib/systemd/system/httpd.service;/lib/systemd/system/php-fpm.service' => "service httpd restart\nservice php-fpm restart",
		      '/lib/systemd/system/httpd.service' => 'service httpd restart');
	$rsltCmd = NULL;
	foreach($cmds as $testFiles => $cmd) {
		$testFilesA = explode(';', $testFiles);
		$okFiles = true;
		foreach($testFilesA as $testFile) {
			if(!file_exists($testFile)) {
				$okFiles = false;
				break;
			}
		}
		if($okFiles) {
			$rsltCmd = $cmd;
			break;
		}
	}
	return($rsltCmd ? 
		$rsltCmd :
		'restart http/apache server');
}

function getPhpVersion__index() {
	$version = phpversion();
	$version = explode('.', $version);
	return((int)$version[0] * 100 + (int)$version[1]);
}

function exists_apt_get__index() {
	return(is_fileinpath__index('apt-get', get_std_path__index()));
}

function exists_yum__index() {
	return(is_fileinpath__index('yum', get_std_path__index()));
}

function exists_unzip__index() {
	return(is_fileinpath__index('unzip', get_std_path__index()));
}

function is_fileinpath__index($find, $paths) {
	$found = false;
	$paths = explode(":", $paths);
	foreach($paths as $p) {
		$fullname = $p . DIRECTORY_SEPARATOR . $find;
		if(is_file($fullname)) {
			$found = $fullname;
			break;
		}
	}
	return $found;
}

function get_std_path__index() {
	return('/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin');
}

function is_set_executable__index($file, $trySet = false) {
	if(is_executable($file)) {
		return(true);
	}
	if($trySet) {
		exec('chmod +x ' . escapeshellarg($file));
		return(is_executable($file));
	}
	return(false);
}

function checkApacheAccess__index($dir = NULL) {
	if(!isset($dir)) {
		$dir = get_dirname__index();
	}
	if(!is_writable($dir)) {
		return(false);
	}
	$files = scandir($dir);
	foreach($files as $file) {
		if($file != '.' && $file != '..') {
			$dir_file = $dir . '/' . $file;
			if(is_dir($dir_file)) {
				if(!checkApacheAccess__index($dir_file)) {
					return(false);
				}
			} else if(!is_writable($dir_file)) {
				return(false);
			}
		}
	}
	return(true);
}

function chownInstruction__index($dir = NULL) {
	$tdir = !isset($dir) ? get_dirname__index() : $dir;
	return('chown ' . get_www_user__index() . ' -R ' . $tdir .
	       '<br>chmod u+w -R ' . $tdir);
}

function get_www_user__index() {
	$whoami = trim(shell_exec('whoami 2>/dev/null'));
	if($whoami && in_array($whoami, array('apache', 'www-data'))) {
		return($whoami);
	}
	$www_user = 'apache';
	if(function_exists('posix_getpwuid')) {
		global $APP_NAME;
		$lockfile = tempnam(sys_get_temp_dir(), "$APP_NAME.testpid");
		touch($lockfile);
		$info = @posix_getpwuid(fileowner($lockfile));
		$www_user = $info['name'];
		if(file_exists($lockfile)) {
			unlink($lockfile);
		}
	}
	return($www_user);
}

function get_dirname__index() {
	return(dirname(__FILE__));
}

function check_ioncube_version__index() {
	if(!function_exists('ioncube_loader_iversion')) {
		return(false);
	}
	$php_version = explode('.', PHP_VERSION);
	return(ioncube_loader_iversion() >= ($php_version[0] >= 7 ? constant('MINIMAL_IONCUBE_VERSION_PHP7') : constant('MINIMAL_IONCUBE_VERSION')));
}

function check_ioncube_php_version__index(&$err, &$instr) {
	$version = phpversion();
	$version = explode('.', $version);
	$phpver = (int)$version[0] * 10 + (int)$version[1];
	$guiionphpver  = @file_get_contents('ioncube_phpver');
	if ($guiionphpver === false) {
		return(true);
	}
	$guiionphpver = trim($guiionphpver, "\r\n");
	if ($phpver == $guiionphpver || 
	    (($phpver == 51 || $phpver == 52) && $guiionphpver == 5) ||
	    ($phpver == 70 && $guiionphpver == 56) || 
        ($phpver == 72 && ($guiionphpver == 72 || $guiionphpver == 71)) ||
        ($phpver == 73 && ($guiionphpver == 72 || $guiionphpver == 71)) ||
	    ($phpver == 74 && $guiionphpver == 74) ||
		($phpver == 81 && $guiionphpver == 81) ||
		($phpver >= 82 && $guiionphpver >= 82)) {
		return(true);
	}
	$err = "You use incompatible version of the gui ($guiionphpver) for your php version ($phpver). Please download proper gui's version for your system.";
	switch ($phpver) {
		case 53:
			$err .= ' (for PHP 5.3)';
			$instr .= 'wget "http://www.voipmonitor.org/download-gui?version=latest&major=5&phpver=53&festry"<br>';
			break;
		case 54:
			$err .= ' (for PHP 5.4)';
			$instr .= 'wget "http://www.voipmonitor.org/download-gui?version=latest&major=5&phpver=54&festry"<br>';
			break;
		case 55:
			$err .= ' (for PHP 5.5)';
			$instr .= 'wget "http://www.voipmonitor.org/download-gui?version=latest&major=5&phpver=55&festry"<br>';
			break;
		case 56:
		case 70:
			$err .= ' (for PHP 5.6 and 7.0)';
			$instr .= 'wget "http://www.voipmonitor.org/download-gui?version=latest&major=5&phpver=56&festry"<br>';
			break;
		case 71:
			$err .= ' (for PHP 7.1)';
			$instr .= 'wget "http://www.voipmonitor.org/download-gui?version=latest&major=5&phpver=71&festry"<br>';
			break;
		case 72:
		case 73:
			$err .= ' (for PHP 7.2 - 7.3)';
			$instr .= 'wget "http://www.voipmonitor.org/download-gui?version=latest&major=5&phpver=72&festry"<br>';
			break;
		case 74:
			$err .= ' (for PHP 7.4)';
			$instr .= 'wget "http://www.voipmonitor.org/download-gui?version=latest&major=5&phpver=74&festry"<br>';
			break;
		case 81:
			$err .= ' (for PHP 8.1)';
			$instr .= 'wget "http://www.voipmonitor.org/download-gui?version=latest&major=5&phpver=81&festry"<br>';
			break;
		case 82:
		case 83:
		case 84:
		case 85:
			$err .= ' (for PHP >= 8.2)';
			$instr .= 'wget "http://www.voipmonitor.org/download-gui?version=latest&major=5&phpver=82&festry"<br>';
			break;
		default:
			$instr .= 'Unknown PHP version. Please contact support@voipmonitor.org<br>';
	}
	return(false);
}


function check_ioncube_loader_phpcli__index(&$err) {
	exec("PATH=\$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin php -r 'echo extension_loaded(\"ionCube Loader\")?\"yes\":\"no\";' 2>&1", $output, $return_var);
	if (count($output)) {
		if ($output[0] == 'yes') {
			return(true);
		} else if ($output[0] == 'no') {
			$err = ": no ionCube extension enabled in PHP cli.";
		} else {
			$err = ': ' . $output[0];
		}
	} else {
		$err = ': really strange, I got no output from php cli command ?!';
	}
	return(false);
}

function isThreadSafe__index() {
	ob_start();
	phpinfo(INFO_GENERAL);
	return preg_match('/Thread\s*Safety => enabled/i', strip_tags(ob_get_clean()));
}

function eol_instructions__index() {
	return("\n");
}

function use_mysqli__index() {
	return(function_exists('mysqli_connect'));
}

function vm_mysql_query__index($query , $link = NULL) {
	return(use_mysqli__index() ?
		@mysqli_query($link, $query) :
		@mysql_query($query , $link));
}

function vm_mysql_connect__index($server, $username, $password, $key, $cert, $cacert, $capath, $ciphers, $new_link = false , $client_flags = 0) {
	if (!use_mysqli__index()) {
		return(@mysql_connect($server, $username, $password, $new_link, $client_flags));
	} else {
		if ($key && $cert || $cacert || $capath) {
			$db = mysqli_init();
			mysqli_options($db, MYSQLI_OPT_CONNECT_TIMEOUT, 5);
			mysqli_ssl_set($db, $key, $cert, $cacert, $capath, $ciphers);
			if (defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT')) {
				$client_flags |= MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
			}
			$link = mysqli_real_connect ($db, $server, $username, $password, $new_link, 3306, NULL, $client_flags);
			if (!$link) {
				return($link);
			}
			return($db);
		} else {
			return(@mysqli_connect($server, $username, $password, $new_link, $client_flags));
		}
	}
}

function vm_mysql_select_db__index($database_name, $link = NULL) {
	return(use_mysqli__index() ?
		@mysqli_select_db($link, $database_name) :
		@mysql_select_db($database_name, $link));
}

function vm_mysql_fetch_array__index($linkRes) {
	return(use_mysqli__index() ?
		@mysqli_fetch_array($linkRes) :
		@mysql_fetch_array($linkRes));
}

function vm_mysql_error__index($link = NULL) {
	return(use_mysqli__index() ?
		($link ?
		  @mysqli_error($link) :
		  @mysqli_connect_error()) :
		($link ?
		  @mysql_error($link) : 
		  @mysql_error()));
}

function vm_mysql_real_escape_string__index($string) {
	return(use_mysqli__index() ?
		@_mysql_escape_string__index($string) :
		@mysql_real_escape_string($string));
}

function _mysql_escape_string__index($string) {
	return(_escape_string__index($string, array(
		"'" => "\\'",
		"\"" => "\\\"",
		"\\" => "\\\\",
		"\n" => "\\n",
		"\r" => "\\r")));
}

function _escape_string__index($string, $conv) {
	if(!isset($string)) {
		return(NULL);
	}
	$escString = "";
	for($pos = 0; $pos < strlen($string); $pos++) {
		$c = false;
		foreach($conv as $s => $d) {
			$sl = strlen($s);
			if(substr($string, $pos, $sl) === $s) {
				$escString .= $d;
				$c = true;
				$pos += $sl - 1;
				break;
			}
		}
		if(!$c) {
			$escString .= substr($string, $pos, 1);
		}
	}
	return($escString);
}

function request__index($config, &$error) {
	$httpOpts = array(
		'timeout' => isset($config['timeout']) ? $config['timeout'] : 5,
		'ignore_errors' => !empty($config['ignore_errors'])
	);
	$params_get = NULL;
	if(!empty($config['params'])) {
		if(!empty($config['post'])) {
			$httpOpts['method'] = 'POST';
			$httpOpts['header']  = 'Content-type: application/x-www-form-urlencoded';
			$httpOpts['content'] = http_build_query($config['params']);
		} else {
			foreach($config['params'] as $name => $param) {
				$params_get .= !$params_get ? '?' : '&';
				$params_get .= $name . '=' . urlencode($param);
			}
		}
	}
	if(!empty($config['header'])) {
		$httpOpts['header'] = (isset($httpOpts['header']) ? $httpOpts['header'] . "\r\n" : '') . $config['header'];
	}
	$ctx = stream_context_create(array( 
		'ssl' => array(
			'verify_peer' => isset($config['verify_peer']) ? $config['verify_peer'] : true,
			'verify_peer_name' => isset($config['verify_peer_name']) ? $config['verify_peer_name'] : true),
		'http' => $httpOpts,
		'https' => $httpOpts));
	$rslt = @file_get_contents($config['url'] . $params_get, false, $ctx);
	if($rslt) {
		$error = false;
	} else {
		$lastError = error_get_last();
		if(isset($lastError['message'])) {
			$error = $lastError['message'];
		} else {
			$error = 'unknown error';
		}
	}
	return($rslt);
}

function _session_start__index() {
	if(session_id() != '') {
		return;
	} else {
		if(file_exists('/dev/shm') && is_writable('/dev/shm')) {
			ini_set('session.save_handler', 'files');
			ini_set('session.save_path','/dev/shm');
		}
	}
	$session_name_by = array();
	if(getConfigurationNameValue__index('SESSION_NAME_BY_SERVER_PORT')) {
		$session_name_by[] = $_SERVER['SERVER_PORT'];
	}
	if(!getConfigurationNameValue__index('SESSION_NAME_IGNORE_SERVER_FOLDER')) {
		$server_folder = _getServerFolder__index();
		if($server_folder) $session_name_by[] = $server_folder;
	}
	if(count($session_name_by)) {
		$session_name_by = implode('-', $session_name_by);
		session_name(session_name() . '-' . _fixSessionName__index($session_name_by));
	}
	session_start();
	_session_write_close__index();
}

function _session_write_close__index() {
	session_write_close();
}

function _session_set_value__index($name, $value) {
	ini_set('session.use_cookies', 0);
	session_start();
	if(getPhpVersion__index() < 702) {
		ini_set('session.use_cookies', 1);
	}
	$_SESSION[$name] = $value;
	_session_write_close__index();
}

function _session_unset_value__index($name) {
	ini_set('session.use_cookies', 0);
	session_start();
	if(getPhpVersion__index() < 702) {
		ini_set('session.use_cookies', 1);
	}
	unset($_SESSION[$name]);
	_session_write_close__index();
}

function _getServerFolder__index() {
	$uri = $_SERVER['REQUEST_URI'];
	$uria = explode('/', $uri);
	$folder = array();
	for($i = 0; $i < count($uria); $i++) {
		if($uria[$i] === '') {
			continue;
		}
		if($uria[$i] == 'php' || strstr($uria[$i], '.php') !== false) {
			break;
		}
		$folder[] = $uria[$i];
	}
	return(implode('/', $folder));
}

function _fixSessionName__index($sessionName) {
	return(str_replace(array(' ', '=', ',', ';', '.', '[', '/', "\t", "\r", "\n", "\013", "\014"), '_', $sessionName));
}

function _getCookie__index($name) {
        $name = _getCookieName__index($name);
        return(isset($_COOKIE[$name]) ? $_COOKIE[$name] : '');
}

function _setCookie__index($name, $value) {
        setcookie(_getCookieName__index($name), $value, time()+60*60*24*365, '/', '', !empty($_SERVER["HTTPS"]), true);
}

function _clearCookie__index($name) {
        setcookie(_getCookieName__index($name), '', 0, '/');
}

function _getCookieName__index($name) {
        if(!getConfigurationNameValue__index('SESSION_NAME_IGNORE_SERVER_FOLDER')) {
                $serverFolder = str_replace('/','_',_getServerFolder__index());
                if($serverFolder) {
                        $name .= '_' . $serverFolder;
                }
        }
        return($name);
}

class cDownload__index {
	function __construct() {
		$this->downloadSize = 0;
		$this->content = NULL;
		$this->error = NULL;
	}
	function download($url) {
		ignore_user_abort(false);
		return($this->_download_file_get_contents($url) ||
		       $this->_download_wget($url));
	}
	function _download_file_get_contents($url) {
		$oldErrorHandler = set_error_handler(array($this, 'error_handler'));
		$ctx = stream_context_create(array(
			"ssl" => array(
				"verify_peer" => false,
				"verify_peer_name" => false)));
		stream_context_set_params($ctx, array("notification" => array($this, "stream_notification_callback")));
		$this->content = file_get_contents($url, false, $ctx);
		if($this->content !== false) {
			$this->error = NULL;
		}
		if($oldErrorHandler) {
			set_error_handler($oldErrorHandler);
		}
		return($this->content !== false);
	}
	function _download_wget($url) {
		if(!is_fileinpath__index("wget", "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin")) {
			return(false);
		}
		$this->setPercentProgressBar('wget');
		$this->content = false;
		$tmpDestFile = tempnam(sys_get_temp_dir(), "vm_inst_");
		$wgetCmd = "wget" . 
			   " --no-cache --no-check-certificate -t 1" . 
			   " --timeout=10" . 
			   " " . escapeshellarg($url) . 
			   " -O " . escapeshellarg($tmpDestFile) . 
			   " 2>&1";
		exec($wgetCmd, $output, $return_var);
		if($return_var === 0 && file_exists($tmpDestFile)) {
			$this->content = file_get_contents($tmpDestFile);
		} else {
			$this->error = (!empty($this->error) ? $this->error . '<br><br>' : '') . 
				       'wget<br><br>' . implode("<br>", $output);
		}
		unlink($tmpDestFile);
		return($this->content !== false);
	}
	function save($toFile) {
		$oldErrorHandler = set_error_handler(array($this, 'error_handler'));
		$rslt = file_put_contents($toFile, $this->content);
		if($rslt !== false) {
			$this->error = NULL;
		}
		if($oldErrorHandler) {
			set_error_handler($oldErrorHandler);
		}
		return($rslt !== false);
	}
	function untar($tarFile) {
		$cmd = 'tar xfz ' . $tarFile;
		$pipeDescr = array(
			1 => array('pipe', 'w'),
			2 => array('pipe', 'w'),
		);
		$process = proc_open($cmd, $pipeDescr, $pipes);
		getContentStreamsFromProcOpen__index($content, $error, $pipes, 10);
		$returnValue = proc_close($process);
		if($returnValue != 0) {
			$this->error = $error;
		}
		return($returnValue == 0);
	}
	function unzip($zipFile) {
		$cmd = 'gunzip ' . $zipFile;
		$pipeDescr = array(
			1 => array('pipe', 'w'),
			2 => array('pipe', 'w'),
		);
		$process = proc_open($cmd, $pipeDescr, $pipes);
		getContentStreamsFromProcOpen__index($content, $error, $pipes, 10);
		$returnValue = proc_close($process);
		if($returnValue != 0) {
			$this->error = $error;
		}
		return($returnValue == 0);
	}
	function chmodx($file) {
		$cmd = 'chmod +x ' . $file;
		$pipeDescr = array(
			1 => array('pipe', 'w'),
			2 => array('pipe', 'w'),
		);
		$process = proc_open($cmd, $pipeDescr, $pipes);
		getContentStreamsFromProcOpen__index($content, $error, $pipes, 10);
		$returnValue = proc_close($process);
		if($returnValue != 0) {
			$this->error = $error;
		}
		return($returnValue == 0);
	}
	function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
		if(connection_status() != 0 || connection_aborted() ||
		   !empty($_SESSION['download_bin_util_abort'])) {
			_session_unset_value__index('download_bin_util_abort');
			die();
		}
		switch($notification_code) {
		case STREAM_NOTIFY_RESOLVE:
		case STREAM_NOTIFY_AUTH_REQUIRED:
		case STREAM_NOTIFY_COMPLETED:
		case STREAM_NOTIFY_FAILURE:
		case STREAM_NOTIFY_AUTH_RESULT:
			//var_dump($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max);
			break;
		case STREAM_NOTIFY_REDIRECTED:
			//echo "Being redirected to: ", $message;
			break;
		case STREAM_NOTIFY_CONNECT:
			//echo "Connected...";
			break;
		case STREAM_NOTIFY_FILE_SIZE_IS:
			$this->downloadSize = $bytes_max;
			//echo "Got the filesize: ", $bytes_max;
			break;
		case STREAM_NOTIFY_MIME_TYPE_IS:
			//echo "Found the mime-type: ", $message;
			break;
		case STREAM_NOTIFY_PROGRESS:
			if($this->downloadSize) {
				$this->setPercentProgressBar($bytes_transferred / $this->downloadSize * 100);
			}
			//echo "Made some progress, downloaded ", $bytes_transferred, " so far";
			break;
		}
	}
	function setPercentProgressBar($percent) {
		_session_set_value__index('download_bin_util_percent', $percent);
	}
	function error_handler($errno, $errstr, $errfile, $errline) {
		$this->error = $errstr;
	}
	private $downloadSize;
	private $content;
	private $error;
};

function getContentStreamsFromProcOpen__index(&$content, &$error, &$pipes, $timeoutSec = NULL, $enableClose = true) {
	$content = '';
	$error = '';
	if($timeoutSec === NULL) {
		$content = stream_get_contents($pipes[1]);
		$error = stream_get_contents($pipes[2]);
	} else {
		$outputStreams = array($pipes[1], $pipes[2]);
		$_write = NULL;
		$_except = NULL;
		while(stream_select($outputStreams, $_write, $_except, $timeoutSec) !== false) {
			$okBuffer = false;
			foreach($outputStreams as $stream) {
				$buffer = fgets($stream, 256);
				if($buffer) {
					if($stream == $pipes[1]) {
						$content .= $buffer;
					} else {
						$error .= $buffer;
					}
					$okBuffer=true;
				}
			}
			if(!$okBuffer) {
				break;
			}
			$outputStreams = array($pipes[1], $pipes[2]);
		}
	}
	if($enableClose) {
		fclose($pipes[1]);
		fclose($pipes[2]);
	}
}

function getExtJs__index($type, $use = NULL, $findPath = 'ROOT', $disableDebug = false) {
	global $debug;
	$suffix = array(
		'debug-patched'   => '-debug-patched',
		'patched'         => '-patched',
		'debug'           => '-debug',
		'normal'          => '');
	$file = NULL;
	$extension = NULL;
	switch($type) {
	case 'main':
		$file = 'extjs-' . EXTJS_VERSION . '/build/ext-all';
		$extension = 'js';
		break;
	case 'css_main':
		$theme = getConfigurationNameValue__index('EXTJS_THEME');
		if(!$theme) {
			$theme = 'vm-gray-flat';
		}
		$themePath = 'extjs-' . EXTJS_VERSION . '/build/classic/theme-' . $theme . '/resources/theme-' . $theme . '-all';
		$file = array();
		for($themePart = 1; $themePart <= 3; $themePart++) {
			$file[] = $themePath . '|_' . $themePart;
		}
		$extension = 'css';
		break;
	}
	if(!is_array($file)) {
		$file = array($file);
	}
	$rslt = array();
	foreach($file as $f) {
		if(preg_match('/\|/', $f)) {
			list($f, $fs) = explode('|', $f);
		} else {
			$fs = NULL;
		}
		$f_ok = false;
		for($pass = 0; $pass < 2 && !$f_ok; $pass++) {
			foreach($suffix as $si => $sv) {
				if($pass == 0 && (!$debug || $disableDebug) && preg_match('/debug/', $si)) {
					continue;
				}
				$test_f = $f . $sv . $fs . '.' . $extension;
				if($rslt_f = findFile__index($test_f, $findPath)) {
					$f_ok = true;
					$rslt[] = $use == 'include' ? $test_f : $rslt_f;
					break;
				}
			}
		}
	}
	switch($use) {
	case 'inline':
		$rslt_i = NULL;
		foreach($rslt as $f) {
			$rslt_i .= file_get_contents($f);
		}
		return($rslt_i);
	case 'include':
		$rslt_i = NULL;
		foreach($rslt as $f) {
			switch($type) {
			case 'main':
				$rslt_i .= '<script type="text/javascript" src="' . $f . '"></script>';
				break;
			case 'css_main':
				$rslt_i .= '<link rel="stylesheet" type="text/css" href="' . $f . '">';
				break;
			}
		}
		return($rslt_i);
	default:
		return(count($rslt) ? $rslt : NULL);
	}
}

function getVersionJs__index($file) {
	if(!defined('VERSION') && ($systemDefsFile = findFile__index('config/system_defs.php', 'ROOT'))) {
		require_once($systemDefsFile);
	}
	if(defined('VERSION')) {
		$versionFile = substr($file, 0, -3) . '-' . constant('VERSION') . (defined('VERSION_BUILD') ? '.' . constant('VERSION_BUILD') : NULL) . '.js';
		if(findFile__index($versionFile, 'ROOT')) {
			return($versionFile);
		}
	}
	return($file);
}

function findFile__index($file, $testPrefix = NULL, $executable = false) {
	if(is_string($testPrefix) && strtoupper($testPrefix) == 'ROOT') {
		$path = getcwd();
		$rootPath = NULL;
		while(file_exists($path)) {
			if(file_exists($path.'/admin.php') && file_exists($path.'/index.php')) {
				$rootPath = $path;
				break;
			}
			$path .= '/..';
		}
		if($rootPath) {
			for($i = 0; $i < ($executable ? 3 : 1); $i++) {
				$testFile = $rootPath . '/' . $file . ($i == 2 ? '-i686' : ($i ? '-' . getTypeCpu() : ''));
				if($executable ? is_executable($testFile) : file_exists($testFile)) {
					return($testFile);
				}
			}
		}
		return(NULL);
	}
	for($i = 0; $i < ($testPrefix ? (is_array($testPrefix) ? count($testPrefix) + 1 : 2) : 1); $i++)
	for($j = 0; $j < 2; $j++) {
		$testFile = ($i ? (is_array($testPrefix) ? $testPrefix[$i-1] : $testPrefix) : '') .
			    $file .
			    ($j ? '-' . getTypeCpu() : '');
		if($executable ? is_executable($testFile) : file_exists($testFile)) {
			return($testFile);
		}
	}
	return(NULL);
}

function echoSuccess__index($resultData = NULL) {
	if($resultData && (is_object($resultData) || is_array($resultData)))
		$rslt = (object)$resultData;
	else {
		$rslt = new stdClass;
		if($resultData) {
			$rslt->result = $resultData;
		}
	}
	$rslt->success = true;
	echo json_encode__index($rslt);
}

function echoError__index($errorData = NULL) {
	if($errorData && (is_object($errorData) || is_array($errorData)))
		$rslt = (object)$errorData;
	else {
		$rslt = new stdClass;
		if($errorData) {
			$errorData = htmlspecialchars_with_exceptions__index($errorData);
			$rslt->error = $errorData;
			$rslt->msg = $errorData;
			$rslt->errors = new stdClass;
			$rslt->errors->reason = $errorData;
		}
	}
	$rslt->success = false;
	echo json_encode__index($rslt);
}

function htmlspecialchars_with_exceptions__index($string) {
	$exceptions = array(
		'<br>', '<b>', '</b>', '<i>', '</i>', '<u>', '</u>', '<s>', '</s>');
	$exceptions_e = array();
	for($i = 0; $i < count($exceptions); $i++) {
		$exceptions_e[] = str_replace(array('<', '>'), array('_[[', ']]_'), $exceptions[$i]);
	}
	$string = str_replace($exceptions, $exceptions_e, $string);
	$string = htmlspecialchars($string);
	$string = str_replace($exceptions_e, $exceptions, $string);
	return($string);
}

function _is_number__index($value) {
	return(is_int($value) || is_float($value) ||
	       is_string($value) && (string)numval__index($value) === $value);
}

function numval__index($val) {
	if(is_integer($val) || is_float($val)) {
		return($val);
	} else if(is_numeric($val) || is_bool($val)) {
		return($val * 1);
	} else if(is_string($val)) {
		if(strtolower($val) == "true") {
			return(1);
		} else if(strtolower($val) == "false") {
			return(0);
		} else {
			$val = trim($val);
			$numChars = 0;
			$valLength = strlen($val);
			while($numChars < $valLength &&
			      (ctype_digit($val[$numChars]) || $val[$numChars] == '-' || $val[$numChars] == '.')) {
				++$numChars;
			}
			if($numChars && is_numeric(substr($val, 0, $numChars))) {
				return(substr($val, 0, $numChars) * 1);
			}
		}
	}
	return(NULL);
}

function escape_app_param__index($param) {
	return(str_replace("'", "\'",
	       str_replace('\\', '\\\\', 
	       str_replace(array('\r\n','\n','\r'), ' ', 
	       remove_risk_js_tags__index($param)))));
}

function remove_risk_js_tags__index($string) {
	return(preg_replace('/<[^s]*script[^>]*>/i', '',
	       preg_replace('/<[^>]*on[^=]+=[^(]+\([^>]*>/i', '', $string)));
}

function json_encode__index($data) {
	if(function_exists('json_encode')) {
		return(json_encode($data));
	} else {
		return(_json_encode__index($data));
	}
}

function _json_encode__index($data, $level = 0) {
	if(is_array($data) || is_object($data)) {
		$is_sequential = true;
		$c = 0;
		foreach($data as $n => $v) {
			if($n !== $c) {
				$is_sequential = false;
				break;
			}
			++$c;
		}
		$rslt = $is_sequential ? '[' : '{';
		$c = 0;
		foreach($data as $n => $v) {
			if($c) {
				$rslt .= ',';
			}
			if(!$is_sequential) {
				$rslt .= '"' . $n . '":';
			}
			$rslt .= _json_encode__index($v, $level + 1);
			++$c;
		}
		$rslt .= $is_sequential ? ']' : '}';
		return($rslt);
	} else {
		return((is_numeric($data) ? $data :
		       (is_bool($data) ? ($data ? '1' : '0') :
		       ((($level ? '"' : '') . 
			 ($level && is_string($data) ? _json_string_escape__index($data) : $data) . 
			 ($level ? '"' : ''))))));
	}
}

function _json_string_escape__index($str) {
	$str_esc = '';
	$str_len = strlen($str);
	for($i = 0; $i < $str_len; $i++) {
		switch($str[$i]) {
		case '\\':	$str_esc .= '\\\\'; break;
		case '"':	$str_esc .= '\\\"'; break;
		case '/':	$str_esc .= '\\/'; break;
		case "\b":	$str_esc .= '\\b'; break;
		case "\f":	$str_esc .= '\\f'; break;
		case "\n":	$str_esc .= '\\n'; break;
		case "\r":	$str_esc .= '\\r'; break;
		case "\t":	$str_esc .= '\\t'; break;
		default:	$str_esc .= $str[$i]; break;
		}
	}
	return($str_esc);
}


// -------------------------------------


function craete_js_login__index() {
	global $APP_URL;
	global $APP_NAME;
	global $LOGO;
	$disable_frame_check = getConfigurationNameValue__index('DISABLE_FRAME_CHECK');
	$default_language = getConfigurationNameValue__index('LANGUAGE');
	$shibboleth_auth = getConfigurationNameValue__index('AUTH_SHIBBOLETH');
	$shib_button_txt = getConfigurationNameValue__index('SHIB_BUTTON_TXT');
	$disable_login_window = $shibboleth_auth && getConfigurationNameValue__index('DISABLE_LOGIN_WINDOW');
	$g_enable_auth = getConfigurationNameValue__index('G_ENABLE_AUTH');
	$g_disable_button = getConfigurationNameValue__index('G_DISABLE_BUTTON');
	$ms_enable_auth = getConfigurationNameValue__index('MS_ENABLE_AUTH');
	$ms_disable_button = getConfigurationNameValue__index('MS_DISABLE_BUTTON');
	$disable_std_login = ($g_enable_auth || $ms_enable_auth || $shibboleth_auth) && 
			     (getConfigurationNameValue__index('G_DISABLE_STD_LOGIN') || 
			      getConfigurationNameValue__index('MS_DISABLE_STD_LOGIN') ||
			      getConfigurationNameValue__index('SHIB_DISABLE_STD_LOGIN'));
	$enable_2fa_login = getConfigurationNameValue__index('ENABLE_2FA_DIALOG');
	$is_demo = file_exists('config/demo');
	$is_cloud = getConfigurationNameValue__index('MYSQL_CLOUD_HOST');
	$enable_debug = getConfigurationNameValue__index('ENABLE_DEBUG');
	echo
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
	<title>
		' . $APP_NAME . '
	</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<link rel="shortcut icon" type="image/x-icon" href="' . Handle_favicon() . '" />
	' . getExtJs__index('css_main', 'include', 'ROOT', true) . '
	<link rel="stylesheet" title="loginCombo" type="text/css" href="css/loginCombo.css">
	<link rel="stylesheet" type="text/css" href="css/icons.css">
	<link rel="stylesheet" type="text/css" href="css/other.css">

	<script type="text/javascript">
		doLogin = true;
		disableFrameCheck = \'' . $disable_frame_check . '\';
		default_language = ' . (empty($default_language) ? 'null' : '\'' . $default_language . '\'') . ';
		cookieu = \'' . _getCookie__index('user') . '\';
		cookiep = \'' . _getCookie__index('pass') . '\';
		cookiel = \'' . _getCookie__index('lang') . '\';
		appWeb = \'' . $APP_URL . '\';
		applName= \'' . $APP_NAME . '\';
		wikiUrl = \'' . Get_brand_wiki() . '\';
		appLicenseUrl = \'' . Get_brand_licenseurl() . '\';
		appFreeTrialUrl = \'' . Get_brand_freetrialurl() . '\';
		appCloudPriceUrl = \'' . Get_brand_cloudpriceurl() . '\';
		appShareUrl = \'' . Get_brand_sharesite() . '\';
		authShibboleth = \'' . $shibboleth_auth . '\';
		shibButtonTxt = \'' . $shib_button_txt . '\';
		disableLoginWindow = \'' . $disable_login_window . '\';
		gEnableAuth = \'' . $g_enable_auth . '\';
		gDisableButton = \'' . $g_disable_button . '\';
		msEnableAuth = \'' . $ms_enable_auth . '\';
		msDisableButton = \'' . $ms_disable_button . '\';
		disableStdLogin = \'' . $disable_std_login . '\';
		enable2faDialog = \'' . $enable_2fa_login . '\';
		DEMO = \'' . $is_demo . '\';
		isCloud = \'' . $is_cloud . '\';
		debug = \'' . $enable_debug . '\';
';
	if(!empty($_REQUEST['login_error'])) {
		echo 'login_error = \'' . addslashes($_REQUEST['login_error']) . '\';' . "\n";
	}
	global $urlParamsType;
	global $urlParamsString;
	foreach($urlParamsType as $paramType) {
		echo "\n";
		$value = !empty($_REQUEST[$paramType]) ? $_REQUEST[$paramType] : NULL;
		echo $paramType . ' = ' . ($value === NULL ? 'null' :
					  (_is_number__index($value) ? $value :
					    '\'' . escape_app_param__index($value) . '\'')) . ';';
	}
	if($urlParamsString) {
		echo "\n";
		echo 'urlParamsString = \'' . escape_app_param__index($urlParamsString) . '\';';
	}
	echo '
	</script>
	' . getExtJs__index('main', 'include') . '
	<script type="text/javascript" src="' . getVersionJs__index('js/ux/IconCombo.js') . '"></script>
	<script type="text/javascript" src="' . getVersionJs__index('js/login.js') . '"></script>
	<script type="text/javascript" src="' . getVersionJs__index('js/other/functions.js') . '"></script>
	<script type="text/javascript" src="' . getVersionJs__index('js/other/functions_sign_in.js') . '"></script>
	<script type="text/javascript" src="' . getVersionJs__index('js/other/compatibility.js') . '"></script>
	<script type="text/javascript" src="' . getVersionJs__index('js/other/bugfixes.js') . '"></script>
	<script type="text/javascript" src="' . getVersionJs__index('js/other/overrides.js') . '"></script>
	<script type="text/javascript" src="' . getVersionJs__index('js/localization/lang-global-en.js') . '"></script>
</head>
<body>
	<div style="text-align: center; padding-top: 50px;"><a href=# onclick=window.open("' . $APP_URL . '")>
	<img src=images/' . $LOGO . '>
	</a>
	</div>
</body>
</html>
';
}

function craete_js_config__index() {
	global $APP_URL;
	global $APP_NAME;
	global $LOGO;
	global $SITE;
	echo
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
	<title>
		' . $APP_NAME . '
	</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<link rel="shortcut icon" type="image/x-icon" href="' . Handle_favicon() . '" />
	<script type="text/javascript">
		logo = \'' . $LOGO . '\';
		app_name = \'' . $APP_NAME . '\';
		app_url = \'' . $APP_URL . '\';
		site = \'' . $SITE . '\';
		license_url = \'' . Get_brand_get_licensekey_url() . '\';
	</script>
	' . getExtJs__index('css_main', 'include', 'ROOT', true) . '
	' . getExtJs__index('main', 'include') . '
	<link rel="stylesheet" type="text/css" href="css/config.css">
	<link rel="stylesheet" title="other" type="text/css" href="css/other.css">
	<script type="text/javascript" src="js/config.js"></script>
</head>
<body>
</body>
</html>
';
}


// -------------------------------------


/*
echo '<pre>';
$configuration = loadConfiguration__index();
$system = checkSystem__index();
$system_ok = check_group__index($system);
$binUtils = checkBinUtils__index();
$binUtils_ok = check_group__index($binUtils);
$config = checkConfiguration__index($configuration);
$config_ok = check_group__index($config);
$license = checkLicense__index();
$license_ok = check_group__index($license);
print_r(array(
	'ok_all' => check_all__index(),
	'exists_configuration' => existsConfigurationFile__index(),
	'exists_key' => existsKeyFile__index(),
	'system' => $system,
	'system_ok' => $system_ok,
	'bin_utils' => $binUtils,
	'bin_utils_ok' => $binUtils_ok,
	'configuration' => $config,
	'configuration_ok' => $config_ok,
	'license' => $license,
	'license_ok' => $license_ok));
die();
*/


if(isset($_REQUEST['logout'])) {
	_session_start__index();
	@session_regenerate_id(true);
	@session_destroy();
	echo '<meta http-equiv="refresh" content="0;URL=./">';
	die();
}


_session_start__index();

if(!empty($_POST['task'])) {
	if(!empty($_POST['timeout']) && intval($_POST['timeout']) > 300) {
		ini_set('max_input_time', intval($_POST['timeout']));
		set_time_limit(intval($_POST['timeout']));
		$timeout = intval($_POST['timeout']);
	} else {
		ini_set('max_input_time', '300');
		set_time_limit(300);
		$timeout = 300;
	}
	switch($_POST['task']) {
	case 'all_status':
		$configuration = loadConfiguration__index();
		$system = checkSystem__index();
		$system_ok = check_group__index($system);
		$binUtils = checkBinUtils__index();
		$binUtils_ok = check_group__index($binUtils);
		$config = checkConfiguration__index($configuration);
		$config_ok = check_group__index($config);
		$license = checkLicense__index();
		$license_ok = check_group__index($license);
		echoSuccess__index(array(
			'ok_all' => check_all__index(),
			'exists_configuration' => existsConfigurationFile__index(),
			'exists_key' => existsKeyFile__index(),
			'system' => $system,
			'system_ok' => $system_ok,
			'bin_utils' => $binUtils,
			'bin_utils_ok' => $binUtils_ok,
			'configuration' => $config,
			'configuration_ok' => $config_ok,
			'license' => $license,
			'license_ok' => $license_ok
		));
		break;
	case 'load_eula':
		echoSuccess__index();
		break;
	case 'load_system':
		$system = checkSystem__index();
		$system_ok = check_group__index($system);
		$rslt = array(
			'system' => $system,
			'system_ok' => $system_ok);
		if(!$system_ok) {
			$rslt['os'] = exists_apt_get__index() ? 'deb' : 'rh';
			$rslt['restart_apache_cmd'] = get_apache_restart_command__index();
		};
		return(echoSuccess__index($rslt));
	case 'load_bin_utils':
		$binUtils = checkBinUtils__index();
		$binUtils_ok = check_group__index($binUtils);
		echoSuccess__index(array(
			'bin_utils' => $binUtils,
			'bin_utils_ok' => $binUtils_ok
		));
		break;
	case 'load_config':
		$configuration = loadConfiguration__index();
		$config = checkConfiguration__index($configuration, false);
		$config_ok = check_group__index($config);
		echoSuccess__index(array(
			'configuration' => $config,
			'configuration_ok' => $config_ok,
			'configuration_items' => getConfigurationItems_forForm__index(),
			'exists_configuration' => existsConfigurationFile__index()
		));
		break;
	case 'check_config':
		$configuration = !empty($_POST['values']) && !existsConfigurationFile__index() ?
				  applyConfiguration__index(json_decode($_POST['values'])) :
				  loadConfiguration__index();
		$config = checkConfiguration__index($configuration, false);
		$config_ok = check_group__index($config);
		echoSuccess__index(array(
			'configuration' => $config,
			'configuration_ok' => $config_ok,
			'configuration_items' => getConfigurationItems_forForm__index(),
			'exists_configuration' => existsConfigurationFile__index()
		));
		break;
	case 'load_license':
		$configuration = !empty($_POST['configuration']) && !existsConfigurationFile__index() ?
				  applyConfiguration__index(json_decode($_POST['configuration'])) :
				  loadConfiguration__index();
		$license = checkLicense__index();		 
		$license_ok = check_group__index($license);
		$rslt = array(
			'license' => $license,
			'license_ok' => $license_ok);
		if(!$license_ok) {
			require_once('php/lib/functions_enc.php');
			$rslt['hwid'] = getHwid();
			$licenseToken = getLicenseToken__index($configuration);
			$rslt['license_token'] = $licenseToken ? $licenseToken : NULL;
			if(existsKeyFile__index()) {
				$rslt['key'] = file_get_contents(getKeyFile__index());
			}
		}
		return(echoSuccess__index($rslt));
	case 'check_license':
		$values = json_decode($_POST['values']);
		$license = checkLicense__index();
		$license_ok = check_group__index($license);
		if(!$license_ok) {
			if(($license = writeKeyFile__index($values->key, $error, $instructions, 'force'))) {
				$license_ok = check_group__index($license);
			} else {
				$license = array(
					   array(
						'type' => 'license',
						'name' => 'GUI license',
						'ok' => false,
						'error' => $error,
						'instructions' => $instructions));
				$license_ok = false;
			}
		}
		echoSuccess__index(array(
			'license' => $license,
			'license_ok' => $license_ok
		));
		break;
	case 'download_bin_util':
		if(empty($_POST['check'])) {
			$confBinUtil = get_configuration_bin_util($_POST['util']);
			if(!$confBinUtil) {
				echoError__index('unknown util');
				die();
			}
			_session_unset_value__index('download_bin_util_abort');
			_session_set_value__index('download_bin_util_file', $_POST['util']);
			_session_set_value__index('download_bin_util_percent', 0);
			$dir = get_dirname__index() . '/bin/';
			$chownInstruction = 'please run: ' . chownInstruction__index($dir);
			$download = new cDownload__index();
			if($download->download($confBinUtil['url'])) {
				$binPathName = 'bin/' . $confBinUtil['bin'];
				$zipName = $confBinUtil['bin'] . '.gz';
				$zipPathName = 'bin/' . $zipName;
				@unlink($zipPathName);
				if($download->save($confBinUtil['zip'] ? $zipPathName : $binPathName)) {
					if($confBinUtil['zip']) {
						@unlink($binPathName);
					}
					if(!$confBinUtil['zip'] || $download->unzip($zipPathName)) {
						if($download->chmodx($binPathName)) {
							echoSuccess__index();
							die();
						} else {
							echoError__index('set chmod +x failed<br>' . $chownInstruction);
							die();
						}
					} else {
						echoError__index('unzip failed<br>' . $chownInstruction);
						die();
					}
				} else {
					echoError__index('save failed<br>' . $chownInstruction);
					die();
				}
			} else {
				echoError__index('download failed');
				die();
			}
		} else {
			echoSuccess__index(array(
				'file' => $_SESSION['download_bin_util_file'],
				'percent' => $_SESSION['download_bin_util_percent']));
		}
		break;
	case 'download_bin_util_abort':
		_session_set_value__index('download_bin_util_abort', true);
		echoSuccess__index();
		break;
	case 'get_license_key':
		$license = checkLicense__index();
		$license_ok = check_group__index($license);
		if($license_ok) {
			echoError__index('License is ok! It is not possible to change a valid license.');
			die();
		}
		require_once('php/lib/functions_enc.php');
		$rslt = getLicenseKey__index($_POST['license_token'], getHwid(),
					     $key, $error);
		if($rslt) {
			echoSuccess__index(array('key' => $key));
		} else {
			echoError__index($error);
		}
		break;
	case 'write':
		$write_configuration = 0;
		$write_license = 0;
		if(!empty($_POST['configuration'])) {
			$data_configuration_new = json_decode($_POST['configuration']);
			if(existsConfigurationFile__index()) {
				echoError__index('rewriting exists configuration is not allowed');
				die();
			}
			$config_old = checkConfiguration__index(loadConfiguration__index(), false);
			$config_old_ok = check_group__index($config_old);
			/** @phpstan-ignore-next-line booleanOr.alwaysTrue */
			if(!$config_old_ok || !existsConfigurationFile__index()) {
				$config_new = checkConfiguration__index(applyConfiguration__index($data_configuration_new), false);
				$config_new_ok = check_group__index($config_new);
				if($config_new_ok) {
					$write_configuration = true;
				} else {
					echoError__index('bad configuration');
					die();
				}
			} else {
				echoError__index('rewriting the correct configuration is not allowed');
				die();
			}
		}
		if(!empty($_POST['license'])) {
			$data_license_new = json_decode($_POST['license']);
			$old_key_exists = existsKeyFile__index();
			$old_key_content = getKeyFileContent__index();
			$license_old = checkLicense__index();
			$license_old_ok = check_group__index($license_old);
			if(!$license_old_ok || $old_key_content == normalizeKey__index($data_license_new->key)) {
				if(($license_new = writeKeyFile__index($data_license_new->key, $error, $instructions, 'force'))) {
					$license_new_ok = check_group__index($license_new);
					if($license_new_ok) {
						$write_license = true;
					} else {
						echoError__index('bad license');
						die();
					}
				} else {
					echoError__index($error);
					die();
				}
			} else {
				echoError__index('rewriting the correct license key is not allowed');
				die();
			}
		}
		if($write_configuration) {
			$data_configuration_new->EULA_AGREE = true;
			if(!writeConfigurationFile__index($data_configuration_new, $error)) {
				echoError__index($error);
				die();
			}
		}
		if($write_license) {
			if(writeKeyFile__index($data_license_new->key, $error, $instructions, true)) {
				saveLicenseToken__index($data_license_new->license_token);
			} else {
				echoError__index($error);
				die();
			}
		}
		foreach($_SESSION as $name => $value) {
			if(preg_match('/^__io_key_/', $name)) {
				_session_unset_value__index($name);
			}
		}
		echoSuccess__index();
		break;
	default:
		echoError__index('unknown task ' . $_POST['task']);
	}
	die();
}

$urlParamsType = array('cdrId', 'messageId', 'ss7Id', 'trackerId', 'disableRtp',
		       'callid', 
		       'num', 'srcnum', 'dstnum', 'caller', 'called',
		       'calldate', 'calldatemin', 'calldatemax',
		       'cdr_filter', 'cdr_group_data',
		       'message_filter', 'message_group_data',
		       'ss7_filter',
		       'register_active_filter', 'register_failed_filter', 'register_state_filter',
		       'sip_msg_active_filter', 'sip_msg_filter',
		       'dashboard', 'dashboard_id', 'hidemenu', 'passivecharts',
		       'activecalls', 'hidegrid',
		       'user','password',
		       'alertId', 'reportId',
		       'exclude_ip', 'exclude_ip_dst', 'exclude_number',
		       'cdr_trend', 'alert_mute', 'alert_mute_group',
		       'svg_paint', 'start_watching',
		       'report_problems',
		       'debug', 'dbcheck',
		       'test');
$urlParams = array();
foreach($urlParamsType as $paramType) {
	if(!empty($_REQUEST[$paramType])) {
		$urlParams[] = $paramType . '=' . $_REQUEST[$paramType];
	}
}
$urlParamsString = count($urlParams) ? implode('&', $urlParams) : NULL;

$rslt_check_all = check_all__index(NULL, false);

if($rslt_check_all &&
   (isset($_SESSION['authuser']['sqlrow']) ||
    (!empty($_REQUEST['user']) && !empty($_REQUEST['password'])) ||
    (!getConfigurationNameValue__index('MYSQL_CLOUD_HOST') && !check_exists_local_admin__index()))) {
	if($urlParamsString) {
		$urlParamsStringEnc = str_replace('+', '%2B',
				      str_replace('#', '%23',
				      str_replace('%', '%25', $urlParamsString)));
	}
	$redirectUrl = 'admin.php' . ($urlParamsString ? '?' . $urlParamsStringEnc : '');
	if(headers_sent()) {
		echo '<script> location.replace("' . $redirectUrl . '"); </script>';
		echo str_repeat(' ', 1024*64);
		flush();
	} else {
		header('Location: ' . $redirectUrl);
	}
	die();
}

$debug = getConfigurationNameValue__index('ENABLE_DEBUG') ? true : false;

if($rslt_check_all) {
	craete_js_login__index();
	die();
}

$debug = true;

craete_js_config__index();


// -------------------------------------


function put_stderr__index($string, $timePrefix = true, $endLine = true) {
	if(php_sapi_name() === 'cli') {
		echo $string;
		if($endLine)
			echo "\n";
		return;
	}
	$eh = fopen('/tmp/php_stderr', "a+");
	if($timePrefix)
		fputs($eh, date('Y-m-d H:i:s') . ': ');
	fputs($eh, $string);
	if($endLine)
		fputs($eh, "\n");
	fclose($eh);
}

function debug_stderr__index($string) {
	if(is_array($string) || is_object($string)) {
		put_stderr__index(print_r($string, true));
	} else {
		put_stderr__index($string);
	}
	return($string);
}


?>
