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


includeFile('search/all.php');


class wikiDirs extends query{
	
	var $useSpace;
	var $useInfo;
	var $searchFor = array();
	var $other = '';
	var $otherPath = '';
	var $displayObject;
	var $query2 = '';
	
	var $levels;
	var $reqLevels = array();
	var $allFilesColumns = array('keywords'=>true,'modified'=>true,'posted'=>true,'created'=>true);
	var $similarUrl = '';
	
	function wikiDirs($name){
		global $dbInfo,$langA;
		
		$this->title = $name;
		$this->space = $name;
		$this->searchUrl = '/'.$name;
		
		$info = $dbInfo[$name];
		
		if( isset($info['dirs']) && ($info['dirs'] !== true) ){ // 'dirs' is used by Directories created by the software
			$this->useSpace = $info['dirs'];
			
		}elseif( isset($info['useInfo']) ){ // 'useInfo' will be used by custom plugins
			$this->useSpace = $info['useInfo'];
			
		}else{
			die('INVALID_REQUEST');
		}
		
		$this->useInfo = $dbInfo[$this->useSpace];
		
		if( isset($dbInfo[$name]['dirs']) && is_array($dbInfo[$name]['dirs']) ){
			$this->levels = $dbInfo[$name]['dirs'];
		}
	}
	
	function getOwner(&$pathArray){
		return $GLOBALS['wbConfig']['pUser'];
	}
	
	function getStep1($pathArray){
		global $page,$langA;
		$page->css2 =true;
		$this->pathArray = $pathArray;
	}
		
	function getStep2(){
		global $wbTables,$langA,$page,$dbInfo;
		
		if( isset($langA[$this->title]) ){
			$this->title = $langA[$this->title];
		}
		
		$page->displayTitle = $this->title;
		$page->regLink($this->title,$this->searchUrl);
		
		//
		//	adjust path array
		//
			$path = array();
			if( !empty($this->pathArray['owner']) ){
				$path[] = $this->pathArray['owner'];
			}
			foreach($this->pathArray['path'] as $value){
				$path[] = $value;
			}
		//
		//	Start the query
		//
			$this->query2 .= ' FROM '.wbData::dbInfo($this->useSpace,'queryFrom');
			$this->query2 .= ' INNER JOIN '.$wbTables['all_files'];
			$this->query2 .= ' ON '.$wbTables['all_files'].'.`file_id` = '.wbData::dbInfo($this->useSpace,'dbTable').'.`file_id` ';
			$this->query2 .= ' WHERE ';
			$this->query2 .= $wbTables['all_files'].'.`visible` = 1 ';
			if( !empty($this->dir['where']) ){
				$this->query2 .= ' AND '.$this->dir['where'];
			}
			
				
		//
		//	Go Through Path
		//
		
			$temp = $this->levels;
			$prevHow = 0;
			$queryA = array();
			
			$how = current($temp);
			$columnSql = key($temp);
			
			foreach($path as $i => $value){
				$value = toDisplay($value);
				if(empty($value)){
					continue;
				}
				$this->setTitle($value);
				$this->searchUrl .= '/'.$value;
				$page->regLink('>');
				$page->regLink($value,$this->searchUrl);
				$this->similarUrl .= '/'.$value;
				
					
				if(  $prevHow == 3 ){
					$prevHow = 0;
					$level = $prevReqLevel.': '.$value;//always a space!
					$this->reqLevels[] = $level;
					$temp2 = array_pop($queryA);
					
					if( $value == $langA['empty'] ){
						if( $prevReqLevel == $langA['empty'] ){
							$queryA[] = $temp2;
						}else{
							$queryA[] = ' AND FIND_IN_SET("'.wbDB::escape(wbHtmlspecialchars($prevReqLevel)).'", '.$columnSql.' ) ';
						}
					}else{
						$queryA[] = ' AND FIND_IN_SET("'.wbDB::escape(wbHtmlspecialchars($level)).'", '.$columnSql.' ) ';
					}
					
				}else{
					$this->reqLevels[] = $value;
					
					//build the query
					if($value == $langA['empty']){
						$queryA[] = ' AND (('.$columnSql.' IS NULL) OR ('.$columnSql.' ="")) ';
						
					}elseif( is_numeric($how) ){
						$pos= strpos($value,':');
						if( ($pos === false)||($pos+1) == strlen($value)){
							$temp2 = ' AND (';
							$temp2 .= ' FIND_IN_SET("'.wbDB::escape(wbHtmlspecialchars($value)).'", '.$columnSql.' ) ';
							$temp2 .= ' OR ('.$columnSql.' LIKE "'.wbDB::like(wbHtmlspecialchars($value.':')).'%") ';
							$temp2 .= ' OR ('.$columnSql.' LIKE "%,'.wbDB::like(wbHtmlspecialchars($value.':')).'%") ';
							$temp2 .= ')';
							$queryA[] = $temp2;
							
						}else{
							$queryA[] = ' AND (FIND_IN_SET("'.wbDB::escape(wbHtmlspecialchars($value)).'", '.$columnSql.' )>0) ';
						}
						
					}else{
						$queryA[] = ' AND "'.wbDB::escape($value).'" = '.$columnSql.' ';
						
					}
					array_shift($temp);
				}
				
				if( $how == 3){
					$prevReqLevel = array_pop($this->reqLevels);
					$prevHow = 3;
					$how = 4;
				}else{
					$how = current($temp);
					$columnSql = key($temp);
				}
			}
			$this->query2 .= implode($queryA);
			
		//
		//	Act According to reqLevels
		//
			$needed = count($this->levels);
			$have = count($this->reqLevels);
			
			if( $have >= $needed ){
				$this->showList(); //group = false
			}else{
				$groupField = 'wbDir_level_'.(count($this->reqLevels)+1);
				if( !is_numeric($how) ){
					$this->query2 .= ' GROUP BY '.$how;
					$this->query2 .= ' ORDER BY '.$how.' ';
				}else{
					$this->query2 .= ' GROUP BY '.$columnSql.' ';
				}
				$this->countValues($how,$groupField);
			}
	}
	function setTitle($arg){
		global $page;
		$this->title = $arg;
		
		if( isset($this->dir['verbose']) && ($this->dir['verbose'] === true) ){
			$page->displayTitle .= ' > '.$arg;
		}else{
			$page->displayTitle = $arg;
		}
	}

	
	
