<?php
defined('WikyBlog') or die("Not an entry point...");

wbLang::getFile('specPreferences'); //has similar fields like language values
wbLang::getFile('SPEC');

class configManager{
	
	function configManager(){
		global $page,$dbObject,$langA,$pageOwner;
		$page->css2 = true;
		
		$dbObject->uniqLink = $contentUri = $page->regLink($langA['configuration'],'/Admin/'.$pageOwner['username'].'/Configuration');
		$page->autoForm = true;
		$page->regLink($langA['confighistory'],'/Admin/'.$pageOwner['username'].'/ConfigHistory');
		$page->regLink('?',$langA['configuration'].'?en=Configuration');
		
		ob_start();
		
		//new
		$this->configGroups['general_config'] = 'ConfigAllGeneral.php';
		$this->configGroups['performance'] = 'ConfigAllwbConfig.php';
		$this->configGroups['default_user_vars'] = 'ConfigAllUser.php';
		$this->configGroups['developer_aids'] = 'ConfigAllDev.php';
		$this->configGroups['registration'] = 'ConfigAllRegister.php';

		
		
		$group = false;
		if( isset($_POST['group']) ){
			$group = $_POST['group'];
		}elseif( isset($_GET['group']) ){
			$group = $_GET['group'];
		}
		$group = $this->selectGroup($group);
		
		if( $group ){
			
			
			
			$configObj = new configurationInstance();
			$configObj->runConfig($group);
		}
		
		$page->contentB[$contentUri] = wb::get_clean();
	}
	
	function selectGroup($group){
		global $langA;
		
		echo '<table class="WBeditArea1" cellpadding="7" style="margin: .5em auto .5em auto">';
		if( !isset($this->configGroups[$group]) ){
			reset($this->configGroups);
			$group = key($this->configGroups);
		}
		$n = 0;
		foreach($this->configGroups as $label => $script){
			if( $n%3 === 0 ){
				if( $n > 0 ){
					echo '</tr>';
				}
				echo '<tr>';
			}
			echo '<td>';
			if( $group == $label ){
				echo '<b>';
				//echo $langA[$label];
				echo wbLinks::admin('Configuration?group='.$label,$langA[$label]);
				echo '</b>';
				echo '<input type="hidden" name="group" value="'.$group.'" />';
				includeFile('admin/'.$script);
			}else{
				echo wbLinks::admin('Configuration?group='.$label,$langA[$label]);
			}
			echo '</td>';
			$n++;
		}
		
		echo '</tr>';
		echo '</table>';
		return $group;
	}
	
}

class configurationGeneric{
	
	var $defaultVals = array();
	var $label = false;
	var $history = true;
	
	function runConfig($group){
		global $page,$langA;
		$this->label = $langA[$group];
		$_POST += array('summary'=>$this->label.': ');

		
		switch($page->userCmd){
			
			// case 'revert':
			// 	$this->setFromRevision();
			// 	$this->showConfigForm();
			// break;
			
			case wbStrtolower($langA['save']):
				$this->saveConfig();
			case 'show':
			default:
				$this->showForm();
			break;
		}
					
		
	}
	
	//
	//	Retrieval
	//
	function getConfig(){
		global $wbTables;
		
		$query = 'SELECT data FROM '.$wbTables['config'].' ORDER BY revision DESC LIMIT 1';
		$result = wbDB::runQuery($query);
		$row = mysql_fetch_assoc($result);
		return unserialize($row['data']);
	}
	
	
	
	//
	//	Saving functions
	//
	
	
	//save to `config_vars`
	function saveToConfigVars($class=false){
		
		if( $class === false ){
			message('$class not set for saveToConfigVars.');
			return;
		}
		
		
		$oldValues = $this->getValues();
		$oldSum = crc32(serialize($oldValues));
		
		$newValues = $this->getFromPost();
		if( $oldSum === crc32(serialize($newValues)) ){
			message('The configuration has not changed.');
			return;
		}
				
		//clean
		foreach($this->defaultVals as $key => $value){
			if( isset($newValues[$key]) && $newValues[$key] === $value ){
				unset($newValues[$key]);
			}
		}
		wbVariables::saveArray($newValues, $class);
		message('Your configuration has been saved.');
	}
	
	//save to `config`
	function saveToConfig($array){
		global $wbTables;
		$insert = array();
		
		
		//get the current configuration
		$query = 'SELECT `revision` , `data` FROM '.$wbTables['config'].' ORDER BY `revision` DESC LIMIT 1';
		$result = wbDB::runQuery($query);
		$row = mysql_fetch_assoc($result);
		$currentRev = $row['revision'];
		$oldSum = crc32($row['data']);
		$config = unserialize($row['data']);

		
		//new data
		$config = configurationGeneric::merge($config,$array);
		$insert['data'] = serialize($config);
		if( $oldSum === crc32($insert['data']) ){
			message('The configuration has not changed.');
			return;
		}
		
		
		//Insert
		$insert['summary'] = $_POST['summary'];
		$insert['username'] = $_SESSION['username'];
		$insert['version'] = $GLOBALS['wbConfig']['version'];
		$query = 'INSERT INTO '.$wbTables['config'].' SET ';
		$query .= wbDB::toSet($insert,true);
		$num = wbDB::runQuery($query,true);
		if( $num < 1){
			message('<b>Warning</b> This configuration was not saved.');
		}else{
			message('Your configuration has been saved.');
		}
	}
	
