<?php
/*
+--------------------------------------------------------------------------
|   TanyaCMS - Question and Answer Sofware
|   -----------------------------------------------------------------------
|   by fbschool dev team
|   (c) 2011 - 2012 FBSCHOOL
|   http://www.fbschool.com/tanyacms
|   -----------------------------------------------------------------------
|   This is NOT a freeware, use is subject to license terms
|   Support: 13455n@gmail.com
+--------------------------------------------------------------------------
*/

require_once('../system/init.php');

HTTP::no_cache_header();

if (file_exists(ASK_PATH . 'config/install.lock.php'))
{
	H::redirect_msg('Your program has been installed, to reinstall please delete system/config/install.lock.php');
}

@set_time_limit(0);

TPL::assign('page_title', 'TanyaCMS - Installation - PersianScript.ir');
TPL::assign('static_url', '../static');

switch ($_POST['step'])
{
	default :
		$system_require = array();
		
		if (version_compare(PHP_VERSION, ENVIRONMENT_PHP_VERSION, '>='))
		{
			$system_require['php'] = TRUE;
		}
		
		if (class_exists('PDO', false))
		{
			if (defined('PDO::MYSQL_ATTR_USE_BUFFERED_QUERY'))
			{
				$system_require['db'] = 'PDO_MYSQL';
			}
		}
		
		if (!$system_require['db'] AND function_exists('mysqli_close'))
		{
			$system_require['db'] = 'MySQLi';
		}
		
		if (function_exists('session_start'))
		{
			$system_require['session'] = TRUE;
		}
		
		if (function_exists('mb_strlen'))
		{
			$system_require['convert_encoding'] = TRUE;
		}
		else if (function_exists('iconv'))
		{
			$system_require['convert_encoding'] = TRUE;
		}
		
		if (isset($_COOKIE))
		{
			$system_require['cookie'] = TRUE;
		}
		
		if (function_exists('gd_info'))
		{
			$system_require['image_lib'] = 'GD';
		}
		
		if ($system_require['image_lib'] AND class_exists('Imagick', false))
		{
			$system_require['image_lib'] = 'ImageMagick';
		}
		
		// Detect ASK_PATH whether you have write access
		if (is_really_writable(ASK_PATH))
		{
			$system_require['config_writable_core'] = TRUE;
		}
		
		// Detect ASK_PATH /config/ whether you have write access
		if (is_really_writable(ASK_PATH . 'config/'))
		{
			$system_require['config_writable_config'] = TRUE;
		}
		
		$base_dir = str_replace("\\", "",dirname(dirname($_SERVER['PHP_SELF'])));
		
		
		TPL::assign('error_messages', $error_messages);
		TPL::assign('system_require', $system_require);
		TPL::assign('base_dir', $base_dir);
		TPL::output('install/index');
		break;
	
	case 2 :
		$data_dir = array(
			'tmp', 
			'cache', 
			'uploads'
		);
		
		foreach ($data_dir as $key => $dir_name)
		{
			if (! is_dir(ROOT_PATH . $dir_name))
			{
				if (! @mkdir(ROOT_PATH . $dir_name))
				{
					$error_messages[] = 'Directory: ' . ROOT_PATH . $dir_name . ' Unable to create, insert web root path permissions set to 777, Or create this directory set permissions to 777';
				}
			}
		}
		
		if (! is_really_writable(ASK_PATH))
		{
			$error_messages[] = 'Directory: ' . ASK_PATH . ' Unable to write, leave this path permissions set to 777';
		}
		
		if (class_exists('PDO', false))
		{
			if (defined('PDO::MYSQL_ATTR_USE_BUFFERED_QUERY'))
			{
				TPL::assign('pdo_support', TRUE);
			}
		}
		
		if (function_exists('mysqli_close'))
		{
			TPL::assign('mysqi_support', TRUE);
		}
		
		TPL::assign('error_messages', $error_messages);
		TPL::output('install/settings');
		break;
	
	case 3 :
		$db_config = array(
			//'charset' => 'utf8',
			'host' => $_POST['db_host'], 
			'username' => $_POST['db_username'], 
			'password' => $_POST['db_password'], 
			'dbname' => $_POST['db_dbname']
		);
		
		if ($_POST['db_driver'])
		{
			$db_driver = $_POST['db_driver'];
		}
		else if (class_exists('PDO', false))
		{
			if (defined('PDO::MYSQL_ATTR_USE_BUFFERED_QUERY'))
			{
				$db_driver = 'PDO_MYSQL';
			}
		}
		
		if (!$db_driver)
		{
			$db_driver = 'MySQLi';
		}
		
		if (!$_POST['db_engine'])
		{
			$_POST['db_engine'] = 'MyISAM';
		}
		
		try
		{
			$db = Zend_Db::factory($db_driver, $db_config);
		}
		catch (Exception $e)
		{
			H::redirect_msg('Database connection failed, Error Messages: ' . strip_tags($e->getMessage()), './');
		}
		
		try
		{
			$tables = $db->fetchAll('SHOW TABLES');
		}
		catch (Exception $e)
		{
			H::redirect_msg('Database connection failed, Error Messages: ' . strip_tags($e->getMessage()), './');
		}
		
		if (number_format($db->getServerVersion(), 1) < 5)
		{
			H::redirect_msg('Installation aborted: TanyaCMS requires MySQL 5.0 or later database support, your server for the current MySQL version: ' . $db->getServerVersion(), './');
		}
		
		$db->query("SET NAMES utf8");
		
		if (!$_POST['db_prefix'] AND count($tables) > 0)
		{
			H::redirect_msg('Database already exists data tables, not allowed to install, if you want to reinstall please clear data sheet.' . strip_tags($e->getMessage()), './');
		}
		
		foreach ($tables AS $key => $table_info)
		{
			if (!is_array($table_info))
			{
				break;
			}
			
			foreach ($table_info AS $_key => $table)
			{
				if (substr($table, 0, strlen($_POST['db_prefix'])) == $_POST['db_prefix'])
				{
					H::redirect_msg('Database already exists the same prefix table may not be installed, such as To reinstall please clear data sheet.', './');
				
					break;
				}
			}
		}
		
		$config = array(
			'charset' => 'utf8', 
			'prefix' => $_POST['db_prefix'], 
			'driver' => $db_driver, 
			'master' => $db_config, 
			'slave' => false
		);
		
		load_class('core_config')->set('database', $config);
		
		// Create a data table
		$db_table_querys = explode(";\r", str_replace(array('[#DB_PREFIX#]', '[#DB_ENGINE#]', "\n"), array($_POST['db_prefix'], $_POST['db_engine'], "\r"), file_get_contents(ROOT_PATH . 'install/db/mysql.sql')));
		
		foreach ($db_table_querys as $_sql)
		{
			if ($query_string = trim(str_replace(array(
				"\r", 
				"\n", 
				"\t"
			), '', $_sql)))
			{
				$db->query($query_string);
			}
		}
		
		$db->insert($_POST['db_prefix'] . 'system_setting', array(
			'varname' => 'db_engine',
			'value' => 's:' . strlen($_POST['db_engine']) . ':"' . $_POST['db_engine'] . '";',
		));
		
		TPL::output('install/final');
		break;
	
	case 4 :		
		$db = load_class('core_db')->setObject('master');
		$db_prefix = load_class('core_config')->get('database')->prefix;
		
		$salt = fetch_salt(4);
		
		$data = array(
			'user_name' => $_POST['user_name'], 
			'password' => compile_password($_POST['password'], $salt), 
			'email' => $_POST['email'], 
			'salt' => $salt,
			'group_id' => 1,
			'reputation_group' => 5,
			'valid_email' => 1,
			'is_first_login' => 1,
			'reg_time' => time(),
			'reg_ip' => ip2long(fetch_ip()),
			'last_login' => time(),
			'last_ip' => ip2long(fetch_ip()),
			'last_active' => time(),
			'invitation_available' => 10,
			'integral' => 2000
		);
		
		$db->insert($db_prefix . 'users', $data);
		$db->insert($db_prefix . 'users_attrib', array('uid' => 1, 'signature' => ''));
		
		$db->insert($db_prefix . 'integral_log', array(
			 'uid' => 1,
			 'action' => 'REGISTER',
			 'integral' => 2000,
			 'note' => 'Initial capital',
			 'balance' => 2000,
			 'time' => time()
		));
		
		//Loading site configuration
		$base_dir = dirname(dirname($_SERVER['PHP_SELF']));
		$base_dir = ($base_dir == DIRECTORY_SEPARATOR) ? '' : $base_dir;
		$base_url =  'http' . ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $base_dir;
		
		$insert_query = file_get_contents(ROOT_PATH . 'install/db/system_setting.sql');
		
		$insert_query = str_replace('[#DB_PREFIX#]', $db_prefix, $insert_query);
		$insert_query = str_replace('[#BASE_URL#]', serialize($base_url), $insert_query);
		$insert_query = str_replace('[#UPLOAD_URL#]', serialize($base_url . "/uploads"), $insert_query);
		$insert_query = str_replace('[#UPLOAD_DIR#]', serialize(str_replace("\\", "/", ROOT_PATH) . "uploads"), $insert_query);
		$insert_query = str_replace('[#FROM_EMAIL#]', serialize($_POST['email']), $insert_query);
		$insert_query = str_replace('[#DB_VERSION#]', serialize(GET_VERSION_BUILD), $insert_query);
		
		//$db->query($insert_query);
		
		$sql_query = str_replace("\n", "\r", $insert_query);
		
		$db_table_querys = explode(";\r", $sql_query);
			
		foreach ($db_table_querys as $_sql)
		{
			if ($query_string = trim(str_replace(array(
				"\r", 
				"\n", 
				"\t"
			), '', $_sql)))
			{
				try {
					$db->query($query_string);
				}
				catch (Exception $e)
				{
					die('SQL Error: ' . $e->getMessage() . '<br /><br />Query: ' . $query_string);
				}
			}
		}
		
		$db->insert($db_prefix . 'system_setting', array(
			'varname' => 'register_agreement',
			'value' => serialize(file_get_contents(ROOT_PATH . 'install/db/register_agreement.txt')),
		));
		
		//Build config.inc.php
		$config_file = file_get_contents(ASK_PATH . '/config.dist.php');
		$config_file = str_replace('{GET_COOKIE_PREFIX}', fetch_salt(3) . '_', $config_file);
		$config_file = str_replace('{GET_SECUKEY}', fetch_salt(12), $config_file);
		$config_file = str_replace('{GET_COOKIE_HASH_KEY}', fetch_salt(15), $config_file);
		
		file_put_contents(ASK_PATH . '/config.inc.php', $config_file);
		file_put_contents(ASK_PATH . '/config/install.lock.php', time());
		
		TPL::output('install/success');
		break;
}