<?php

//	Can I just update the database?
//		..no! because the primary key for `pages` won't be right .. we'll get a duplicate entry for `file_id`
//



class to11 extends fromSkeleton{
	var $MySQL41;

	function to11($updateObj=null,$versionNum=null){
		$this->updateObj = $updateObj;
		$this->versionNum = $versionNum;
	}

	
	function go($MySQL41){
		$this->MySQL41 = $MySQL41;
		
		$_GET += array('cmd'=>'');
		switch( $_GET['cmd']){
			case 'start':
				$this->alterHistoryTable();
				message('<a href="?cmd=second">Second</a>');
			break;
			
			case 'second':
				$this->done = true;
			break;
			
			
			default:
				message('<a href="?cmd=start">Start</a>');
			break;
		}
	}
	
	function alterHistoryTable(){
		global $dbInfo;
		
		//A
		//		`file_id`,`revision` will be changed later.. need primary key and auto_increment
		//
		$query = 'CREATE TABLE '.$wbTables['all_history'].' ( ';
		$query .= ' `file_id` int(8) unsigned NOT NULL default \'0\', ';
		$query .= ' `revision` smallint(6) unsigned NOT NULL, ';
		$query .= '`modified` timestamp NOT NULL default \'0000-00-00 00:00:00\', ';
		$query .= ' `instructions` blob NOT NULL, ';
		$query .= '	`username` varchar(20) default NULL, ';
		$query .= ' `ip` varchar(15) NOT NULL default \'\', ';
		$query .= ' `summary` varchar(200) default NULL ';
		$query .= '	) ENGINE=MyISAM ';
		if( $this->MySQL41 ){
			$query .= ' DEFAULT CHARSET=utf8';
		}
		$result = wbDB::runQuery($query);
		if( !$result ){
			message($query. '<br/>'.mysql_error());
			return false;
		}
		
			
		foreach($dbInfo as $info){
			if(!isset($info['dbHistoryTable'])){
				continue;
			}
			
			//A
			//Insert into all_history
			//
			$query = 'INSERT INTO '.$wbTables['all_history'];
			$query .= ' SELECT '.$info['dbTable'].'.`file_id`, ';
			$query .=  ' '.$info['dbHistoryTable'].'.`revision`, ';
			$query .=  ' '.$info['dbHistoryTable'].'.`modified`, ';
			$query .=  ' '.$info['dbHistoryTable'].'.`instructions`, ';
			$query .=  ' '.$info['dbHistoryTable'].'.`username`, ';
			$query .=  ' '.$info['dbHistoryTable'].'.`ip`, ';
			$query .=  ' '.$info['dbHistoryTable'].'.`summary` ';
			//
			$query .= ' FROM '.$info['dbHistoryTable'].' INNER JOIN '.$info['dbTable'];
			$query .= ' on ';
			$whereA = array();
			foreach($info['keys'] as $key => $null){
				$whereA[]= $info['dbTable'].'.`'.$key.'` = '.$info['dbHistoryTable'].'.`'.$key.'` ';
			}
			$query .= implode(' AND ',$whereA);
			$query .= ' AND '.$info['dbTable'].'.`file_id` IS NOT NULL  ';
			$result = wbDB::runQuery($query);
			if( !$result){
				message($query. '<br/>'.mysql_error());
				return false;
			}


			//B
			//Delete old history table
			$query = 'DROP TABLE '.$info['dbHistoryTable'];
			wbDB::runQuery($query);
		}
	}
}

