<?php
/*------------------------------------------------
 * Config File Editor 					2024-09-05
 * Copyright © FinBoss 2024
 * finboss.ua@gmail.com 
 *
 * використання eval(str_replace('<?php', '', str_replace('&#039;', "\'", file_get_contents($cron_prefix.'ИМЯ-ФАЙЛА.cfg.php'))));
 *
 * License: Commercial open source software (COSS) 
 *------------------------------------------------
 */

	error_reporting (E_ALL);
	
	header('Content-Type: text/html; charset=UTF-8');
	
	// контроль доступа по IP
	$a_allow = false;
	$a_ips = '';
	if (is_file('.allowed_ip')){
		$a_ips = file('.allowed_ip');
	}elseif (is_file('../.allowed_ip')){
		$a_ips = file('../.allowed_ip');
	}
	
	if (is_array($a_ips)){
		foreach ($a_ips as $a_ip){
			$a_ip = trim($a_ip);
			if (strpos($a_ip, '*') !== false){
				
				// process 127.0.*.*
				
				$remote = explode('.', $_SERVER['REMOTE_ADDR']);
				$a = explode('.', $a_ip);
				
				$true_count = 0;
				for ($i=0;$i<4;$i++){
					switch ($i){
						case 0:
						case 1:
							if ($remote[$i] != $a[$i]){
								break 2;
							}else{
								$true_count++;
							}
							break;
						case 2:
						case 3:
							if ($a[$i] == '*'){
								// пропускаем
								$true_count++;
							}else{
								if ($remote[$i] != $a[$i]){
									break 2;
								}else{
									$true_count++;
								}
							}
						
					}
				}
				if ($true_count == 4){
					$a_allow = true;
					break;
				}
				
			}else{
				if ($_SERVER['REMOTE_ADDR'] == trim($a_ip)){
					$a_allow = true;
					break;
				}
			}
		}
		
	}
	if ($a_allow === false){
		die('доступ для IP '.$_SERVER['REMOTE_ADDR'].' заблоковано');
	}
	
	// имя файла
	$d = dir(".");
	
	$config_file = '';
	
	while (false !== ($entry = $d->read())) {
		if ($entry != ".")
			if ($entry != "..")
				if (strpos($entry, '.cfg.') !== false){
					$config_file = $entry;
					break;
				}
	}
	$d->close();
	
	if ($config_file == ''){
		die ('Конфігураційний файл не знайдено');
	}
	
	
	
	if (isset($_POST['fields'])){
		$config = $_POST['fields'];
		
		$data = array();
//		$data[0] = '<?php'."\n";
		$trans = array("'"=>"&#039;", '//'=>'');
		foreach ($config as $i => $fields){

			switch ($fields['type']){
				
				case 'comment':
					$string = '//'.stripslashes($fields['comment']);
					break;
				case 'int':
					$value = (int)stripslashes($fields['value']);
					$string = $fields['variable'].'='.$value.'; //'.stripslashes($fields['comment']);
					break;
				case 'real':
					$value = (float)stripslashes($fields['value']);
					$string = $fields['variable'].'='.$value.'; //'.stripslashes($fields['comment']);
					break;
				case 'array':
					$string = $fields['variable'].'=array('.str_replace("\r\n", ",", stripslashes($fields['value'])).'); //'.stripslashes($fields['comment']);
					break;
				case 'textarea':
					$string = $fields['variable']."='".str_replace("\r\n", "/r/n", strtr(stripslashes($fields['value']), $trans))."'; //".stripslashes($fields['comment']);
					break;
				case 'string':
					$fields['value'] = strtr(stripslashes($fields['value']), $trans);
					$string = $fields['variable']."='".$fields['value']."'; //".stripslashes($fields['comment']);
					break;
				case 'bool':
					$string = $fields['variable']."=".($fields['value']=='так'?'true':'false')."; //".stripslashes($fields['comment']);
					break;
				case 'select':
					$string = $fields['variable']."='".$fields['value']."'; //".stripslashes($fields['comment']);
					break;
			}
			$data[$i] = $string;
		}
		file_put_contents($config_file, "<?php\n".implode("\n", $data));
	}


	if (is_file($config_file)){
		
		$data = file($config_file, FILE_IGNORE_NEW_LINES);
		
		$i = 0;
		foreach ($data as $string){
			if (strpos($string, '//') !== false){
				list($parameter, $comment) = explode('//', $string);
				if (strpos($parameter, '=')){
					list($variable, $value) = explode('=', trim($parameter), 2);
					$value = substr(trim($value), 0, -1);  // удаляем точку с запятой
					if (strpos($value, 'array') === 0){
//						$value = str_replace("array", '', trim($value));
						$value = substr($value, 6);
						$value = substr($value, 0, -1);
						$type = 'array';
					}else{
						if (strpos($variable, '_bool')){
							$type = 'bool';
							if ($value == 'true'){
								$value == 'так';
							}else{
								$value = 'ні';
							}
						}else{
							if (strpos($variable, '_int')){
								$type = 'int';
							}else{
								if (strpos($variable, '_real')){
									$type = 'real';
								}else{
									if (strpos($variable, '_select')){
										$type = 'select';
									}else{
										if (strpos($variable, '_textarea')){
											$type = 'textarea';
										}else{
											// string - по умолчанию
											$type = 'string';
											$value = str_replace("'", '', trim($value));
										}
									}
								}
							}
						}
						
//						if (strpos($value, "'") !== false){
//							$type = 'string';
//							$value = str_replace("'", '', trim($value));
//						}else{
//							$value = trim($value);
//							if ($value == 'true' OR $value == 'false'){
//								$type = 'bool';
//							}else{
//								$type = 'number';
//							}
//						}
					}
					
				}else{
					$variable = $value = NULL;
					$type = 'comment';
				}
				$config[$i]['variable'] = is_null($variable)?$variable:trim($variable);
				$config[$i]['value'] = $value;
				$config[$i]['type'] = $type;
				$config[$i]['comment'] = trim($comment);
				$i++;
			}
		}
		
	}else{
		$config = array();
	}
	$title = $config_file;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
