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

if( !isAdmin() ){
	message('You must be an administrator to access this page.');
	return;
}

includeFile('admin/DirectoryFunctions.php');

class createDirectory extends directoryFunctions{
	var $existStruct = array();
	
	//for the wbParser
	var $flags = '';
	
	//
	var $pre, $post = '';
	var $className;
	
	function createDirectory(){
		global $page,$dbInfo,$pageOwner,$dbObject;
		
		$contentUri = $page->regLink('Directories','/Admin/'.$pageOwner['username'].'/Directories');
		$page->regLink('Keyword Spaces','/Admin/'.$pageOwner['username'].'/KeywordSpaces');
		$page->autoForm = true;
		
		$page->regLink('?','Manage Directories?en=Manage_Directories');
		$show = true;
		
		$this->setSpaces();
		$this->setCurrentSpaces('dirs');
		
		ob_start();
		echo '<br/>';
		switch($page->userCmd){
			case 'finish':
				if( !$this->finish() ){
					$this->create();
					$show = false;
				}
			break;
			
			case 'check':
				if( $this->check() ){
					message('The directory is ready for creation.');
				}
				$this->create();
				$show = false;
			break;
			
			case 'create':
				if( $this->create() ){
					$show = false;
				}
			break;
			
			case 'remove':
				$this->removeDirCheck();
				$show = false;
			break;
			case 'confirm removal':
				$this->removeDir('dirs');
			break;
			
			case 'update':
				if( !$this->update() ){
					$show = false;
				}
			break;
			case 'edit':
				if( $this->editVals($_GET['name'])  ){
					$show = false;
				}
			break;
			case 'checkindex':
				$this->checkIndex();
			break;
			
			case 'export':
				$this->exportAsPlugin($_GET['space']);
				$show = false;
			break;
						
			//these function are in PluginAdd.php
			case 'rawedit';
				$this->editRawCode($_GET['name']);
				$show = false;
			break;
			case 'save changes':
				$this->saveRawCode();
			break;
		}
		
		if( $show ){
			echo '<table>';
			$this->form();
			$this->showCurrent();
			echo '</table>';
		}
		
		$page->contentB[$contentUri] = wb::get_clean();
	}
	
	
	
	//////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//	Index functions
	//
	function checkIndex(){
		global $page,$dbInfo;
		$name = $_GET['name'];
		if( !isset($dbInfo[$name]) ){
			message('INVALID_REQUEST');
			return;
		}
		
		
		//get existing indeces
		$useName = $dbInfo[$name]['useInfo'];
		$useTable = $dbInfo[$useName]['dbTable'];
		$query = 'SHOW INDEX FROM '.$useTable;
		$result = wbDB::runQuery($query);
		$indeces = array();
		while($row = mysql_fetch_assoc($result)){
			$indexName = $row['Key_name'];
			if( !isset($indeces[$indexName]) ){
				$indeces[$indexName] = array();
			}
			$column = $row['Column_name'];
			//$column = $useTable.'.`'.$row['Column_name'].'` ';
			$indeces[$indexName][(int)$row['Seq_in_index']] = $column;

		}
		message('indeces: '.showArray($indeces));
		
		//get columns used for directory
		$class = wbData::getClass($name,false);
		if( !$class ){
			message('INVALID_REQUEST');
			return;
		}
		$vars = get_class_vars($class);
		if( !isset($vars['columns']) ){
			message('Data not available for this type (1)');
			return;
		}
		$columns = $vars['columns'];
		$checkColumns = array();
		
		//$similar = array_keys($this->existStruct,$structure);
			
		
	}
	
	
	//////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//	Functions for creating sql and php
	//
	
