<?php

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

includeFile('admin/PluginAdd.php');

class createPluginTool extends pluginAdd{
	var $types = array();
	var $className;
	
	//used for checking
	var $existingVars = array();
	var $usedCols = array();
	var $searchFields = array();
	
	//resulting files
	var $sqlFile, $infoFile, $classFile;
	var $tableName;
	
	function createPluginTool(){
		global $page;
		
		includeFile('admin/CheckPrivs.php');
		if( !checkPrivs::isGranted() ){
			return;
		}
		
		$temp = get_class_vars('dbPage');
		foreach($temp as $var => $value){
			$this->existingVars[wbStrtolower($var)] = $value;
		}
		if( array_key_exists('content', $this->existingVars ) ){
			unset($this->existingVars['content']);
		}
		if( array_key_exists('keywords', $this->existingVars ) ){
			unset($this->existingVars['keywords']);
		}
		
		$this->types['SPECIAL TYPES'] = FALSE;
		$this->types['WIKI SYNTAX'] = 'WIKI SYNTAX';
		$this->types['URL'] = 'url';
		
		$this->types['LIST TYPES'] = FALSE;
		$this->types['ENUM'] = 'list';
		$this->types['SET'] = 'list';
		
		$this->types['DATE &amp; TIME TYPES'] = FALSE;
		$this->types['DATE'] = 'date';
		//$this->types['DATETIME'] = 'date';
		//$this->types['TIMESTAMP'] = 'date';
		$this->types['TIME'] = 'date';
		//$this->types['YEAR'] = 'date';
		
		$this->types['STRING TYPES'] = FALSE;
		$this->types['CHAR'] = 'len';
		$this->types['VARCHAR'] = 'len';
		$this->types['BINARY'] = 'len';
		$this->types['VARBINARY'] = 'len';
		
		$this->types['NUMERIC TYPES'] = FALSE;
		$this->types['TINYINT'] = 'int';
		$this->types['SMALLINT'] = 'int';
		$this->types['MEDIUMINT'] = 'int';
		$this->types['INT'] = 'int';
		$this->types['BIGINT'] = 'int';
		// $this->types['FLOAT'] = 'dec';
		// $this->types['DOUBLE'] = 'dec';
		// $this->types['DECIMAL'] = 'dec';
		
		
		//$this->types['TEXT'] = 'text';
		//$this->types['TINYBLOB'] = 'text';
		//$this->types['TINYTEXT'] = 'text';
		//$this->types['BLOB'] = 'text';
		//$this->types['MEDIUMBLOB'] = 'text';
		//$this->types['MEDIUMTEXT'] = 'text';
		//$this->types['LONGBLOB'] = 'text';
		//$this->types['LONGTEXT'] = 'text';
		
		
		//$this->types['BOOL'] = '';
	}
	
	function createScripts($nameSpace){
		global $packageVersion,$page,$rootDir;
		
		
		//
		//	SQL File
		//
		
			$this->sqlFile = array();
			$this->sqlFile['Engine'] = 'MyISAM';
			$this->sqlFile['Collation'] = 'utf8_general_ci';
			$this->sqlFile['Default_charset'] = 'DEFAULT CHARSET=utf8';
			$this->sqlFile['columns'] = array();
			$this->sqlFile['columns']['file_id'] = '`file_id` int(8) unsigned NOT NULL';
			$this->sqlFile['columns']['owner'] = '`owner` varchar(20) NOT NULL';
			$this->sqlFile['columns']['title'] = '`title` varchar(40) NOT NULL';
			$this->sqlFile['columns']['summary'] = '`summary` varchar(200) DEFAULT NULL';
			$this->sqlFile['columns']['hitcounter'] = '`hitcounter` mediumint(8) unsigned NOT NULL DEFAULT "0"';
			$this->sqlFile['keys'] = array();
			$this->sqlFile['keys']['PRIMARY'] = 'PRIMARY KEY (`owner`, `title`)';
			$this->sqlFile['keys']['file_id'] = 'UNIQUE (`file_id`)';
			
			foreach($_POST['add'] as $array){
				$this->createSql($array);
			}
			//message(showArray($this->sqlFile));

			
		$this->createClass($nameSpace);
		
		//
		//	dbInfo File
		//
			
			$this->infoFile = array();
			$this->infoFile[] = '<'.'?'.'php';
			$this->infoFile[] = '$installInfo[\'class\'] = \''.$this->className.'\';';
			$table = $this->getTableName($this->className);
			$this->infoFile[] = '$installInfo[\'dbTable\'] = "`{$wbTablePrefix}'.$table.'`";';
			
			//search
			$this->infoFile[] = '$installInfo[\'searchTitle\'] = array(\'title\');';
			if( count($this->searchFields) > 0 ){
				$searchContent = '$installInfo[\'searchContent\'] = array(';
				foreach($this->searchFields as $field){
					$searchContent .= '\''.$field.'\',';
				}
				$this->infoFile[] = $searchContent.');';
			}
		
		
	}
	
	function getTableName($plugin){
		global $wbTablePrefix;
		if( isset($this->tableName) ){
			return $this->tableName;
		}
		
		$tableName = wbStrtolower('xt_'.$plugin);
		$checkName = $tableName;
		$int = 0;
		while( !$this->checkTableName($checkName) ){
			$checkName = $tableName.$int;
			$int++;
		}
		$this->tableName = $checkName;
		return $checkName;
	}
	
