<?
if( file_exists("config.php") && file_exists("update.php") ){
	header("location: update.php");
	die();
}

header ("Content-Type: text/html;charset=utf-8"); 
$error = false;
if(isset($_POST['install'])){
	$config = array(
		'db'=>array(
			'host'=>$_POST['db']['host'],
			'user'=>$_POST['db']['user'],
			'name'=>$_POST['db']['name'],
			'password'=>$_POST['db']['password']
		),
		'root'=>$_POST['root'],
		'domain'=>$_POST['domain'],
		'solt'=>$_POST['solt'],
		'solt_auth'=>$_POST['solt_auth'],
		'http_dir'=>$_POST['http_dir'],
	);
	
  if($dbLink = @mysql_connect($config['db']['host'], $config['db']['user'], $config['db']['password'])){
		@mysql_query('SET NAMES "utf8"', $dbLink);    
	}
	                                                        
  if(!$dbLink || !mysql_select_db($config['db']['name'], $dbLink)){
		$error = "Ошибка подключения MySQL. ".mysql_error();
	}elseif(empty($config['solt'])){
	  $error = "Укажите соль для кодирования";
	}elseif(empty($config['solt_auth'])){
	  $error = "Укажите соль для авторизации";
	}elseif(empty($_POST['email'])){
	  $error = "Укажите E-Mail администратора";
	}elseif(empty($_POST['password'])){
	  $error = "Укажите пароль администратора";
	}elseif($_POST['password']!=$_POST['password_c']){
	  $error = "Укажите пароль администратора правильно";
	}else{
		mysql_query("CREATE TABLE IF NOT EXISTS `mod_users` (
		  `id` int(15) NOT NULL AUTO_INCREMENT,
		  `fio` varchar(255) NOT NULL,
		  `email` varchar(255) NOT NULL,
		  `password` char(32) NOT NULL,
		  `is_active` enum('yes','no') NOT NULL DEFAULT 'no',
		  `avatar` varchar(255) NOT NULL,
		  `type` enum('admin','user') NOT NULL DEFAULT 'user',
		  `date` datetime NOT NULL,
		  `renew_key` char(32) NOT NULL,
		  PRIMARY KEY (`id`)
		) ENGINE=MyISAM  DEFAULT CHARSET=utf8;", $dbLink);
		

		if(mysql_num_rows(mysql_query("SELECT id FROM mod_users WHERE email='".$_POST['email']."'", $dbLink))<=0){
			mysql_query("INSERT INTO `mod_users` (`id`, `fio`, `email`, `password`, `is_active`, `type`, `date`) 
				VALUES (1, 
				'".mysql_real_escape_string($_POST['name'], $dbLink)."', 
				'".mysql_real_escape_string($_POST['email'], $dbLink)."', 
				'".md5($_POST['password'].$config['solt_auth'])."', 'yes', 'admin', NOW());", $dbLink);
		}
		
		mysql_query("CREATE TABLE IF NOT EXISTS `mod_projects` (
		  `id` int(15) NOT NULL AUTO_INCREMENT,
		  `protocol` enum('http://','https://') NOT NULL DEFAULT 'http://',
		  `domain` varchar(255) NOT NULL,
		  `path` varchar(255) NOT NULL,
		  `spath` varchar(255) NOT NULL,
		  `scode` varchar(255) NOT NULL,
		  `ext` varchar(255) NOT NULL,
		  `exc` varchar(255) NOT NULL,
		  `excf` varchar(255) NOT NULL,
		  `enc` enum('normal','lite') NOT NULL DEFAULT 'normal',
		  `date` datetime NOT NULL,
		  `crypt_type` enum('default','lite','reinforced') NOT NULL DEFAULT 'lite',
		  `maxdir` int(15) NOT NULL DEFAULT '0',
		  `users_id` int(15) NOT NULL DEFAULT '0',
		  `last_date_check` datetime NOT NULL,
		  `last_date_process` datetime NOT NULL,
		  `attempt_check` int(1) NOT NULL DEFAULT '0',
			`status` enum('ok','process','error','check','waiting') NOT NULL DEFAULT 'ok',
		  `check_hour` int(15) NOT NULL DEFAULT '12',
		  `error_msg` text NOT NULL,
		  `is_active` enum('yes','no') NOT NULL DEFAULT 'yes',
		  `is_change_email` enum('yes','no') NOT NULL DEFAULT 'no',
		  `maxtime` int(15) NOT NULL DEFAULT '0',
		  PRIMARY KEY (`id`),
		  KEY `users_id` (`users_id`),
		  KEY `last_date_check` (`last_date_check`),
		  KEY `is_active` (`is_active`)
		) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;", $dbLink);	

    mysql_query("CREATE TABLE IF NOT EXISTS `mod_projects2users` (
		  `projects_id` int(15) NOT NULL,
		  `users_id` int(15) NOT NULL,
		  PRIMARY KEY (`projects_id`,`users_id`)
		) ENGINE=MyISAM DEFAULT CHARSET=utf8;", $dbLink);
    
    mysql_query("CREATE TABLE IF NOT EXISTS `mod_scan` (
		  `id` int(15) NOT NULL,
		  `project_id` int(15) NOT NULL,
		  `status` enum('new','process','ok','error','warning') NOT NULL,
		  `date` datetime NOT NULL,
		  `data_process` longtext NOT NULL,
		  `error_msg` text NOT NULL,
		  `step` int(15) NOT NULL DEFAULT '0',
		  `file_c` int(15) NOT NULL DEFAULT '0',
		  `dir_c` int(15) NOT NULL DEFAULT '0',
		  `new_c` int(15) NOT NULL DEFAULT '0',
		  `change_c` int(15) NOT NULL DEFAULT '0',
		  `delete_c` int(15) NOT NULL DEFAULT '0',
		  `is_verified` enum('yes','no') NOT NULL DEFAULT 'no',
		  `is_last` enum('yes','no') NOT NULL DEFAULT 'no',
		  `last_steps` int(15) NOT NULL DEFAULT '0',
		  PRIMARY KEY (`id`),
		  KEY `project_id` (`project_id`),
		  KEY `date` (`date`),
		  KEY `status` (`status`),
		  KEY `is_verified` (`is_verified`),
		  KEY `is_last` (`is_last`)
		) ENGINE=MyISAM DEFAULT CHARSET=utf8;", $dbLink);
    
    mysql_query("CREATE TABLE IF NOT EXISTS `mod_scan_log` (
		  `scan_id` int(15) NOT NULL,
		  `project_id` int(15) NOT NULL DEFAULT '0',
		  `path` varchar(255) NOT NULL,
		  `dir` varchar(255) NOT NULL,
		  `size` int(15) NOT NULL,
		  `is_hash` char(32) NOT NULL,
		  `is_hash_name` char(32) NOT NULL,
		  `status` enum('ok','new','change','delete') NOT NULL DEFAULT 'ok',
		  `level` int(15) NOT NULL DEFAULT '0',
		  KEY `scan_id` (`scan_id`),
		  KEY `project_id` (`project_id`),
		  KEY `is_hash` (`is_hash`),
		  KEY `is_hash_name` (`is_hash_name`),
		  KEY `path` (`path`),
		  KEY `level` (`level`),
		  KEY `dir` (`dir`)
		) ENGINE=MyISAM DEFAULT CHARSET=utf8;", $dbLink);
		
    mysql_query("CREATE TABLE IF NOT EXISTS `mod_scan_dir` (
		  `scan_id` int(15) NOT NULL,
		  `project_id` int(15) NOT NULL,
		  `path` varchar(255) NOT NULL,
		  `level` int(15) NOT NULL,
		  `is_change` enum('yes','no') NOT NULL DEFAULT 'no',
		  KEY `scan_id` (`scan_id`),
		  KEY `project_id` (`project_id`),
		  KEY `path` (`path`),
		  KEY `level` (`level`)
		) ENGINE=MyISAM DEFAULT CHARSET=utf8;", $dbLink);
    
    mysql_query("CREATE TABLE IF NOT EXISTS `mod_settings` (
		  `is_key` varchar(100) NOT NULL,
		  `is_value` text NOT NULL,
		  UNIQUE KEY `is_key` (`is_key`)
		) ENGINE=MyISAM DEFAULT CHARSET=utf8;", $dbLink);
    
    mysql_query("INSERT INTO `mod_settings` (`is_key`, `is_value`) VALUES
		('scanner_maxdir', '300'),
		('default_ext', '.htaccess,.php,.php3,.phtml,.htm,.html,.txt,.js,.pl,.cgi,.py,.bash,.sh,.xml,.ssi,.inc,.pm,.tpl'),
		('scanner_timeout', '550'),
		('limit_scanner', '10'),
		('clear_log', '30');", $dbLink);
		/**/

		$res = "<?php \nreturn ".var_export($config, true).";\n?>";
		file_put_contents("config.php", $res);
		unlink("install.php");
		if( file_exists("update.php") ){
			unlink("update.php");
		}
		header("location: {$config['http_dir']}");
		die();
	} 

}else{
	if( file_exists("config.php") ){
		$oldConfig = include_once("config.php");
		$_POST['solt'] = $oldConfig['solt'];
		$_POST['solt_auth'] = $oldConfig['solt_auth'];	
	}
}
$version = file_exists("version.txt") ? file_get_contents("version.txt") : '';

$dirPrem = array(
	'tmp',
	'uploads',
	'uploads/avatar'
);
$dirPremError = array();
foreach($dirPrem as $d){
	if( perms ( $d )!=777 ){
		@chmod($d, 0777);
		clearstatcache();
		if(perms ( "tmp" )!=777){
			$dirPremError[] = $d;
		}
	}
}

$http_dir = explode("?",$_SERVER['REQUEST_URI']);
$http_dir = str_replace("install.php","",$http_dir[0]);

?>
<!DOCTYPE html>
<head>
	<title>Serval - Install</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=1260" />
	<link rel="stylesheet" href="skin/css/styles.css" type="text/css" media="screen">
</head>

<body>
    <div class="plate" style="max-width:700px;margin:10px auto 10px auto;">
        <div class="plate_ttl __secondary ic_edit"><h1>Установка Serval <?=$version?></h1></div>
				<div class="inner-wrap pad-wrap" style="border:3px solid #0d5e89;border-top:none;">
					<?=$error?>
					<?if(count($dirPremError)>0){?>
						<p>Не удалось поставить права на директории "<?=implode(",",$dirPremError)?>". Установите 0777 вручную!</p>
					<?}?>
					<form method="post">
						<table class="tbl-base">
							<tr>
								<th colspan="2" style="color:#000;">База</th>
							</tr>
							<tr>
								<td class="sbold">Сервер</td>
								<td><input type="text" class="inp-base" required name="db[host]" value="<?=$_POST['db']['host'] ? strip_tags($_POST['db']['host']) : 'localhost'?>"></td>
							</tr>
							<tr>
								<td class="sbold">Имя базы</td>
								<td><input type="text" class="inp-base" required name="db[name]" value="<?=strip_tags($_POST['db']['name'])?>"></td>
							</tr>
							<tr>
								<td class="sbold">Имя пользователя</td>
								<td><input type="text" class="inp-base" required name="db[user]" value="<?=strip_tags($_POST['db']['user'])?>"></td>
							</tr>
							<tr>
								<td class="sbold">Пароль</td>
								<td><input type="password" class="inp-base" name="db[password]" value="<?=strip_tags($_POST['db']['password'])?>"></td>
							</tr>
							<tr>
								<th colspan="2" style="color:#000;">Настройки</th>
							</tr>
							
							<tr>
								<td class="sbold">Document Root</td>
								<td><input class="inp-base" type="text" required name="root" value="<?=$_POST['root'] ? $_POST['root'] : dirname(__FILE__)?>"></td>
							</tr>
							<tr>
								<td class="sbold">Папка</td>
								<td><input class="inp-base" type="text" required name="http_dir" value="<?=$_POST['http_dir'] ? $_POST['http_dir'] : $http_dir?>"></td>
							</tr>
							
							<tr>
								<td class="sbold">Домен</td>
								<td><input class="inp-base" type="text" required name="domain" value="<?=$_POST['domain'] ? $_POST['domain'] : str_replace("www.","",$_SERVER['HTTP_HOST'])?>"></td>
							</tr>
							
							<tr>
								<td class="sbold">Соль для кодирования</td>
								<td><input class="inp-base" type="text" required name="solt" value="<?=$_POST['solt'] ? $_POST['solt'] : _generate(rand(30,100))?>"></td>
							</tr>
							<tr>
								<td class="sbold">Соль для авторизации</td>
								<td><input class="inp-base" type="text" required name="solt_auth" value="<?=$_POST['solt_auth'] ? $_POST['solt_auth'] : _generate(rand(30,100))?>"></td>
							</tr>
							<tr>
								<td class="sbold">Имя администратора</td>
								<td><input class="inp-base" type="text" required name="name" value="<?=strip_tags($_POST['email'])?>"></td>
							</tr>
							<tr>
								<td class="sbold">E-mail администратора</td>
								<td><input class="inp-base" type="email" required name="email" value="<?=strip_tags($_POST['email'])?>"></td>
							</tr>
							<tr>
								<td class="sbold">Пароль администратора</td>
								<td><input class="inp-base" type="password" required name="password" value="<?=strip_tags($_POST['password'])?>"></td>
							</tr>
							<tr>
								<td class="sbold">Повторите пароль</td>
								<td><input class="inp-base" type="password" required name="password_c" value="<?=strip_tags($_POST['password_c'])?>"></td>
							</tr>
							<tr>
								<td colspan="2" align="center"><input type="submit" class="btn __primary ic_edit" name="install" value="Установить"></td>
							</tr>
						</table>
					
					</form>
				</div>
		</div>
<?
function _generate($num){
    $arr = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','r','s','t','u','v','x','y','z','A','B','C','D','E','F',
                 'G','H','I','J','K','L','M','N','O','P','R','S','T','U','V','X','Y','Z','1','2','3','4','5','6','7','8','9','0');
    $pass = "";
    for($i = 0; $i < $num; $i++){
      $index = rand(0, count($arr) - 1);
      $pass .= $arr[$index];
    }
    return $pass;
}

function perms($filename)
{
    return substr(decoct(fileperms($filename)), -3);
}
?>