	////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//		Show a Direcotry List
	//
	function showList(){
		global $dbInfo,$wbTables,$langA;
		$this->displayClass = wbData::getClass($this->useSpace,true);
		
		$this->query = 'SELECT /* showlist() */ SQL_CALC_FOUND_ROWS ';
		$this->query .= wbData::dbInfo($this->useSpace,'querySelect');
		$this->query .= ', '.wbData::dbInfo($this->useSpace,'uniqLink').' as uniqLink ';
		$this->query .= ', '.wbData::getDTitle($this->useSpace);
		$this->query .= ', '.$wbTables['all_files'].'.* ';
		$this->query .= $this->query2;
		if(isset($this->dir['order']) ){
			$this->query .= ' ORDER BY '.$this->dir['order'];
		}
		
		//message($this->query);
		$this->rowLimit = 30;
		$this->browse($this->title);
	}
	
	function abbrevOutput(&$row,&$i,&$actualRowsFound){
		call_user_func(array($this->displayClass,'abbrevOutput'),$row,$i,$actualRowsFound);
	}
	function mysqlFetch(&$result){
		return mysql_fetch_object($result);
	}
	function limit(){
		if(isset($this->dir['limit']) ){
			$this->rowLimit = $this->dir['limit'];
		}
		parent::limit();
	}
	function displayPre(){
		if( !empty($this->dir['pre']) ){
			echo $this->dir['pre'];
		}
	}
	function displayPost($prev,$pages,$next){

		$more = $this->similarDirs();
		
		if( !empty($this->dir['post']) ){
			echo $this->dir['post'];
		}
		parent::displayPost($prev,$pages,$next,$more);
	}
	