	function checkTableName($name){
		global $wbTablePrefix;
		$query = 'SHOW TABLE STATUS LIKE "'.$wbTablePrefix.$name.'"';
		$result = wbDB::runQuery($query);
		if( mysql_num_rows($result) > 0 ){
			return false;
		}
		return true;
	}
	
	function modify($nameSpace){
		global $rootDir,$packageVersion,$page,$dbObject;
		

		//
		//	Output
		//
			ob_start();
			
			$this->exportHeader();
			
			echo '<h3 class="heading">class.php</h3>';
			echo '<div style="margin:0 3em 0 3em;">';
			echo '<textarea wrap="off" style="width:100%;margin:0;" rows="20">';
			$temp = '<'.'?'.'php'."\n";
			$temp .= 'defined(\'WikyBlog\') or die(\'Not an entry point...\');'."\n";
			$temp .= implode("\n",$this->classFile);
			
			echo wbHtmlspecialchars($temp);
			echo '</textarea>';
			echo '</div>';
			
						
			echo '<h3 class="heading">config.php</h3>';
			echo '<div style="margin:0 3em 0 3em;">';
			echo '<textarea wrap="off" style="width:100%;" rows="7">';
			$temp = implode("\n",$this->infoFile);
			echo wbHtmlspecialchars($temp);
			echo '</textarea>';
			echo '</div>';
			
			echo '<h3 class="heading">sql.php</h3>';
			echo '<div style="margin:0 3em 0 3em;">';
			echo '<textarea wrap="off" style="width:100%;" rows="7">';
			
			//this is from admin/PluginSQL.php
			$text = '<'.'?'."php\n";
			$text .= "//\n";
			$text .= "//\t\tWikyBlog Generated File\n";
			$text .= "//\t\tpackage version ".$packageVersion."\n";
			$text .= "//\t\tadminPluginSQL.php\n";		
			$text .= "//\t\t********************************************************************************************************\n";
			$text .= "//\t\tThis file contains a serialized array used to create/alter database tables used by the WikyBlog software\n";
			$text .= "//\t\tDon't edit anything in this file!\n";
			$text .= "//\n\n";
			$text .= 'defined(\'WikyBlog\') or die(\'Not an entry point...\');';
			$text .= "\n\n";
			$text .= '$dbData = \'';
			$array = array();
			$array[$this->getTableName($nameSpace)] = $this->sqlFile;
			$text .= addcslashes(serialize($array),"\'");
			$text .= '\';';
			$text .= "\n\n\n";
			echo wbHtmlspecialchars($text);
			echo '</textarea>';
			echo '</div>';
			
			$page->contentA['Plugin Code'] = wb::get_clean();

		return true;
	}
	
	function addToDB($nameSpace){
		global $wbTables,$wbTablePrefix,$page,$dbInfo;
		$selector = 'class:'.$this->className;
		
		//
		//	class
		//	
			$class = implode("\n",$this->classFile);
			if( !$this->ad_object($selector,$class) ){
				$page->contentA['Plugin Installation'] = '<div style="text-align:center;margin:5em;">Plugin installation failed. (2)</div>';
				return;
			}
			
		//
		//	dbInfo and sql
		//	
			$info = array();
			$info['dbPlugin'] = true;
			$table = $this->getTableName($nameSpace);
			$info['dbTable'] = "`{$wbTablePrefix}{$table}`";
			$info['class'] = $this->className;
			
			$info['searchTitle'] = array('title');
			if( count($this->searchFields) > 0 ){
				$info['searchContent'] = $this->searchFields;
			}
			
			$array = array();
			$array[$table] = $this->sqlFile;
			$temp = serialize($array);
			
			if( !$this->addPlugin($nameSpace,$temp,$info) ){
				$page->contentA['Plugin Installation'] = '<div style="text-align:center;margin:5em;">Plugin installation failed. (3)</div>';
				return;
			}
			
		$page->contentA['Plugin Installation'] = '<div style="text-align:center;margin:5em;">Plugin added successfully.</div>';
		
	}
	
