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

global $page,$dbInfo,$pageOwner,$dbObject;
$page->regLink('Create Plugin','/Admin/'.$pageOwner['username'].'/CreatePlugin');
$page->regLink('Data Types','/Admin/'.$pageOwner['username'].'/ManageTypes');
$page->displayTitle = 'Update Plugin';

if( !isAdmin() ){
	$page->contentA[$page->displayTitle] = 'You must be an administrator to access this page.';
	return;
}

includeFile('admin/PluginCreateTool.php');

class updatePlugin extends createPluginTool{
	var $pluginClass;
	
	function updatePlugin(){
		global $page;
		
		$this->createPluginTool();
		
		switch($page->userCmd){
			case 'update':
				$this->doUpdate();
			break;
			
			case 'check':
				if( $this->checkAll(false) ){
					message('Your plugin is ready for update.');
				}
			default:
				$this->editForm();
			break;
		}
	}
	
	
	function initiateEdit(){
		$_GET += array('plugin'=>'');
		if( empty($_GET['plugin']) ){
			message('INVALID_REQUEST');
			return false;
		}
		
		$this->pluginClass = wbData::getClass($_GET['plugin'],true);
		if( !is_callable(array($this->pluginClass,'creationvalues')) ){
			message('Sorry, the creation values were not saved for this data type.');
			return false;
		}
		return call_user_func(array($this->pluginClass,'creationvalues'));
	}
	
	function editForm(){
		global $page,$dbObject,$dbInfo,$pageOwner;
		
		if( isset($_POST['plugin']) ){
			$args =& $_POST;
		}else{
			$args = $this->initiateEdit();
		}
		if( !$args ){
			return;
		}
	
		
		$page->regLink('Update Plugin','/Admin/'.$pageOwner['username'].'/UpdatePlugin?plugin='.$args['plugin']);
		$page->autoForm = true;
		
		ob_start();
		
		$this->form($args,false);
		$page->contentA['Update Plugin'] = wb::get_clean();
	}
	function formSubmit(){
		echo '<div style="text-align:right">';
		echo ' <input type="submit" name="cmd" value="Check" />';
		echo ' &nbsp; ';
		echo ' <input type="submit" name="cmd" value="Update" />';
		echo '</div>';
		
	}
	function doUpdate(){
		global $dbInfo;
		if( !$this->checkAll(false) ){
			return;
		}
		$nameSpace = toStorage($_POST['plugin']);
		
		if( !isset($dbInfo[$nameSpace]) ){
			message('INVALID_REQUEST');
			return false;
		}
		if( !isset($dbInfo[$nameSpace]['class']) ){
			message('INVALID_REQUEST');
			return false;
		}
		
		if( !isset($dbInfo[$nameSpace]['dbTable']) ){
			message('INVALID_REQUEST');
			return false;
		}
		
		$this->tableName = substr($dbInfo[$nameSpace]['dbTable'],1,-1); //remove ` from beginning and end of tablename
		$this->className = $dbInfo[$nameSpace]['class'];
		
		$this->createScripts($nameSpace);
		$this->addToDB($nameSpace);
	}
}

new updatePlugin();

