<?php
//	updating so that searches use FULL_TEXT indexes
//		SELECT ...  WHERE MATCH(..) AGAINST "..."
//		rows returned are automatically sorted with highest relevance first
//		.. issue is going to be getting the old data into the tables..
//

//
//	Configuration Value
//		$wbConfig['search'] = true/false

//	is search a site wide feature, or limited to an account?
//
//

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

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


	


//
//				Flow Control
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//				Functions
//

includeFile('search/all.php');

class searchOptions extends query{
	var $enabled;
	
	function searchOptions(){
		global $page,$wbTables,$dbObject,$langA;
		
		$this->currUri = $page->regLink($langA['search_options'],'/Admin/Main/SearchOptions');
		$this->searchUrl = '/Admin/Main/SearchOptions';
		$page->displayTitle = $langA['search_options'];
		
		//	check for content
		//		all_search should be empty if search is disabled
		//
		$query = 'SELECT count(*) as count FROM '.$wbTables['all_search'];
		$result = wbDB::runQuery($query);
		$row = mysql_fetch_assoc($result);
		
		if( $row['count'] == 0){
			$this->enabled = false;
		}else{
			$this->enabled = true;
		}
		switch($page->userCmd){
			case 'enable':
				$this->enable();
			break;
			
			case 'disable':
				$this->disable();
			default:
				$this->defaultDisplay();
			break;
		}
	}
	
	function defaultDisplay(){
		global $page,$langA;
		ob_start();
		
		echo '<table class="tableRows" ><tr><th style="white-space:nowrap">'.$langA['search_status'].'</th><th style="white-space:nowrap" colspan="2">'.$langA['options'].'</th></tr>';
		echo '<tr>';
	
		if( $this->enabled ){
			echo '<td style="white-space:nowrap">'.$langA['search_enabled'].'</td>';
			echo '<td style="white-space:nowrap">'.wbLinks::admin('SearchOptions?cmd=disable',$langA['disable']).'</td>';
			echo '<td>'.$langA['SEARCH_ENABLED'].'</td>';
		}else{
			echo '<td style="white-space:nowrap">'.$langA['search_disabled'].'</td>';
			echo '<td style="white-space:nowrap">'.wbLinks::admin('SearchOptions?cmd=enable',$langA['enable']).'</td>';
			echo '<td>'.$langA['SEARCH_DISABLED'].'</td>';
		}
		echo '</tr></table>';
		
		$page->contentB[$this->currUri] = wb::get_clean();
	}
		
	
	function disable(){
		global $wbTables;
		$query = 'TRUNCATE TABLE '.$wbTables['all_search'];
		$result = wbDB::runQuery($query);
		message('SEARCH_IS_DISABLED');
		$this->updateConfig(false);
	}


	//	take the content from each file, strip if of tags/formatting, then insert it into all_search
	//		for the standard spaces, just
	//
	//!! still getting a "filesort" from the EXPLAIN SELECT.. is it because we're not using all spaces.. no, still getting filesort with all spaces???
	//	
	function enable(){
		global $dbInfo,$wbTables,$langA;
		
		$this->startTime = microtime();
		if(isset($_GET['limit']) && is_numeric($_GET['limit']) ){
			$this->rowLimit = $_GET['limit'];
		}else{
			// this doesn't seem to work.. the enable keys doesn't work right for full-text
			// $query = 'ALTER TABLE '.$wbTables['all_search'].' DISABLE KEYS';
			// wbDB::runQuery($query);
			$this->rowLimit = 50;
		}
		
		$this->allSelect = array('file_id','owner_id');
		$this->infoSelect = array('selectSearchTitle','selectSearchContent');

		foreach($dbInfo as $space => $info){
			if( !isset($info['dbTable']) ){
				continue;
			}
			if(!isset($info['searchTitle']) ){
				continue;
			}
			if( $info['searchTitle'] === false){
				continue;
			}
			$this->useTables[$space] = true;
			
			//create selectSearchTitle
			$dbInfo[$space]['selectSearchTitle'] = ' CONCAT(';
			foreach($info['searchTitle'] as $value){
				$dbInfo[$space]['selectSearchTitle'] .= $info['dbTable'].'.`'.$value.'`, ';
			}
			$dbInfo[$space]['selectSearchTitle'] .= '"" )';
			
			//create selectSearchTitle
			if( isset($info['searchContent']) && is_array($info['searchContent']) ){
				$dbInfo[$space]['selectSearchContent'] = ' CONCAT(';
				foreach($info['searchContent'] as $value){
					//skip keywords if set, because they're in `all_files`
					if( $value == 'keywords' ){
						continue;
					}
					$dbInfo[$space]['selectSearchContent'] .= $info['dbTable'].'.`'.$value.'`, ';
				}
				$dbInfo[$space]['selectSearchContent'] .= $wbTables['all_files'].'.`keywords`, ';
				$dbInfo[$space]['selectSearchContent'] .= '"" )';
			}
		}
		
		$this->queryAllFiles();
		$this->query .= ' AND '.$wbTables['all_files'].'.`visible` = 1 ';//deleted, hidden, redirect and relvisible flags
		
		$this->query .= ' ORDER BY '.$wbTables['all_files'].'.`file_id` ASC '; //I don't know why, but EXPLAIN is showing a FILESORT
		$this->browse($langA['search_options']);
	}
	