	////////////////////////////////////////////////////////////////////////
	//
	//		Create the class File
	//
	function createClass($nameSpace){
		$tab = "\t";
		$lockedValue = false;
		
		
		$t =& $this->classFile;
		$t = array();
		
		
		$dbValues = ' array(\'owner\'=>1,\'title\'=>1';
		$vars = array();
		$user = array();
		
		foreach($_POST['add'] as $i => $array){
			$temp = wbStrtolower($array['name']);
			if( $temp == 'keywords'){
				$user[] = '\''.$temp.'\'=>1';
			}else{
				$dbValues .= ',\''.$temp.'\'=>1';
				$user[] = '\''.$temp.'\'=>1';
				$vars[] = '$'.$temp;
				$this->searchFields[] = $temp;
			}
			if( strpos($array['options'],'lock') !== false){
				$lockedValue = true;
			}
		}
		$dbValues .= ');';
		$userValues = ' array('.implode(',',$user).');';
		
		
		
		$t[] = '';
		$t[] = 'class '.$this->className.' extends dbPage{';
		$t[] = '';
		
		if( count($vars) > 0){
			$t[] = $tab.'var '.implode(',',$vars).';';
			$t[] = '';
		}
		
		$t[] = '';
		$t[] = $tab.'var $dbValues ='.$dbValues;
		$t[] = $tab.'var $userValues ='.$userValues;
		$t[] = '';
		$t[] = $tab.'function '.$this->className.'($type){';
		$t[] = $tab.$tab.'$this->objectType = $type;';
		$t[] = $tab.$tab.'$this->setDbInfo();';
		$t[] = $tab.'}';
		
		$t[] = '';
		$t[] = $tab.'function setLinks(){';
		$t[] = $tab.$tab.'global $page,$pageOwner,$langA;';
		$t[] = $tab.$tab.'parent::setLinks();';
		$t[] = $tab.$tab.'$page->displayTitle = $langA[$this->objectType] .\' > \'.toDisplay($this->title);';
		$t[] = $tab.$tab.'$page->regLink(\'?\',\''.$nameSpace.'\');';
		$t[] = $tab.'}';
		
		//newPage
		//
		//!!	hmm.. they won't all have content!
		//
		$t[] = '';
		$t[] = $tab.'function newPage(){';
		$t[] = $tab.$tab.'global $includeDir,$page,$userLanguage,$langA;';
		$t[] = $tab.$tab.'parent::newPage();';
		$t[] = $tab.$tab.'if( $this->editable ){';
		$t[] = $tab.$tab.$tab.'$this->content = wbLang::text(\'DEFAULT_CONTENT\',$this->uniqLink);';
		$t[] = $tab.$tab.$tab.'if( empty($page->userCmd) && cookies() ){';
		$t[] = $tab.$tab.$tab.$tab.'$page->userCmd = \'edit\';';
		$t[] = $tab.$tab.$tab.'}';
		$t[] = $tab.$tab.'}else{';
		$t[] = $tab.$tab.$tab.'$this->content = $langA[\'DEFAULT_CONTENT_PROTECTED\'];';
		$t[] = $tab.$tab.'}';
		
		foreach($_POST['add'] as $array){
			$lowerName = wbStrtolower($array['name']);
			switch($array['type']){
				case 'URL':
					$t[] = $tab.$tab.'$this->'.$lowerName.' = "http://";';
				break;
				case 'DATE':
					$t[] = $tab.$tab.'$this->'.$lowerName.' = "0000-00-00";';
				break;
				case 'TIME':
					$t[] = $tab.$tab.'$this->'.$lowerName.' = "00:00:00";';
				break;
			}
		}
		$t[] = $tab.'}';
		$t[] = '';
		
		
		//outputObj
		$t[] = '';
		$t[] = $tab.'//This function makes use of the pluginDisplay class in /include/tool/pluginDisplay.php';
		$t[] = $tab.'function outputObj($field=true){';
		$t[] = $tab.$tab.'global $page;';
		$t[] = $tab.$tab.'includeFile(\'tool/pluginDisplay.php\');';
		$t[] = $tab.$tab.'if( $field === true ){';
		$t[] = $tab.$tab.$tab.'$field = $this->uniqLink;';
		$t[] = $tab.$tab.'}';
		
		
		$t[] = '';
		$t[] = $tab.$tab.'ob_start();';
		$t[] = $tab.$tab.'echo \'<table cellpadding="7">\';';
		
		$savebarKeywords = false;
		$len = count($_POST['add']);
		$i = 1;
		foreach($_POST['add'] as $array){
			$lowerName = wbStrtolower($array['name']);
			if( ($i == $len) && ($lowerName =='keywords')){
				if( $array['type'] === 'VARCHAR' ){
					$savebarKeywords = true;
					continue;
				}
			}
			$i++;
			
			$this->classDisplayValues($array);
		}
		$t[] = $tab.$tab.'echo \'</table>\';';
		$t[] = '';
		
		
		$t[] = $tab.$tab.'$page->contentB[$field] = wb::get_clean();';
		$t[] = $tab.$tab.'return $field;';
		$t[] = $tab.'}';
		$t[] = '';
		
		
		
		//abbrevOutput
		
		$t[] = '';
		$t[] = $tab.'function abbrevOutput(&$row){';
		$t[] = $tab.$tab.'parent::abbrevOutputHeader($row);';
		$t[] = $tab.$tab.$this->className.'::abbrevOutputContent($row);';
		$t[] = $tab.'}';
		$t[] = '';
		
		
		$t[] = '';
		$t[] = $tab.'//This function makes use of the pluginDisplay class in /include/tool/pluginDisplay.php';
		$t[] = $tab.'function abbrevOutputContent(&$row){';
		$t[] = $tab.$tab.'includeFile(\'tool/pluginDisplay.php\');';
		//$t[] = $tab.$tab.'pluginDisplay::abbrevHeading($row);';
		$t[] = '';
		$t[] = $tab.$tab.'echo \'<table>\';';
		
		$i = 0;
		$comment = '';
		foreach($_POST['add'] as $array){
			if( $i == 3 ){
				$comment = '//';
				$t[] = '';
				$t[] = $tab.$tab.$comment.'The following values were commented out to create an abbreviated display for this object.';
			}
			$i++;
			
			$lowerName = wbStrtolower($array['name']);
			
			switch($array['type']){
				case 'WIKI SYNTAX':
					$t[] = $tab.$tab.$comment.'pluginDisplay::abbrevWiki($row->'.$lowerName.',$row->uniqLink);';
				break;
				
				case 'URL':
					$t[] = $tab.$tab.$comment.'pluginDisplay::url(\''.$array['name'].'\',$row->'.$lowerName.');';
				break;
				case 'TIME':
					$t[] = $tab.$tab.$comment.'pluginDisplay::time(\''.$array['name'].'\',$row->'.$lowerName.');';
				break;
				case 'DATE':
					$t[] = $tab.$tab.$comment.'pluginDisplay::date(\''.$array['name'].'\',$row->'.$lowerName.');';
				break;

				default:
					$t[] = $tab.$tab.$comment.'pluginDisplay::display(\''.$array['name'].'\',$row->'.$lowerName.');';
				break;
			}
		}
		
		$t[] = '';
		$t[] = $tab.$tab.'echo \'</table>\';';
		$t[] = $tab.'}';
		$t[] = '';
		
		
		//setFromPost
		$t[] = '';
		$t[] = $tab.'//This function makes use of the pluginFromPost class in /include/tool/pluginEdit.php';
		$t[] = $tab.'function setFromPost(){';
		$t[] = $tab.$tab.'includeFile(\'tool/pluginEdit.php\');';
		
		foreach($_POST['add'] as $array){
			$name = wbStrtolower($array['name']);
			if( strpos($array['options'],'lock') !== false){
				$t[] = $tab.$tab.'if( !isOwner(false,false) ){';
				$t[] = $tab.$tab.'unset($_POST[\''.$name.'\']);';
				$t[] = $tab.$tab.'}';
			}
			
			if( isset($array['type']) ){
				switch($array['type']){
					case 'SET':
						$t[] = $tab.$tab.'pluginFromPost::setSet(\''.$name.'\');';
					break;
				}
			}
			
		}
		$t[] = $tab.$tab.'parent::setFromPost();';
		$t[] = $tab.'}';
		$t[] = '';

		//check
		$t[] = '';
		$t[] = $tab.'function checkData($warn=true){';
		$t[] = $tab.$tab.'if(!$warn){ return;}';
		$t[] = $tab.$tab.'global $wbParser,$langA;';
		$t[] = $tab.$tab.'includeFile(\'tool/pluginCheck.php\');';
			foreach($_POST['add'] as $array){
				$name = wbStrtolower($array['name']);
				switch($array['type']){
					case 'URL':
						$t[] = $tab.$tab.'pluginCheck::url(\''.$name.'\',$warn);';
					break;
					case 'WIKI SYNTAX':
						$t[] = $tab.$tab.'pluginCheck::wiki(\''.$name.'\',$warn);';		
					break;
					
					///Date and Time
					case 'DATE':
						$this->classFile[] = $tab.$tab.'pluginCheck::date(\''.$array['name'].'\');';
					break;
					case 'TIME':
						$this->classFile[] = $tab.$tab.'pluginCheck::time(\''.$array['name'].'\');';
					break;
					
					///Integers
					case 'TINYINT':
						$this->classFile[] = $tab.$tab.'pluginCheck::integer(\''.$array['name'].'\',\'TINYINT\');';
					break;
					case 'SMALLINT':
						$this->classFile[] = $tab.$tab.'pluginCheck::integer(\''.$array['name'].'\',\'SMALLINT\');';
					break;
					case 'MEDIUMINT':
						$this->classFile[] = $tab.$tab.'pluginCheck::integer(\''.$array['name'].'\',\'MEDIUMINT\');';
					break;
					case 'INT':
						$this->classFile[] = $tab.$tab.'pluginCheck::integer(\''.$array['name'].'\',\'INT\');';
					break;
					case 'BIGINT':
						$this->classFile[] = $tab.$tab.'pluginCheck::integer(\''.$array['name'].'\',\'BIGINT\');';
					break;
				}
			}
		$t[] = $tab.'}';
		$t[] = '';
		
		//editValues
		$t[] = '';
		$t[] = $tab.'//This function makes use of the pluginEdit class in /include/tool/pluginEdit.php';
		$t[] = $tab.'function editValues(){';
		$t[] = $tab.$tab.'global $page,$jsNum;';
		$t[] = $tab.$tab.'$page->css2 = true;';
		$t[] = $tab.$tab.'$page->scripts[] = \'/include/js/editing.js?\'.$jsNum;';
		$t[] = $tab.$tab.'$page->scripts[] = \'/include/js/editingAll.js?\'.$jsNum;';
		$t[] = $tab.$tab.'includeFile(\'tool/pluginEdit.php\');';
		if( $lockedValue){
			$t[] = $tab.$tab.'includeFile(\'tool/pluginDisplay.php\');';
		}
		$t[] = $tab.$tab.'ob_start();';
		$t[] = $tab.$tab.'echo \'<table style="width:100%">\';';
		
			foreach($_POST['add'] as $array){
				$temp = wbStrtolower($array['name']);
				if( $savebarKeywords && $temp =='keywords'){
					continue;
				}
				$this->classEditValues($array);
			}
		
		$t[] = $tab.$tab.'echo \'</table>\';';
		$t[] = $tab.$tab.'$link = \'/Edit\'.$this->uniqLink.\'?cmd=edit\';';
		$t[] = $tab.$tab.'$page->contentB[$link] = wb::get_clean();';
		if( $savebarKeywords ){
			$t[] = $tab.$tab.'$page->contentB[$link] .= saveBar();';
		}else{
			$t[] = $tab.$tab.'$page->contentB[$link] .= saveBar(false);';
		}

		$t[] = $tab.'}';
		$t[] = $tab.'function creationValues(){';
		$t[] = $tab.$tab.'return unserialize(\''.addcslashes(serialize($_POST),"\'").'\');';
		$t[] = $tab.'}';
		$t[] = '';
		$t[] = '}';
	}
	
