<?php

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



includeFile('admin/PluginAdd.php');

class adminPlugins extends pluginAdd{
	var $available = array();
	var $installed = array();
	var $installedInfo = array();
	var $pluginDir;
	var $scriptName = 'plugins';
	
	
	//used during installation
	var $existingTables = false;
	var $installAs = false;
	
	function adminPlugins(){
		global $page,$rootDir,$langA,$pageOwner,$dbObject;
		
		$contentUri = $page->regLink('Manage Plugins','/Admin/'.$pageOwner['username'].'/Plugins');
		$page->regLink('Plugin SQL','/Admin/'.$pageOwner['username'].'/PluginSQL');
		$page->regLink('?','Manage Plugins?en=Manage_Plugins');
		$page->displayTitle = 'Manage Plugins';
		$page->autoForm = true;		
		
		
		$this->pluginDir = $rootDir.'/plugins';
		
		includeFile('admin/CheckPrivs.php');
		if( !checkPrivs::isGranted() ){
			return;
		}
		
		
		ob_start();
		$this->getPlugins();
		
		switch( $page->userCmd ){
			case 'upgrade':
				$this->upgrade();
			break;
			case 'confirm upgrade':
				$this->upgradeConfirm();
				$this->show();
			break;
			
			
			case 'check code':
				$this->checkAllCode();
				$this->show();
			break;
			case 'install':
				$this->install();
			break;
			case 'checkfile':
				$this->checkFile();
			break;
			
			case 'confirm install':
				$this->confirmedInstall();
			break;
			
			
			case 'remove':
				if( !$this->removePlugin() ){
					$this->show();
				}
			break;
			
			case 'confirm removal':
				$this->removeConfirm();
			break;
			
			case 'view tables':
				$this->viewTables();
			break;
			
			case 'links':
				$this->pluginLinks();
			break;
			
			
			default:
				$this->show();
			break;
			
		}
		
		$page->contentB[$contentUri] = wb::get_clean();
	}
	
	
	////////////////////////////////////////////////////////////////////////////////
	//
	//		Plugin Information
	//
	function pluginLinks($plugSpace = false){
		global $dbInfo,$page,$wbTables;
		$hasLinks = false;
		$controlPanelLinks = false;
		
		
		if( $plugSpace === false ){
			$plugSpace = $page->cmdArg[0];
		}
		
		if( !isset($dbInfo[$plugSpace]) ){
			message('INVALID_REQUEST');
			return;
		}
		
		includeFile('special/ControlPanel.php',false);
		$page->displayTitle .= ' > '.$plugSpace;
		
		
		//class link
		if( isset($dbInfo[$plugSpace]['class']) ){
			echo '<div style="text-align:right" class="sm">';
			echo wbLinks::admin('Plugins?refresh','back');
			echo '</div>';
			echo '<fieldset style="padding:9px;margin-top:1em;">';
			echo '<legend>Namespace Link</legend>';
			echo '<span class="sm">This plugin created a namespace. You may want to ';
			echo wbLinks::admin('ManageTypes','change the settings').' for this namespace.</span><br/>';
			echo wbLinks::local('/'.$plugSpace,$plugSpace);
			$hasLinks = true;
			echo '</fieldset>';
		}
		
		//special links
		$query = 'SELECT * FROM '.$wbTables['config_links'];
		$query .= ' WHERE ';
		$query .= ' `userlevel` < 5 ';
		$query .= ' AND `plugin_space` = "'. wbDB::escape($plugSpace) .'" ';
		$query .= ' ORDER BY `order_group`, `order_link` ';
		$result = wbDB::runQuery($query);
		if( mysql_num_rows($result) > 0 ){
			echo '<div style="text-align:right" class="sm">';
			echo wbLinks::admin('Plugins?refresh','back');
			echo '</div>';
			echo '<fieldset style="padding:9px;margin-top:1em;">';
			echo '<legend>Control Panel</legend>';
			echo '<span>The following links are available to users. ';
			echo 'You can '.wbLinks::Admin('ConfigLinks','rearrange these links').' on the Control Panel.';
			echo '</span>';
			
			cPanel::showResult($result);
			
			$hasLinks = true;
			$controlPanelLinks = true;
			echo '</fieldset>';
		}

		//admin links
		$query = 'SELECT * FROM '.$wbTables['config_links'];
		$query .= ' WHERE ';
		$query .= ' `userlevel` = 5 ';
		$query .= ' AND `plugin_space` = "'. wbDB::escape($plugSpace) .'" ';
		$query .= ' ORDER BY `order_group`, `order_link` ';
		$result = wbDB::runQuery($query);
		if( mysql_num_rows($result) > 0 ){
			echo '<div style="text-align:right" class="sm">';
			echo wbLinks::admin('Plugins?refresh','back');
			echo '</div>';
			echo '<fieldset style="padding:9px;margin-top:1em;">';
			echo '<legend>Administration Control Panel</legend>';
			echo '<span>The following links are available to the administrator. ';
			echo 'You can '.wbLinks::Admin('ConfigLinks','rearrange these links').' on the Control Panel.';
			echo '</span>';
			
			cPanel::showResult($result);
			
			$hasLinks = true;
			$controlPanelLinks = true;
			echo '</fieldset>';
		}
		
		if( !$hasLinks){
			message('This plugin does not appear to have any links.');
			return;
		}
		
		
		echo '<div style="text-align:right" class="sm">';
		echo wbLinks::admin('Plugins?refresh','back');
		echo '</div>';
		
		if( $controlPanelLinks ){
			echo '<div class="WBsearchFooter">';
			echo '<ul>';
			echo '<li>You can '.wbLinks::Admin('ConfigLinks','rearrange special and admin links').' on the Control Panel.</li>';
			echo '</ul>';
			echo '</div>';			
		}
		
	}
	
