<?php
/**
	 * AKB_INSTALL
	 *
	 * This class handles the install wizard used for installing Interspire Knowledge Manager.
	 *
	 * @version     $Id: class.install.php,v 1.57 2008-04-29 03:21:13 david.chandra Exp $
	 * @author      Paul Marquez
	 * @copyright   Copyright (c) 2004-2008 Interspire Pty. Ltd.
	 * @package     Interspire Knowledge Manager
	 *
	 */

define("IS_OK", 5000);
define("DOESNT_EXIST", 50001);
define("NOT_WRITABLE", 50002);

define('IS_TRIAL', false);

class AKB_INSTALL
{
	var $apiMode = false;

	var $FoldersToCheck = array('admin/includes/config.php','templates','images','attachments','admin/tmp', 'admin/tmp/cache');

	var $ErrorMessage;

	/**
		 * AKB_INSTALL
		 *
		 * Constructor function that determines whether or not the installer should be run.
		 * @return Void Doesn't return anything.
		 */
	function AKB_INSTALL()
	{
		// set the product version
		$GLOBALS['ProductVersion'] = VERSION_NUMBER;

		// is it already setup? if so, don't run the installer!
		if(!$GLOBALS['isSetup']) {
			if(isset($_GET["ToDo"])) {
				$todo = $_GET["ToDo"];
			} else {
				$todo = "";
			}

			if (file_exists(AKB_ROOT.DS.'admin'.DS.'includes'.DS.'config.copy.php')) {
				//OK, its not setup but there are config backup files.
				//Which means the user has probably just copied all files over (including) config to do an upgrade.

				//Get rid of all the previous config settings.
				require_once(dirname(__FILE__)."/class.settings.php");
				$akb_settings = new AKB_SETTINGS();
				$akb_settings->unsetAllSettings();

				//Now include the previous config.
				require_once(AKB_ROOT.DS.'admin'.DS.'includes'.DS.'config.copy.php');
			} else {
				//A typical fresh install
				include_once(dirname(__FILE__).'/../../../lib/api/class.config.php');
				include_once(dirname(__FILE__).'/../../../lib/general.php');
				ob_end_clean();

				// Make the folders appear in alphabetical order to make it easier to go through and fix up permissions
				natsort($this->FoldersToCheck);

				if(defined('IS_TRIAL') && IS_TRIAL == true) {
					$GLOBALS['HideLicenseKey'] = 'display: none';
					$GLOBALS['HidePhoneNumber'] = '';
					$GLOBALS['HideCountryLocation'] = '';
				}
				else {
					$GLOBALS['HideLicenseKey'] = '';
					$GLOBALS['HidePhoneNumber'] = 'display: none';
					$GLOBALS['HideCountryLocation'] = 'display: none';
				}


				// XML INSTALLATION
				if((isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] == "application/xml") || (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] == "application/xml")) {
					$this->apiMode = true;

					// Set up the API request, move the incoming variables in to the _POST array
					$this->SetupApiInstall();

					// Check the prerequisites
					$this->CheckInstallationPrerequisites();

					// All that can be accessed in the install XML API is the RunInstall method, so run it now
					$this->RunInstall();
					exit;
				}

				// Check the prerequisites
				$this->CheckInstallationPrerequisites();

				switch(strtolower($todo)) {
					case "runinstallation": {
						$this->RunInstall();
						break;
					}
					default: {
						$this->GetVariables();
					}
				}

				// We don't want anything running after the installer!
				die();
			}
		}

		// Make the folders appear in alphabetical order to make it easier to go through and fix up permissions
		natsort($this->FoldersToCheck);

		// Check the prerequisites
		$this->CheckInstallationPrerequisites();

		// downForMaintenance was introduced in ActiveKB 2005. If it's not
		// set run the upgrade factory
		if (!isset($GLOBALS['downForMaintenance'])) {
			include_once(dirname(__FILE__).'/../../../lib/upgrade_factory.php');
			$uf = new Upgrade_Factory();

			$_SESSION['__prevVersion'] = "Pre AKB2005!";

			if (isset($_REQUEST['confirm']) && $_REQUEST['confirm'] == 1) {
				$uf->RunUpgrades('2005');
			} else {
				$uf->ShowConfirm('2005');
			}
			die();
		}

		// cleanUrls was introduced in ActiveKB NX2. If it's not set run
		// the upgrade factory
		if (!isset($GLOBALS['cleanUrls'])) {
			include_once(dirname(__FILE__).'/../../../lib/upgrade_factory.php');
			$uf = new Upgrade_Factory();

			if (!isset($_SESSION['__prevVersion'])) {
				$_SESSION['__prevVersion'] = "AKB2005";
			}

			if (isset($_REQUEST['confirm']) && $_REQUEST['confirm'] == 1) {
				$uf->RunUpgrades('NX2');
			} else {
				$uf->ShowConfirm('NX2');
			}
			die();
		}

		// Embedded templates were introduced in ActiveKB NX2.6
		if (!isset($GLOBALS['templateHeader'])) {
			include_once(dirname(__FILE__).'/../../../lib/upgrade_factory.php');
			$uf = new Upgrade_Factory();

			if (!isset($_SESSION['__prevVersion'])) {
				$_SESSION['__prevVersion'] = "NX2";
			}

			if (isset($_REQUEST['confirm']) && $_REQUEST['confirm'] == 1) {
				$uf->RunUpgrades('NX2.6');
			} else {
				$uf->ShowConfirm('NX2.6');
			}
			die();
		}

		// categoryRestrictOption for frontend user system was introduced in ActiveKB NX2.7
		if (!isset($GLOBALS['categoryRestrictOption'])) {
			include_once(dirname(__FILE__).'/../../../lib/upgrade_factory.php');
			$uf = new Upgrade_Factory();

			if (isset($_REQUEST['confirm']) && $_REQUEST['confirm'] == 1) {
				//Check to see if we can send stats.
				if ((isset($_REQUEST['sstats'])) && ($_REQUEST['sstats'] == "1")) {
					if (isset($_SESSION['__prevVersion'])) {
						$prevVersion = $_SESSION['__prevVersion'];
					} else {
						$prevVersion = "NX2.6";
					}

					SendServerInfo(1,$prevVersion,VERSION);
				}

				$uf->RunUpgrades('NX2.7');
			} else {
				$uf->ShowConfirm('NX2.7');
			}
			die();
		}

		// SMTPDefault for specifying SMTP Details was introduced in IKM4.0
		if (!isset($GLOBALS['smtpDefault'])) {
			include_once(dirname(__FILE__).'/../../../lib/upgrade_factory.php');
			$uf = new Upgrade_Factory();

			if (isset($_REQUEST['confirm']) && $_REQUEST['confirm'] == 1) {
				//Check to see if we can send stats.
				if ((isset($_REQUEST['sstats'])) && ($_REQUEST['sstats'] == "1")) {
					if (isset($_SESSION['__prevVersion'])) {
						$prevVersion = $_SESSION['__prevVersion'];
					} else {
						$prevVersion = "NX2.7";
					}

					SendServerInfo(1,$prevVersion,VERSION);
				}
				$uf->RunUpgrades('IKM4.0');
			} else {
				$uf->ShowConfirm('IKM4.0');
			}
			die();
		}

		// LDAPFeature for Ldap Authentication was introduced in IKM4.5
		if (!isset($GLOBALS['ldapHost'])) {
			include_once(dirname(__FILE__).'/../../../lib/upgrade_factory.php');
			$uf = new Upgrade_Factory();

			if (isset($_REQUEST['confirm']) && $_REQUEST['confirm'] == 1) {
				//Check to see if we can send stats.
				if ((isset($_REQUEST['sstats'])) && ($_REQUEST['sstats'] == "1")) {
					if (isset($_SESSION['__prevVersion'])) {
						$prevVersion = $_SESSION['__prevVersion'];
					} else {
						$prevVersion = "IKM4.0";
					}

					SendServerInfo(1,$prevVersion,VERSION);
				}

				$uf->RunUpgrades('IKM4.5');
			} else {
				$uf->ShowConfirm('IKM4.5');
			}
			die();
		}

		// Multiple Database Type for was introduced in IKM5.0
		if (!isset($GLOBALS['databaseType'])) {
			include_once(dirname(__FILE__).'/../../../lib/upgrade_factory.php');
			$uf = new Upgrade_Factory();

			if (isset($_REQUEST['confirm']) && $_REQUEST['confirm'] == 1) {
				//Check to see if we can send stats.
				if ((isset($_REQUEST['sstats'])) && ($_REQUEST['sstats'] == "1")) {
					if (isset($_SESSION['__prevVersion'])) {
						$prevVersion = $_SESSION['__prevVersion'];
					} else {
						$prevVersion = "IKM4.5";
					}

					SendServerInfo(1,$prevVersion,VERSION);
				}

				$uf->RunUpgrades('IKM5.0.2');
			} else {
				$uf->ShowConfirm('IKM5.0.2');
			}
			die();
		}

		// currentLanguage was added in IKM5.1
		if (!isset($GLOBALS['currentLanguage'])) {
			include_once(dirname(__FILE__).'/../../../lib/upgrade_factory.php');
			$uf = new Upgrade_Factory();

			if (isset($_REQUEST['confirm']) && $_REQUEST['confirm'] == 1) {
				//Check to see if we can send stats.
				if ((isset($_REQUEST['sstats'])) && ($_REQUEST['sstats'] == "1")) {
					if (isset($_SESSION['__prevVersion'])) {
						$prevVersion = $_SESSION['__prevVersion'];
					} else {
						$prevVersion = "IKM5.0";
					}

					SendServerInfo(1,$prevVersion,VERSION);
				}

				$uf->RunUpgrades('IKM5.1');
			} else {
				$uf->ShowConfirm('IKM5.1');
			}
			die();
		}
	}

	function ShowInstallErrors($message, $errors, $showRetry = false, $onRunInstall = false)
	{
		if($this->apiMode == true) {
			header("Content-Type: text/xml");
			echo '<'.'?xml version="1.0" encoding="'.$GLOBALS["charset"].'" ?'.">\n";
			echo "<response>\n";
			echo "  <status>ERROR</status>\n";
			echo "  <message>".htmlspecialchars($message, ENT_QUOTES, $GLOBALS["charset"])."</message>\n";
			echo "  <errors>\n";
			foreach($errors as $error) {
				$error['message'] = strip_tags($error['message']);
				if(isset($error['extra']) && $error['extra'] != '') {
					$extra = " extra=\"".$error['extra']."\"";
				}
				else {
					$extra = '';
				}
				echo "      <error code=\"".$error['code']."\"".$extra.">".htmlspecialchars($message, ENT_QUOTES, $GLOBALS["charset"])."</error>\n";
			}
			echo "  </errors>\n";
			echo "</response>";
			exit;
		}
		else {
			// Currently in the middle of the install, need to redirect back to the main screen
			if($onRunInstall == true) {
				$this->GetVariables(true, $message);
			}
			// Only on the main screen, just set globals
			else {
				if (isset($GLOBALS['isSetup']) && $GLOBALS['isSetup']) {
					$GLOBALS["PermissionErrors"] = "<h3 style='padding-bottom:10px'>" . GetLang("UpgradeInterspireKnowledgeManager") . "</h3>";
					$GLOBALS["PermissionErrors"] .= $message;
				} else {
					$GLOBALS["PermissionErrors"] = "<h3 style='padding-bottom:10px'>" . GetLang("InstallInterspireKnowledgeManager") . "</h3>";
					$GLOBALS["PermissionErrors"] .= $message;
				}
				$GLOBALS["PermissionErrors"] .= "<br /><br /><ul>";
				foreach($errors as $error) {
					$GLOBALS['PermissionErrors'] .= "<li>".$error['message']."</li>";
				}
				$GLOBALS['PermissionErrors'] .= "</ul>";
				if($showRetry == true) {
					$GLOBALS["PermissionErrors"] .= "<br /><input type='button' value='Try Again' style='margin-bottom:20px; font-size:11px' onclick=\"document.location.href='./'\" />";
				}
				$GLOBALS["CriticalErrors"] = 1;
			}
		}
	}

	function SetupApiInstall()
	{
		$request = file_get_contents("php://input");
		if(!$request) {
			exit;
		}

		if (!function_exists('simplexml_load_string')) {
			$errors = array(
			0 => array(
			'code' => 'extensionNotFound',
			'message' => ''
			)
			);
			$this->ShowInstallErrors('Please enable Simple XML extension on your php installation.', $errors, false, false);
		}


		$request = @simplexml_load_string($request);
		if(!is_object($request)) {
			$errors = array(
			0 => array(
			'code' => 'invalidRequest',
			'message' => ''
			)
			);
			$this->ShowInstallErrors('The request contained invalid XML.', $errors, false, false);
		}

		if(isset($request->install->licenseKey)) {
			$_POST['licenseKey'] = strval($request->install->licenseKey);
		}

		if(isset($request->install->knowledgebaseName)) {
			$_POST['knowledgebaseName'] = strval($request->install->knowledgebaseName);
		}

		if(isset($request->install->pathToKB)) {
			$_POST['pathToKB'] = strval($request->install->pathToKB);
		}

		if(isset($request->install->pathToKB)) {
			$_POST['pathToKB'] = strval($request->install->pathToKB);
		}

		if(isset($request->install->user->username)) {
			$_POST['username'] = strval($request->install->user->username);
		}

		if(isset($request->install->user->password)) {
			$_POST['password'] = strval($request->install->user->password);
			$_POST['password1'] = strval($request->install->user->password);
		}

		if(isset($request->install->user->email)) {
			$_POST['email'] = strval($request->install->user->email);
		}

		if(isset($request->install->user->username)) {
			$_POST['username'] = strval($request->install->user->username);
		}

		if(isset($request->install->user->firstname)) {
			$_POST['firstname'] = strval($request->install->user->firstname);
		}

		if(isset($request->install->user->lastname)) {
			$_POST['lastname'] = strval($request->install->user->lastname);
		}

		if(isset($request->install->database->databaseType)) {
			$_POST['databaseType'] = strval($request->install->database->databaseType);
		}

		if(isset($request->install->database->dbUser)) {
			$_POST['mySQLUser'] = strval($request->install->database->dbUser);
		}

		if(isset($request->install->database->dbPass)) {
			$_POST['mySQLPass'] = strval($request->install->database->dbPass);
		}

		if(isset($request->install->database->dbDatabase)) {
			$_POST['mySQLDatabase'] = strval($request->install->database->dbDatabase);
		}

		if(isset($request->install->database->dbServer)) {
			$_POST['mySQLServer'] = strval($request->install->database->dbServer);
		}

		if(isset($request->install->database->tablePrefix)) {
			$_POST['tablePrefix'] = strval($request->install->database->tablePrefix);
		}

		if(isset($request->install->sendStats)) {
			$sendStats = strval($request->install->sendStats);
			if($sendStats == 1 || $sendStats == "true") {
				$_POST['sendStats'] = 1;
			}
		}
	}

	/**
	 * Build an XML request from the passed array.
	 *
	 * @param array An array of tags/keys/values to build the XML from.
	 * @return string The built XML.
	 */
	function BuildXMLFromArray($array)
	{
		$xml = '';
		foreach($array as $k => $v) {
			$xml .= '<'.$k.'>';
			if(is_array($v)) {
				$xml .= "\n";
				$xml .= $this->BuildXMLFromArray($v);
				$xml .= "\n";
			}
			else {
				$xml .= $v;
			}
			$xml .= '</'.$k.'>';
		}
		return $xml;
	}

	/**
	 * _CheckPermissions
	 * Create the database and perform other install-orientated tasks
	 *
	 * @param none
	 *
	 * @return void
	 */
	function RunInstall()
	{
		// Check for the required fields

		if (!isset($_POST['phoneNumber'])) {
			$_POST['phoneNumber'] = '';
		}
		if (!isset($_POST['countryLocation'])) {
			$_POST['countryLocation'] = '';
		}

		$lk = '';
		if(isset($_POST['licenseKey'])) {
			$lk = $GLOBALS['AKB_CLASS_HELPER']->array_merge_invis($_POST['licenseKey'], $_POST['databaseType']);
		}

		$php_check = version_compare(PHP_VERSION, PHP_VERSION_INSTALL_REQUIRED);
		if($lk === false || $lk === '') {
			$installMessage = GetLang('LKBad');
			$installCode = "badLicenseKey";
		}
		else if($lk === 0) {
			$installMessage = GetLang('LKOracleBad');
			$installCode = "badOracleLicenseKey";
		}
		else if($php_check < 0) {
			$installMessage = sprintf(GetLang("PHPV43Message"), PHP_VERSION_INSTALL_REQUIRED, PHP_VERSION);
			$installCode = "phpVersion";
		}
		else if(!isset($_POST['knowledgebaseName']) || $_POST['knowledgebaseName'] == '') {
			$installMessage = GetLang('InstallMissingKnowledgebaseName');
			$installCode = "missingKnowledgebaseName";
		}
		else if(!isset($_POST['pathToKB']) || $_POST['pathToKB'] == '') {
			$installMessage = GetLang('InstallMissingPathToKB');
			$installCode = "missingPathToKB";
		}
		else if(!isset($_POST['username']) || $_POST['username'] == '') {
			$installMessage = GetLang('InstallMissingUsername');
			$installCode = "missingUsername";
		}
		else if(!isset($_POST['password']) || $_POST['password'] == '') {
			$installMessage = GetLang('InstallMissingPassword');
			$installCode = "missingPassword";
		}
		else if(!isset($_POST['email']) || $_POST['email'] == '') {
			$installMessage = GetLang('InstallMissingEmail');
			$installCode = "missingEmail";
		}
		else if(!isset($_POST['firstname']) || $_POST['firstname'] == '') {
			$installMessage = GetLang('InstallMissingFirstname');
			$installCode = "missingFirstname";
		}
		else if(!isset($_POST['lastname']) || $_POST['lastname'] == '') {
			$installMessage = GetLang('InstallMissingLastname');
			$installCode = "missingLastname";
		}
		else if((!isset($_POST['countryLocation']) || $_POST['countryLocation'] == '') && !$this->apiMode && (defined('IS_TRIAL') && IS_TRIAL == true)) {
			$installMessage = GetLang('InstallMissingCountryLocation');
			$installCode = "missingCountryLocation";
		}
		else if((!isset($_POST['phoneNumber']) || $_POST['phoneNumber'] == '') && !$this->apiMode && (defined('IS_TRIAL') && IS_TRIAL == true)) {
			$installMessage = GetLang('InstallMissingPhoneNumber');
			$installCode = "missingPhoneNumber";
		}
		else if(!isset($_POST['databaseType']) || $_POST['databaseType'] == '') {
			$installMessage = GetLang('InstallMissingDbType');
			$installCode = "missingDbType";
		}
		else if($_POST['databaseType'] == 'oci8' && strlen($_POST['tablePrefix']) > 4) {
			$installMessage = GetLang('InstallTFExceedLength');
			$installCode = "missingDbType";
		}
		else if(!isset($_POST['mySQLServer']) || $_POST['mySQLServer'] == '') {
			$installMessage = GetLang('InstallMissingDbServer');
			$installCode = "missingDbServer";
		}
		else if(!isset($_POST['mySQLUser']) || $_POST['mySQLUser'] == '') {
			$installMessage = GetLang('InstallMissingDbUser');
			$installCode = "missingDbUser";
		}
		else if(!isset($_POST['mySQLPass'])) {
			$installMessage = GetLang('InstallMissingDbPass');
			$installCode = "missingDbPass";
		}
		else if(!isset($_POST['mySQLDatabase']) || $_POST['mySQLDatabase'] == '') {
			$installMessage = GetLang('InstallMissingDbDatabase');
			$installCode = "missingDbDatabase";
		}
		$config = realpath(dirname(__FILE__).'/../config.php');
		$c = new Config($config);
		// One or more error messages were detected
		if(isset($installMessage)) {
			$errors = array(
			0 => array(
			"code" => $installCode,
			"message" => $installMessage
			)
			);
			$this->ShowInstallErrors($installMessage, $errors, false, true);
			return;
		}

		//
		// Import the MySQL schema and run it
		// Get a connect to the database
		if ((isset($_POST['databaseType']) && $_POST['databaseType'] == 'mssql')) {
			$GLOBALS['AKB_DB'] = new MsSQLDb($_POST['mySQLServer'], $_POST['mySQLUser'], $_POST['mySQLPass'], $_POST['mySQLDatabase']);
		} elseif ((isset($_POST['databaseType']) && $_POST['databaseType'] == 'oci8')) {
			$GLOBALS['AKB_DB'] = new Oci8Db($_POST['mySQLServer'], $_POST['mySQLUser'], $_POST['mySQLPass'], $_POST['mySQLDatabase']);
		} else {
			$GLOBALS['AKB_DB'] = new MySQLDb($_POST['mySQLServer'], $_POST['mySQLUser'], $_POST['mySQLPass'], $_POST['mySQLDatabase']);
		}

		$GLOBALS['AKB_DB']->Connect($_POST['mySQLServer'], $_POST['mySQLUser'], $_POST['mySQLPass'], $_POST['mySQLDatabase']);
		$GLOBALS['tablePrefix'] = $_POST["tablePrefix"];
		$err = $GLOBALS['AKB_DB']->GetErrorMsg();

		if (!$err) {
			if (!$GLOBALS['AKB_DB']->IsFulltextInstalled()) {
				$err = $GLOBALS['AKB_DB']->GetErrorMsg();
			}
		}

		if ($err) {
			$GLOBALS['Error'] = $err;

			// One or more error messages were detected
			if(isset($err)) {
				$errors = array(
				0 => array(
				"code" => 'FailedDatabaseConnection',
				"message" => $err
				)
				);
				$this->ShowInstallErrors($err, $errors, false, true);
				return;
			}
		}
		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('install.schema.'.$_POST['databaseType']);
		$schema = $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
		$arrSchema = explode(';', $schema);
		foreach ($arrSchema as $query) {
			$query = str_replace('__SEMI_COLUMN__', ' ; ', trim($query));

			if (!empty($query)) {
				@$GLOBALS['AKB_DB']->Query($query);
			}
		}

		$GLOBALS['OneHourAgo'] = date("Y-m-d H:i:s", mktime(date("H")-1,date("i"),date("s"),date("m"),date("d"),date("Y")));
		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('install.sample.'.$_POST['databaseType']);
		$schema = $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
		$arrSchema = explode(';', $schema);
		foreach ($arrSchema as $query) {
			$query = trim($query);

			if (!empty($query)) {
				@$GLOBALS['AKB_DB']->Query($query);
			}
		}
		$GLOBALS['licenseKey'] = $_POST['licenseKey'];

		// Create the default administrator account
		$_POST['status'] = 1;
		$_POST['forgotpasscode'] = '';
		$u = new API_USER();

		// If there was a problem creating the user, display an error and take them back
		// to the create user step
		if (!$u->create()) {
			$GLOBALS['HideErrorPanel'] = 'block';
			$GLOBALS['Error'] = $u->error;

			// One or more error messages were detected
			if(isset($u->error)) {
				$errors = array(
				0 => array(
				"code" => 'FailedCreateAdmin',
				"message" => $u->error
				)
				);
				$this->ShowInstallErrors($u->error, $errors, false, true);
				return;
			}
		}

		$config = realpath(dirname(__FILE__).'/../config.php');
		$c = new Config($config);

		$c->Update('contactEmail', $_POST['email'], false);

		// Add other default settings
		$c->Update('isSetup', 'true', false);
		$c->Update('downForMaintenance', 'false', false);
		$c->Update('allowVisitorComments', 'true', false);
		$c->Update('autoApproveComments', 'true', false);
		$c->Update('allowEmailQuestion', 'true', false);
		$c->Update('allowPrintQuestion', 'true', false);
		$c->Update('allowQuestionRatings', 'true', false);
		$c->Update('enableContactPage', 'true', false);
		$c->Update('sendContactEmail', 'true', false);
		$c->Update('saveSubmittedContact', 'true', false);
		$c->Update('useWYSIWYGEditor', 'true', false);
		$c->Update('cookiePrefix', 'AKB_', false);
		$c->Update('popularSearchTerms', '', false);
		$c->Update('skipWords', '', false);
		$c->Update('sendCommentEmail', 'false', false);
		$c->Update('emailOnUnhelpfulRating', 'true', false);
		$c->Update('allowSubscribeToQuestions', 'false', false);
		$c->Update('useCaptchaCheck', 'true', false);
		$c->Update('popularQuestionNumber', '10', false);			//NX2.6
		$c->Update('recentQuestionNumber', '10', false);			//NX2.7
		$c->Update('enablePDFExport', 'true', false);				//NX2.7
		$c->Update('categoryRestrictOption', '1', false);			//NX2.7

		$c->Update('smtpDefault', 'true', false);					//IKM4.0
		$c->Update('smtpServer', '', false);						//IKM4.0
		$c->Update('smtpUsername', '', false);						//IKM4.0
		$c->Update('smtpPassword', '', false);						//IKM4.0
		$c->Update('smtpPort', '', false);							//IKM4.0



		if ($_POST["databaseType"] == 'mysql') {
			$dbversion = $GLOBALS['AKB_DB']->FetchOne("SELECT VERSION()");
			if (version_compare($dbversion, '4', '<')) {
				$c->Update('defaultSearchType', '1', false);
			} else {
				$c->Update('defaultSearchType', '3', false);
			}
		} else {
			$c->Update('defaultSearchType', '2', false);
		}

		$c->Update('frontendUser', '', false);
		$c->Update('frontendPass', '', false);

		// Only turn on clean urls by default on apache
		$cleanurl_sapis = array(
		'apache',
		'apache2handler',
		'apache2filter',
		);

		if (in_array(php_sapi_name(), $cleanurl_sapis)) {
			$c->Update('cleanUrls', 'true', false);
		} else {
			$c->Update('cleanUrls', 'false', false);
		}

		$GLOBALS["mySQLUser"] = $_POST["mySQLUser"];
		$GLOBALS["databaseType"] = $_POST["databaseType"];
		$GLOBALS["mySQLPass"] = $_POST["mySQLPass"];
		$GLOBALS["mySQLServer"] = $_POST["mySQLServer"];
		$GLOBALS["mySQLDatabase"] = $_POST["mySQLDatabase"];
		$GLOBALS["licenseKey"] = $_POST["licenseKey"];
		$GLOBALS["knowledgebaseName"] = $_POST["knowledgebaseName"];
		$GLOBALS["pathToKB"] = $_POST["pathToKB"];
		$GLOBALS["tablePrefix"] = $_POST["tablePrefix"];

		// get the default tmp directory for indexing temp file

		$c->Update('enableAttachmentSearch', 'false', false);	//IKM5.0
		$c->Update('enableFullindexPopulation', 'true', false);	//IKM5.0
		$c->Update('indexPlugins', '', false);	//IKM5.0
		$c->Update('databaseType', $_POST["databaseType"], false);	//IKM5.0
		$c->Update('featuredQuestionNumber', '10', false);	//IKM5.0
		$c->Update('newsQuestionNumber', '10', false);	//IKM5.0
		$c->Update('mySQLUser', $_POST["mySQLUser"], false);
		$c->Update('mySQLPass', $_POST["mySQLPass"], false);
		$c->Update('mySQLServer', $_POST["mySQLServer"], false);
		$c->Update('mySQLDatabase', $_POST["mySQLDatabase"], false);
		$c->Update('licenseKey', $_POST["licenseKey"], false);
		$c->Update('knowledgebaseName', $_POST["knowledgebaseName"], false);
		$c->Update('pathToKB', $_POST["pathToKB"], false);
		$c->Update('tablePrefix', $_POST["tablePrefix"], false);

		// checking the attachment plugin ability
		$tempDirectory = realpath('./');
		if ($tempDirectory[strlen($tempDirectory)-1] != DIRECTORY_SEPARATOR) {
			$tempDirectory = $tempDirectory . DIRECTORY_SEPARATOR;
		}
		$tempDirectory = $tempDirectory.'tmp';

		$c->Update('tempDirectory', $tempDirectory, false);	//IKM5.0
		if (isset($GLOBALS['DocumentPlugins'])) {
			$plugin = '';
			$tempAvailPlugins = array();
			foreach ($GLOBALS['DocumentPlugins'] as $eachPlugin) {
				if ($eachPlugin != 'Default_Plugin') {
					unset($plugin);
					$plugin = new $eachPlugin();
					$pluginCheck = $plugin->Check();

					// if word check for the directory length
					if ($eachPlugin == 'External_Doc_Plugin') {
						if (substr(strtolower(PHP_OS), 0, 3) == 'win') {
							$separator = '\\';
							if (strstr($tempDirectory, '/')) {
								$separator = '/';
							}
							$tempDirectoriesName = explode($separator, $tempDirectory);
							foreach ($tempDirectoriesName as $eachDirName) {
								if (strlen($eachDirName) > TEMP_DIR_LEN) {
									$pluginCheck = false;
									break;
								}
							}
						}
					}

					if ($pluginCheck) {
						$tempAvailPlugins[] = $eachPlugin;
					}
				}
			}
			if (sizeof($tempAvailPlugins) > 0) {
				array_unshift($tempAvailPlugins, 'Default_Plugin');
				$c->Update('enableAttachmentSearch', 'true', false);	//IKM5.0
				$c->Update('indexPlugins', implode(',',$tempAvailPlugins), false);	//IKM5.0
			}
		}

		$c->Save();

		//Check to see if we can send stats.
		if ((isset($_POST['sendStats'])) && ($_POST['sendStats'] == "true")) {
			SendServerInfo(0,0,VERSION);
		}

		// The installation was complete!
		if($this->apiMode == true) {
			echo '<'.'?xml version="1.0" encoding="'.$GLOBALS["charset"].'" ?'.">\n";
			echo "<response>\n";
			echo "  <status>OK</status>\n";
			echo "  <kb>\n";
			echo "      <pathToKB>".$_POST['pathToKB']."</pathToKB>\n";
			echo "      <controlPanel>".$_POST['pathToKB']."/admin/index.php</controlPanel>\n";
			echo "  </kb>\n";
			echo "  <user>\n";
			echo "      <username>".$_POST['username']."</username>\n";
			echo "      <password>".$_POST['password']."</password>\n";
			echo "  </user>\n";
			echo "</response>\n";
			exit;
		}
		else {

			$GLOBALS['CPMessage'] = sprintf(GetLang("AdminUPMessage"), "<span style=\"font-weight:bold;color:#FC2A01;font-size:14px;\">{$_POST['username']}</span>", "<span style=\"font-weight:bold;color:#FC2A01;font-size:14px;\">{$_POST['password']}</span>");
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('install.final');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

	}

	/**
		 * _CheckPermissions
		 * Make sure files/folders have appropriate permissions
		 *
		 * @param none
		 *
		 * @return Array containing folders with permissions
		 */
	function _CheckPermissions()
	{
		$result = array();

		$old_umask = umask(0);

		include_once(dirname(__FILE__).'/../../../lib/class.file.php');
		$f = new FileClass();

		foreach($this->FoldersToCheck as $folder) {
			$path = dirname(__FILE__).'/../../../' . $folder;

			if(file_exists($path)) {
				if (is_file($path)) {
					$file = true;
					$mode = '0666';
				} elseif (is_dir($path)) {
					$file = false;
					$mode = '0777';
				}
				//@ikm_chmod($path, $mode);

				if(is_dir($path) && $f->CheckDirWritable($path)) {
					$result[] = array($folder, IS_OK, $file);
				}
				else if (is_file($path) && $f->CheckFileWritable($path)) {
					$result[] = array($folder, IS_OK, $file);
				}
				else {
					$result[] = array($folder, NOT_WRITABLE, $file);
				}
			}
			else {
				$result[] = array($folder, DOESNT_EXIST);
			}
		}

		umask($old_umask);

		return $result;
	}

	function CheckInstallationPrerequisites()
	{
		// Check the permissions on required files/folders
		$folders = $this->_CheckPermissions();
		$bad_folders = 0;
		$folder_messages = array();
		foreach($folders as $folder) {
			switch($folder[1]) {
				case NOT_WRITABLE: {
					if ($folder[2]) {
						$type = "file";
					} else {
						$type = "folder";
					}
					$message = "The ".$type." <b>" . $folder[0] . "</b> is not writable. Please CHMOD it to ";
					if (isset($folder[2]) && $folder[2] === true) {
						$message .= "646 or 664 or 666";
					} else {
						$message .= "757 or 775 or 777";
					}
					$code = "filePermissions";
					break;
				}
				case DOESNT_EXIST: {
					$message = "The file/folder <b>" . $folder[0] . "</b> doesn't exist. Please create it.";
					$code = "doesntExist";
					break;
				}
				default: {
					$code = '';
					$message = '';
				}
			}
			if($code != '' && $message != '') {
				$folder_messages[] = array(
				"code" => $code,
				"extra" => $folder[0],
				"message" => $message
				);
			}
		}

		if(!empty($folder_messages)) {
			if (isset($GLOBALS['isSetup']) && $GLOBALS['isSetup']) {
				$this->ShowInstallErrors(GetLang('UpgradePermissionsError'), $folder_messages, true);
			} else {
				$this->ShowInstallErrors(GetLang('InstallPermissionsError'), $folder_messages, true);
			}
		}

		// Are we running the required version of PHP?
		$php_check = version_compare(PHP_VERSION, PHP_VERSION_REQUIRED);

		if($php_check < 0) {
			$errors = array(
			0 => array(
			"code" => "phpVersion",
			"extra" => PHP_VERSION,
			"message" => sprintf(GetLang("PHPV43Message"), PHP_VERSION_REQUIRED, PHP_VERSION)
			)
			);
			$this->ShowInstallErrors(GetLang('BadPHPVersion'), $errors);
		}

		// Is MySQL supported?
		if(!function_exists('mysql_connect')) {
			$errors = array(
			0 => array(
			"code" => "mySqlRequired",
			"message" => GetLang('MySqlRequiredMessage'),
			)
			);
			$this->ShowInstallErrors(GetLang('MySqlRequired'), $errors);
		}
	}

	/**
		 * GetVariables
		 * This is step 1 of the installation process. It checks all the right files
		 * and folders have write permissions and prompts the user for all install variables.
		 *
		 * @param Boolean $Error defaults to false, if its set to true, something went wrong!
		 *
		 * @return Void
		 */
	function GetVariables($Error = false, $Message = "")
	{
		// Get the product version

		// Check the prerequisites
		$this->CheckInstallationPrerequisites();
		if($Error) {
			$GLOBALS["Message"] = "<h3 style='padding:0px;margin-top:0px; color:red'>" . GetLang("Oops") . "</h3>" . $Message;
			$GLOBALS["LicenseKey"] = $_POST["licenseKey"];

			$GLOBALS["knowledgebaseName"] = $_POST["knowledgebaseName"];
			$GLOBALS["pathToKB"] = $_POST["pathToKB"];
			$GLOBALS["username"] = $_POST["username"];
			$GLOBALS["password"] = $_POST["password"];
			$GLOBALS["password1"] = $_POST["password1"];
			$GLOBALS["email"] = $_POST["email"];
			$GLOBALS["firstname"] = $_POST["firstname"];
			$GLOBALS["lastname"] = $_POST["lastname"];
			$GLOBALS["mySQLUser"] = $_POST["mySQLUser"];
			$GLOBALS["mySQLPass"] = $_POST["mySQLPass"];
			$GLOBALS["mySQLServer"] = $_POST["mySQLServer"];
			$GLOBALS["mySQLDatabase"] = $_POST["mySQLDatabase"];
			$GLOBALS["tablePrefix"] = $_POST["tablePrefix"];
			$GLOBALS["AutoJS"] = "window.setTimeout(\"$('#dbChoice1').click(); $('.DBDetails').show();\", 100);";
			if (isset($_POST["databaseType"]) && $_POST["databaseType"] != '') {
				if ($_POST["databaseType"] == 'mssql') {
					$GLOBALS["useMySql"] = '';
					$GLOBALS["useMsSql"] = ' selected ';
					$GLOBALS["useOci8"] = '';
				} elseif ($_POST["databaseType"] == 'oci8') {
					$GLOBALS["useMySql"] = '';
					$GLOBALS["useMsSql"] = '';
					$GLOBALS["useOci8"] = ' selected ';
				} else {
					$GLOBALS["useMySql"] = ' selected ';
					$GLOBALS["useMsSql"] = '';
					$GLOBALS["useOci8"] = '';
				}
			} else {
				$GLOBALS["useMySql"] = ' selected ';
				$GLOBALS["useMsSql"] = '';
			}
		}
		else {
				if(defined('IS_TRIAL') && IS_TRIAL == true) {
					$GLOBALS['IsTrial'] = 1;
					$GLOBALS['Message'] = "<h3 style='padding-bottom:10px;margin:0px;'>" . GetLang("InstallTrial") . "</h3>" . GetLang("InstallTrialIntro");
					$GLOBALS['CountryList'] = $this->GenerateCountryOptions('', 'country_name', 'country_name', array());
				}
				else {
					$GLOBALS['IsTrial'] = 0;
					$GLOBALS["Message"] = "<h3 style='padding-bottom:10px;margin:0px;'>" . GetLang("InstallInterspireKnowledgeManager") . "</h3>" . GetLang("InstallIntro");
					$GLOBALS['CountryList'] = $this->GenerateCountryOptions('', 'numeric_code', 'country_name', array());
				}
		}

		if(!isset($GLOBALS['username']) || $GLOBALS["username"] == "") {
			$GLOBALS["username"] = "admin";
		}

		if(!isset($GLOBALS['mySQLServer']) || $GLOBALS["mySQLServer"] == "") {
			$GLOBALS["mySQLServer"] = "localhost";
		} else {
			$GLOBALS["mySQLServer"] = $_POST["mySQLServer"];
		}

		if(!isset($GLOBALS['tablePrefix']) || $GLOBALS["tablePrefix"] == "") {
			$GLOBALS["tablePrefix"] = "ikm_";
		}

		$app_path = dirname(dirname($_SERVER['PHP_SELF']));

		if(!isset($GLOBALS['pathToKB']) || $GLOBALS["pathToKB"] == "" || $GLOBALS["pathToKB"] == "http://") {
			$GLOBALS["pathToKB"] = "http://" . $_SERVER["HTTP_HOST"] . $app_path;
		}

		$GLOBALS["AKB_CLASS_TEMPLATE"]->SetTemplate("install.form");
		echo $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
	}

	function GenerateCountryOptions ($selected, $valueKey, $textKey, $countryList)
	{
		$countryList = $this->GetCountryList();
		$countryOptions = '';
		if (is_array($countryList) && sizeof($countryList)) {
			foreach ($countryList as $eachCountry) {
				$sel = '';
				if ($selected == $eachCountry[$valueKey]) {
					$sel = ' selected ';
				}
				$countryOptions .= '<option '.$sel.' value="'.$eachCountry[$valueKey].'">'.$eachCountry[$textKey].'</option> ';
			}
		}
		return $countryOptions;
	}

	function GetCountryList()
	{
		$file = dirname(dirname(dirname(__FILE__))) . '/templates/install.countries.csv.tpl';
		if (!is_readable($file)) {
			return array();
		}

		$data = file_get_contents($file);
		$lines = explode("\n", trim($data));
		unset ($data);

		reset($lines);
		$list = array();
		while (list(, $line) = each($lines)) {
			$line = trim($line);

			if (empty($line)) {
				continue;
			}

			if (preg_match('/(\d{3})\s*?,\s*?(\w{2})\s*?,\s*?(\w{3})\s*?,(.*)/', $line, $matches)) {
				if (count($matches) == 5) {
					array_push($list, array(	'country_name'	=> $matches[4],
												'numeric_code'	=> $matches[1],
												'alpha2_code'	=> $matches[2],
												'alpha3_code'	=> $matches[3]));
				}
			}
		}
		unset($lines);

		return  $list;
	}

}

?>