	function classDisplayValues(&$array){
		$tab = "\t";
		$lowerName = wbStrtolower($array['name']);
		
		switch($array['type']){
			
			case 'WIKI SYNTAX':
				$this->classFile[] = $tab.$tab.'pluginDisplay::wiki($this->'.$lowerName.');';
			break;
			
			case 'URL':
				$this->classFile[] = $tab.$tab.'pluginDisplay::url(\''.$array['name'].'\',$this->'.$lowerName.');';
			break;
			case 'TIME':
				$this->classFile[] = $tab.$tab.'pluginDisplay::time(\''.$array['name'].'\',$this->'.$lowerName.');';
			break;
			case 'DATE':
				$this->classFile[] = $tab.$tab.'pluginDisplay::date(\''.$array['name'].'\',$this->'.$lowerName.');';
			break;

			default:
				$this->classFile[] = $tab.$tab.'pluginDisplay::display(\''.$array['name'].'\',$this->'.$lowerName.');';
			break;
		}
	}
	
	function classEditValues($array){
		$tab = "\t";
		
		$temp = wbStrtolower($array['name']);
		
		$locked = false;
		if( strpos($array['options'],'lock') !== false){
			$locked = true;
			$this->classFile[] = $tab.$tab.'if( !isOwner(false,false) ){';
			$this->classDisplayValues($array);
			$this->classFile[] = $tab.$tab.'}else{';
		}
		
		switch($array['type']){
			
			case 'ENUM':
				$this->editEnum($array['name'],$array['len']);
			break;
			case 'SET':
				$this->editSET($array['name'],$array['len']);
			break;
			
			case 'WIKI SYNTAX';
				$this->classFile[] = $tab.$tab.'pluginEdit::editWiki(\''.$array['name'].'\');';
			break;
			
			case 'URL';
				$this->classFile[] = $tab.$tab.'pluginEdit::editUrl(\''.$array['name'].'\',255);';
			break;
			
			case 'VARCHAR':
				$this->classFile[] = $tab.$tab.'pluginEdit::editVarchar(\''.$array['name'].'\','.$array['len'].');';
			break;
			
			case 'YEAR':
				$this->classFile[] = $tab.$tab.'pluginEdit::editYear(\''.$array['name'].'\');';
			break;
			
			case 'TIME':
				$this->classFile[] = $tab.$tab.'pluginEdit::editTime(\''.$array['name'].'\');';
			break;
			
			case 'DATE':
				$this->classFile[] = $tab.$tab.'pluginEdit::editDate(\''.$array['name'].'\');';
			break;
			
			
			//length plus one (for - sign)
			case 'TINYINT':
				$this->classFile[] = $tab.$tab.'pluginEdit::editInteger(\''.$array['name'].'\',4);';
			break;
			case 'SMALLINT':
				$this->classFile[] = $tab.$tab.'pluginEdit::editInteger(\''.$array['name'].'\',6);';
			break;
			case 'MEDIUMINT':
				$this->classFile[] = $tab.$tab.'pluginEdit::editInteger(\''.$array['name'].'\',8);';
			break;
			case 'INT':
				$this->classFile[] = $tab.$tab.'pluginEdit::editInteger(\''.$array['name'].'\',11);';
			break;
			case 'BIGINT':
				$this->classFile[] = $tab.$tab.'pluginEdit::editInteger(\''.$array['name'].'\',20);';
			break;
			
			// case 'FLOAT':
			// 	$this->classFile[] = $tab.$tab.'pluginEdit::editDecimal(\''.$array['name'].'\');';
			// break;
			// case 'DOUBLE':
			// 	$this->classFile[] = $tab.$tab.'pluginEdit::editDecimal(\''.$array['name'].'\');';
			// break;
			// case 'DECIMAL':
			// 	$this->classFile[] = $tab.$tab.'pluginEdit::editDecimal(\''.$array['name'].'\');';
			// break;
			
			default:
				message('unknown type: '.$array['type']);
			break;
		}
		if( $locked ){
			$this->classFile[] = $tab.$tab.'}';
		}
	}
	
