<?php

/**
 *--------------------------------------
 * install
 *--------------------------------------
 * @project		: install
 * @author		: cblee
 * @created		: 2013-12-27
 * @copyright	: (c)2013 AsThis
 *--------------------------------------
 */
defined('PFA_PATH') or exit('Access Denied');

class IndexCtrlr extends Ctrlr {
	public function index() {
		check_lock();
		define('SITE_URL', trim(__HOST__.dirname(APP_ROOT), '/\\').'/');

		$step = isset($_POST['step']) ? $_POST['step'] : 0;
		switch ($step) {
			case '1':
				$this->_step1();
				break;
			case '2':
				$this->_step2();
				break;
			case '3':
				$this->_step3();
				break;
			case '4':
				$this->_step4();
				break;
			case '5':
				$errorMessage = check_post(array('founderEmail' => $_POST['founderEmail'], 'founderPassword' => $_POST['founderPassword']));
				$errorMessage .= check_db($_POST['dbHost'], $_POST['dbPort'], $_POST['dbUser'], $_POST['dbPassword'], $_POST['dbDatabase'], $_POST['dbPrefix'], $_POST['dbConnection']);
				if('' != $errorMessage) {
					$this->_step4($errorMessage);
				}
				else {
					$this->_step5();
				}
				break;
			case '6':
				$this->_step6();
				break;
			default:
				$this->_step0();
				break;
		}
	}

	/* choose language */
	private function _step0() {
		$_LS = get_langset();
		$selectHight = count($_LS) > 5 ? count($_LS) : 5;
		$this->assign('selectHight', $selectHight);
		$this->assign('_LS', $_LS);
		$this->display('index');
	}

	/* show introduce */
	private function _step1() {
		$_README = file_get_contents(LANG_PATH.D_S.LANG_NAME.D_S.'README.html');
		$this->assign('_README', $_README);
		$this->display('step1');
	}

	/* show license */
	private function _step2() {
		$_LICENSE = file_get_contents(LANG_PATH.D_S.LANG_NAME.D_S.'LICENSE.html');
		$this->assign('_LICENSE', $_LICENSE);
		$this->display('step2');
	}

	/* check environment */
	private function _step3() {
		$checkNextStep = true;

		/* check system */
		$systemItems = C('CHECK_ITEMS.SYSTEM');
		if(!empty($systemItems)) {
			check_system($systemItems, $checkNextStep);
			foreach($systemItems as $k => $v) {
				$systemItems[L($k)]['r'] = L($v['r']);
				$systemItems[L($k)]['b'] = L($v['b']);
				$systemItems[L($k)]['c'] = L($v['c']);
				if(1 == $v['s']) {
					$systemItems[L($k)]['c_c'] = 'class="y"';
				}
				else {
					$systemItems[L($k)]['c_c'] = 'class="n"';
				}
				unset($systemItems[$k]);
			}
		}

		/* check dir and file */
		$dirFileItems = C('CHECK_ITEMS.DIR_FILE');
		if(!empty($dirFileItems)) {
			check_dirfile($dirFileItems, $checkNextStep);
			foreach($dirFileItems as $k => $v) {
				$dirFileItems[L($k)]['type'] = L($v['type']);
				$dirFileItems[L($k)]['c'] = L($v['c']);
				$dirFileItems[L($k)]['path'] = $v['path'];
				if(1 == $v['s']) {
					$dirFileItems[L($k)]['c_c'] = 'class="y"';
				}
				else {
					$dirFileItems[L($k)]['c_c'] = 'class="n"';
				}
				unset($dirFileItems[$k]);
			}
		}

		/* check php config */
		$phpConfigItems = C('CHECK_ITEMS.PHP_CONFIG');
		if(!empty($phpConfigItems)) {
			check_phpConfig($phpConfigItems, $checkNextStep);
			foreach($phpConfigItems as $k => $v) {
				if(1 == $v['s']) {
					$phpConfigItems[$k]['c_c'] = 'class="y"';
				}
				else {
					$phpConfigItems[$k]['c_c'] = 'class="n"';
				}
			}
		}

		/* check extension */
		$extensionItems = C('CHECK_ITEMS.EXTENSION');
		if(!empty($extensionItems)) {
			check_extension($extensionItems, $checkNextStep);
			foreach($extensionItems as $k => $v) {
				if(1 == $v['s']) {
					$extensionItems[$k]['c_c'] = 'class="y"';
					$extensionItems[$k]['s'] = L('SUPPORT');
				}
				else {
					$extensionItems[$k]['c_c'] = 'class="n"';
					$extensionItems[$k]['s'] = L('NONSUPPORT');
				}
			}
		}

		/* check function */
		$functionItems = C('CHECK_ITEMS.FUNCTION');
		if(!empty($functionItems)) {
			check_function($functionItems, $checkNextStep);
			foreach($functionItems as $k => $v) {
				if(1 == $v['s']) {
					$functionItems[$k]['c_c'] = 'class="y"';
					$functionItems[$k]['s'] = L('SUPPORT');
				}
				else {
					$functionItems[$k]['c_c'] = 'class="n"';
					$functionItems[$k]['s'] = L('NONSUPPORT');
				}
			}
		}

		$this->assign('checkNextStep', $checkNextStep);
		$this->assign('systemItems', $systemItems);
		$this->assign('dirFileItems', $dirFileItems);
		$this->assign('phpConfigItems', $phpConfigItems);
		$this->assign('extensionItems', $extensionItems);
		$this->assign('functionItems', $functionItems);
		$this->display('step3');
	}