	function viewTables(){
		global $dbInfo,$page;
		
		//get sqlFile
		$plugDir = $page->cmdArg[0];
		$sqlFile = $this->pluginDir.'/'.$plugDir.'/sql.php';
		if( !is_file($sqlFile) ){
			$sqlFile = false;
		}
		
		if( !$sqlFile ){
			message('This plugin doesn\'t have a table structure.');
			return;
		}
		
		
		
		require($sqlFile);
		if( !isset($dbData) ){
			message('Invalid sql.php file. Consult the plugin developer for more information.');
			return;
		}
		echo '<a name="WB_TOP"></a>';
		echo '<p>';
		echo 'The table structure for '.$plugDir;
		echo '<div style="text-align:right" class="sm">';
		echo wbLinks::admin('Plugins?refresh','back');
		echo '</div>';
		echo '</p>';
		
		$sqlData = unserialize($dbData);
		foreach($sqlData as $table => $info){
			echo '<fieldset style="padding:1em">';
			echo '<legend>Table: '.$table.'</legend>';
			echo showArray($info);
			echo '</fieldset>';
			echo '<div style="text-align:right" class="sm">';
			echo '<a href="#WB_TOP">Top</a>';
			echo ' - ';
			echo wbLinks::admin('Plugins?refresh','back');
			echo '</div>';
		}
	}
	
	//This should just update the current config..
	function saveConfig(){
		global $wbTables;
		
		$query = 'SELECT revision, modified, data FROM '.$wbTables['config'].' ORDER BY revision DESC LIMIT 1'; 
		$result = wbDB::runQuery($query);
		$row = mysql_fetch_assoc($result);
		$data = unserialize($row['data']);
		$revision = $row['revision'];
		
		//Update
		$serialized = serialize($data);
		if( $serialized == $row['data'] ){
			return;
		}
		
		$query = 'UPDATE '.$wbTables['config'].' SET `modified`=`modified`, `data`="'.wbDB::escape($serialized).'"';
		$query .= ' WHERE `revision` = '.$revision;
		$num = wbDB::runQuery($query,true);
		if( $num < 1){
			message('<b>Warning</b> This configuration was not updated.');
		}else{
			message('Your configuration has been updated.');
		}
		
	}
	
