<?php

error_reporting(E_ERROR);
//error_reporting(E_ALL);
ini_set("display_errors", true);

$path = dirname(__FILE__).'/../../libraries/';
try {
    $contents = file_get_contents($_GET['config']);
    $values   = unserialize($contents);

    Install :: prepareSetup($path);
    Install :: checkPrerequisites($path);
    Install :: createDatabase($path, $values);
    Install :: populateDatabase($path, $values);
} catch (Exception $e) {
    echo '
    <div style = "border:1px solid blue;background-color:#aacfeb;text-align:center;font-family:trebuchet ms">
    	The operation could not be completed: '.$e -> getMessage().'<br>
    	<a href = "javascript:void(0)" onclick = "document.getElementById(\'full_message\').style.display = \'\'">View complete message</a> -
    	<a href = "javascript:void(0)" onclick = "location=\'install.php\'">Switch to interactive mode</a> - 
    	<a href = "javascript:void(0)" onclick = "location.reload()">Retry</a> 
    </div>
    <div id = "full_message" style = "display:none"><pre>'.print_r($e, true).'</pre></div>';
}

/**
 * Enter description here...
 *
 */
class Install 
{
    
    public static function createDatabase($path, $values) {
        /**ADODB database abstraction class*/
        require_once($path.'adodb/adodb.inc.php');
        /**ADODB exceptions class*/
        require_once($path.'adodb/adodb-exceptions.inc.php');
        $db = ADONewConnection('mysql');                                    //Set Connection parameter to "mysql"
        $db -> NConnect($values['db_host'], $values['db_user'], $values['db_password']);
        
        $db -> Execute("SET NAMES 'UTF8'");
        //@todo: maybe remove
        //$db -> Execute("drop database if exists ".$values['db_name']);
        $db -> Execute("create database ".$values['db_name']." DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");                          //Create the new database
        $db -> Execute("use ".$values['db_name']);
        $file_contents = trim(file_get_contents("sql_".'mysql'.".txt"));                                  //Get the sql queries text
        $file_contents = explode(';',$file_contents);                                       //Form the sql queries, by splitting each CREATE statement
        if (!end($file_contents)) {
            array_pop($file_contents);                                                      //Remove last element, if it is an empty array (which is usually the case)
        }
        foreach ($file_contents as $query) {                                                //Run queries
            preg_match('/CREATE TABLE (\w+) .*/', $query, $matches);
            $db -> Execute($query);
        }
        if (is_file($path."configuration_temp.php")) {
            unlink($path."configuration_temp.php");                                         //Delete any temporary configuration file left from previous attempt
        }
        $file_contents = file_get_contents('sample_config.php');                            //Load sample configuration file
        $patterns = array('/(define\("G_DBTYPE", ").*("\);)/',
                          '/(define\("G_DBHOST", ").*("\);)/',
                          '/(define\("G_DBUSER", ").*("\);)/',
                          '/(define\("G_DBPASSWD", ").*("\);)/',
                          '/(define\("G_DBNAME", ").*("\);)/');
        $replacements = array('${1}'.'mysql'.'${2}', '${1}'.$values['db_host'].'${2}', '${1}'.$values['db_user'].'${2}', '${1}'.$values['db_password'].'${2}', '${1}'.$values['db_name'].'${2}');
        $new_file_contents = preg_replace($patterns, $replacements, $file_contents, -1, $count);    //Replace sample settings with current settings
        file_put_contents($path.'configuration_temp.php', $new_file_contents);

        $file_contents = file_get_contents($path.'configuration_temp.php');                            //Load configuration file
        $patterns      = array('/(define\("G_SERVERNAME", ")http(:\/\/"\.\$_SERVER\["HTTP_HOST"\]\."\/).*("\);)/',
                               '/(define\("G_SERVERPORT", ").*("\);)/',
                               '/(define\("G_ROOTPATH", ").*("\);)/',
                               '/\/\/(require_once\("globals\.php"\);)/');
        $values['site_url'] != '/' ? $values['site_url'] = trim($values['site_url'], "/")."/" : $values['site_url'] = '';
        $replacements      = array('${1}'.($values['site_protocol']).'${2}'.$values['site_url'].'${3}', '${1}'.$values['site_port'].'${2}', '${1}'.$values['site_path'].'${2}', '${1}');       //${1} and ${2} is needed in port, because port is a number)                    
        $new_file_contents = preg_replace($patterns, $replacements, $file_contents, -1, $count);    //Replace sample settings with current settings       
        file_put_contents($path.'configuration_temp.php', $new_file_contents);
                
    }