	/* setup installation */
	private function _step4($errorMessage = '') {
		$formV['dbHost'] = isset($_POST['dbHost']) ? $_POST['dbHost'] : 'localhost';
		$formV['dbPort'] = isset($_POST['dbPort']) ? $_POST['dbPort'] : '3306';
		$formV['dbUser'] = isset($_POST['dbUser']) ? $_POST['dbUser'] : 'root';
		$formV['dbPassword'] = isset($_POST['dbPassword']) ? $_POST['dbPassword'] : '';
		$formV['dbDatabase'] = isset($_POST['dbDatabase']) ? $_POST['dbDatabase'] : strtolower(SOFT_NAME);
		$formV['dbPrefix'] = isset($_POST['dbPrefix']) ? $_POST['dbPrefix'] : strtolower(SOFT_NAME).str_replace('.', '', strtolower(SOFT_CODENAME)).'_';
		$formV['dbConnection'] = isset($_POST['dbConnection']) ? $_POST['dbConnection'] : 'mysql';
		$formV['founderEmail'] = isset($_POST['founderEmail']) ? $_POST['founderEmail'] : 'admin@admin.com';
		$formV['founderPassword'] = isset($_POST['founderPassword']) ? $_POST['founderPassword'] : '';
		$formV['securityCode'] = isset($_POST['securityCode']) ? $_POST['securityCode'] : AString::rand_string(16);
		$formV['manageFilename'] = isset($_POST['manageFilename']) ? $_POST['manageFilename'] : 'admin';
		$this->assign('formV', $formV);
		$this->assign('errorMessage', $errorMessage);
		$this->display('step4');
	}