	///////////////////////////////////////////////////////////////////////////
	//
	//	Upgrade
	//
	function upgrade(){
		global $page,$dbInfo;
		$page->css2 = true;
		
		$space = $page->cmdArg[0];
		$plugDir = $dbInfo[$space]['isPlugin'];
		
		if( !$this->checkConfig($plugDir) ){
			return false;
		}
		echo '<table style="margin:2em auto 0 auto;">';
		echo '<tr><td style="text-align:center">';
		
		echo '<table cellpadding="10" class="WBeditArea1">';
			echo '<tr>';
			echo '<td style="white-space:nowrap;text-align:right"><b>';
			echo 'Upgrading Plugin: ';
			echo '</b></td>';
			echo '<td>';
			echo $plugDir;
			echo '</td>';
			echo '</tr>';
		echo '</table>';		
		
		echo '<input type="submit" name="cmd['.$space.']" value="Confirm Upgrade" /> ';
		echo '<input type="submit" name="cmd" value="Cancel" />';
		
		echo '</td></tr>';
		echo '</table>';		
		
		return true;
	}
	
	function upgradeConfirm(){
		global $page,$dbInfo,$wbTablePrefix,$wbPluginSpace,$wbPluginDir;
		
		if( !isset($dbInfo[$page->cmdArg[0]] ) ){
			message('Invalid Plugin: '.$page->cmdArg[0]);
			return;
		}
		$space = $page->cmdArg[0];
		$plugDir = $dbInfo[$space]['isPlugin'];
		
		if( isset($dbInfo[$page->cmdArg[0]]['alias']) ){
			$name = $dbInfo[$page->cmdArg[0]]['alias'];
		}else{
			$name = $page->cmdArg[0];
		}
		$name = toStorage($name);
		
		//update scripts
		$wbPluginSpace = $name;
		$wbPluginDir = $plugDir;
		$configFile = $this->pluginDir.'/'.$plugDir.'/config.php';
		if( is_file($configFile) ){
			require($configFile);
		}
		
		if( isset($upgradeScriptBefore) ){
			$this->installScript($plugDir,$upgradeScriptBefore);
		}
		
		
		if( !$this->installUpdate($name,$plugDir) ){
			return;
		}
		
		message('<tt>'.$name.'</tt> was successfully upgraded.');
		
		if( isset($upgradeScriptAfter) ){
			$this->installScript($plugDir,$upgradeScriptAfter);
		}
	}
	
	
	function installScript($plugDir,$script){
		$script = $this->pluginDir.'/'.$plugDir.'/'.$script;
		if( !is_file($script) ){
			message('<b>Warning</b> This plugin\'s install/upgrade script could not be found: '.$script);
			return;
		}
		require($script);
	}
	
	
	///////////////////////////////////////////////////////////////////////////
	//
	//	Install
	//
	function confirmedInstall(){
		global $page,$wbTablePrefix,$wbPluginSpace,$wbPluginDir;
		
		$name = toStorage($_POST['as']);
		$plugDir = $page->cmdArg[0];

		//
		//	Check Name
		//
			if( !$this->checkName($name) ){
				return false;
			}
			
		//
		//	install
		//
			if( !$this->installUpdate($name,$plugDir) ){
				return false;
			}
			
			
			unset($this->available[$plugDir]);
			$this->saveConfig();
			
			if( isset($_POST['extables']) && $_POST['extables'] == 'empty' ){
				$this->emptyExistingTables($plugDir);
			}
			
			//custom install script
			$wbPluginSpace = wbStrtolower(toStorage($name));
			$wbPluginDir = $plugDir;
			$configFile = $this->pluginDir.'/'.$plugDir.'/config.php';
			if( is_file($configFile) ){
				require($configFile);
			}
			
			if( isset($installScript) ){
				$this->installScript($plugDir,$installScript);
			}
			
		//
		// Done
		//		
			$mess = '<tt>'.$plugDir.'</tt> was installed successfully. Below, you\'ll find the links that allow you to access the features of this plugin. ';
			$mess .= wbLinks::admin('Plugins?refresh','continue');
			message($mess);
			$this->pluginLinks($wbPluginSpace);
			
	}
		