	function editEnum($name,$list){
		$tab = "\t";
		$list = str_replace("'","\'",$list);
		$list = "array('".str_replace(',',"','",$list)."')";
		$this->classFile[] = $tab.$tab.'pluginEdit::editList(\''.$name.'\','.$list.',false);';
	}
	function editSet($name,$list){
		$tab = "\t";
		$list = str_replace("'","\'",$list);
		$list = "array('".str_replace(',',"','",$list)."')";
		$this->classFile[] = $tab.$tab.'pluginEdit::editList(\''.$name.'\','.$list.',true);';
	}
	
	////////////////////////////////////////////////////////////////////////
	//
	//		Create the SQL File
	//
	
	// this needs to match the format of installDB.php
	function createSql($array){
		//Name
			$name = toStorage($array['name'],true);
			if($name=='keywords'){
				return;
			}
		
		//sql
			$column =& $this->sqlFile['columns'][$name];
			$column = '`'.$name.'` ';
			
			switch($array['type']){
				case 'URL':
					$column .= 'VARCHAR(255)';
				break;
				case 'WIKI SYNTAX':
					$column .= 'TEXT ';
				break;
				default:
					$column .= $array['type'];
				break;
			}
			
			switch($this->types[$array['type']]){
				case 'len':
				case 'int':
					if( !empty($array['len']) ){
						$column .= '('.$array['len'].')';
					}
					$column .= ' NOT NULL';
				break;
				case 'list':
					$array['len'] = str_replace("'","\'",$array['len']);
					$array['len'] = "'".str_replace(',',"','",$array['len'])."'";
					$column .= '('.$array['len'].') NOT NULL';
				break;
				
				default:
					$column .= ' NOT NULL';
				break;
			}
	}
	
	
	///////////////////////////////////////////////////////////////
	//
	//		Check Values
	//
	
