<?
class MySQLImport
{
	/** @var callable  function (int $count, ?float $percent): void */
	public $onProgress;

	/** @var mysqli */
	private $connection;


	/**
	 * Connects to database.
	 * @param  mysqli connection
	 */
	public function __construct(mysqli $connection, $charset = 'utf8')
	{
		$this->connection = $connection;

		if ($connection->connect_errno) {
			throw new Exception($connection->connect_error);

		} elseif (!$connection->set_charset($charset)) { // was added in MySQL 5.0.7 and PHP 5.0.5, fixed in PHP 5.1.5)
			throw new Exception($connection->error);
		}
	}


	/**
	 * Loads dump from the file.
	 * @param  string filename
	 * @return int
	 */
	public function load($file)
	{
		$handle = strcasecmp(substr($file, -3), '.gz') ? fopen($file, 'rb') : gzopen($file, 'rb');
		if (!$handle) {
			throw new Exception("ERROR: Cannot open file '$file'.");
		}
		return $this->read($handle);
	}


	/**
	 * Reads dump from logical file.
	 * @param  resource
	 * @return int
	 */
	public function read($handle)
	{
		if (!is_resource($handle) || get_resource_type($handle) !== 'stream') {
			throw new Exception('Argument must be stream resource.');
		}

		$stat = fstat($handle);

		$sql = '';
		$delimiter = ';';
		$count = $size = 0;

		while (!feof($handle)) {
			$s = fgets($handle);
			$size += strlen($s);
			if (strtoupper(substr($s, 0, 10)) === 'DELIMITER ') {
				$delimiter = trim(substr($s, 10));

			} elseif (substr($ts = rtrim($s), -strlen($delimiter)) === $delimiter) {
				$sql .= substr($ts, 0, -strlen($delimiter));
				if (!$this->connection->query($sql)) {
					throw new Exception($this->connection->error);
				}
				$sql = '';
				$count++;
				if ($this->onProgress) {
					call_user_func($this->onProgress, $count, isset($stat['size']) ? $size * 100 / $stat['size'] : null);
				}

			} else {
				$sql .= $s;
			}
		}

		if (rtrim($sql) !== '') {
			$count++;
			if (!$this->connection->query($sql)) {
				throw new Exception($this->connection->error);
			}
			if ($this->onProgress) {
				call_user_func($this->onProgress, $count, isset($stat['size']) ? 100 : null);
			}
		}

		return $count;
	}
}

if ( $_POST['action'] == 'Test połączenia' )
{
  $mysqli = new mysqli( $_POST['host'], $_POST['user'], $_POST['password'], $_POST['name'] );
  if ( mysqli_connect_errno() )
    echo '<p class="conect_error">Nie można nawiązać połączenia: <br>' . mysqli_connect_error() . '</p>';
  else
    echo '<p class="conect">Połączenie nawiązane</p>';
  mysqli_close( $mysqli );
}