<meta charset="utf-8" >
<title><?php echo $title; ?></title>
</head>
<body style="font-family:Trebuchet MS; font-size: 10pt;" bgcolor="#f5f8fb">

<table width="100%" bgcolor="#416e98">
<tr valign="middle">
<td><span style="font-size:25px; color:#FFF; font-family:Trebuchet MS"> </span></td>
<td align="right"><span style="font-size:15px; color:#FFF; font-family:Trebuchet MS"><?php echo $title; ?></span></td>
</tr>
</table>
<center>
<br />
<form method="post" enctype="multipart/form-data" name="excelform" autocomplete="off">


<table width="100%" border=1 bordercolor=black style="border-collapse:collapse">

<tr>
	<th align=center width="50%">Параметр</th>
	<th align=center width="50%">Значення</th>
</tr>

<?php 
	foreach ($config as $i => $fields){
		
		switch ($fields['type']){
			
			case 'comment':
?>
<tr>
	<td align=center colspan=2><b><?php echo $fields['comment']?></b>
		<input type=hidden name="fields[<?php echo $i?>][type]" value=<?php echo $fields['type']?> /> 
		<input type=hidden name="fields[<?php echo $i?>][comment]" value='<?php echo $fields['comment']?>' />
	</td>
</tr>

<?php 
				break;
			case 'array':
?>
<tr>
	<td align=right title=<?php echo $fields['type'] ?>> <?php echo $fields['comment']?>
		<input type=hidden name="fields[<?php echo $i?>][comment]" value='<?php echo $fields['comment']?>' />
		<input type=hidden name="fields[<?php echo $i?>][variable]" value='<?php echo $fields['variable']?>' />
		<input type=hidden name="fields[<?php echo $i?>][type]" value='<?php echo $fields['type'] ?>' />
	</td>
	<td align=center>
		<textarea style="width:95%" rows=7 name=fields[<?php echo $i?>][value]><?php 
		echo (str_replace(',', "\n", $fields['value']));
		?></textarea>
	</td>
</tr>
<?php 
				break;
			
			case 'bool':
?>
<tr>
	<td align=right title=<?php echo $fields['type'] ?>> <?php echo $fields['comment']?>
		<input type=hidden name="fields[<?php echo $i?>][comment]" value='<?php echo $fields['comment']?>' />
		<input type=hidden name="fields[<?php echo $i?>][variable]" value='<?php echo $fields['variable']?>' />
		<input type=hidden name="fields[<?php echo $i?>][type]" value='<?php echo $fields['type'] ?>' />
	</td>
	<td align=center>
		<select style="width:95%" name=fields[<?php echo $i?>][value]><?php
		$fields['value'] = str_replace("'", '', $fields['value']);
		echo "<option value='так' ".($fields['value']=='так'?'selected':'').">так</option>";
		echo "<option value='ні' ".($fields['value']=='ні'?'selected':'').">ні</option>";
		?></select>
	</td>
</tr>
<?php 
				break;			
			case 'select':
?>
<tr>
	<td align=right title=<?php echo $fields['type'] ?>> <?php echo $fields['comment']?>
		<input type=hidden name="fields[<?php echo $i?>][comment]" value='<?php echo $fields['comment']?>' />
		<input type=hidden name="fields[<?php echo $i?>][variable]" value='<?php echo $fields['variable']?>' />
		<input type=hidden name="fields[<?php echo $i?>][type]" value='<?php echo $fields['type'] ?>' />
	</td>
	<td align=center>
		<select style="width:95%" name=fields[<?php echo $i?>][value]><?php 
		$fields['value'] = str_replace("'", '', $fields['value']);
		// определяем список опций - в скобках
		$options_string = substr($fields['comment'], strpos($fields['comment'], '(')+1);
		$options_string = substr($options_string, 0, strpos($options_string, ')'));
		$options = explode(',', $options_string);
		foreach ($options as $option){
			echo "<option value='$option' ".($fields['value']==$option?'selected':'').">$option</option>";
		}
		?></select>
	</td>
</tr>
<?php 
				break;	
			case 'textarea':
?>
<tr>
	<td align=right title=<?php echo $fields['type'] ?>> <?php echo $fields['comment']?>
		<input type=hidden name="fields[<?php echo $i?>][comment]" value='<?php echo $fields['comment']?>' />
		<input type=hidden name="fields[<?php echo $i?>][variable]" value='<?php echo $fields['variable']?>' />
		<input type=hidden name="fields[<?php echo $i?>][type]" value='<?php echo $fields['type'] ?>' />
	</td>
	<td align=center>
		<textarea style="width:95%" rows=12 name=fields[<?php echo $i?>][value]><?php 
		$fields['value'] = str_replace("/r/n", "\r\n", str_replace("'", '', $fields['value']));
		echo ($fields['value']);
		?></textarea>
	</td>
</tr>
<?php 
				break;
				
			case 'string':
			case 'int':
			case 'real':
?>
<tr>
	<td align=right title=<?php echo $fields['type'] ?>> <?php echo $fields['comment']?>
		<input type=hidden name="fields[<?php echo $i?>][comment]" value='<?php echo $fields['comment']?>' />
		<input type=hidden name="fields[<?php echo $i?>][variable]" value='<?php echo $fields['variable']?>' />
		<input type=hidden name="fields[<?php echo $i?>][type]" value='<?php echo $fields['type'] ?>' />
	</td>
	<td align=center><input type=text style="width:95%" name=fields[<?php echo $i?>][value] value='<?php echo $fields['value']?>' /></td>
</tr>

<?php 
				break;
		}
	}
?>
</table>
<br /><br />
<input type=submit name=submit value=Зберегти />
</form>
</center>
<br/>
Вікно контроля. Якщо у ньому пусто, то помилок немає.
<br/>
<table><tr><td>
<iframe src="<?php echo $config_file; ?>" align="left">
    Ваш браузер не підтримує плаваючі фрейми!
 </iframe>
<br/>
</td></tr>
<tr><td>
<br/>
Довідково: нижче виводиться текст конфігураційного файла з номерами рядків.<br/>Використовується під час пошуку помилок<br/>
<span style="font-weight:bold;cursor:hand;" onclick="document.getElementById('block').setAttribute('style', 'display:block')" title="Щелкните для просмотра">Показати</span>
<br/>
<p id=block style='display:none'>
<?php 
$file = file($config_file);
foreach ($file as $i => $string){
//	if ($i == 0){
		$string = htmlspecialchars($string);
//	}
	echo ($i+1).':'.$string.'<br/>';
}
?>
</p>
</td></tr></table>
</body>
</html>