	function similarDirs(){
		global $dbInfo;
		$links = array();
		$similar = array();
		if( !isset($dbInfo[$this->space]['similar']) ){
			return;
		}
		$similar =& $dbInfo[$this->space]['similar'];
		foreach($similar as $space){
			$temp = '/'.$space.$this->similarUrl;
			$links[] = wbLinks::local($temp,$space);
		}
		if( count($similar) > 0){
			return 'Find similar entries: '.implode(', ',$links);
		}
	}
	

	
	////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//		Count the Values for each directory
	//
	function countValues($how,$groupField){
		global $dbInfo,$page,$wbTables,$langA;
		
		
		//
		//	Create the query
		//
			$this->query = 'SELECT /* countValues */ SQL_CALC_FOUND_ROWS COUNT(*) as `count` ';
			$i = 1;
			foreach($this->levels as $level => $null){
				$this->query .= ', '.$level.' as `wbDir_level_'.$i.'` ';
				$i++;
			}
			
			$this->query .= ', AVG(`modified`) as `avg_modified` '; //this is used for the Last-Modified header
			$this->query .= $this->query2;

			
			switch($how){
				case 4:
					$count = $this->countSet2($groupField,$how);
				break;
					
				case 3:
				case 2:
					$count = $this->countSet($groupField,$how);
				break;
				default:
					$count = $this->countResult($groupField);
				break;
			}
		//
		//	Output Counts
		//
			ob_start();
			
			if( !empty($this->dir['pre']) ){
				echo $this->dir['pre'];
			}
			
			if( count($count) == 0){
				echo $langA['EMPTY_SET'];
			}
			
			//move empty to the end of $count
			if( isset($count[$langA['empty']]) ){
				$temp = $count[$langA['empty']];
				unset($count[$langA['empty']]);
				
				if( isset($this->dir['empties']) && ($this->dir['empties'] === false) ){
					//delete the empty
				}else{
					$count[$langA['empty']] = $temp;
				}
			}
			
			$half = count($count)/2;
			$i = 0;
			echo '<table width="100%"><tr><td>';
			foreach($count as $key => $num){
				if( strpos($key,'/') !== false){
					continue;
				}
				if( $i >= $half){
					$i = -1;
					echo '</td><td>';
				}
				$i++;
				if( isset($this->plurals[wbStrtolower($key)]) ){
					$key = $key.='s';
				}
				echo wbLinks::local($this->searchUrl.'/'.$key,$key.' ('.$num.')');
				//echo wbLinks::local($this->searchUrl.'/'.rawurlencode($key),$key.' ('.$num.')'); //this doesn't work for "/" characters
				echo '<br/>';
			}
			echo '</td></tr></table>';
			$more = $this->similarDirs();
			if( $more ){
				echo '<p>';
				echo $more;
				echo '</p>';
			}
			
			if( !empty($this->dir['post']) ){
				echo $this->dir['post'];
			}
			
		$page->contentA[$this->title] = wb::get_clean();
	}
		
	///////////////////////////////////////////////////////////////
	//
	//	Count The Results
	//
	function countSet($column,$how){
		global $langA,$page;
		
	
		$result = wbDB::runQuery($this->query);
		$count = array();
		
		while($row = mysql_fetch_assoc($result)){
			$page->setLastModified($row['avg_modified']);
			
			$keywords = explode(',',$row[$column]);
			foreach($keywords as $key){
				$pos = strpos($key,':');
				if($pos != 0){
					$prev = trim(substr($key,0,$pos));
					if( !isset($count[$prev]) ){
						$count[$prev] = 0;
					}
					$count[$prev] += $row['count'];
					if( $how == 3){
						continue;
					}
				}elseif( empty($key) ){
					
					// if( $how == 3){ //prevents empties
					// 	continue;
					// }
					$key = $langA['empty'];
				}
				if( !isset($count[$key])){
					$count[$key] = 0;
				}
				$count[$key] += $row['count'];
			}
		}
		ksort($count);
		return $count;
	}
	function countSet2($column,$how){
		global $langA,$page;
		
		
		$result = wbDB::runQuery($this->query);
		$count = array();
		
		while($row = mysql_fetch_assoc($result)){
			$page->setLastModified($row['avg_modified']);
			
			$keywords = explode(',',$row[$column]);
			foreach($keywords as $key){
				$pos = strpos($key,':');
				if($pos === false){
					$key = $langA['empty'];
				}else{
					$key = trim(substr($key,$pos+1));
				}
				if( !isset($count[$key])){
					$count[$key] = 0;
				}
				$count[$key] += $row['count'];
			}
		}
		ksort($count);
		return $count;		
	}	
	
	function countResult($column){
		global $langA,$page;
		
		$result = wbDB::runQuery($this->query);
		$count = array();
		while($row = mysql_fetch_assoc($result)){
			$key =& $row[$column];
			if( empty($key) ){
				$key = $langA['empty'];
			}
			if( !isset($count[$key])){
				$count[$key] = 0;
			}
			$count[$key] += $row['count'];			
		}
		return $count;
	}
	
	
}