    public static function populateDatabase($path, $values) {
        /**Include the database functions*/
        /**Include the newly created configuration file*/
    	
        require_once($path."configuration_temp.php");
        require_once($path."tools.php");
        require_once($path."database.php");
        $GLOBALS['db'] = ADONewConnection(G_DBTYPE);
        $GLOBALS['db'] -> Connect(G_DBHOST, G_DBUSER, G_DBPASSWD, G_DBNAME);
        $GLOBALS['db'] -> Execute("SET NAMES 'UTF8'");
                       
        require_once "insert_languages.php";
        addLanguagesDB();
        
        $admin_values = array('login'    => $values['admin_user'],
                              'password' => $values['admin_password'],
                              'email'    => $values['admin_email'],
                              'name'     => $values['admin_name'],
                              'surname'  => $values['admin_surname'],
                              'languages_NAME' => 'english',
                              'active'   => '1',
                              'user_type'=> 'administrator');


        EfrontUser :: createUser($admin_values);
        if (MODULE_HCD_INTERFACE) {
            EfrontHcdUser :: createUser(array("users_login" => $values['admin_user']));
        }
        
        //Initialize configuration
        EfrontConfiguration::getValues();
        foreach (EfrontConfiguration::getDefaultValues() as $option => $value) { 
        	EfrontConfiguration::setValue($option, $value);
        }
        
        //@todo: create professor,student
        //@todo: create default lessons                
        
        if (is_file($path."configuration.php")) {
            unlink($path."configuration.php");
        }
        rename($path."configuration_temp.php", $path."configuration.php");        
        
        header("location:".G_SERVERNAME);
    }
    
    /**
     * Check prerequisites
     *
     * @param unknown_type $path
     * @return unknown
     */
    public static function checkPrerequisites($path) {
        $php_version  = explode('.', phpversion());
        $extensions   = get_loaded_extensions();    
        $ini_settings = ini_get_all();
        
        $prerequisites['PHP']    = (isset($php_version[0]) && $php_version[0] <= 4 ? false : true);
        
        $prerequisites['mbstring'] = in_array('mbstring', $extensions);
        $prerequisites['session']  = in_array('session',  $extensions);
        $prerequisites['iconv']    = in_array('iconv',    $extensions);
        $prerequisites['pcre']     = in_array('pcre',     $extensions);
        $prerequisites['mysql']    = in_array('mysql',    $extensions);
        $prerequisites['zip']      = in_array('zip',      $extensions);
    
        $prerequisites['register_globals']        = ($ini_settings['register_globals']['global_value']        ? 0 : 1);
        $prerequisites['magic_quotes_gpc']        = ($ini_settings['magic_quotes_gpc']['global_value']        ? 0 : 1);
        $prerequisites['magic_quotes_runtime']    = ($ini_settings['magic_quotes_runtime']['global_value']    ? 0 : 1);
        $prerequisites['safe_mode']               = ($ini_settings['safe_mode']['global_value']               ? 0 : 1);
        $prerequisites['file_uploads']            = ($ini_settings['file_uploads']['global_value']            ? 1 : 0);
        $prerequisites['zlib.output_handler']     = ($ini_settings['zlib.output_handler']['global_value']     ? 0 : 1);
        $prerequisites['zlib.output_compression'] = ($ini_settings['zlib.output_compression']['global_value'] ? 0 : 1);
        
        $prerequisites['www/content']                 = is_writable($path.'../www/content') && is_writable($path.'../www/content/lessons') && is_writable($path.'../www/content/admin');
        $prerequisites['www/css']                     = is_writable($path.'../www/css');
        $prerequisites['www/images/avatars']          = is_writable($path.'../www/images/avatars');
        $prerequisites['www/images/logo']             = is_writable($path.'../www/images/logo');
        $prerequisites['www/modules']                 = is_writable($path.'../www/modules');
        $prerequisites['libraries']                   = is_writable($path);
        $prerequisites['libaries/language']           = is_writable($path.'language');
        $prerequisites['libaries/smarty/templates_c'] = is_writable($path.'smarty/templates_c');
        $prerequisites['libaries/smarty/cache']       = is_writable($path.'smarty/cache');
        $prerequisites['backups']                     = is_writable($path.'../backups');
        $prerequisites['upload']                      = is_writable($path.'../upload');
        $prerequisites['libaries/language/lang-english.php.inc'] = is_writable($path.'language/lang-english.php.inc');                                                
        
        $prerequisites['PEAR.php']                                = (fopen ('../../PEAR/PEAR.php', 'r', true)                                ? true : false);
        $prerequisites['HTML/QuickForm.php']                      = (fopen ('../../PEAR/HTML/QuickForm.php', 'r', true)                      ? true : false);
        $prerequisites['HTML/QuickForm/Renderer/ArraySmarty.php'] = (fopen ('../../PEAR/HTML/QuickForm/Renderer/ArraySmarty.php', 'r', true) ? true : false);
        $prerequisites['Mail.php']                                = (fopen ('../../PEAR/Mail.php', 'r', true)                                ? true : false);
        $prerequisites['Net/SMTP.php']                            = (fopen ('../../PEAR/Net/SMTP.php', 'r', true)                            ? true : false);
        $prerequisites['Net/Socket.php']                          = (fopen ('../../PEAR/Net/Socket.php', 'r', true)                          ? true : false);
    
        if (!array_product($prerequisites)) {
            //@todo: output which prerequisites
            throw new Exception("Prerequisites not met!");
        } else {
            return true;
        }
        
    }    

    public static function prepareSetup($path) {
        $smarty -> compile_dir   = $path.'smarty/templates_c/';
        $smarty -> cache_dir     = $path.'smarty/cache/';
        is_dir($smarty -> cache_dir)   or mkdir($smarty -> cache_dir, 0755);                      //Create cache and template cache directories, if they don't exist
        is_dir($smarty -> compile_dir) or mkdir($smarty -> compile_dir, 0755);
    }
}

?>