	function installUpdate($name,$plugDir){
		global $page,$wbTablePrefix,$dbObject,$wbTablePrefix,$dbInfo;

		includeFile('installDB.php');

		$lowerName = wbStrtolower($name);
		$wbPluginSpace = $lowerName;
		
		
		//	SQL File
		$sqlFile = $this->pluginDir.'/'.$plugDir.'/sql.php';
		if( is_file($sqlFile) ){
			require($sqlFile);
			if( !isset($dbData) ){
				$dbData = false;
			}
		}
		
		//dbInfo File
		$configFile = $this->pluginDir.'/'.$plugDir.'/config.php';
		if( is_file($configFile) ){
			require($configFile);
		}
		if( !isset($installInfo) ){
			$installInfo = array();
		}
		$installInfo['isPlugin'] = $plugDir;
		
		//class
		$classFile = $this->pluginDir.'/'.$plugDir.'/class.php';
		if( is_file($classFile) ){
			if( !isset($installInfo['class']) ){
				$installInfo['class'] = $plugDir;
			}
		}
		
		
		// Add The Plugin
		if( !$this->addPlugin($name,$dbData,$installInfo) ){
			return false;
		}
		
		//	Admin Links
		$this->addPluginLinks($plugDir,$lowerName);
		
		return true;
	}
	
	
	function install(){
		global $page,$wbTablePrefix;
		$plugDir = $page->cmdArg[0];
		$page->css2 = true;
		
		includeFile('installDB.php');

		
		//check plugin
		if( !isset($this->available[$plugDir]) ){
			message('Invalid data type: '.$plugDir);
			return false;
		}
		
		if( !$this->checkConfig($plugDir) ){		//checks config.php
			return false;
		}
		
				
		//Install as
		$wbPluginSpace = ''; //not needed here
		$configFile = $this->pluginDir.'/'.$plugDir.'/config.php';
		if( is_file($configFile) ){
			require($configFile);
			if( isset($installAs) ){
				$this->installAs = $installAs;
			}
		}
		
		// if( !isset($_POST['as']) && empty($this->installAs) ){
		// 	$_POST['as'] = $this->getNameFrom($plugDir);
		// }
		if( !isset($_POST['as']) && empty($this->installAs) ){
			$_POST['as'] = '';
			$arg = $plugDir;
			while(strlen($arg) > 0){
				$char = substr($arg,0,1);
				$arg = substr($arg,1);
				if( ctype_alnum($char) ){
					$_POST['as'] .= $char;
				}
			}
		}
	
		
		if( !$this->checkClassName($plugDir) ){ 	//check class.php and config.php
			return false;
		}
		if( !$this->checkDbTable($plugDir) ){		//requires config.php if available
			return false;
		}
		if( !$this->checkSql($plugDir) ){			//uses sql.php if available
			return false;
		}
		
		echo '<table style="margin:2em auto 0 auto;">';
		echo '<tr><td style="text-align:center">';
		
		echo '<table cellpadding="10" class="WBeditArea1">';
		echo '<tr><td style="white-space:nowrap;text-align:right"><b>';
			echo 'Installing Plugin: ';
			echo '</b></td><td>';
			echo $plugDir;
			echo '</td><td class="sm">';
			echo 'The name of the plugin your are installing.';
			echo '</td></tr>';
			
		if( is_array($this->existingTables) ){
			echo '<tr><td style="white-space:nowrap;text-align:right"><b>';
				echo 'Existing Tables: ';
				echo '</b></td><td>';
				echo '<label><input type="radio" name="extables" value="empty" checked="checked" /> Empty and Alter</label>';
				echo '<br/>';
				echo '<label><input type="radio" name="extables" value="" /> Alter Only</label>';
				
				echo '</td><td class="sm">';
				echo 'Choose what to do with the following existing tables: '.implode($this->existingTables);
				echo '</td></tr>';
		}
					
		echo '<tr><td style="text-align:right"><b>';
			echo 'Install as: ';
			echo '</b></td><td>';
			if( !empty($this->installAs) ){
				echo '<input type="hidden" name="as" value="'.wbHtmlspecialchars($this->installAs).'" />';
				echo $this->installAs;
			}else{
				echo '<input type="text" name="as" value="'.wbHtmlspecialchars($_POST['as']).'" />';
			}
			echo '</td><td class="sm">';
			echo 'A unique name for your data type that will be used for urls and page titles.<br/> (a-z, A-Z, 1-9, underscore (_) and dash(-) only) ';
			echo '</td></tr>';
			
		echo '</table>';
			
			echo '<input type="submit" name="cmd['.$plugDir.']" value="Confirm Install" /> ';
			echo '<input type="submit" name="cmd" value="Cancel" />';
			
			echo '<p>';
			echo 'You should always backup your data before installing new components.';
			echo '</p>';
			
		echo '</td></tr>';
		echo '</table>';
		
		
		
			
	}
	
