<?php
if (!defined('entry') || !entry) {
    die('Not a valid page');
}
require(Absolute_Path.'/classes/mysql_connection.class.php');

class Install
{
    public $data = null;
    public $errors = null;
    public $showForm;
    public $errors_d = array();

    public function __construct()
    {
        $this->errors_d[1]="The login field cannot be empty";
        $this->errors_d[2]="The password field cannot be empty";
        $this->errors_d[3]="Password does not match the confirm password";
        $this->errors_d[4]="The e-mail field cannot be empty";
        $this->errors_d[5]="The installation URL field cannot be empty";
        $this->errors_d[6]="Error establishing a database connection";
        $this->errors_d[7]="Please add a hostname for the database server";
        $this->errors_d[8]="Please name the database";
        $this->errors_d[9]="Password does not match the confirm password";
        $this->errors_d[10]="The login field cannot be empty";
    }

    public function run()
    {
        if (empty($this->data)) {
            false;
        }

        if (!$this->create_db()) {
            return false;
        }

        if (!$this->install_db()) {
            return false;
        }

        return true;
    }

    public function create_db()
    {
        $db_host = $this->data['db_host'];
        $db_name = $this->data['db_name'];
        $db_login = $this->data['db_login'];
        $db_password = $this->data['db_password'];

        try {
          $link = new PDO("mysql:host=$db_host;dbname=$db_name", $db_login, $db_password);
        }
        catch (Exception $e)
        {
          return false;
        }

        if (!$link) {
            die('Could not connect: ' . $link->errorInfo());
        }

        $sql = 'CREATE DATABASE IF NOT EXISTS ' . $this->data['db_name'];
        if (!$link->query($sql)) {
            $link = NULL;
            return false;
        }

        return true;
    }

    public function install_db()
    {
        $db = new Conexion_Mysql($this->data['db_name'], $this->data['db_host'], $this->data['db_login'], $this->data['db_password']);
        $sqlStr = array();

        $sqlStr[] = "CREATE TABLE `".Table_prefix."data` ( `id_post` INT(11) NOT NULL AUTO_INCREMENT , `title` TEXT NULL , `url` VARCHAR(250) NULL DEFAULT NULL , `description` TEXT NULL , `type` TINYINT(4) NOT NULL DEFAULT '1' , `date` DATETIME NOT NULL , `id_user` INT(10) NOT NULL , PRIMARY KEY (`id_post`)) ENGINE = MyISAM;";

        $sqlStr[] = "CREATE TABLE `".Table_prefix."users` ( `id_user` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT , `name` VARCHAR(100) NULL DEFAULT NULL , `login` VARCHAR(100) NOT NULL DEFAULT '' , `password` VARCHAR(64) NOT NULL DEFAULT '' , `email` VARCHAR(100) NULL DEFAULT NULL , `website` VARCHAR(150) NULL DEFAULT NULL , `about` TEXT NOT NULL , PRIMARY KEY (`id_user`)) ENGINE = MyISAM;";

        $sqlStr[] = "CREATE TABLE `".Table_prefix."config` ( `posts_limit` INT(3) NOT NULL , `title` VARCHAR(250) NOT NULL , `description` TEXT NOT NULL , `lang` VARCHAR(10) NOT NULL , `template` VARCHAR(100) NOT NULL , `url_installation` VARCHAR(250) NOT NULL , PRIMARY KEY (`title`)) ENGINE = MyISAM;";

        $sqlStr[] = "CREATE TABLE `".Table_prefix."options` ( `name` VARCHAR(100) NOT NULL , `val` VARCHAR(255) NOT NULL , PRIMARY KEY (`name`)) ENGINE = MyISAM;";


        $sqlStr[] = "CREATE TABLE `".Table_prefix."comments` ( `id_comment` INT(11) NOT NULL AUTO_INCREMENT , `id_post` INT(11) NOT NULL , `username` VARCHAR(50) NOT NULL , `email` VARCHAR(100) NOT NULL , `web` VARCHAR(250) NULL DEFAULT NULL , `content` TEXT NOT NULL , `ip_user` VARCHAR(50) NOT NULL , `comment_date` DATETIME NOT NULL , `spam` TINYINT(4) NOT NULL , PRIMARY KEY (`id_comment`)) ENGINE = MyISAM;";

        $sqlStr[] = "CREATE TABLE `".Table_prefix."feeds` ( `id_feed` INT(11) NOT NULL AUTO_INCREMENT , `url` VARCHAR(255) NOT NULL , `title` VARCHAR(255) NOT NULL , `type` TINYINT(4) NOT NULL DEFAULT '1' , `updated_at` DATETIME NOT NULL , `error` TINYINT(1) NOT NULL DEFAULT '0' , `credits` INT(1) NOT NULL DEFAULT '0' , `site_url` VARCHAR(255) NOT NULL , `id_user` INT(10) NOT NULL , PRIMARY KEY (`id_feed`)) ENGINE = MyISAM;";

        $sqlStr[] = "INSERT INTO `".Table_prefix."config` VALUES (". $db->sql_escape($this->data['posts_limit']).", ".$db->sql_escape($this->data['title']).", ".$db->sql_escape($this->data['description']).", ".$db->sql_escape($this->data['lang']).", ".$db->sql_escape($this->data['template']).", ".$db->sql_escape($this->data['url_installation']).");";
        $sqlStr[] = "INSERT INTO `".Table_prefix."users` (name, login, password, email, website, about) VALUES ('', ".$db->sql_escape($this->data['login']).", '".md5($this->data['password'])."', ".$db->sql_escape($this->data['email']).", ".$db->sql_escape($this->data['website']).", ".$db->sql_escape($this->data['about']).");";
        $sqlStr[] = "INSERT INTO `".Table_prefix."options` VALUES ('url_friendly', '0');";
        $sqlStr[] = "INSERT INTO `".Table_prefix."options` VALUES ('rich_text', '0');";
        $sqlStr[] = "INSERT INTO `".Table_prefix."options` VALUES ('allow_comments', '0');";
        $sqlStr[] = "INSERT INTO `".Table_prefix."options` VALUES ('offset_city', ".$db->sql_escape($this->data['offset_city']).");";
        $sqlStr[] = "INSERT INTO `".Table_prefix."options` VALUES ('offset_time', ".$db->sql_escape($this->data['offset_time']).");";
        $sqlStr[] = "INSERT INTO `".Table_prefix."options` VALUES ('shorten_links', '0');";
        $sqlStr[] = "INSERT INTO `".Table_prefix."options` VALUES ('rss_import_frec', '5 minutes');";
        $sqlStr[] = "INSERT INTO `".Table_prefix."options` VALUES ('check_version', '1');";
        $sqlStr[] = "INSERT INTO `".Table_prefix."options` VALUES ('active_plugins', '[{\"total\":0},[]]');";

        foreach ($sqlStr as $key => $query) {
            if (!$db->ejecutarConsulta($query)) {
                return false;
            }
        }

        if($this->writeConfig($this->data['db_name'], $this->data['db_host'], $this->data['db_login'], $this->data['db_password']) === FALSE)
        {
          return false;
        }

        return true;
    }