	//php's array_merge_recursive() screws things up
	function merge(&$array1, &$array2){
		
		foreach($array2 as $key => $value){
			if( !isset($array1[$key]) ){
				$array1[$key] = $value;
				continue;
			}
			
			if( is_array($value) ){
				$array1[$key] = configurationGeneric::merge($array1[$key],$value);
				continue;
			}
			$array1[$key] = $value;
		}
		
		
		return $array1;
	}

	
	function getFromPost(){
		$possibleValues = $this->getPossible();
		$newValues = array();
		foreach($possibleValues as $possKey => $possValue){
			if( isset($_POST[$possKey]) ){
				$newValues[$possKey] = $_POST[$possKey];
			}
		}
		return $newValues;
	}
	
	
	
	//
	//	Display Functions
	//
	
	function showForm($langLocal=false){
		global $langA;
		
		
		$possibleValues = $this->getPossible();
		if( !$langLocal ){
			$langLocal =& $langA;
		}
	
		
		if( $_SERVER['REQUEST_METHOD'] != 'POST'){
			$array =& $this->getValues();
		}else{
			$array = $_POST;
		}
		
		
		echo '<fieldset>';
		echo '<legend>'.$this->label.'</legend>';
		
		echo '<table width="100%" cellpadding="4">';
		
		//order by the possible values
		foreach($possibleValues as $key => $possibleValue){
			if( isset($array[$key]) ){
				$value = $array[$key];
			}else{
				$value = '';
			}
			
			echo "\n\n";
			echo '<tr><td class="row1">';
			echo '<b>';
			if( isset($langLocal[$key]['alias']) ){
				echo $langLocal[$key]['alias'];
			}else{
				echo $key;
			}
			echo '</b>';
			if( isset($this->beta[$key]) && $this->beta ){
				echo ' &nbsp; <span style="color:red;">Beta</span>';
			}
			echo '<br/><span class="sm">';
			if( isset($langLocal[$key]['desc']) ){
				echo $langLocal[$key]['desc'];
			}
			echo '</span>';
			echo '</td>';
			echo '<td style="vertical-align:middle;width:35%" class="row2">';
			
			if( $possibleValues[$key] === false ){
				echo $langA['unavailable'];
			}elseif( is_array($possibleValues[$key]) ){
				echo formSelect($key,$possibleValues[$key],$value);
			}else{
				echo formInput($key,$value);
			}
			if( isset($this->defaultVals[$key]) ){
				echo '<br/> <span class="sm">';
				echo $this->defaultVals[$key];
				echo '</span>';
			}
			
			echo '</td></tr>';
		}
		
		echo '<tr>';
// 		echo '<td class="row1">';
// 		echo '</td>';
		echo '<td style="vertical-align:middle;" class="row2" colspan="3">';
		echo '<div style="text-align:center;margin:1em">';
		echo '<input value="'.$langA['save'].'" type="submit" name="cmd" accesskey="s" />';
		echo ' &nbsp; ';
 		echo '<input value="'.$langA['reset'].'" type="reset"  />';
 		if( $this->history ){
	 		echo ' &nbsp; ';
			echo $langA['edit_summary'].': <input value="'.$_POST['summary'].'" type="text" name="summary" size="60" maxlength="200"   />';
		}
 		echo '</div>';
 		echo '</td>';
 		echo '</tr>';
		
		echo '</table>';
		
		echo '</fieldset>';
		
		$this->footer();
		
// 		$_POST += array('summary'=>'');
// 		echo '<table class="WBtoolbar"><tr>';
// 		echo '<td>';
// 		echo '<input value="'.$langA['save'].'" type="submit" name="cmd" accesskey="s" class="WBbutton" />';
// 		echo '</td>';
// 		echo '<td>';
//  		echo '<input value="'.$langA['reset'].'" type="reset" class="WBbutton"  />';
// 		echo '</td>';
// 		echo '<td>';
// 		echo $langA['edit_summary'].': <input value="'.$_POST['summary'].'" type="text" name="summary" size="60" maxlength="200" class="WBinputText"  />';
// 		echo '</td>';
// 		echo '</table>';

		
	}
	
	function footer(){
		global $langA;
		echo '<p class="sm" style="text-align:center">';
		if( $this->history ){
			echo $langA['CONFIG_SAVING'];
		}else{
			echo '<b>Notice:</b> A history of the changes made to these values is not stored.';
		}
		echo '</p>';
	}
	
	
}

global $initiateFileClass;
if($initiateFileClass){
	new configManager();
}


//
//	Form Functions
//

function formInput($name,$value){
	global $langA;
	
	$len = (strlen($value)+10)/10;
	$len = round($len);
	$len = $len*10;
	
	$value = wbHtmlspecialchars($value);
	
	static $textarea = '<textarea name="%s" cols="30" rows="%d">%s</textarea>';
	if($len > 100 && (strpos($value,' ') != false) ){
		$cols=40;
		$rows = ceil($len/$cols);
		return sprintf($textarea,$name,$rows,$value);
	}
	
	
	$len = min(40,$len);
	static $text = '<input name="%s" size="%d" value="%s" type="text"/>';
	return "\n".sprintf($text,$name,$len,$value);
}


// this function is in multiple files
// similar to functions in searchSearch.php, specPreferences.php
function formSelect($name,$possible,$value=null){
	
	$result = "\n".'<select name="'.$name.'">';
	if( !isset($possible[$value]) ){
		$result .= '<option value="" selected="selected"></option>';
	}

	foreach($possible as $optionKey => $optionValue){
		if($optionKey == $value){
			$focus = ' selected="selected" ';
		}else{
			$focus = '';
		}
		$result .= '<option value="'.wbHtmlspecialchars($optionKey).'" '.$focus.'>'.$optionValue.'</option>';
	}
	$result .= '</select>';
	return $result;
}