	///////////////////////////////////////////////////////////////////////////
	//
	//	Show
	//
	function show(){
		global $dbInfo;
		
		echo '<table style="width:100%" cellpadding="15"><tr><td>';
		$this->showUninstalled();
		echo '</td></tr>';
		
		echo '<tr><td>';
		echo '<h3 class="heading">Your Plugin Directory</h3><div class="underline"></div>';
		echo '<ul><li>';
		echo '<tt>'.$this->pluginDir.'</tt>';
		echo '</li></ul>';
		
		echo '</td></tr>';
		
		echo '<tr><td colspan="2">';
		echo '<h3 class="heading">How To Install Plugins</h3><div class="underline"></div>
				<ol>
				<li> Download plugins from <a href="http://www.wikyblog.com/Main/Plugins">WikyBlog.com</a>.</li>
				<li> Copy the appropriate files into your plugins directory.</li>
				<li> Reload this page, then click "Install" for the new plugin.</li>
				</ol>';
				
		echo '</td></tr>';
		
		echo '<tr><td colspan="2">';
		echo '<h3 class="heading">Plugin Development</h3><div class="underline"></div>';
		echo 'If you plan on creating a custom plugin, the following may be useful.';
		echo '<ul>';
		echo '<li>'.wbLinks::admin('CreatePlugin','Custom Data Types').' &nbsp; This script can output php code for custom plugins.</li>';
		echo '<li>'.wbLinks::admin('PluginSQL','Plugin Development').' &nbsp; This script will create the data needed in a plugin\'s sql.php file.</li>';
		echo '<li>Integrated debugging is available. Uncomment the following line in your wiki.php file.<br/><pre>	define(\'wbDebug\',true);</pre></li>';
		echo '</ul>';
		
		echo '</td></tr>';
		
		echo '</table>';
	}
	