	function checkAll($name=true){
		global $wbTablePrefix;
		$done = true;
		$_POST['plugin'] = toStorage($_POST['plugin']);
		

		//
		//	Plugin Name
		//
			if( $name ){
				$methods = get_class_methods('dbPage');
				$methods = array_flip($methods);
				
				if( empty($_POST['plugin']) ){
					message('Plugin Name cannot be empty.');
					$done = false;
					
				}else{
					
					if( isset($methods[wbStrtolower($_POST['plugin'])])){
						message('Please choose a different plugin name. (2)');
						$done = false;
					}
					
					if( !$this->checkName($_POST['plugin']) ){
						$done = false;
					}
				}
			}
				
			
		//
		//	Check all the additional
		//
		if( isset($_POST['add']) && is_array($_POST['add']) ){
			$temp = array();
			foreach($_POST['add'] as $key => $array){
				
				if( !$this->checkAdditional($array) ){
					$done = false;
					continue;
				}
				$_POST['add'][$key] = $array;
				$temp[$_POST['add'][$key]['codeName']] = true;
			}
			
			if( count($_POST['add']) != count($temp) ){
				$done = false;
				message('Two columns cannot share the same name.');
			}
		
		}else{
			$done = false;
			message('There must be at least one Column to create a plugin.');
		}

		return $done;
	}
	
	function checkAdditional(&$array){
			static $warn_name = false;
			
			if( empty($array['name']) ){
				if( !$warn_name ){
					message('You must specify a Name for each of the additional fields');
					$warn_name = true;
				}
				return false;
			}
			$array['name'] = str_replace(' ','_',$array['name']);
			$lowerName = wbStrtolower($array['name']);
			$array['codeName'] = $lowerName;

			
		//
		//	special names
		//
			if( $lowerName === 'keywords' ){
				if( empty($array['len']) ){
					$array['len'] = '255';
				}
			}elseif( array_key_exists($lowerName, $this->existingVars ) ){
				message('"'.$array['name'].'" is a reserved word and cannnot be used for the Name of an additional field.');
				return false;
			}
		
		//
		//	isset checks
		//
			
			$lowerName = toStorage($lowerName);
			$regExp = '^[A-Za-z0-9_-]+$';
			if(!eregi($regExp,$lowerName)){
				message('Name must only contain alphanumeric, underscore and dash characters.');
				return false;
			}
			
			if( isset($this->usedCols[$lowerName]) ){
				message('You cannot have two fields named "'.$array['name'].'".');
				return false;
			}
			if( !isset($this->types[$array['type']]) || !$this->types[$array['type']] ){
				if( empty($array['type']) ){
					message('Unknown Type given for "'.$array['name'].'".');
				}else{
					message('Unknown Type "'.$array['type'].'" given for "'.$array['name'].'".');
				}
				return false;
			}
		
		//
		//	check type
		//
		
			$goodType = true;
			$temp = $this->types[$array['type']];
			switch($temp){
				case 'dec':
				case 'int':
					if( !empty($array['len']) && !is_numeric($array['len']) ){
						$goodType = false;
						message('Must supply a numeric value for "'.$array['name'].'" ');
					}
				break;
				case 'len':
					if( !is_numeric($array['len']) ){
						$goodType = false;
						message('Must supply a numeric value for "'.$array['name'].'" ');
					}
				break;
				
				case 'list':
					$goodType = $this->needCommaList($array['len'],$array['name']);
				break;

				case 'WIKI SYNTAX';
				case 'url':				
				case 'text':
				case 'date':
					//nothing needed
				break;
				default:
					trigger_error('oops');
				break;
			}
			
			if( !$goodType ){
				return false;
			}
			
		$this->usedCols[$array['name']] = 1;
		return true;
	}
	
	function needCommaList($string,$name){
		if( empty($string) ){
			message('"'.$name.'" must be a comma separated list of words.');
			return false;
		}
		if( strpos($string,',') === false){
			message('"'.$name.'" must be a comma separated list of words.');
			return false;
		}
		return true;
	}
	
