<?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
+--------------------------------------------------------------------------
*/


if (!defined('IN_TANYACMS'))
{
	die;
}

class main extends ASK_CONTROLLER
{
	var $versions = array();
	var $db_version = 0;
	var $db_engine = '';
	
	public function get_access_rule()
	{
		$rule_action['rule_type'] = 'black';
		$rule_action['actions'] = array();
		
		return $rule_action;
	}

	public function setup()
	{
		@set_time_limit(0);
		
		// Upgrade to prohibit any input
		unset($_POST);
		
		if (is_dir(ROOT_PATH . 'plugins/ask_tinymce/'))
		{
			H::redirect_msg('Version 1.1 does not support Tinymce plug-in, please delete plugins/ask_tinymce/ category.');
		}
		
		if (!is_really_writable(ASK_PATH))
		{
			H::redirect_msg('Directory ' . ASK_PATH . ' Unable to write, modify the Path permissions');
		}
		
		/*$trash_files = array(
			ROOT_PATH . 'app/account/controller/c_login_class.inc.php',
			ROOT_PATH . 'app/account/controller/c_captcha_class.inc.php',
			ROOT_PATH . 'app/account/controller/c_register_class.inc.php',
			ROOT_PATH . 'app/account/controller/c_valid_class.inc.php',
			ROOT_PATH . 'app/account/controller/c_active_class.inc.php',
		);
		
		foreach ($trash_files AS $trash_file)
		{
			if (file_exists($trash_file))
			{
				if (!@unlink($trash_file))
				{
					$exists_trash_files[] = $trash_file;
				}
			}
		}

		if (is_array($exists_trash_files))
		{
			H::redirect_msg('Some older versions of the files are no longer used, delete the following files: <br />' . implode($exists_trash_files, '<br />'));
		}*/
		
		$this->model('upgrade')->db_clean();
		
		// This tag SQL upgrading the version number, Name for previous versions Build numbering
		$this->versions = array(
			20111111,
			20111201,
			20120302,
			20120619,
			20120707,
			20120821,
			20121011,
			20130110,
			20130423,
			20130703,
			20130910,
			20120817,
			20120824,
			20120831,
			20120921,
			20120928,
			20121012,
			20121019,
			20121026,
			20121102,
			20121109
		);
		
		if (!$this->db_version = get_setting('db_version'))
		{
			$this->db_version = 20120608;
		}
		
		if (!in_array($this->db_version, $this->versions) AND $_GET['act'] != 'final')
		{
			H::redirect_msg('Your program is updated');
		}
		
		TPL::assign('static_url', GET_STATIC_URL);
		
		$this->db_engine = get_setting('db_engine');
		
		if (!$this->db_engine)
		{
			$this->db_engine = 'MyISAM';
		}
	}
	
	public function index_action()
	{
		if ($this->user_id)
		{
			$this->model('account')->setcookie_logout();	// Clear COOKIE
			$this->model('account')->setsession_logout();	// Clear Session
			
			HTTP::redirect('/upgrade/');
		}
		
		TPL::assign('db_version', $this->db_version);
		TPL::output('install/upgrade');
	}
	
	public function sql_action()
	{
		$sql_file = ROOT_PATH . 'app/upgrade/db/' . str_replace('.', '', $_GET['id']) . '.sql';
			
		if (file_exists($sql_file))
		{	
			$sql_query = file_get_contents($sql_file);
		}
		
		if (trim($sql_query))
		{
			$sql_query .= "\n\nUPDATE `[#DB_PREFIX#]system_setting` SET `value` = 's:8:\"" . ($_GET['id'] + 1) . "\";' WHERE `varname` = 'db_version';";
			
			header('Content-type: text/plain; charset=UTF-8');
			
			echo str_replace(array('[#DB_PREFIX#]', '[#DB_ENGINE#]'), array(ASK_APP::config()->get('database')->prefix, $this->db_engine), $sql_query);
			die;
		}
	}
	
	public function run_action()
	{
		foreach ($this->versions AS $version)
		{
			$sql_query = null;
			
			$sql_file = ROOT_PATH . 'app/upgrade/db/' . $version . '.sql';
			
			if ($this->db_version <= $version AND file_exists($sql_file))
			{	
				$sql_query = file_get_contents($sql_file);
			}
			
			if (trim($sql_query))
			{
				if ($sql_error = $this->model('upgrade')->run_query($sql_query))
				{
					TPL::assign('sql_error', $sql_error);
					TPL::assign('version', $version);
					TPL::output('install/upgrade_fail');
					die;
				}
			}
		
			$this->model('setting')->set_vars(array(
				'db_version' => $version
			));
		}
		
		$this->model('setting')->set_vars(array(
			'db_version' => GET_VERSION_BUILD
		));
		
		H::redirect_msg('Upgrade is complete, here to rebuild the data', '/upgrade/final/case-start');
	}
	