	/* write data */
	private function _step5() {
		/* replace admin info */
		$email = strtolower(ARequest::get('founderEmail'));
		$password = md5($email.md5(ARequest::get('founderPassword')));
		$securityCode = trim(ARequest::get('securityCode'));
		$sql = file_get_contents(SQL_FILE);
		$sql = str_replace(
			array(
				'{-time-}',
				'{-ip-}',
				's:9:"{-email-}";',
				's:8:"{-apwd-}";',
				'{-site_url-}',
				's:16:"{-security_code-}";',
				's:5:"{-language-}";'
			),
			array(
				NOW_TIME,
				CLIENT_IP,
				's:'.strlen($email).':"'.$email.'";',
				's:'.strlen($password).':"'.$password.'";',
				SITE_URL,
				's:'.strlen($securityCode).':"'.$securityCode.'";',
				's:'.strlen(LANG_NAME).':"'.LANG_NAME.'";'
			),
			$sql);
		@file_put_contents(DATA_PATH.D_S.'_data.sql', $sql);

		$formV['manageFilename'] = isset($_POST['manageFilename']) ? $_POST['manageFilename'] : 'admin';
		$this->assign('formV', $formV);

		$this->display('step5');

		C('DB', array (
			'TYPE' => $_POST['dbConnection'],
			'USER' => $_POST['dbUser'],
			'PWD' => $_POST['dbPassword'],
			'HOST' => $_POST['dbHost'],
			'PORT' => $_POST['dbPort'],
			'NAME' => $_POST['dbDatabase'],
			'CHARSET' => 'UTF8',
			'PREFIX' => $_POST['dbPrefix'],
		));

		run_sql(DATA_PATH.D_S.'_data.sql');

		$uuid = substr(AString::uuid(), 1, -1);
		$define = array(
			'SOFT_NAME' => SOFT_NAME,
			'SOFT_CODENAME' => SOFT_CODENAME,
			'SOFT_VERSION' => SOFT_VERSION,
			'SOFT_CHARSET' => SOFT_CHARSET,
			'SOFT_AUTHOR' => SOFT_AUTHOR,
			'SOFT_AUTHOR_URL' => SOFT_AUTHOR_URL,
			'SOFT_OFFICIAL_FORUM_URL' => SOFT_OFFICIAL_FORUM_URL,
			'SOFT_ONLINE_MANUAL_URL' => SOFT_ONLINE_MANUAL_URL,
			'SOFT_UPGRADE_URL' => SOFT_UPGRADE_URL,
			'SOFT_AUTHORIZATION_URL' => SOFT_AUTHORIZATION_URL,
			'UUID' => $uuid
		);
		save_defineFile(DEFINE_FILE, $define);

		$_C = include(CONFIG_FILE);
		$_C['LANG']['NAME'] = LANG_NAME;
		$_C['DB']['TYPE'] = $_POST['dbConnection'];
		$_C['DB']['USER'] = $_POST['dbUser'];
		$_C['DB']['PWD'] = $_POST['dbPassword'];
		$_C['DB']['HOST'] = $_POST['dbHost'];
		$_C['DB']['PORT'] = $_POST['dbPort'];
		$_C['DB']['NAME'] = $_POST['dbDatabase'];
		$_C['DB']['CHARSET'] = SOFT_DB_CHARSET;
		$_C['DB']['PREFIX'] = strtolower($_POST['dbPrefix']);
		$_C['COOKIE']['KEY'] = $_POST['securityCode'];
		$_C['URL']['BASE_ENTRY'] = ('' == trim(dirname(dirname(_PHP_FILE_)), '\\/') ? '' : dirname(dirname(_PHP_FILE_))).'/index.php';
		save_configFile(CONFIG_FILE, $_C);
		/* delete temp files */
		@unlink(DATA_PATH.D_S.'_data.sql');
		$runtimeFile = SOFT_APP_PATH.D_S.'rt'.D_S.'_runtime.php';
		@unlink($runtimeFile);

		/* update extension install lock file datetime */
		$dh = dir(SOFT_APP_PATH.D_S.'rt'.D_S.'ext');
		while(false !== ($filename = @$dh->read())) {
			if(preg_match("/\.install\.lock\.php$/", $filename)) {
				touch(SOFT_APP_PATH.D_S.'rt'.D_S.'ext'.D_S. $filename);
			}
		}
		$dh->close();

		/* rename manage file */
		$manageFilename = trim(ARequest::get('manageFilename'));
		@rename(SOFT_PATH.D_S.'admin.php', SOFT_PATH.D_S.$manageFilename.'.php');
	}

	/* lock installation */
	private function _step6() {
		lock();

		$formV['manageFilename'] = isset($_POST['manageFilename']) ? $_POST['manageFilename'] : 'admin';
		$this->assign('formV', $formV);

		$this->display('step6');
	}

}
?>