<?php
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// 				Start Upgrade
//
//		need authentication

	$autoStart = false;
	@set_time_limit(30);
	require_once('../../wiki.php');
	require_once('../wiki2.php');
	@ini_set( "display_errors", true ); //overwrite
	error_reporting( E_ALL );
	restore_error_handler();

	includeFile('maintenance/Versions.php');

	$upgrade = new upgradeSoftware();
	class upgradeSoftware{
		var $done = false;
		var $MySQL41 = false;
		
		function upgradeSoftware(){
			global $packageVersion;
			wbDB::connect();
			

			
			ob_start();
			wbData::getConfig(true);
			
			
			// Which Mysql Version
			//
			$query = 'SHOW VARIABLES LIKE "VERSION"';
			$result = wbDB::runQuery($query);
			$row = mysql_fetch_assoc($result);
			if( version_compare($row['Value'],'4.1','>=') ){
				//message('MySQL 4.1 or greater was found.');
				$this->MySQL41 = true;
			}
			
	
			session_cache_expire(30);
			session_start();
			$_POST += array('cmd'=>'');
			if( $_POST['cmd'] == 'Log In'){
				$this->login();
			}
			
			includeFile('admin/CheckPrivs.php');
			if( !checkPrivs::isGranted() ){
				
			}elseif( !isset($_SESSION['maintenance']) ){
				$this->loginForm();
			}else{
				$this->upgradeRun();
			}
			
			
			$text = wb::get_clean();
			echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><TITLE>WikyBlog Upgrade</TITLE></HEAD>';
			echo '<body>';
			echo '<h2>Upgrade WikyBlog</h2>';

			echo returnMessages(false);
			echo $text;
			
		}
		
		function upgradeRun(){
			global $packageVersion,$wbDirPrefix;
			
			if( empty($GLOBALS['wbConfig']['version']) ){
				echo 'Please download and upgrade to version 0.11 before trying to upgrade to '.$packageVersion.'.';
				return;
			}
			if(version_compare($GLOBALS['wbConfig']['version'],'0.11','<')){
				echo 'Please download and upgrade to version 0.11 before trying to upgrade to '.$packageVersion.'.';
				return;
			}

			
			if(version_compare($GLOBALS['wbConfig']['version'],$packageVersion,'eq')){
				echo 'This software appears to be up to date.';
				echo ' ... <a href="'.$wbDirPrefix.'/">Home</a>';
				return;
			}
			
			
			// 			has to be updated from V0.11
			// $scripts['1.0'] = array('to1.0.php','to10');
			// $scripts['1.1'] = array('to1.1.php','to11');
			// $scripts['1.2.1'] = array('','fromSkeleton');
			// $scripts['1.3'] = array('to1.3.php','to13');
			// $scripts['1.4.0'] = array('to1.4.php','to14');
			$scripts = versions::getVersions();
			
			end($scripts);
			$latestVersion = key($scripts);
			
			
			reset($scripts);
			foreach($scripts as $versionNum => $data){
				if( !is_array($data) ){
					continue;
				}
				if(version_compare($versionNum,$GLOBALS['wbConfig']['version'],'<=')){
					continue;
				}
				if( $versionNum !== $latestVersion ){
					message('<b>Warning:</b> You should update to version '.$versionNum.' before updating to '.$latestVersion.' version.<p>You can download version '.$versionNum.' from <a href="http://sourceforge.net/project/showfiles.php?group_id=148518&package_id=163821">SourceForge</a>.');
					return;
				}
				
				if( !empty($data[0]) ){
					includeFile('maintenance/'.$data[0]);
				}
				if( empty($data[1]) ){
					trigger_error('No class defined');
					die();
				}
				
				$updateClass = new $data[1]($this,$versionNum);
				$updateClass->header();
				$updateClass->go($this->MySQL41);
				
				$this->done = $updateClass->done;
				
				if( $this->done ){
					message('<h3>Checking MySQL Database</h3>');
					$this->updateDB();
				}
				if( $this->done ){
					$this->finish($versionNum);
				}
				return;
			}
		}
		function continueLink($array=array(),$label='Continue'){
			$linkA = array();
			foreach($array as $key => $value){
				$linkA[]=$key.'='.$value;
			}
			message('<a href="?'.implode('&',$linkA).'" accesskey="c" title="Continue [alt-c]">'.$label.'</a>');
			
		}
		function updateDB(){
			global $wbTablePrefix;

			includeFile('installDB.php');
			$alterDb = new dbAlter();
			$done = $alterDb->go($wbTablePrefix);

			//update links while we're at it
			includeFile('admin/ConfigLinks.php',false);
			ConfigLinks::setDefaults();
			
			$this->done = $this->done && $done;
		}
		
		function finish($version){
			global $wbTables, $packageVersion;
			
			$query = 'UPDATE '.$wbTables['config'].' SET `modified`=`modified`, `version`="'.wbDB::escape($packageVersion).'"';
			message($query);
			$done = @mysql_query($query);
			
			if( $done ){
				message('Finished upgrading to version '.$packageVersion);
			}else{
				message('Problem upgrading to version '.$packageVersion);
			}
			$this->continueLink();
			return;
		}
		
		
		function loginForm(){
			$_POST += array('username'=>'username');
			echo '<form method="post">';
			echo '<div style="padding-top:4em;text-align:center">';
			echo '<table border=0 style="margin-left:auto;margin-right:auto;">';
			echo '<tr><td colspan="2"><h3>Admin Login</h3></td></tr>';
			echo '<tr><td colspan="2">'.returnMessages().'</td></tr>';
			echo '<tr><td>Username:</td><td> <input size="12" type="text" name="username" value="'.wbHtmlspecialchars($_POST['username']).'" class="input" /></td></tr>';
			echo '<tr><td>Password:</td><td> <input size="12" type="password"	name="password" value="" class="input" /></td></tr>';
			
			echo '<tr><td></td><td><input type="submit" name="cmd" value="Log In" /></td></tr>';
			
			echo '<tr><td colspan="2" style="font-size:80%;padding-top:3em;">To upgrade the WikyBlog software, please enter<br/> the administrator\'s username and password.</td></tr>';
			echo '</table>';
			echo '<div style="margin-top:5em;"><b>Always backup your data before performing a software update.</b></div>';
			echo '</div>';
			echo '</form>';
			
		}
		function login(){
			global $wbTables;
			
			$query = 'SELECT username FROM '.$wbTables['users'].' ';
			$query .= ' WHERE username = "'. wbDB::escape($_POST['username']) .'" ';
			$query .= ' AND password = "'. md5($_POST['password']) .'" ';
			$query .= ' LIMIT 1 OFFSET 0';
			$result = wbDB::runQuery($query);
			$num = mysql_num_rows($result);
			if( $num === 1){
				message('Logged In');
				$_SESSION['maintenance'] = true;
				return true;
			}else{
				message('Log In Failed');
				return false;
			}
		}
		
// 		function updateConfig(){
// 			global $wbTables;
// 			
// 			$query = 'SELECT revision, data FROM '.$wbTables['config'].' ORDER BY revision DESC LIMIT 1'; 
// 			$result = @mysql_query($query); //use mysql_query here because I don't want to report any errors here
// 			if( !$result ){
// 				echo 'Please download and upgrade to version 0.7 before trying to upgrade to '.$packageVersion.'.';
// 				return;
// 			}
// 			
// 			$row = mysql_fetch_assoc($result);
// 			$temp = unserialize($row['data']); // serialize is faster than exec()
// 		
// 			//neither of these merging operations works for some reason
// 			//$GLOBALS = $temp + $GLOBALS;
// 			//$GLOBALS = array_merge($GLOBALS,$temp);
// 			foreach($temp as $key => $value){
// 				$GLOBALS[$key] = $value;
// 			}
// 			
// 			
// 			$_GET += array('cmd'=>'');
// 			if( $_GET['cmd'] === 'updateconfig'){
// 				$this->updateDB();
// 				$query = 'UPDATE '.$wbTables['config'].' SET `modified`=`modified`, `version`="'.wbDB::escape($GLOBALS['wbConfig']['version']).'"';
// 				message($query);
// 				$this->done = @mysql_query($query);
// 			}
// 			
// 			if( !$this->done ){
// 				$this->continueLink(array('cmd'=>'updateconfig'),'Update Database Structure');
// 			}else{
// 				$this->continueLink(array(),'Continue');
// 			}
// 				
// 		}
		
	}
	
	//
	//
	//
	////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//		fromSkeleton
	//
	
	class fromSkeleton{
		var $updateObj;
		var $done = false;
		var $versionNum;
		
		function fromSkeleton($updateObj,$versionNum){
			$this->updateObj = $updateObj;
			$this->versionNum = $versionNum;
		}
		function header(){
			message('<h3>Upgrading to Version '.$this->versionNum.'</h3>');
		}
		
			
		function go(){
			
			$_GET += array('cmd'=>'');
			switch( $_GET['cmd']){
				case 'start':
					if( $this->updateDB() ){
						$this->done = true;
						return;
					}
				default:
					message('<a href="?cmd=start">Start</a>');
				break;
			}
		}
		
		//
		function updateDB(){
			global $wbTablePrefix;
			$done = true;

			includeFile('installDB.php');
			$alterDb = new dbAlter();
			
			$done = $alterDb->go($wbTablePrefix);
			
			
			return $done;
		}
	}