	function showUninstalled(){
		global $langA,$dbInfo;
		
		
		$this->showInstalled();
		
		echo '<table class="tableRows sortable" style="width:100%" >';

		
		$i = 0;
		$classes[] = ' class="tableRowOdd" ';
		$classes[] = ' class="tableRowEven" ';

					
		echo '<tr>';
		echo '<th style="white-space:nowrap" colspan="2">'.$langA['available_plugins'].'</th>';
		echo '<th colspan="3" class="unsortable">'.$langA['options'].'</th>';
		echo '</tr>';
		ksort($this->available);
		foreach($this->available as $plugDir => $info){
			echo '<tr'.$classes[($i%2)].'>';
			echo '<td colspan="2">';
			echo $plugDir;
			echo '</td>';
			echo '<td colspan="3">';
			echo '<input type="submit" name="cmd['.$plugDir.']" value="Install" />';
			echo ' &nbsp; ';
			echo '<input type="submit" name="cmd['.$plugDir.']" value="Check Code" />';
			echo ' &nbsp; ';
			if( $info['has_sql'] ){
				echo '<input type="submit" name="cmd['.$plugDir.']" value="View Tables" />';
			}
			echo '</td>';
			echo '</tr>';
			$i++;
		}
		if( $i === 0){
			echo '<tr>';
			echo '<td style="text-align:center" colspan="3">';
			echo $langA['empty'];
			echo '</td>';
			echo '</tr>';			
		}
		

		echo '</table>';
	}
	function showInstalled(){
		global $langA;
		
		if( count($this->installed) < 1){
			return;
		}
		
		echo '<table class="tableRows sortable" style="width:100%" >';
		
		$i = 0;
		$classes[] = ' class="tableRowOdd" ';
		$classes[] = ' class="tableRowEven" ';
		echo '<tr>';
		echo '<th style="white-space:nowrap">Installed Plugins</th>';
		echo '<th>Installed As</th>';
		echo '<th colspan="2" class="unsortable">'.$langA['options'].'</th>';
		echo '</tr>';
		foreach($this->installed as $plugDir => $pluginName){
			
			
			echo '<tr'.$classes[($i%2)].'>';
			echo '<td>';
			echo $plugDir;
			echo '</td>';
			echo '<td>';
			
			if( $this->installedInfo[$plugDir]['has_class'] ){
				echo wbLinks::local('/'.$pluginName,$pluginName);
			}else{
				echo $pluginName;
			}
			
			echo '</td>';
			echo '<td>';
			if( $this->installedInfo[$plugDir]['has_dir'] ){
				echo '<input type="submit" name="cmd['.$pluginName.']" value="Upgrade" />';
			}
			echo ' <input type="submit" name="cmd['.$plugDir.']" value="Check Code" />';
			echo ' <input type="submit" name="cmd['.$pluginName.']" value="Links" />';
			
			if( $this->installedInfo[$plugDir]['has_sql'] ){
				echo ' <input type="submit" name="cmd['.$plugDir.']" value="View Tables" />';
			}
			
			
			echo '</td>';
			echo '<td>';
			
			echo '<input type="submit" name="cmd['.$pluginName.']" value="Remove" />';
			
			echo '</td>';
			echo '</tr>';
			$i++;
		}
		echo '</table>';
		echo '<br/>';
	}
	
	
	
	function getPlugins(){
		global $rootDir,$dbInfo;
		
		$newInfo = array();
		
		if( !file_exists($this->pluginDir) ){
			return;
		}
		$dh = @opendir($this->pluginDir);
		if(!$dh ){
			return;
		}
		
		while(($file = readdir($dh)) !== false){
			if( strpos($file,'.') === 0){
				continue;
			}
			
			$fullPath = $this->pluginDir.'/'.$file;
			$info = $this->checkPluginDir($fullPath);
			if( !$info ){
				continue;
			}
			$this->available[$file] = $info;
		}
		
		//cannot have two of the same plugin because of database table names!
		foreach($dbInfo as $space => $info){
			if( !isset($info['isPlugin']) ){
				continue;
			}
			$plugDir =& $info['isPlugin'];
			
			if( isset($this->available[$plugDir])){
				$this->installed[$plugDir] = $space;
				$this->installedInfo[$plugDir] = $this->available[$plugDir];
				unset($this->available[$plugDir]);
			}else{
				$this->installed[$plugDir] = $space;
				$this->installedInfo[$plugDir] = array('has_sql'=>false,'has_dir'=>false,'has_class'=>false);
			}
			
		}
	}
	
	////////////////////////////////////////////////////////////////////////////////
	//
	//			Checking Functions
	//
	
	
	
	//
	//	one of four files needs to exist!
	//
	function checkPluginDir($dir){
		
		$passed = false;
		if( !is_dir($dir) ){
			return false;
		}
		$info = array();
		$info['has_dir'] = true;
		$info['has_sql'] = false;
		$info['has_class'] = false;
		
		
		$file = $dir.'/sql.php';
		if( is_file($file) ){
			$passed = true;
			$info['has_sql'] = true;
		}
		
		if( is_file($dir.'/class.php') ){
			$passed = true;
			$info['has_class'] = true;
			return $info;
		}
		
		if( is_file($dir.'/config.php') ){
			$passed = true;
			return $info;
		}
		$file = $dir.'/links.php';
		if( is_file($file) ){
			
			$passed = true;
			return $info;
		}
		
		if( $passed ){
			return $info;
		}
		return false;
	}
	