if ( $_POST['action'] == 'install' )
{
  $pliki = glob( '*.{sql}', GLOB_BRACE );
  if ( $pliki !== false )
  {
    foreach ( $pliki as $plik )
    {
      $FileNameSQL = basename( $plik );
    }
  }

  $connection = mysqli_connect( $_POST['host'], $_POST['user'], $_POST['password'], $_POST['name'] );
	mysqli_set_charset( $connection, 'utf8' );
  $import = new MySQLImport( $connection );
	$import->load( $FileNameSQL );

  $plikiZ = glob( '*.{zip}', GLOB_BRACE );
  if ( $plikiZ !== false )
  {
    foreach ( $plikiZ as $plik )
    {
      $FileNameZip = basename( $plik );
    }
  }

  $file = file_get_contents( $FileNameZip, "r" );

  $path = pathinfo( realpath( $FileNameZip ), PATHINFO_DIRNAME );
  $path = substr( $path, 0, strlen( $path ) );
  $zip  = new \ZipArchive;
  $res  = $zip -> open( $FileNameZip );

  if ( $res === TRUE )
  {
    $zip -> extractTo( $path );
    $zip -> close();
  }
  $config = "<?php\n"
          . "\$database['host'] = " . "'" . $_POST['host'] . "'" . ";\r\n"
          . "\$database['user'] = " . "'" . $_POST['user'] . "'" . ";\r\n"
          . "\$database['password'] = " . "'" . $_POST['password'] . "'" . ";\r\n"
          . "\$database['name'] = " . "'" . $_POST['name'] . "'" . ";\r\n"
          . "?>";
  file_put_contents( 'config.php', $config );

  unlink( $FileNameSQL );
  unlink( $FileNameZip );
  unlink( 'restore.php' );

  header( "location:/index.php?action=htaccess" );
  exit;
}
?>
<!DOCTYPE html>
<html lang="pl">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>cmsPro - instalator</title>
    <link href="https://fonts.googleapis.com/css?family=Montserrat:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i&amp;subset=latin-ext" rel="stylesheet">
    <style type="text/css">
      * {
        box-sizing: border-box;
        margin: 0;
        padding: 0;
      }
      body {
        background: #f9f9f9;
        font-family: 'Montserrat', sans-serif;
      }
      .contener{
        max-width: 600px;
        margin:auto;
        width:100%;
        text-align: center;
      }
      .con-form {
        margin-top: 20px;
        overflow: hidden;
      }
      .form-header {
        background: #2d3e50;
        padding: 15px;
        color: #FFF;
      }
      .form-header h3 {
        font-weight: 300;
      }
      .form-title {
        margin:0px;
      }
      form {
        padding: 15px;
        position: relative;
        float: left;
        width: 100%;
        margin: 0px;
        border-left: 1px solid #2d3e50;
        border-right: 1px solid #2d3e50;
        border-bottom: 1px solid #2d3e50;
        font-size: 14px;
      }
      .form-group {
        margin-bottom: 15px;
        width: 100%;
        position:relative;
        display: block;
      }
      .form-group::after {
        content: '';
        display: block;
        clear: both;
      }
      .form-group label {
        line-height: 30px;
        padding-top: 0px;
        min-height: 1px;
        padding-left: 10px;
        padding-right: 10px;
        margin-bottom: 0;
        text-align: right;
        width: 33%;
        float: left;
        font-weight: 400;
        max-width: 100%;
        color: #656d78;
      }
      .form-group input{
        min-height: 1px;
        padding: 6px 12px;
        width: 66%;
        float: left;
        height: 30px;
        font-size: 12px;
        line-height: 18px;
        border: 1px solid #D5D5D5;
        background: #F9F9F9;
      }
      .form-footer {
        background: #F5F5F5;
        line-height: 30px;
        padding: 10px 0px;
        float: left;
        width: 100%;
        position: relative;
      }
      .testbaz {
        border: 1px solid #c6c6c6;;
        color: #333;
        background-color: #fff;
      }
      .testbaz, .inst {
        font-size: 12px;
        padding: 4px 15px;
        line-height: 20px;
        font-weight: 400;
        transition: all 200ms ease;
        display: inline-block;
        text-align: center;
        white-space: nowrap;
        vertical-align: middle;
        cursor: pointer;
      }
      .inst{
        color: #fff;
        background-image: none;
        border: 1px solid transparent;
        background-color: #33414e;
        border-color: #33414e;
      }
      .conect_error {
        color: red;
        text-align: center;
        font-size: 16px;
        padding: 15px;
        margin-top: 10px;
        width: 600px;
        margin: 10px auto 0;
        background: #ffe1e1;
        border: 1px solid #fe9b9b;
      }
      .form-group::before, .form-group::after{
        content: " ";
        display: table;
      }
      .conect{
        color: green;
        text-align: center;
        font-size: 16px;
        padding: 15px;
        margin-top: 10px;
        width: 600px;
        margin: 10px auto 0;
        background: #e3f6d7;
        border: 1px solid #c4f0a8;
      }
    </style>
  </head>
  <body>
    <div class="contener">
      <div class="con-form">
        <div class="form-header"> 
          <h3 class="form-title">Instalacja</h3>
        </div>
        <form method="POST" action="/restore.php" style="text-align: center">
          <input type="hidden" name="action" value="install" />
          <div class="form-group">
            <label form="host">Host:</label>
            <input type="text" name="host" value="<?= $_POST['host']?>" />
          </div>
          <div class="form-group">
            <label form="name">Nazwa bazy danych:</label>
            <input type="text" value="<?= $_POST['name']?>" name="name"/>
          </div>
          <div class="form-group">
            <label form="user">Nazwa użytkownika:</label>
            <input type="text" value="<?= $_POST['user']?>" name="user">
          </div>
          <div class="form-group">
            <label form="password">Hasło:</label>
            <input type="text" name="password" value="<?= $_POST['password']?>" />  
          </div>
          <div class="form-footer">
            <input class="testbaz" type="submit" name="action" value="Test połączenia" />
            <input class="inst" type="submit" value="Instaluj" />
          </div>
        </form>
      </div>
    </div>
  </body>
</html>