<?php
/*

need to update the database first!

*/


class to171 extends fromSkeleton{
	var $MySQL41;

	function to171($updateObj=null,$versionNum=null){
		$this->updateObj = $updateObj;
		$this->versionNum = $versionNum;
	}
	
	function go($MySQL41){
		$this->done = false;
		$this->MySQL41 = $MySQL41;
		
		
		$_GET += array('cmd'=>'');
		switch( $_GET['cmd']){
			
			case 'start':
				if( !$this->start() ){
					message('The first step was not successful');
					message('<a href="?cmd=start">Try Again</a>');
					return;
				}
				message('<a href="?cmd=end">Finish</a>');
			break;
			
			case 'end':
				$this->done = true;
			break;
			
			default:
				message('<a href="?cmd=start">Start</a>');
			break;
		}
	}
	
	
	function start(){
		global $wbTables, $dbInfo, $wbAdminUser;
		
		//change `summary` to `restricted`
		$test = $GLOBALS['wbConfig']['version'];
		if( version_compare($test, '1.7.1b2', '<') ){
			
			$query = 'SELECT * FROM '.$wbTables['users'].' LIMIT 1;';
			$result = wbDB::runQuery($query);
			$row = mysql_fetch_assoc($result);
			if( array_key_exists('summary',$row) ){
				
				$query = 'ALTER TABLE '.$wbTables['users'].' CHANGE `summary` `restricted` VARCHAR(255) NULL';
				if( !wbDB::runQuery($query) ){
					return false;
				}
			}
		}
		
		
		$this->updateDB();
		
		
		//add admin flags to `users` table
		$query = 'SELECT `flags`, `user_id` ';
		$query .= ' FROM '.$wbTables['workgroup'].' JOIN '.$wbTables['users'].' ON `username` = `owner` ';
		$query .= '	WHERE `userlevel` = 5 ';
		$result = wbDB::runQuery($query);
		if( !$result ){
			return false;
		}
		while( $row = mysql_fetch_assoc($result) ){
			$flags = explode(',',$row['flags']);
			$flags[] = 'admin';
			$flags = array_unique($flags);
			$flags = array_diff($flags,array(''));
			
			$query = 'UPDATE '.$wbTables['users'];
			$query .= ' SET ';
			$query .= ' `flags` = "'.wbDB::escape(implode(',',$flags)) .'" ';
			$query .= ' , `modified` = `modified` ';
			$query .= ' WHERE ';
			$query .= ' `user_id` = '.$row['user_id'];
			if( !wbDB::runQuery($query) ){
				return false;
			}
		}
		
		$query = 'DELETE FROM '.$wbTables['workgroup'];
		$query .= ' WHERE `userlevel` = 5';
		if( !wbDB::runQuery($query) ){
			return false;
		}		
		
		//add admin flags for adminuser
		$query = 'UPDATE '.$wbTables['users'];
		$query .= ' SET ';
		$query .= ' `flags` = '.wbDB::add_to_set('admin','`flags`');
		$query .= ' , `modified` = `modified` ';
		$query .= ' WHERE ';
		$query .= ' `username` = "'.wbDB::escape(toStorage($wbAdminUser)).'" ';
		if( !wbDB::runQuery($query) ){
			return false;
		}
		
		
		//Update `workgroup` table
		$query = 'UPDATE '.$wbTables['workgroup'].' SET ';
		$query .= ' `type` = IF( LOCATE(".",`guest`) > 0, "ip","username") ';
		$result = wbDB::runQuery($query);
		if( !$result ){
			return false;
		}
		
		return true;
	}
}