	function checkAllCode(){
		global $rootDir,$page;
		
		includeFile('admin/CheckCode.php');
		
		$plugDir = $page->cmdArg[0];
		$dirPath = $this->pluginDir.'/'.$plugDir;
		if( checkSyntax::checkAllFiles($dirPath,$files) ){
			message('All of the .php files appeared correct for '.$plugDir.'.');
			return;
		}
		if( is_array($files) ){
			foreach($files as $file){
				message('An error was found in '.wbLinks::admin('Plugins?cmd=checkfile&file='.urlencode($file),$file));
			}
		}
	}
	
	function checkFile(){
		includeFile('admin/CheckCode.php');
		if( !is_file($_GET['file']) ){
			message('INVALID_REQUEST');
		}
		$mess = checkSyntax::checkFile($_GET['file'],true);
		message($mess);
	}
	

	
	function checkConfig($plugDir){
		global $wbTablePrefix,$packageVersion;
		includeFile('admin/CheckCode.php');
		$wbPluginSpace = '';//not really needed here
		
		$noVersion = '<b>Notice:</b> This plugin does not specify which version of WikyBlog it is compatible with. Before continuing, please make sure it is compatible with version '.$packageVersion.'.';
		
		$checkFiles[] = 'config.php';
		$checkFiles[] = 'sql.php';
		$checkFiles[] = 'links.php';
		$checkFiles[] = 'class.php';
		
		$errorFiles = array();
		foreach($checkFiles as $fileName){
			$filePath = $this->pluginDir.'/'.$plugDir.'/'.$fileName;
			if( !checkSyntax::checkFile($filePath,false) ){
				$errorFiles[] = $filePath;
			}
		}
		if( count($errorFiles) > 0 ){
			message('<b>Warning</b> The configuration files for this plugin appear to have errors: <br/> '. implode('<br/> ',$errorFiles));
			return false;
		}
		
		
		//check configuratoin file
		$configFile = $this->pluginDir.'/'.$plugDir.'/config.php';
		if( !is_file($configFile) ){
			message($noVersion);
			return true;
		}
		require($configFile);
		
		$passed = true;
		//checkMySQL
		if( isset($requiredMySQL) ){
			if( !$this->checkMySQL($requiredMySQL) ){
				$passed = false;
			}
		}
		
		//checkPHP
		if( isset($requiredPHP) ){
			if( version_compare(phpversion(),$requiredPHP,'<') ){
				message('This plugin requires a miniumum of PHP '.$requiredPHP);
				$passed = false;
			}
		}
		
		//checkFunctions
		if( isset($requiredFunctions) && is_array($requiredFunctions) ){
			foreach($requiredFunctions as $function){
				if( !function_exists($function) ){
					message('This plugin requires the <tt>'.$function.'()</tt> PHP function.');
					$passed = false;
				}
			}
		}
					
		
		
		if( !isset($requiredVersion) ){
			message($noVersion);
			$passed = true;
			
		}elseif(version_compare($packageVersion,$requiredVersion,'<')){
			message('This plugin requires a miniumum of WikyBlog V'.$requiredVersion);
			$passed = false;
		}		
		
		return $passed;
	}


	function checkMySQL($requiredMySQL){
		$query = 'SHOW VARIABLES LIKE "VERSION"';
		$result = wbDB::runQuery($query);
		$row = mysql_fetch_row($result);
		$currentVersion = $row[1];
		if( version_compare($currentVersion,$requiredMySQL,'>=') ){
			return true;
		}
		
		message('<b>Notice:</b> This plugin requires MySQL version '.$requiredMySQL.' or higher. The current version is '.$currentVersion.'.');
		return false;
	}
	