	//////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//		Editing forms
	//

	
	function form($args,$newPlugin=true){
		global $page;
		
		
		if( empty($args) ){
			$args['plugin'] = '';
			$array[] =  array('name'=>'','type'=>'','len'=>'');
			$array[] =  array('name'=>'','type'=>'','len'=>'');
			$array[] =  array('name'=>'Content','type'=>'WIKI SYNTAX','len'=>'');
			$array[] =  array('name'=>'Keywords','type'=>'','len'=>'');
			$args['add'] = array();
			$args['add'] += $array;
		}
		
		
		switch($page->userCmd){
			
			case 'options':
				$this->moreOptions();
			return;
			
			case 'save options':
				$args = $this->saveOptions();
			break;
			
			case 'remove':
				if( isset($args['add'][$page->cmdArg[0]]) ){
					unset($args['add'][$page->cmdArg[0]]);
				}
			break;
			case 'up':
				if( isset($args['add'][$page->cmdArg[0]]) && isset($args['add'][$page->cmdArg[0]-1])){
					$temp = $args['add'][$page->cmdArg[0]];
					$args['add'][$page->cmdArg[0]] = $args['add'][$page->cmdArg[0]-1];
					$args['add'][$page->cmdArg[0]-1] = $temp;
				}
			break;
			case 'down':
				if( isset($args['add'][$page->cmdArg[0]]) && isset($args['add'][$page->cmdArg[0]+1])){
					$temp = $args['add'][$page->cmdArg[0]+1];
					$args['add'][($page->cmdArg[0]+1)] = $args['add'][$page->cmdArg[0]];
					$args['add'][$page->cmdArg[0]] = $temp;
				}
			break;
			case 'add field';
				$args['add'][] = array();
			break;
		}
		
		echo '<table style="width:100%" cellspacing="0" border="0" class="tableRows">';
		echo '<tr>';
			echo '<td>';
			echo 'Data Type Name: ';
			echo '</td>';
			echo '<td colspan="2">';
			if( $newPlugin ){
				echo '<input type="text" name="plugin" value="'.$args['plugin'].'" /> &nbsp; ';
				echo ' <input type="submit" name="cmd" value="Check" />';
			}else{
				echo '<input type="text" name="plugin" value="'.$args['plugin'].'" readonly="readonly" style="background-color:#f1f1f1" /> &nbsp; ';
			}
			echo '</td>';
		echo '</tr>';
		echo '<tr>';
			echo '<th>Column Name</th>';
			echo '<th>Type</th>';
			echo '<th >Length/Values</th>';
			echo '<th colspan="4">Actions</th>';
		echo '</tr>';
		echo '<tr>';
			echo '<td>Title</td>';
			echo '<td>VARCHAR</td>';
			echo '<td>40</th>';
			echo '<td colspan="4"></td>';
		echo '</tr>';
		
		if( isset($args['add']) && is_array($args['add']) ){
			$count = count($args['add']);
			foreach($args['add'] as $temp){
				$this->formRow($temp,$count);
			}
		}		
		
		echo '<tr>';
			echo '<td>';
			echo '<input type="submit" name="cmd" title="Add Field" value="Add Field" /> &nbsp; ';
			echo '</td>';
			echo '<td></td>';
			echo '<td></td>';
			echo '<td>';
			echo '</td>';
		echo '</tr>';
		echo '</table>';
		$this->formSubmit();
		$this->formFooter();
	}
	
	function formSubmit(){}
	
	function formFooter(){
		echo '<br/>';
		echo '<h2 class="heading underline">Note</h2>';
		echo '<ul>';
		echo '<li>';
		echo 'Most of the column types are the same as the <a href="http://dev.mysql.com/doc/refman/5.0/en/data-types.html" class="external" target="_blank">MySQL Column Types</a>.';
		echo '</li>';
		echo '</ul>';
	}
	