	function setLinks(&$currentPageNum,&$rowsFound,&$tabLabel){
		$this->currLabel = $tabLabel;
	}
	function displayNumbers(&$from,&$to,&$rowsFound,&$prev,&$next){
		global $langA;
		$this->toOffset = $to;
		$this->fromOffset = $from;
		$this->rowsFound = $rowsFound;
	}
	
	function displayPre(){}
	function abbrevOutput(&$row){
		global $dbInfo,$wbTables;
		$this->queryAllResult($row);
		
		// so from each space i need to select some specific things for this step
		//	the title and content to be put in the search database
		//
		
		//	GETTING THE SEARCHABLE TEXT
		//		1)	strip_tags()
		//		2)	MySQL: A ``word'' is any sequence of characters consisting of letters, digits, `'', and `_'
		//			...The default minimum length of words that will be found by full-text searches is four characters
		//
		
		$row['selectSearchContent'] = allSearch::cleanText($row['selectSearchContent']);
		
		$insertA['file_id'] =& $row['file_id'];
		$insertA['all_title'] = toDisplay($row['selectSearchTitle']);
		$insertA['all_content'] =& $row['selectSearchContent'];
		
		$query = 'INSERT IGNORE INTO '.$wbTables['all_search'].' SET'; 
		$query .= wbDB::toSet($insertA,true);
		wbDB::runQuery($query);

		//echo '<p>';
		//echo $query;
		//echo showArray($row);
		//echo '</p>';
	}
	function displayEmpty(){
		return true;
	}

	function displayPost(&$prev,&$pages,&$next){
		global $langA;
		
		$maxTime = 7;
		$duration = microtime_diff($this->startTime, microtime());
		$timePerRow = $duration/$this->rowLimit;
		$nextLimit = floor($maxTime/$timePerRow);
		
		echo '<div style="width:40em;margin-right:auto;margin-left:auto">';
		if( $this->toOffset < $this->rowsFound){
			echo '<p>';
			echo wbLang::text('FINISHED_ENTRIES','<b>'.$this->toOffset.'</b>','<b>'.($this->rowsFound-$this->toOffset).'</b>');
			echo '</p>';
			echo '<p>';
			echo wbLinks::admin('SearchOptions?cmd=enable&offset='.$this->toOffset.'&limit='.$nextLimit,$langA['continue']);
			echo '</p>';
		}else{
			$this->enableFinish();
		}
		echo '</div>';
	}
	
	function enableFinish(){
		global $langA, $wbTables,$wbConfig;
		message('SEARCH_IS_ENABLED');
		
		// Doesn't work
		// $query = 'ALTER TABLE '.$wbTables['all_search'].' ENABLE KEYS';
		// wbDB::runQuery($query);
		
		$this->updateConfig(true);
		$this->defaultDisplay();
		
	}
	
	function updateConfig($bool){
		global $wbTables;
		
		$this->enabled = $bool;
		//Update Config
		$query = 'SELECT revision, data FROM '.$wbTables['config'].' ORDER BY revision DESC LIMIT 1'; 
		$result = wbDB::runQuery($query);
		$row = mysql_fetch_assoc($result);
		$configData = unserialize($row['data']);
		$revision =& $row['revision'];
		
		$configData['wbConfig']['search'] = $bool;
		$serialized = serialize($configData);
		$query = 'UPDATE '.$wbTables['config'].' SET `modified`=`modified`, `data`="'.wbDB::escape($serialized).'"';
		$query .= ' WHERE `revision` = '.$revision;
		if( !wbDB::runQuery($query) ){
			message('<b>Error Updating Configuration</b>');
		}
	}
	
}

new searchOptions();