	function createClass(){
		$_POST += array('limit'=>'20','where'=>'');
		$this->setVariables($_POST['space']);
		
		//
		//	Start Class
		//
			$tab = "\t";
			$class = array();
			$class[] = '////////////////////////////////////////////////////////////';
			$class[] = '//';
			$class[] = '//		WikyBlog Generated Code';
			$class[] = '//		Edit with care';
			$class[] = '//';
			$class[] = '////////////////////////////////////////////////////////////';
			$class[] = '';
			$class[] = '';
			$class[] = 'includeFile(\'search/WikiDirs2.php\');';
			$class[] = '';
			$class[] = 'class '.$this->className.' extends wikiDirs2{';
			$class[] = $tab.'var $levels;';
			$class[] = $tab.'var $columns;';
			$class[] = '';
			
			$class[] = $tab.'//Directory Structure';
			$class[] = $tab.'//static';
			$class[] = $tab.'function getlevels(){'; //all lowercase for addsimilar
			$class[] = $tab.$tab.'global $wbTablePrefix;';
			$class[] = '';
			$class[] = $tab.$tab.'$levels = array();';
			$cols = false;
			$j = 0;
			foreach($_POST['columns'] as $i => $column){
				if( empty($column) ){
					continue;
				}
				
				$temp = $this->columnSQL($column);
				
				$class[] = $tab.$tab.$tab.'$levels['.$j.'] = array();';
				$class[] = $tab.$tab.$tab.'$levels['.$j.'][\'sqlShow\'] = '.$this->escapeSafe($temp['sqlShow']).';';
				$class[] = $tab.$tab.$tab.'$levels['.$j.'][\'sqlOrder\'] = '.$this->escapeSafe($temp['sqlOrder']).';';
				if( $temp['instruction'] ){
					$class[] = $tab.$tab.$tab.'$levels['.$j.'][\'instruction\'] = '.$this->escapeSafe($temp['instruction']).';';
				}
				$class[] = '';
				$cols = true;
				
				//store the column names
				$pos = strpos($column,':');
				$how = substr($column,$pos+1);
				$column = substr($column,0,$pos);
				$columns[] = '"'.$column.'"';
				$j++;
			}
			if( !$cols){
				message('You must define at least on level to have a valid directory.');
				return false;
			}
			//$class[] = $tab.$tab.$tab.');';
			$class[] = $tab.$tab.'return $levels;';
			$class[] = $tab.'}';
			$class[] = '';
			
			//
			//	Constructor
			//
			$class[] = $tab.'function '.$this->className.'($name){';
			$class[] = $tab.$tab.'global $wbTablePrefix;';
			$class[] = '';
			
		//
		//	Display
		//
			
			$class[] = $tab.$tab.'$this->columns = array('.implode(',',$columns).');';
			
			$class[] = '';
			$class[] = $tab.$tab.'$this->levels = $this->getlevels();';
			$class[] = $tab.$tab.'$this->dir[\'where\'] = '.$this->escape($_POST['where']).'; ';
			
		//
		//	Display
		//
			$class[] = '';
			$class[] =  $tab.$tab.'//';
			$class[] =  $tab.$tab.'//Display';
			$class[] =  $tab.$tab.'//';
		
			$orderBy = $this->createClassOrderBy();
			if( $orderBy ){
				$class[] = $tab.$tab.'$this->dir[\'order\'] = '.$orderBy.'; ';
			}
			
			
			$class[] = $tab.$tab.'$this->dir[\'limit\'] = '.$this->escape($_POST['limit']).';';
			$class[] = $tab.$tab.'$this->dir[\'pre\'] = '.$this->escape($this->pre).';';
			$class[] = $tab.$tab.'$this->dir[\'post\'] = '.$this->escape($this->post).';';
			
			if( isset($_POST['empties']) ){
				$class[] = $tab.$tab.'$this->dir[\'empties\'] = false;';
			}
			if( isset($_POST['verbose']) ){
				$class[] = $tab.$tab.'$this->dir[\'verbose\'] = true;';
			}

			
			$class[] = '';
			$class[] =  $tab.$tab.'//';
			$class[] =  $tab.$tab.'//Continue';
			$class[] =  $tab.$tab.'//';
			$class[] = $tab.$tab.'$this->wikiDirs2($name);';
			
			$class[] = $tab.'}';
			$class[] = '';
			$class[] = '}';
			$class[] = '';
			
			return implode("\n",$class);
	}
	
	function newDbInfo(){
		$name = wbStrtolower($_POST['name']);
		$newInfo= array();
		$displayName = toDisplay($_POST['name']);
		if( $name !== $displayName){
			$newInfo['alias'] = $displayName;
		}
		$newInfo['dirs'] = $_POST['space'];
		$newInfo['class'] = $this->className;
		$newInfo['dbPlugin'] = true;
		
		//!! version 1.5.7 used this, but we'll just use keySpace from V1.5.8 on out
		$newInfo['useInfo'] = $_POST['space'];
		return $newInfo;
	}


	
	//
	//	Save the POST data for later editing
	//

		
	function addSimilar(&$data,$name){
		global $dbObject,$dbInfo;
		$this->setStructures();
		
		$structure = $this->getStructureForSpace($name);
		
		$similar = array_keys($this->existStruct,$structure);
		if( count($similar) == 0){
			return;
		}
		$currentNameKey = array_search($name,$similar);
		if( !is_int($currentNameKey) ){
			$similar[] = $name;
		}
		foreach($similar as $i => $space){
			//message('set for '.$space);
			$temp = $similar;
			unset($temp[$i]);
			if( count($temp) < 1){
				unset($data['dbInfo'][$space]['similar']);
			}else{
				$data['dbInfo'][$space]['similar'] = $temp;
			}
		}
	}
	