    public function inerrors($n)
    {
        if (strpos($this->errors, (string)$n)===false) {
            return false;
        }
        return true;
    }

    public function writeConfig($name, $host, $login, $password)
    {
      $strToWrite = "define('DB_Server', '$host');\ndefine('DB_name', '$name');\ndefine('DB_User', '$login');\ndefine('DB_Password', '$password');\n";
      return file_put_contents(Absolute_Path.'config.php', $strToWrite, FILE_APPEND | LOCK_EX);
    }

    public function mostrarerror($n)
    {
        if ($this->inerrors($n)) {
            return '<span class="error">'.$this->errors_d[$n].'</span>';
        } else {
            return "";
        }
    }

    public function is_sorbet_installed()
    {
        if (file_exists(Absolute_Path.'config.php')) {
            include_once(Absolute_Path."config.php");
            if (!$this->check_for_config()) {
                return false;
            } else {
                if (!$this->is_db_installed()) {
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }
    }

    public function is_db_installed()
    {
        $db = new Conexion_Mysql(DB_name, DB_Server, DB_User, DB_Password);
        $sqlStr = "SELECT * FROM `".Table_prefix."config`";
        if ($db->ejecutarConsulta($sqlStr)) {
            return ($db->contarRegistros() > 0);
        } else {
            return false;
        }
    }

    public function check_for_config()
    {
        if (!defined('DB_Server')) {
            return false;
        }
        if (!defined('DB_name')) {
            return false;
        }
        if (!defined('DB_User')) {
            return false;
        }
        if (!defined('DB_Password')) {
            return false;
        }
        return true;
    }

    public function check_form()
    {
        $action="";

        if (isset($this->data['action'])) {
            $action=$this->data['action'];
        }

        if (!$this->is_sorbet_installed()) {
            $this->showForm = true;

            if ($action=="config") {
                $sep_err="";
                $this->errors = false;

                if (!$this->data['login']) {
                    $this->errors =$this->errors.$sep_err."1";
                    $sep_err="|";
                }
                if (!$this->data['db_login']) {
                    $this->errors =$this->errors.$sep_err."10";
                    $sep_err="|";
                }
                if (!$this->data['password']) {
                    $this->errors=$this->errors.$sep_err."2";
                    $sep_err="|";
                }
                if (!$this->data['email']) {
                    $this->errors=$this->errors.$sep_err."4";
                    $sep_err="|";
                }
                if (!$this->data['url_installation']) {
                    $this->errors=$this->errors.$sep_err."5";
                    $sep_err="|";
                }
                if (!$this->data['db_host']) {
                    $this->errors=$this->errors.$sep_err."7";
                    $sep_err="|";
                }
                if (!$this->data['db_name']) {
                    $this->errors=$this->errors.$sep_err."8";
                    $sep_err="|";
                }
                if ($this->data['password']!=$_POST['password2']) {
                    $this->errors=$this->errors.$sep_err."3";
                    $sep_err="|";
                }
                if ($_POST['db_password']!=$_POST['db_password2']) {
                    $this->errors=$this->errors.$sep_err."9";
                    $sep_err="|";
                }

                $off_r= explode(",", $this->data['time_offsets']);
                $this->data['offset_time'] = $off_r[0];
                $this->data['offset_city'] = $off_r[1];
                unset($this->data['time_offsets']);

                if (!$this->errors) {
                    if ($this->run($this->data)) {
                        $this->showForm=false;
                    } else {
                        $this->errors=$this->errors.$sep_err."6";
                        $sep_err="|";
                        $this->showForm=true;
                    }
                } else {
                    $this->showForm=true;
                }
            }
        }
    }
}