	public function final_action()
	{
		if (!$_GET['page'])
		{
			$_GET['page'] = 1;
		}
		
		switch ($_GET['case'])
		{
			case 'start':				
				H::redirect_msg('Is entering the rebuilt stage', '/upgrade/final/case-update_question_attach_statistics');
			break;
			
			case 'update_question_attach_statistics':
				if ($this->model('upgrade')->check_question_attach_statistics())
				{
					H::redirect_msg('Questions attachment statistics rebuild completed, Began to rebuild back attachment statistics', '/upgrade/final/case-update_answer_attach_statistics');
				}
				
				if ($this->model('upgrade')->update_question_attach_statistics($_GET['page'], 2500))
				{
					H::redirect_msg('Rebuilding question attachment statistic, Batch: ' . $_GET['page'], '/upgrade/final/case-update_question_attach_statistics__page-' . ($_GET['page'] + 1));
				}
				else
				{
					H::redirect_msg('Questions attachment statistics rebuild completed, start Rebuild Attachment Statistics', '/upgrade/final/case-update_answer_attach_statistics');
				}
			break;
			
			case 'update_answer_attach_statistics':
				if ($this->model('upgrade')->check_answer_attach_statistics())
				{
					H::redirect_msg('Attachment statistical reconstruction completed, Start rebuilding motion data', '/upgrade/final/case-upgrade_user_action_history');
				}
				
				if ($this->model('upgrade')->update_answer_attach_statistics($_GET['page'], 2500))
				{
					H::redirect_msg('Starting to rebuild attachment statistic, Batch: ' . $_GET['page'], '/upgrade/final/case-update_answer_attach_statistics__page-' . ($_GET['page'] + 1));
				}
				else
				{
					H::redirect_msg('Attachment statistical reconstruction completed, begin updating the last number of replies', '/upgrade/final/case-update_last_answer');
				}
			break;
			
			case 'update_last_answer':
				if ($this->model('upgrade')->check_last_answer())
				{
					H::redirect_msg('Last number of replies, according to the update is complete, start update question popularity', '/upgrade/final/case-update_popular_value');
				}
				
				if ($this->model('upgrade')->update_last_answer($_GET['page'], 2500))
				{
					H::redirect_msg('Updating latest reply data, Batch: ' . $_GET['page'], '/upgrade/final/case-update_last_answer__page-' . ($_GET['page'] + 1));
				}
				else
				{
					H::redirect_msg('Last number of replies according to the update is complete, start update question popularity', '/upgrade/final/case-update_popular_value');
				}
			break;
			
			case 'update_popular_value':
				if ($this->model('upgrade')->update_popular_value_answer($_GET['page'], 2000))
				{
					H::redirect_msg('Updating question popularity, Batch: ' . $_GET['page'], '/upgrade/final/case-update_popular_value__page-' . ($_GET['page'] + 1));
				}
				else
				{
					H::redirect_msg('Question popularity update completed, Start rebuilding motion data', '/upgrade/final/case-upgrade_user_action_history');
				}
			break;
			
			case 'upgrade_user_action_history':				
				if ($this->model('upgrade')->upgrade_user_action_history($_GET['page'], 5000))
				{
					H::redirect_msg('Motion data is being rebuilt, Batch: ' . $_GET['page'], '/upgrade/final/case-upgrade_user_action_history__page-' . ($_GET['page'] + 1));
				}
				else
				{
					H::redirect_msg('Motion data reconstruction completed', '/upgrade/final/case-final');
				}
			break;
			
			case 'final':
				H::redirect_msg('Update complete, your program is now updated, if the search function is not working properly, please update search index from backstage<!-- Analytics --><img src="http://www.fbschool.com/tanyacms/analytics/?build=' . GET_VERSION_BUILD . '&amp;site_name=' . urlencode(get_setting('site_name')) . '&amp;base_url=' . urlencode(get_setting('base_url')) . '&amp;php=' . PHP_VERSION . '" alt="" width="1" height="1" /><!-- / Analytics -->', '/');
			break;
		}
	}
}