	function setStructures(){
		if( is_array($this->currentSpaces) ){
			foreach($this->currentSpaces as $space => $null){
				$this->existStruct[$space] = $this->getStructureForSpace($space);
			}
		}
	}
	
	function getStructureForSpace($space){
		$class = wbData::getClass($space,false);
		if( is_callable(array($class,'getlevels')) ){
			$structure = call_user_func(array($class, 'getlevels'));
		}else{
			$vars = get_class_vars($class);
			$structure =& $vars['levels'];
		}
		return $structure;		
	}
	
	
	function removeSimilar(&$data,$name){
		$dbInfo =& $data['dbInfo'];
		
		
		foreach($dbInfo as $space => $info){
			if( !isset($info['dirs']) ){
				continue;
			}
			if( !isset($info['similar']) ){
				continue;
			}
			$info = $dbInfo[$space];
			
			$key = array_search($name,$info['similar']);
			if( ($key !== false) && !is_null($key)){
				unset($info['similar'][$key]);
				unset($info['similar'][$key]);
			}
			if( !is_array($info['similar']) || (count($info['similar']) < 1) ){
				unset($info['similar']);
				unset($info['similar']);
			}
			$dbInfo[$space] = $info;
		}
	}	
	
	function check(){
		global $dbInfo,$wbTables, $wbParser;
		$done = true;
		
		if( !empty($_POST['limit']) && !is_numeric($_POST['limit'])){
			message('Limit was not a numeric value');
			$done = false;
		}
		if( !empty($_POST['pre']) || !empty($_POST['post']) ){
			initiateParser();
			if( !empty($_POST['pre']) ){
				$this->pre = $wbParser->parse($_POST['pre'],true,$this);
				if( $wbParser->errors ){
					$done = false;
					foreach($wbParser->errors as $error){
						message('<strong>Error Parsing Top of Page Wiki Syntax</strong><br/>'.$error);
					}
				}
			}
			if( !empty($_POST['post']) ){
				$this->post = $wbParser->parse($_POST['post'],true,$this);
				if( $wbParser->errors ){
					$done = false;
					foreach($wbParser->errors as $error){
						message('<strong>Error Parsing Top of Page Wiki Syntax</strong><br/>'.$error);
					}
				}
			}
		}
		if( !$this->checkWhere() ){
			$done = false;
		}
		
		return $done;
	}

	
	function create($new=true){
		global $dbInfo,$page;
		
			$_POST += array(
							'limit'=>'20',
							'where'=>'',
							'pre'=>'',
							'post'=>'',
							);
							
		
		//
		//	Check
		//
			if( $new && !$this->checkDirName() ){
				return false;
			}
			$this->setVariables($_POST['space']);
			
		//
		//	Get Object
		//
			
			echo '<table>';
			echo '<tr>';
			echo '<td>';
			
			echo '<fieldset style="padding:1em;">';
			echo '<legend>Directory: '.$_POST['name'].'</legend>';
			
			
			echo '<table cellpadding="7" border="0">';
			
			echo '<tr>';
				echo '<td colspan="2">';
				echo '<h4 class="heading">Levels*</h4>';
				echo '</td>';
				echo '<td colspan="2">';
				echo '<h4 class="heading">Where</h4>';
				echo '</td>';
				echo '</tr>';
				
			
			echo '<tr>';
			echo '<td style="white-space:nowrap;" rowspan="3"> &nbsp; &nbsp; &nbsp; </td>';
			echo '<td style="width:25em" rowspan="3">';
			echo '<table cellpadding="0" cellspacing="0">';
			$i = 0;
			foreach($this->variables as  $null){
				echo '<tr>';
					echo '<td>';
					$this->selectVariables('columns',$i);
					echo '</td>';
					echo '</tr>';
				$i++;
			}
			echo '</table>';
			echo '</td>';
			
		//
		//	Where
		//
			echo '<td></td>';
			echo '<td>';
			echo '<textarea name="where" rows="5" cols="30">';
			echo wbHtmlspecialchars($_POST['where']);
			echo '</textarea>';
			echo '</td>';
			echo '</tr>';
			
		//
		//	Empties
		//
			echo '<tr>';
				echo '<td colspan="2">';
				echo '<h4 class="heading">Empties</h4>';
				echo '</td>';
				echo '</tr>';
				
			echo '<tr>';
			echo '<td style="white-space:nowrap;"> &nbsp; &nbsp; &nbsp; </td>';
			echo '<td><label>';
			if( isset($_POST['empties']) ){
				echo '<input type="checkbox" name="empties" checked="checked" />';
			}else{
				echo '<input type="checkbox" name="empties" />';
			}
			echo ' Hide Display for Empties';
			echo '</label>';
			echo '</td>';
			echo '</tr>';
			
			echo '</table>';
			echo '</fieldset>';
			
			echo '</td>';
			echo '</tr>';

						
		////////////////////////////////
		//
		//	Display
		//
			
			echo '<tr>';
			echo '<td>';
			echo '<fieldset style="padding:1em;height:100%;">';
			echo '<legend>Display</legend>';
			echo '<table cellpadding="7" border="0">';
			
			echo '<tr>';
				echo '<td colspan="2">';
				echo '<h4 class="heading">Title</h4>';
				echo '</td>';
		
				echo '<td colspan="2">';
				echo '<h4 class="heading">Limit</h4>';
				echo '</td>';
				echo '</tr>';
			

				
			
			echo '<tr>';
			
			
		
		//
		//	Verbose Title
		//
				
				echo '<td style="white-space:nowrap;"> &nbsp; &nbsp; &nbsp; </td>';
				echo '<td><label>';
				if( isset($_POST['verbose']) ){
					echo '<input type="checkbox" name="verbose" checked="checked" />';
				}else{
					echo '<input type="checkbox" name="verbose" />';
				}
				echo ' Show a verbose title for each page';
				echo '</label>';
				echo '</td>';
			
		//
		//	Limit
		//
		

		
				echo '<td></td>';
				echo '<td>';
				echo '<input name="limit" type="text" size="4" value="'.wbHtmlspecialchars($_POST['limit']).'" />';
				echo '</td>';			
			echo '</tr>';
			
			
			
			
			
		//
		//	Headings
		//
				echo '<tr>';
					echo '<td colspan="2">';
					echo '<h4 class="heading">Top of Page</h4>';
					echo '</td>';
					echo '<td colspan="2">';
					echo '<h4 class="heading">Bottom of Page</h4>';
					echo '</td></tr>';
					
				echo '<tr>';
					echo '<td style="white-space:nowrap;"> &nbsp; &nbsp; &nbsp; </td>';
					echo '<td style="width:25em">';
					echo '<textarea name="pre" rows="5" cols="30">';
					echo wbHtmlspecialchars($_POST['pre']);
					echo '</textarea>';
					echo '</td>';
					echo '<td style="white-space:nowrap;"> &nbsp; &nbsp; &nbsp; </td>';
					echo '<td style="width:25em">';
					echo '<textarea name="post" rows="5" cols="30">';
					echo wbHtmlspecialchars($_POST['post']);
					echo '</textarea>';
					echo '</td></tr>';
					
					
			echo '<tr>';
			
			
		//
		//	Order By
		//
			
						
			echo '<tr>';
				echo '<td colspan="2">';
				echo '<h4 class="heading">Order By</h4>';
				echo '</td>';
				echo '<td colspan="2">';
				echo '<h4 class="heading"></h4>';
				echo '</td>';
				echo '</tr>';
		//
		//	Order By
		//
			$order2['ASC'] = 'Ascending';
			$order2['DESC'] = 'Descending';
			echo '<td style="white-space:nowrap;"> &nbsp; &nbsp; &nbsp; </td>';
			echo '<td style="width:25em">';
			echo '<table cellpadding="0" cellspacing="0">';
			$i = 0;
			foreach($this->variables as $null){
				echo '<tr>';
					echo '<td>';
					$this->selectVariables('order',$i);
					echo '</td>';
					echo '<td>';
					echo '<select name="order2[]">';
					foreach($order2 as $value => $disp){
						if( isset($_POST['order2'][$i]) && ($_POST['order2'][$i] == $value)){
							echo '<option value="'.$value.'" selected="selected">'.$disp.'</option>';		
						}else{
							echo '<option value="'.$value.'">'.$disp.'</option>';
						}
					}
					echo '</select>';
					echo '</td>';
					echo '</tr>';
					$i++;
			}
			echo '</table>';
			echo '</td>';
			echo '</tr>';
					
					
					
					
			echo '</table>';
				
				
			echo '</fieldset>';
			echo '</td>';
			echo '</tr><tr>';
			echo '<td style="text-align:center;">';
			
				if( $new ){
					echo '<input type="submit" name="cmd" value="Check" />';
					echo ' &nbsp; ';
					echo '<input type="submit" name="cmd" value="Finish" />';
				}else{
					echo '<input type="submit" name="cmd" value="Update" />';
				}
				echo ' &nbsp; <input type="submit" name="cmd" value="Start Over" />';
				echo '<br/><span class="sm">* Levels is the only required setting.</span>';
				echo '<input type="hidden" name="name" value="'.wbHtmlspecialchars($_POST['name']).'" />';
				echo '<input type="hidden" name="space" value="'.wbHtmlspecialchars($_POST['space']).'" />';
				
			echo '</td></tr>';
			
			

			
			
			
			
			echo '</table>';
			
		return true;
	}
	
	
	function showCurrent(){
		global $dbInfo,$langA;
		
		if( count($this->currentSpaces) < 1 ){
			return;
		}
		
		echo '<tr>';
		echo '<td>';
		echo '<fieldset style="padding:1em;">';
		echo '<legend>Current Directories</legend>';

		echo '<table class="tableRows sortable"">';
			
		echo '<tr>';
			echo '<th>';
				echo 'Name';
				echo '</th>';
			echo '<th>';
				echo 'Built On Data Type';
				echo '</th>';
			// echo '<th>';
			// 	echo 'Structure';
			// 	echo '</th>';
			echo '<th>';
				echo 'Similar To';
				echo '</th>';
			echo '<th class="unsortable">';
				echo 'Options';
				echo '</th>';
			echo '</tr>';
		
		$i = 0;
		$classes[] = ' class="tableRowEven" ';
		$classes[] = ' class="tableRowOdd" ';
		foreach($this->currentSpaces as $nameSpace => $useInfo){
			$i++;
			echo '<tr'.$classes[($i%2)].'>';

			
				echo '<td>';
				$temp = $nameSpace;
				if( isset($langA[$nameSpace]) ){
					$temp = $langA[$nameSpace];
				}
				echo wbLinks::local('/'.$nameSpace,$temp);
				echo '</td>';
				
				echo '<td>';
				echo $useInfo;
				echo '</td>';
				
				echo '<td>';
				if( isset($dbInfo[$nameSpace]['similar']) ){
					$tempA = array();
					foreach($dbInfo[$nameSpace]['similar'] as $simSpace){
						$temp = $simSpace;
						if( isset($langA[$simSpace]) ){
							$temp = $langA[$simSpace];
						}
						$tempA[] = $temp;
					}
					echo implode(', ',$tempA);
						
				}else{
					echo ' - ';
				}
				
				echo '</td>';
				
				echo '<td>';
				echo wbLinks::admin('Directories?cmd=edit&name='.$nameSpace,'edit');
				echo ' &nbsp; &nbsp; ';
				echo wbLinks::admin('Directories?cmd=rawedit&name='.$dbInfo[$nameSpace]['class'],'Raw Edit');
				echo ' &nbsp; &nbsp; ';
				
				if( function_exists('var_export') ){
					echo wbLinks::admin('Directories?cmd=export&space='.$nameSpace,'Export');
					echo ' &nbsp; &nbsp; ';
				}

				echo wbLinks::admin('Directories?cmd=remove&name='.$nameSpace,'Remove');
				//echo ' &nbsp; ';
				//echo wbLinks::admin('Directories?cmd=CheckIndex&name='.$name,'Check Index');
				echo '</td>';
				echo '</tr>';
		}
		echo '</table>';
		echo '</fieldset>';
		echo '</td>';
		echo '</tr>';
	}
	

	
	function form(){
		global $langA;
		$_POST += array('name'=>'');
		
		echo '<tr>';
		echo '<td>';
		echo '<fieldset style="padding:1em;">';
		echo '<legend>Create New Directory</legend>';
		
		echo '<table>';
		echo '<tr>';
			echo '<td>';
			echo 'Name: ';
			echo '</td>';
			echo '<td>';
			echo '<input type="text" size="20" name="name" value="'.wbHtmlspecialchars($_POST['name']).'" />';
			echo '</td>';
			echo '</tr>';
			
		echo '<tr>';
			echo '<td>';
			echo 'Over Space: ';
			echo '</td>';
			echo '<td>';
			echo '<select name="space">';
			foreach($this->spaces as $space => $null){
				echo '<option value="'.$space.'">'.$langA[$space].'</option>';
			}
			echo '</select>';
			echo '</td>';
			echo '</tr>';
			
		echo '<tr>';
			echo '<td>';
			echo '</td>';
			echo '<td>';
			echo '<input type="submit" name="cmd" value="Create" />';
			echo '</td>';
			echo '</tr>';
		echo '</table>';
		
		echo '</fieldset>';
		echo '</td>';
		echo '</tr>';
	}
	
}


new createDirectory();
