<? 
ob_start();
header('Content-type: text/html; charset=utf-8');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="ru">
<head>
<meta http-equiv="Content-Type" content="application/vnd.wap.xhtml+xml; charset=UTF-8" />
<meta name="format-detection" content="telephone=no"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="shortcut icon" href="favicon.ico">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css" type="text/css" media="screen">
<link rel="stylesheet" href="anim.css" type="text/css" media="screen">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script type="text/javascript">
    $(function hideDiv(){
        $('#closeBlock').delay(3000).fadeOut(); 
    })
</script>
<title>Установка движка</title>
</head>


<div class="LogoType text-center">
	<a href="/">
		<img src="/themes/adaptiv/images/LogoType.png" style="max-width: 100%;">
	</a>
</div>
<br/>
<div class="content">

<?

include 'core.php';
$type = (isset($_GET['type']) ? $_GET['type'] : false);
if (!$type) {
	?>
		<div class='load_pages' id="closeBlock">
			<div class="loading-wrap">
				<div class="triangle1"></div>
				<div class="triangle2"></div>
				<div class="triangle3"></div>
			</div>
		</div>	
		
		<div class='loadblock text-center' >
		<h2 style="font-size: 14px;">
			<b>Добро пожаловать в мастер-установщик движка</b><br/>
			Автор : <b>Djkohade</b> <br/>
			Год выпуска : 2020г<br/> <br/>
			<b>Контакты</b> :<br/>
			Вконтакте : <a style="font-size: 15px;color:#5181b8;" href="//vk.com/Djkohade">Djkohade</a><br/>
			4i4i.ru : <a style="font-size: 15px;color:#5491ab;" href="//4i4i.ru/@Djkohade">Djkohade</a><br/>
			Gix.su : <a style="font-size: 15px;color:#00adab;" href="//gix.su/user/Djkohade">Djkohade</a><br/>
			Fiera.su : <a style="font-size: 15px;color:#222;" href="//Fiera.su/">Djkohade</a><br/>
			<br/>
			
		</h2>
		<?
			if (phpversion() < 7) {
				echo '<div class="err">Требуется версия php не ниже 7.0.8</div></div></div></body></html>';
				die();
			}
		?>
		
		<a class="spanlink" href="?type=step1"><h2 style="font-size: 22px;" >Начать установку</h2></a>

		</div>
		<?
}
if ($type == 'step1') {
	if (isset($_POST['user'], $_POST['pass'], $_POST['host'], $_POST['dbname'])) {
		$_SESSION['user'] = $_POST['user'];
		$_SESSION['pass'] = $_POST['pass'];
		$_SESSION['host'] = $_POST['host'];
		$_SESSION['dbname'] = $_POST['dbname'];

		try {
			$db = new PDO("mysql:host={$_SESSION['host']};dbname={$_SESSION['dbname']}", $_SESSION['user'], $_SESSION['pass']);
		} catch (PDOException $e) {
			echo '<div class="err">Введены неверные данные</div>';
		}
		if (empty($e)) {	
			$filedb = file_get_contents(H."pages/install/table.sql");
			$file = explode(';', $filedb);
			
			foreach ($file AS $p) {
				$db->query($p);
				$re = $db->query($filedb);
				/*
				echo '<pre>';
				print_r($db->errorInfo());
				echo '</pre>';
				*/
			}
			die(header('Location: /pages/install/?type=step2'));
		}		
	}
	?>
	<b class="text-center">Соединение с базой данных</b><br/><br/>
	<form method="post" name="save" action="?type=step1">
	  <div class="form-group">
		<input type="text" name="user" class="form-control" placeholder="Пользователь базы данных" value="<?=isset($_SESSION['user']) ? $_SESSION['user'] : ''?>">
	  </div>
	  <div class="form-group">
		<input type="text" name="pass" class="form-control" placeholder="Пароль от базы" value="<?=isset($_SESSION['pass']) ? $_SESSION['pass'] : ''?>">
	  </div>
	  <div class="form-group">
		<input type="text" name="host" class="form-control" placeholder="Host" value="<?=isset($_SESSION['host']) ? $_SESSION['host'] : 'localhost'?>">
	  </div>
	  <div class="form-group">
		<input type="text" name="dbname" class="form-control" placeholder="База данных" value="<?=isset($_SESSION['dbname']) ? $_SESSION['dbname'] : ''?>">
	  </div>	  
	  
	  <button type="submit" class="btn btn-primary">Подключиться</button>
	</form>	
	<?
}
if ($type == 'step2') {
	if (isset($_POST['login'], $_POST['password'])) {
		$_SESSION['password'] = $_POST['password'];
		$_SESSION['login'] = $_POST['login'];
		
		try {
			$db = new PDO("mysql:host={$_SESSION['host']};dbname={$_SESSION['dbname']}", $_SESSION['user'], $_SESSION['pass']);
		} catch (PDOException $e) {
			echo '<div class="err">Введены неверные данные</div>';
		}
		include H.'core/autoload/Err.func.php';
		include H.'core/autoload/Translate.func.php';
		include H.'core/autoload/Shif.func.php';
		include H.'core/autoload/FileSystem.class.php';
		include H.'core/autoload/Cookie.func.php';

		
		if (stripos(file_get_contents(H.'core/config/if_password.txt'), $_SESSION['password']) !== false || $_SESSION['password'] == $_SESSION['login'] || is_numeric($_SESSION['password'])) {
			$err[] = 'Пароль слишком простой';
		}
		if (mb_strlen($_SESSION['password'], 'UTF-8') < 8) {
			$err[] = 'Пароль слишком короткий';
		}		
		if (mb_strlen($_SESSION['login'], 'UTF-8') < 8) {
			$err[] = 'Логин слишком короткий';
		}
		
		$link = Translit($_SESSION['login'] , 1, 1, 1);
		$link = preg_replace("/[^-a-zа-я-0-9\s]/ui", "", $link);
		$link = str_replace(' ','-', $link);
		$link = str_replace('  ','', $link);
		$link = trim($link);	
		
		
		if (empty($e)) {
		$text = "
			mysql_host = '{$_SESSION['host']}';
			mysql_user = '{$_SESSION['user']}';
			mysql_pass = '{$_SESSION['pass']}';
			mysql_db_name = '{$_SESSION['dbname']}';
			charset_names = 'utf8';
			";
			
			$fp = fopen(H."core/config/db.ini", "w");
			fwrite($fp, $text);
			fclose($fp);	
			
			$text = "salt = 'DjkohadeNewsCms-".md5(time() . mt_rand(1,999999)) ."';";
			$fp = fopen(H."core/config/shif.ini", "w");
			fwrite($fp, $text);
			fclose($fp);
			
			$continue = ['_default_1.jpg','_default_2.jpg','_default_3.jpg'];
			FileSystem::DirClear(H.'files/avatars/big/', false, $continue);
			FileSystem::DirClear(H.'files/avatars/mid/', false, $continue);
			FileSystem::DirClear(H.'files/avatars/min/', false, $continue);
			
			FileSystem::DirClear(H.'files/cache/cron/', false, '.htaccess');
			FileSystem::DirClear(H.'files/cache/news/', false, '.htaccess');
			FileSystem::DirClear(H.'files/cache/users/', false, '.htaccess');
			FileSystem::DirClear(H.'files/logs/', false, '.htaccess');
			unlink(H.'core/config/errors.log');
			
			$continue[] = '_default_4.jpg';
			
			FileSystem::DirClear(H.'files/news-images/big/', false, $continue);
			FileSystem::DirClear(H.'files/news-images/mid/', false, $continue);
			FileSystem::DirClear(H.'files/news-images/min/', false, $continue);
			FileSystem::DirClear(H.'files/news-images/large/', false, $continue);
			
			FileSystem::DirClear(H.'files/tmp/', false, '.htaccess');
			
			removeDirectory(H.'pages/install/');
			
			$_SESSION['password'] = shif($_SESSION['password']);
			
			$sql = $db->prepare('INSERT INTO `users` (`avatar`, `date_create`, `link`, `login`, `password`, `id_level`) VALUES (?, ?, ?, ?, ?, ?);');
			$sql->execute(
			[
				'_default_1.jpg',
				time(),
				$link ,
				$_SESSION['login'] ,
				$_SESSION['password'] , 
				3
			]);
			
			$lastInsertId = $db->lastInsertId(); 
			$_SESSION['user_id'] = $lastInsertId;
			cookie('user_id', $lastInsertId, 86400 * 30);
			cookie('user_pass', $_SESSION['password'], 86400 * 30);	
			
			$db->query("INSERT INTO `users` (`avatar`,`id`, `date_create`, `link`, `login`) VALUES ('_default_2.jpg', 2, '". time() ."', 'Journalist', 'Журналист');");
			unset($_SESSION['host'], $_SESSION['dbname'], $_SESSION['user'], $_SESSION['pass']);
			die(header('Location: /apanel/'));
		}
	}
	if (isset($err)) {
		echo err($err);
	}
	?>
	<b class="text-center">Создание администратора</b><br/><br/>
	<form method="post" name="save" action="?type=step2">
	  <div class="form-group">
		<input type="text" name="login" class="form-control" placeholder="Ваш логин" value="<?=isset($_SESSION['login']) ? $_SESSION['login'] : 'admin'?>">
	  </div>
	  <div class="form-group">
		<input type="text" name="password" class="form-control" placeholder="Придумайте пароль" value="<?=isset($_SESSION['password']) ? $_SESSION['password'] : md5(time())?>">
	  </div> 
	  <button type="submit" class="btn btn-primary">Создать профиль</button>
	</form>	
	<?
}



?>
</div></body></html>