<?php

	require_once(dirname(__FILE__).'/class.adminview.php');

	class AKB_SETTINGS extends AdminView
	{
		var $boolean = array(
			'downForMaintenance',
			'allowVisitorComments',
			'autoApproveComments',
			'allowEmailQuestion',
			'allowPrintQuestion',
			'allowQuestionRatings',
			'enableContactPage',
			'sendContactEmail',
			'saveSubmittedContact',
			'useWYSIWYGEditor',
			'useCaptchaCheck',
			'emailOnUnhelpfulRating',
			'cleanUrls',
			'allowSubscribeToQuestions',
			'sendCommentEmail',
			'allowSubscribeToQuestions',
			'rightToLeft',
			'enablePDFExport',
			'smtpDefault',
			'ldapNegoTLS',
			'enableAttachmentSearch',
			'enableFullindexPopulation',
		);

		var $integerConfigVars = array(
			'popularQuestionNumber',
			'recentQuestionNumber',
			'featuredQuestionNumber',
			'newsQuestionNumber',
		);

		var $required = array (
			'knowledgebaseName',
			'pathToKB',
			'licenseKey',
			'template',
			'mySQLServer',
			'mySQLUser',
			'mySQLDatabase',
			'databaseType',
			'contactEmail',
			'charset',
		);

		var $allowedConfigVars = array(
			'isSetup',
			'templateHeader',
			'templateFooter',
			'currentLanguage',
			'knowledgebaseName',
			'pathToKB',
			'licenseKey',
			'charset',
			'template',
			'frontendUser',
			'frontendPass',
			'mySQLServer',
			'mySQLUser',
			'mySQLPass',
			'mySQLDatabase',
			'tablePrefix',
			'allowVisitorComments',
			'allowEmailQuestion',
			'allowPrintQuestion',
			'allowQuestionRatings',
			'enableContactPage',
			'sendContactEmail',
			'saveSubmittedContact',
			'useWYSIWYGEditor',
			'useCaptchaCheck',
			'emailOnUnhelpfulRating',
			'cleanUrls',
			'defaultSearchType',
			'skipWords',
			'cookiePrefix',
			'contactEmail',
			'downForMaintenance',
			'autoApproveComments',
			'allowSubscribeToQuestions',
			'sendCommentEmail',
			'rightToLeft',
			'popularQuestionNumber',
			'recentQuestionNumber',
			'featuredQuestionNumber',
			'newsQuestionNumber',
			'categoryRestrictOption',
			'smtpDefault',
			'smtpServer',
			'smtpUsername',
			'smtpPassword',
			'smtpPort',
			'enablePDFExport',
			'ldapEnabled',
			'ldapVersionThree',
			'ldapHost',
			'ldapPort',
			'ldapFollowReferral',
			'ldapNegoTLS',
			'ldapUserDn',
			'ldapSearchString',
			'ldapBaseDn',
			'ldapConnectUsername',
			'ldapConnectPassword',
			'ldapEmailMapto',
			'ldapLastnameMapto',
			'ldapFirstnameMapto',
			'ldapRemoveUser',
			'ldapGroupMapping',
			'ldapAllowUserUpdateDetails',
			'ldapUserAccountType',
			'ldapEnableGroupMapping',
			'ldapDefaultAction',
			'ldapGroupMemberAttb',
			'databaseType',
			'enableAttachmentSearch',
			'enableFullindexPopulation',
			'tempDirectory',
			'indexPlugins',
			'bannedRetried',
			'bannedPeriod',
		);

		/**
		* SaveSettings
		* Save the settings to disk
		*
		* @return void
		*/
		function SaveSettings()
		{
			if (!$_SESSION['user']->verify('setting', 'edit')) {
				$this->NoPermissions();
				return;
			}

			$toIgnore = array('SubmitButton1', 'SubmitButton2');
			$requiredFailed = array();
			$output = '';

			// Normal settings
			foreach ($this->boolean as $n) {
				if (!isset($_POST[$n])) {
					$_POST[$n] = 'false';
				}
			}

			foreach ($_POST as $k=>$v) {
				if ($_POST[$k] == 'on') {
					$_POST[$k] = 'true';
				}
			}
			
			// Setting for Attachment search.
			$availableExtension = $GLOBALS['DocumentPlugins'];
			$_POST['indexPlugins'] = array();
			$selectedIndexPlugins = array('Default_Plugin');
			foreach ($availableExtension as $ext) {
				if (isset($_POST[$ext])) {
					$selectedIndexPlugins[] = $ext;
				}
			}
			$_POST['indexPlugins'] = implode(',', $selectedIndexPlugins);

			foreach ($_POST as $k=>$v) {
				if ((!in_array($k, $toIgnore)) && (in_array($k,$this->allowedConfigVars))) {

					if (substr($v,0,4) == "EMB_") { //Special case for embedded templates.
						$v = substr($v,4);
					}

					if (in_array($k,$this->integerConfigVars)) {
						$output .= "\t\$GLOBALS['" . $k . "'] = " . (int)$v . ";\n";
					} else if ($v != 'true' && $v != 'false') {
						$output .= "\t\$GLOBALS['" . $k . "'] = '" . addslashes($v) . "';\n";
					} else {
						$output .= "\t\$GLOBALS['" . $k . "'] = " . $v . ";\n";
					}
				}
			}

			// Debug mode
			if (isset($GLOBALS['debug']) && $GLOBALS['debug'] === true) {
				$output .= "\t\$GLOBALS['debug'] = true;\n";
			} else {
				$output .= "\t\$GLOBALS['debug'] = false;\n";
			}

			// Database version
			if (!isset($GLOBALS['DBVersion']) || empty($GLOBALS['DBVersion'])) {
				$dbversion = $GLOBALS['databaseVersion'];
			} else {
				$dbversion = $GLOBALS['DBVersion'];
			}
			$output .= "\t\$GLOBALS['DBVersion'] = '".addslashes($dbversion)."';\n";

			// Finish up
			$output = "\t\$GLOBALS[\"isSetup\"] = true;\n\n" . $output;
			$output = sprintf("<?php\n\n%s\n\n?>", $output);

			//Copy the current working (previous) version to a backup before saving
			@copy(dirname(__FILE__)."/../config.php", dirname(__FILE__)."/../config.backup.php");

			// Try and open the config file
			if ($fp = fopen(dirname(__FILE__)."/../config.php", "wb")) {
				if (fwrite($fp, $output)) {
					//Make backup of current (now saved) config.
					@copy(dirname(__FILE__)."/../config.php", dirname(__FILE__)."/../config.copy.php");

					ob_end_clean();
					header('Location: index.php?ToDo=editSettings&updated=true');
					die();
				} else {
					ob_end_clean();
					header('Location: index.php?ToDo=editSettings&updated=false');
					die();
				}
			} else {
				ob_end_clean();
				header('Location: index.php?ToDo=editSettings&updated=false');
				die();
			}
		}

		/**
		* UpdateSettings
		* Show the manage settings page
		*
		* @return void
		*/
		function UpdateSettings()
		{
			if (!$_SESSION['user']->verify('setting', 'edit')) {
				$this->NoPermissions();
				return;
			}

			if (!is_writeable(dirname(__FILE__).'/../config.php')) {
				$GLOBALS['Message'] .= MessageBox(GetLang('SettingsReadOnly'), MSG_WARNING);
			}

			$GLOBALS['LdapMessage'] = '';
			$GLOBALS['LdapExtension'] = 1;
			if (!function_exists('ldap_connect')) {
				$GLOBALS['LdapMessage'] .= MessageBox(GetLang('MissingLdapExtension'), MSG_WARNING).'<br />';
				$GLOBALS['LdapExtension'] = 0;
			}

			if (substr($GLOBALS['pathToKB'], -1) == '/') {
				$GLOBALS['Message'] .= MessageBox(GetLang('SettingsTrailingSlashInPath'), MSG_WARNING);
			}

			AKB_HELPER::breakline();

			if (isset($_GET['updated'])) {
				if ($_GET['updated'] == 'true') {
					$GLOBALS['Message'] .= MessageBox(GetLang('SettingsSavedOK'), MSG_SUCCESS);
				} else {
					$GLOBALS['Message'] .= MessageBox(GetLang('SettingsNotSaved'), MSG_ERROR);
				}
			}

			$GLOBALS['EmailOnUnhelpfulRatingHelp'] = sprintf(GetLang('EmailOnUnhelpfulRatingHelp'), $GLOBALS['contactEmail']);

			$checkboxes = array (
				'downForMaintenance'		=> 'YesDown',
				'allowVisitorComments'		=> 'YesEnableComments',
				'autoApproveComments'		=> 'YesAutoApproveComments',
				'allowEmailQuestion'		=> 'YesEnableEmailQuestion',
				'allowPrintQuestion'		=> 'YesEnablePrintQuestion',
				'allowQuestionRatings'		=> 'YesEnableQuestionRatings',
				'cleanUrls'					=> 'YesCleanUrls',
				'sendCommentEmail'			=> 'YesSendCommentEmail',
				'emailOnUnhelpfulRating'	=> 'YesEmailOnUnhelpfulRating',
				'allowSubscribeToQuestions'	=> 'YesEnableSubscribeToQuestions',
				'useWYSIWYGEditor'			=> 'YesUseWYSIWYGEditor',
				'useCaptchaCheck'			=> 'YesUseCaptchaCheck',
				'rightToLeft'				=> 'YesRightToLeft',
				'enablePDFExport'			=> 'YesEnablePDFExport',
				'ldapEnabled'				=> 'YesLdapEnabled',
				'ldapEnableGroupMapping'	=> 'YesLdapEnableGroupMapping',
				'ldapNegoTLS'				=> 'YesLdapNegoTLS',
				'ldapAllowUserUpdateDetails'=> 'YesLdapAllowUserUpdateDetails',
				'enableAttachmentSearch'	=> 'YesEnableAttachmentSearch',
				'enableFullindexPopulation'	=> 'YesEnableFullindexPopulation',
			);

			foreach ($checkboxes as $var => $check) {
				if (isset($GLOBALS[$var]) && $GLOBALS[$var]) {
					$GLOBALS[$check] = 'checked';
				} else {
					$GLOBALS[$check] = '';
				}
			}

			$GLOBALS['PHPSMTP'] = ini_get("SMTP");

			$group = new API_GROUP();
			$groupList = $group->getList();
			$GLOBALS['groupList'] = '';
			while (list($k, $v) = each($groupList)) {
				$GLOBALS['groupList'] = $GLOBALS['groupList'] . '<option onclick="mapGroup();" value="'.$k.'">'.$v.'</option>';
			}
			reset($groupList);

			$groupList = array('-1' => 'Disable users Login') + $groupList;
			$groupList = array('0' => 'No Action') + $groupList;
			$GLOBALS['defaultActionList'] = '';
			while (list($k, $v) = each($groupList)) {
				$actionSelected = '';
				if ($GLOBALS['ldapDefaultAction'] == $k) {
					$actionSelected = ' selected';
				}
				if ($k != 0 && $k != -1) {
					$GLOBALS['defaultActionList'] .= '<option value="'.$k.'" '.$k.$actionSelected.'>Assign to: '.$v.'</option>';
				} else {
					$GLOBALS['defaultActionList'] .= '<option value="'.$k.'"'.$actionSelected.'>'.$v.'</option>';
				}
			}

			if (!isset($GLOBALS['smtpDefault'])) {
				$GLOBALS['smtpDefault'] = true;
			}

			if ($GLOBALS['smtpDefault']) {
				$GLOBALS['GLOBAL_usesmtp_true'] = "checked";
				$GLOBALS['GLOBAL_usesmtp_false'] = "";
				$GLOBALS['SMTPIntialToggle'] = 0;
			} else {
				$GLOBALS['GLOBAL_usesmtp_true'] = "";
				$GLOBALS['GLOBAL_usesmtp_false'] = "checked";
				$GLOBALS['SMTPIntialToggle'] = 1;
			}

			if ($GLOBALS['enableContactPage']) {
				$GLOBALS['YesEnableContactPage'] = 'CHECKED';
				$GLOBALS['DisableSendEmail'] = '';
				$GLOBALS['DisableSaveSubmittedContact'] = '';

				if ($GLOBALS['sendContactEmail']) {
					$GLOBALS['YesSendContactEmail'] = 'CHECKED';
				} else {
					$GLOBALS['YesSendContactEmail'] = '';
				}

				if ($GLOBALS['saveSubmittedContact']) {
					$GLOBALS['YesSaveSubmittedContact'] = 'CHECKED';
				} else {
					$GLOBALS['YesSaveSubmittedContact'] = '';
				}
			} else {
				$GLOBALS['DisableSendEmail'] = 'DISABLED';
				$GLOBALS['DisableSaveSubmittedContact'] = 'DISABLED';
			}

			if ($GLOBALS['defaultSearchType'] == 1) {
				$GLOBALS['SearchType1'] = ' selected';
				$GLOBALS['SearchType2'] = '';
				$GLOBALS['SearchType3'] = '';
			} elseif ($GLOBALS['defaultSearchType'] == 2) {
				$GLOBALS['SearchType1'] = '';
				$GLOBALS['SearchType2'] = ' selected';
				$GLOBALS['SearchType3'] = '';
			} else {
				$GLOBALS['SearchType1'] = '';
				$GLOBALS['SearchType2'] = '';
				$GLOBALS['SearchType3'] = ' selected';
			}
			if ($GLOBALS['ldapVersionThree'] == 1) {
				$GLOBALS['LdapVersionThreeYes'] = ' selected';
				$GLOBALS['LdapVersionThreeNo'] = '';
			} else {
				$GLOBALS['LdapVersionThreeYes'] = '';
				$GLOBALS['LdapVersionThreeNo'] = ' selected';
			}

			if ($GLOBALS['ldapFollowReferral'] == 1) {
				$GLOBALS['LdapFollowReferralYes'] = ' selected';
				$GLOBALS['LdapFollowReferralNo'] = '';
			} else {
				$GLOBALS['LdapFollowReferralYes'] = '';
				$GLOBALS['LdapFollowReferralNo'] = ' selected';
			}

			if ($GLOBALS['ldapUserAccountType'] == 'ad') {
				$GLOBALS['LdapActiveDirectoryAccount'] = ' selected';
				$GLOBALS['LdapEDirectoryAccount'] = '';
				$GLOBALS['LdapPosixAccountRfc2307'] = '';
				$GLOBALS['LdapPosixAccountRfc2307Bis'] = '';
				$GLOBALS['LdapSambaAccount'] = '';
				$GLOBALS['LdapOtherAccount'] = '';
			} else if ($GLOBALS['ldapUserAccountType'] == 'ed') {
				$GLOBALS['LdapActiveDirectoryAccount'] = '';
				$GLOBALS['LdapEDirectoryAccount'] = ' selected';
				$GLOBALS['LdapPosixAccountRfc2307'] = '';
				$GLOBALS['LdapPosixAccountRfc2307Bis'] = '';
				$GLOBALS['LdapSambaAccount'] = '';
				$GLOBALS['LdapOtherAccount'] = '';
			} else if ($GLOBALS['ldapUserAccountType'] == 'po2307') {
				$GLOBALS['LdapActiveDirectoryAccount'] = '';
				$GLOBALS['LdapEDirectoryAccount'] = '';
				$GLOBALS['LdapPosixAccountRfc2307'] = ' selected';
				$GLOBALS['LdapPosixAccountRfc2307Bis'] = '';
				$GLOBALS['LdapSambaAccount'] = '';
				$GLOBALS['LdapOtherAccount'] = '';
			} else if ($GLOBALS['ldapUserAccountType'] == 'po2307bis') {
				$GLOBALS['LdapActiveDirectoryAccount'] = '';
				$GLOBALS['LdapEDirectoryAccount'] = '';
				$GLOBALS['LdapPosixAccountRfc2307'] = '';
				$GLOBALS['LdapPosixAccountRfc2307Bis'] = ' selected';
				$GLOBALS['LdapSambaAccount'] = '';
				$GLOBALS['LdapOtherAccount'] = '';
			} else if ($GLOBALS['ldapUserAccountType'] == 'sam') {
				$GLOBALS['LdapActiveDirectoryAccount'] = '';
				$GLOBALS['LdapEDirectoryAccount'] = '';
				$GLOBALS['LdapPosixAccountRfc2307'] = '';
				$GLOBALS['LdapPosixAccountRfc2307Bis'] = '';
				$GLOBALS['LdapOtherAccount'] = '';
				$GLOBALS['LdapSambaAccount'] = ' selected';
			} else {
				$GLOBALS['LdapActiveDirectoryAccount'] = '';
				$GLOBALS['LdapEDirectoryAccount'] = '';
				$GLOBALS['LdapPosixAccountRfc2307'] = '';
				$GLOBALS['LdapPosixAccountRfc2307Bis'] = '';
				$GLOBALS['LdapSambaAccount'] = '';
				$GLOBALS['LdapOtherAccount'] = ' selected';
			}
			if ($GLOBALS['ldapRemoveUser'] == 0) {
				$GLOBALS['LdapRemoveUserOpt1'] = ' selected';
				$GLOBALS['LdapRemoveUserOpt2'] = '';
			} else {
				$GLOBALS['LdapRemoveUserOpt1'] = '';
				$GLOBALS['LdapRemoveUserOpt2'] = ' selected';
			}

			if (!isset($GLOBALS['tempDirectory']) || $GLOBALS['tempDirectory'] == '') {
				$GLOBALS['tempDirectory'] = realpath('./').'tmp';
			}
			
			$validTempDirectory = true;
			$GLOBALS['Word2003Message'] = '';
			if (ikm_substr(ikm_strtolower(PHP_OS), 0, 3) == 'win') {
				$separator = '\\';
				if (strstr($GLOBALS['tempDirectory'], '/')) {
					$separator = '/';
				}
				$tempDirectoriesName = explode($separator, $GLOBALS['tempDirectory']);
				foreach ($tempDirectoriesName as $eachDirName) {
					if (strlen($eachDirName) > TEMP_DIR_LEN) {
						$GLOBALS['Word2003Message'] = GetLang('TempDirectoryMessage');
						break;
					}
				}
			}
			
			

			if (!isset($GLOBALS['DBVersion']) || empty($GLOBALS['DBVersion'])) {
				$GLOBALS['DBVersion'] = $GLOBALS['databaseVersion'];
			}

			if (version_compare($GLOBALS['DBVersion'], '4', '<') && $GLOBALS['databaseType'] == 'mysql') {
				$GLOBALS['SearchType3'] = ' disabled';
			} else if ($GLOBALS['databaseType'] == 'oci8') {
				$GLOBALS['SearchType3'] = ' disabled';
			}

			$GLOBALS['PHPVersion'] = htmlspecialchars(PHP_VERSION, ENT_QUOTES, $GLOBALS['charset']);
			$GLOBALS['PHPSapi'] = htmlspecialchars(php_sapi_name(), ENT_QUOTES, $GLOBALS['charset']);
			$GLOBALS['ServerSoftware'] = htmlspecialchars($_SERVER['SERVER_SOFTWARE'], ENT_QUOTES, $GLOBALS['charset']);

			if (isset($GLOBALS['charset'])) {
				$GLOBALS['CharSetOptions'] = GetCharsetOptions($GLOBALS['charset']);
			} else {
				$GLOBALS['CharSetOptions'] = GetCharsetOptions();
			}

			$GLOBALS['Version'] = VERSION_NUMBER;

			if ((isset($GLOBALS['categoryRestrictOption'])) && ($GLOBALS['categoryRestrictOption'] == "0")) {
				$GLOBALS['categoryRestrictOption'] = "checked=\"checked\"";
			} else {
				$GLOBALS['categoryRestrictOption'] = "";
			}

			if(isset($GLOBALS['Message']) && $GLOBALS['Message'] != '') {
				$GLOBALS['Message'] .= '<br />';
			}

			// Default the LDAP port to 389 if it's not set
			if($GLOBALS['ldapPort'] == '') {
				$GLOBALS['ldapPort'] = '389';
			}
			
			$GLOBALS['EnableAttachmentSearchChecked'] = '';
			if (isset($GLOBALS['enableAttachmentSearch']) && $GLOBALS['enableAttachmentSearch']) {
				$GLOBALS['EnableAttachmentSearchChecked'] = ' CHECKED ';
			}
			
			$GLOBALS['YesFullTextPopulationChecked'] = '';
			if (isset($GLOBALS['enableFullindexPopulation']) && $GLOBALS['enableFullindexPopulation']) {
				$GLOBALS['YesFullTextPopulationChecked'] = ' CHECKED ';
			}
			
			$GLOBALS['ManualFullTextPopulation'] = (isset($GLOBALS['databaseType']) && ($GLOBALS['databaseType'] == 'mssql' || $GLOBALS['databaseType'] == 'oci8'))?1:0;
			
			$availableExtension = array('Default_Plugin', 'External_Doc_Plugin', 'Docx_Plugin', 'External_Ppt_Plugin', 'Pdf_Plugin', 'Image_Plugin');
			if (isset($GLOBALS['indexPlugins'])) {
				foreach ($availableExtension as $ext) {
					$GLOBALS[$ext] = '';
					if (strstr($GLOBALS['indexPlugins'], $ext)) {
						$GLOBALS[$ext] = ' CHECKED ';
					}
				}
			}
			
			$GLOBALS['LNG_FulltextSearch'] = GetLang('FulltextSearch' . $GLOBALS['databaseType']);
			$GLOBALS['LNG_KeywordSearch'] = GetLang('KeywordSearch' . $GLOBALS['databaseType']);
			$GLOBALS['LNG_BooleanFulltextSearch'] = GetLang('BooleanFulltextSearch' . $GLOBALS['databaseType']);
			$GLOBALS['LNG_DefaultSearchTypeHelp'] = GetLang('DefaultSearchTypeHelp' . $GLOBALS['databaseType']);
			
			if($GLOBALS['databaseType'] == 'mysql') {
				$GLOBALS['DatabaseTypeDisplay'] = GetLang('UseMySQL');
			} else if($GLOBALS['databaseType'] == 'oci8') {
				$GLOBALS['DatabaseTypeDisplay'] = GetLang('UseOci8');
			} else {
				$GLOBALS['DatabaseTypeDisplay'] = GetLang('UseMsSQL');
			}

			$GLOBALS['TemplateOptions'] = $GLOBALS['AKB_CLASS_HELPER']->GetTemplateOptions();
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('settings.manage');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* checkRequired
		* Check that all the required fields are filled in and report if any are
		* not
		*
		* @return void
		*/
		function checkRequired()
		{
			foreach ($this->required as $setting) {
				if (!isset($GLOBALS[$setting]) || trim($GLOBALS[$setting]) == '') {
					$GLOBALS['Message'] .= MessageBox(GetLang('MissingRequiredValues'), MSG_ERROR);
					break;
				}
			}
		}

		/**
		* unsetAllSettings
		* Takes the allowedConfigVars array and clears all of them from the globals
		*
		* @return void
		*/
		function unsetAllSettings() {
			if (is_array($this->allowedConfigVars)) {
				foreach ($this->allowedConfigVars as $val) {
					if (isset($GLOBALS[$val])) {
						unset($GLOBALS[$val]);
					}
				}
			}
		}
	}

?>
