<?php
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//					Task Manager
//


	class taskManager{
		var $tables = array();
		var $buffer = '';
		var $AtPlugin = false;
		
		function run(){
			global $wbMaintain;
			wbDB::connect();
			wbData::getConfig();
			
			
			if( is_array($wbMaintain) ){

				$this->all();
			}
		}
		
		function all(){
			
			includeFile('tool/Variables.php');
			$this->AtPlugin = wbVariables::get('AtPlugin');
			
			$this->setTables();
			if( !$this->plugins() ){
				return false;
			}
			
			//$this->deleteBackup();
			$this->maintainConfig();
			$this->emptyTrash();
			$this->checkTables();
			//$this->cleanUser();
			
			return true;
		}
		
		function plugins(){
			global $wbTables,$rootDir,$wbPluginDir;
			
			
			if( empty($this->AtPlugin) ){
				$next = true;
			}else{
				$next = false;
			}
			
			
			$query = 'SELECT `data`, `selector` FROM '.$wbTables['ad_objects'];
			$query .= ' WHERE `selector` LIKE "maintenance:%" ';
			$result = wbDB::runQuery($query);
			while($row = mysql_fetch_assoc($result)){
				
				$thisPluginDir = substr($row['selector'],'12');
				$wbPluginDir = $thisPluginDir;
				
				//run the next plugin script
				if( $next ){
					message('Running scheduled tasks for '.$thisPluginDir);
					$wbPluginDir = $thisPluginDir;
					pluginIncludeFile($row['data']);
					$wbPluginDir = false;
					wbVariables::set('AtPlugin',$thisPluginDir);
					return false;
					
				}elseif( $this->AtPlugin == $thisPluginDir ){
					
					$next = true;
					
				}
			}
			
			wbVariables::set('AtPlugin','');
			return true;
		}
		
		//do all tables with prefix
		function setTables(){
			global $wbTablePrefix;
			
			$query = 'SHOW TABLE STATUS ';
			if( !empty($wbTablePrefix) ){
				$query .= ' LIKE "'.wbDB::like($wbTablePrefix).'%"';
			}
			$result = wbDB::runQuery($query);
			while($row = mysql_fetch_assoc($result)){
				$this->tables[$row['Name']] = '`'.$row['Name'].'`';
			}			
		}
		
		//delete files used for database backup
		function deleteBackup(){
			global $wbUniq,$rootDir;
			$tmpFile = $rootDir.'/userfiles/backup.'.$wbUniq.'.tmp';
			$fp = fopen($tmpFile,'wb');
			fclose($fp);
			unlink($tmpFile);
			message('Deleted Backup.');
		}
		
		//
		//	Delete from tables
		//
		function emptyTrash(){
			global $wbTables,$dbInfo,$wbNow;
			
			//
			//	find old files in the trash
			//	
				$query = 'SELECT `file_id` FROM '.$wbTables['all_files'];
				$query .= ' WHERE FIND_IN_SET("deleted", flags) AND ';
				$query .= ' (ADDDATE('.$wbTables['all_files'].'.modified,INTERVAL 30 DAY) < "'.$wbNow.'" ) ';
				$result = wbDB::runQuery($query);
				
				$list = array();
				while($row = mysql_fetch_assoc($result)){
					$list[] = $row['file_id'];
				}
				
				includeFile('tool/emptyTrash.php');
				emptyTrash($list);
				
			
			//
			//	Delete the corresponding entries in content tables
			//
				$tables = array();
				$tables[] = $wbTables['all_history'];
				$tables[] = $wbTables['all_search'];
				$tables[] = $wbTables['all_links'];
				foreach($dbInfo as $space => $info){
					if( !isset($info['dbTable']) ){
						continue;
					}
					$tables[] = $info['dbTable'];
				}
				
				foreach($tables as $table){
					$query = 'DELETE ';
					$query .= $table;
					$query .= ' FROM ';
					$query .= $table.' LEFT JOIN '.$wbTables['all_files'];
					$query .= ' USING(`file_id`) ';
					$query .= ' WHERE '.$wbTables['all_files'].'.`file_id` IS NULL ';
					wbDB::runQuery($query);
				}
				
			message('Trash Purged.');
		}
		
		//
		//	check tables
		//
		function checkTables(){
			global $wbTables,$dbInfo,$wbTablePrefix;

			$query = ' CHECK TABLE '.implode(',',$this->tables);
			wbDB::runQuery($query);
			message('Tables Checked.');

			//should only do this once a week
			//	'0' (Sunday)
			//	'6' (Saturday)
			if( date('w') == '0'){
				$query = ' OPTIMIZE TABLE '.implode(',',$this->tables);
				wbDB::runQuery($query);
				message('Tables Optimized.');
			}
		}
		
		function maintainConfig(){
			global $dbInfo,$wbTables,$wbNow;
			
			$newVersion = $this->checkVersion();
			
			$query = 'SELECT `revision`, `data` FROM '.$wbTables['config'];
			$query .= ' ORDER BY revision DESC LIMIT 1'; 
			$result = wbDB::runQuery($query);
			$row = mysql_fetch_assoc($result);
			$data = unserialize($row['data']);
			if( $newVersion ){
				$data['wbConfig']['newVersion'] = $newVersion;
			}else{
				unset($data['wbConfig']['newVersion']);
			}
			
			$query = 'UPDATE '.$wbTables['config'].' SET ';
			$query .= ' `modified` = `modified` ';
			$query .= ' ,`maintained` = "'.$wbNow.'" ';
			$query .= ' , `data` = "'.wbDB::escape(serialize($data)).'" ';
			$query .= ' WHERE `revision` = '.$row['revision'];
			wbDB::runQuery($query);
			
			message('Configuration Updated.');
		}
		
	
		/////////////////////////////////////////////////////////
		//
		//		Check For New Version
		//
		function checkVersion(){
			global $serverName4,$packageVersion;
			
			//$host = 'wikyblog.loc';
			$host = 'www.wikyblog.com';
			$path = '/special/main/info?xml=true';
			
			$newLine = "\r\n";
			$errNum=null;
			$errString=null;
			
			$handle = @fsockopen($host,'80',$errNum,$errString,3);
			if( !$handle){
				return;
			}
			
			$xml = '<?xml version="1.0"?><methodCall><methodName>checkVersion</methodName>';
			$xml .= '<params>';
			$xml .= '<param><value>';
			$xml .= $serverName4;
			$xml .= '</value></param>';
			$xml .= '</params></methodCall>';
			
			$request = 'GET '.$path.' HTTP/1.0'.$newLine;
			$request .= 'User-Agent: WikyBlog Version Checker'.$newLine;
			$request .= 'Host: '.$host.$newLine;
			$request .= 'Accept: text/xml'.$newLine;
			$request .= $newLine.$newLine;
			
			fputs($handle, $request);
			
			$gotFirstLine = false;
			$gettingHeaders = true;
			$contents = '';
			while (!feof($handle)) {
				$line = fgets($handle, 4096);
				if (!$gotFirstLine) {
					// Check line for '200'
					if (strstr($line, '200') === false) {
						return false;
					}
					$gotFirstLine = true;
				}
				if (trim($line) == '') {
					$gettingHeaders = false;
				}
				if (!$gettingHeaders) {
					$contents .= trim($line)."\n";
				}
			}
			
			$pos = strpos($contents,'<version>');
			if( !$pos ){
				return false;
			}
			$version = substr($contents,$pos+9);
			$pos = strpos($version,'</version>');
			$version = substr($version,0,$pos);
			
			message('Checked Version');

			if( version_compare($version,$packageVersion,'>') ){
				return $version;
			}else{
				return false;
			}
			
		}
		
	}
	
	
//
//					Scheduled Task Manager
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//					
//
	
	
	if( !defined('WikyBlog') ){
		$autoStart = false;
		require_once('../../wiki.php');
		require_once('../wiki2.php');
		$manager = new taskManager();
		$manager->run();
	}
	
	