	function checkClassName($plugDir){
		global $dbInfo,$wbTablePrefix;;

		//is there a class?
		$classFile = $this->pluginDir.'/'.$plugDir.'/class.php';
		if( !is_file($classFile) ){
			return true;
		}
		
		//check the config
		$wbPluginSpace = '';//not really needed here
		$configFile = $this->pluginDir.'/'.$plugDir.'/config.php';
		if( is_file($configFile) ){
			require($configFile);
			if( !isset($installInfo) ){
				$installInfo = array();
			}
		}
		
		if( !isset($installInfo['class']) ){
			$checkName = $plugDir;
		}else{
			$checkName = $installInfo['class'];
		}
		
		if( !parent::checkClassName($checkName) ){
			message('The class <tt>'.$checkName.'</tt> already exists, the plugin code will have to be modified to change the class name.');
			return false;
		}
		
		return true;
	}
	
	function checkDbTable($plugDir){
		global $dbInfo,$wbTablePrefix;

		$wbPluginSpace = ''; //not needed here
		$configFile = $this->pluginDir.'/'.$plugDir.'/config.php';
		if( !is_file($configFile) ){
			return true;
		}
		
		require($configFile);
		if( !isset($installInfo) ){
			return true;
		}
		if( !is_array($installInfo) ){
			return true;
		}
		if( !isset($installInfo['dbTable']) ){
			return true;
		}
		
		$test2 = strtolower($installInfo['dbTable']);
		$test2 = trim($test2);
		
		foreach($dbInfo as $space => $info){
			if( isset($info['dbTable']) ){
				$test = strtolower($info['dbTable']);
				$test = trim($test);
				
				if(  $test == $test2 ){
					message('This plugin uses the same primary table as another data type. To continue, please modify your code or see the developer of this plugin.');
					return false;
				}
			}
		}
		return true;
	}

	
	function checkSql($plugDir){
		global $langA,$page;
		
		
		if( !$this->checkTables($plugDir) ){
			
			if( isset($_POST['overrideSql']) ){
				if( $_POST['overrideSql'] == $langA['continue'] ){
					return true;
				}
			}
			
			echo '<div style="margin-top:1em;text-align:center;">';
			
			echo '<p>';
			echo '<b>Installing Plugin:</b> ';
			echo $plugDir;
			echo '</p>';
			
			echo '<p>';
			echo '<input type="hidden" name="cmd['.$plugDir.']" value="Install" />';
			echo '<input type="submit" name="overrideSql" value="'.$langA['continue'].'" /> ';
			echo '<input type="submit" name="cmd" value="Cancel" />';
			echo '</p>';
						

			echo '</div>';
			
			return false;
		}
		
		return true;
	}
	
	function checkTables($plugDir,$warn=true){
		global $wbTablePrefix;
		
		$sql = $this->getSql($plugDir);
		if( !$sql ){
			return true;
		}
		
		$existing = array();
		foreach($sql as $table => $info){
			$query = 'SHOW TABLE STATUS LIKE "'.$wbTablePrefix.$table.'"';
			$result = wbDB::runQuery($query);
			if( !$result ){
				continue;
			}
			if( mysql_num_rows($result) > 0 ){
				$existing[] = $wbTablePrefix.$table;
			}
		}
		
		if( count($existing) > 0 ){
			if( $warn ){
				message('<b>Warning:</b> This plugin uses the following existing MySQL tables: '.implode(', ',$existing).'.<br/> Before continuing, make sure these tables are not currently in use.');
			}
			$this->existingTables = $existing;
			return false;
		}
		
		return true;
	}
	
	function getSql($plugDir){
		
		//is there a class?
		$sqlFile = $this->pluginDir.'/'.$plugDir.'/sql.php';
		if( !is_file($sqlFile) ){
			return false;
		}
		
		require($sqlFile);
		if( !isset($dbData) ){
			return false;
		}
		$sql = unserialize($dbData);
		if( !is_array($sql) ){
			return false;
		}
		return $sql;
	}
	
	function emptyExistingTables($plugDir){
		if( $this->checkTables($plugDir,false) ){
			return;
		}
		foreach($this->existingTables as $table ){
			$query = 'TRUNCATE TABLE `'.$table.'`';
			wbDB::runQuery($query);
		}
		
		message('Emptied these tables: '.implode($this->existingTables));
	}
}


new adminPlugins();