	function formRow($array=array(),$count){
		static $i = 0;
		$array += array('name'=>'','type'=>'','len'=>'','options'=>'');
				
		//static $classes = array(' class="tableRowEven" ',' class="tableRowOdd" ');
		//echo '<tr'.$classes[($i%2)].'>'; //messes up the display of <input> elements
		echo '<tr style="BORDER-STYLE: none none dashed none;BORDER-COLOR: #aaaaaa;border-width: 1px;vertical-align:middle;padding: .7em 1em .7em 1em;">';
		echo '<td>';
			$name = wbStrtolower($array['name']);
			
			if( $name === 'keywords' ){
				echo 'Keywords / Tags';
				echo '<input type="hidden" name="add['.$i.'][name]" value="Keywords" />';
				echo '</td>';
				echo '<td>';
					echo '<select name="add['.$i.'][type]">';
						if( $array['type'] === 'SET' ){
							echo '<option value="VARCHAR">VARCHAR</option>';
							echo '<option value="ENUM">ENUM</option>';
							echo '<option value="SET" selected="selected">SET</option>';
						}elseif($array['type'] === 'ENUM' ){
							echo '<option value="VARCHAR">VARCHAR</option>';
							echo '<option value="ENUM" selected="selected">ENUM</option>';
							echo '<option value="SET">SET</option>';
						}else{
							echo '<option value="VARCHAR">VARCHAR</option>';
							echo '<option value="ENUM">ENUM</option>';
							echo '<option value="SET">SET</option>';
						}
					echo '</select>';
				echo '</td>';
				echo '<td><input type="text" name="add['.$i.'][len]" value="'.wbHtmlspecialchars($array['len']).'" />';
				echo '</td>';
				
			}else{
			
				echo '<input type="text" name="add['.$i.'][name]" value="'.wbHtmlspecialchars($array['name']).'"/>';
				echo '</td>';
				echo '<td>';
					echo '<select name="add['.$i.'][type]">';
						$inGroup = false;
						foreach($this->types as $type => $null){
							if( is_bool($null) ){
								if( $inGroup ){
									echo '<option value=""></option>';
									echo '</optgroup>';
								}
								echo '<option value=""></option>';
								echo '<optgroup label="'.$type.'" title="'.$type.'">';
								$inGroup = true;
							}elseif( $array['type'] === $type ){
								echo '<option value="'.$type.'" selected="selected">'.$type.'</option>';
							}else{
								echo '<option value="'.$type.'">'.$type.'</option>';
							}
						}
						if( $inGroup ){
							echo '<option value=""></option>';
							echo '</optgroup>';
						}
					echo '</select>';
				echo '</td>';
				echo '<td>';
					echo '<input type="text" name="add['.$i.'][len]" value="'.wbHtmlspecialchars($array['len']).'" />';
				echo '</td>';
			}
			
			echo '<td style="margin-left:0;margin-right:0;padding-left:0;padding-right:0">';
				if( $i != 0){
					echo '<input type="submit" name="cmd['.$i.']" title="Move Up" value="Up"/>';
				}else{
					echo '<input type="submit" name="" title="Move Up" value="Up"/>';
				}
			echo '</td>';
			echo '<td style="margin-left:0;margin-right:0;padding-left:0;padding-right:0">';
				if( ($i+1) != $count ){
					echo '<input type="submit" name="cmd['.$i.']" title="Move Down" value="Down" />';
				}else{
					echo '<input type="submit" name="" value="Down" />';
				}
			echo '</td>';
			echo '<td style="margin-left:0;margin-right:0;padding-left:0;padding-right:0">';
				echo '<input type="submit" name="cmd['.$i.']" title="Remove Field" value="Remove" />';
			echo '</td>';
			echo '<td style="margin-left:0;margin-right:0;padding-left:0;padding-right:0">';
				
				echo '<input type="submit" name="cmd['.$i.']" value="Options" title="Options" />';
				echo '<input type="hidden" name="add['.$i.'][options]" value="'.wbHtmlspecialchars($array['options']).'" />';
			echo '&nbsp; <span class="sm">';
			echo str_replace(',',', ',$array['options']);
			echo '</span>';
			echo '</td>';
		echo '</tr>';
		$i++;
	}
	function moreOptions(){
		global $page;
		
		$currOptions = array();
		$index =& $page->cmdArg[0];
		
		if( isset($_POST['add'][$index]['options']) ){
			$currOptions = explode(',',$_POST['add'][$index]['options']);
			$currOptions = array_flip($currOptions);
			
		}

		
		$temp = serialize($_POST);
		echo '<textarea name="serialized" style="display:none">';
		echo wbHtmlspecialchars($temp);
		echo '</textarea>';
		
		echo '<input type="hidden" name="index" value="'.$page->cmdArg[0].'" />';
		echo '<table class="tableRows" style="margin: 2em auto 0 auto;">';
		echo '<tr>';
		echo '<th>Option</th>';
		echo '<th>Value</th>';
		echo '</tr>';
		echo '<tr>';
			echo '<td style="text-align:right">';
			echo 'Edit By Owner Only';
			echo '</td>';
			echo '<td>';
			echo '<input type="checkbox" name="options[]" value="lock" ';
				if( isset($currOptions['lock']) ){
					echo 'checked="checked" ';
				}
				echo '/>';
			echo '</td>';
			echo '</tr>';
			
		echo '<tr>';
			echo '<td></td>';
			echo '<td>';
			echo '<input type="submit" name="cmd" value="Save Options" />';
			echo '</td>';
			echo '</tr>';
		
		echo '</table>';
		
	}
	
	function saveOptions(){
		
		//
		//	Check
		//
		if( empty($_POST['serialized']) ){
			message('<b>Error</b> Your plugin data was lost.');
			return false;
		}
		$temp = unserialize($_POST['serialized']);
		if( !is_array($temp) ){
			message('<b>Error</b> Your plugin data was lost.');
			return false;
		}
		if( !isset($_POST['index']) ){
			return $temp;
		}
		$index =& $_POST['index'];
		if( !isset($temp['add'][$index]) ){
			return $temp;
		}
		
		//
		//	set option
		//
		
		if( isset($_POST['options']) ){
			foreach($_POST['options'] as $option){
			
				switch( $option ){
					case 'lock':
						$options[] = 'lock';
					break;
				}
			}
			$options = array_unique($options);
			$temp['add'][$index]['options'] = implode(',',$options);
		}else{
			$temp['add'][$index]['options'] = '';
		}
		
		return $temp;
		
	}
	
}
