<?php
/*======================================================================*\
|| #################################################################### ||
|| # vBulletin Hack Management System                                 # ||
|| # ---------------------------------------------------------------- # ||
|| # All PHP code in this file is ©2004 GameCrash.org.                # ||
|| # http://www.gamecrash.org (soon) | http://www.letzplay.de         # ||
|| # ---------------------------------------------------------------- # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ---------------- VBULLETIN IS NOT FREE SOFTWARE ---------------- # ||
|| # http://www.vbulletin.com | http://www.vbulletin.com/license.html # ||
|| #################################################################### ||
\*======================================================================*/

// ##### OUTPUTLINE ###############################################
// # Output a line with any informations                          #
// ################################################################

function vbhms_do_outputline($action)
{
	vbhms_print_info_line($action['data']);
}

vbhms_add_executefunction('outputline', 'vbhms_do_outputline',
	array
	(
		'possibledata' => 'STR'
	)
);

// ##### STARTLIST ################################################
// # Begin a list (which every output will use then)              #
// ################################################################

function vbhms_do_startlist($action)
{
	vbhms_print_list_start();
}

vbhms_add_executefunction('startlist', 'vbhms_do_startlist',
	array
	(
		'possibledata' => 'NONE'
	)
);

// ##### ENDLIST ##################################################
// # Close the list we began before                               #
// ################################################################

function vbhms_do_endlist($action)
{
	vbhms_print_list_end();
}

vbhms_add_executefunction('endlist', 'vbhms_do_endlist',
	array
	(
		'possibledata' => 'NONE'
	)
);

// ##### CHECKFILEEXISTS ##########################################
// # Make sure the user has uploaded all files                    #
// ################################################################

function vbhms_do_checkfileexists($action)
{
	vbhms_print_info_line_start("Checking if file {$action['data']} exists... ");
	
	if (file_exists($action['data']) && is_readable($action['data']))
	{
		vbhms_print_info_line_end('ok.');
		return;
	}
	
	vbhms_print_info_line_end('<strong>failed!</strong>');

	if (!empty($action['attrs']['exit']))
	{
		vbhms_print_fatal_error("The file {$action['data']} must exist to go on.");
	}
}

vbhms_add_executefunction('checkfileexists', 'vbhms_do_checkfileexists',
	array
	(
		'possibledata' => 'STR',
		'attributes' => array
		(
			'exit' => array
			(
				'musthave' => false,
				'possiblevalues' => 'STR'
			)
		)
	)
);

// ##### CREATEPHRASEGROUP ########################################
// # Create a new phrase group                                    #
// ################################################################

function vbhms_do_createphrasegroup($action)
{
	global $DB_site;

	if (empty($action['data']))
	{
		$action['data'] = $action['attrs']['handler'];
	}
	
	vbhms_print_info_line_start("Creating new phrasegroup '$action[data]' ({$action[attrs][handler]})... ");
	
	if ($DB_site->query_first("SELECT * FROM " . TABLE_PREFIX . "phrasetype WHERE fieldname='" . addslashes($action['attrs']['handler']) . "'"))
	{
		if ($action['attrs']['onduplicate'] == 'skip')
		{
			vbhms_print_info_line_end('skipped (already exists).');
			return;
		}
		else
		{
			vbhms_print_fatal_error("The phrasegroup {$action['attrs']['handler']} does already exist.");
		}
	}
	
	// max() does not work as we need a value below 1000
	$newid = $DB_site->query_first("SELECT phrasetypeid FROM " . TABLE_PREFIX . "phrasetype WHERE phrasetypeid<1000 ORDER BY phrasetypeid DESC LIMIT 1");
	$newid = $newid['phrasetypeid'] + 1;
	
	$DB_site->query("INSERT INTO " . TABLE_PREFIX . "phrasetype (phrasetypeid, fieldname, title, editrows) VALUES ({$newid}, '" . addslashes($action['attrs']['handler']) . "', '" . addslashes($action['data']) . "', 3)");
	$DB_site->query("ALTER TABLE " . TABLE_PREFIX . "language ADD phrasegroup_" . addslashes($action['attrs']['handler']) . " MEDIUMTEXT NOT NULL");
	
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('createphrasegroup', 'vbhms_do_createphrasegroup',
	array
	(
		'possibledata' => 'STR_NOHTML',
		'attributes' => array
		(
			'handler' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			),
			'onduplicate' => array
			(
				'musthave' => true,
				'possiblevalues' => array('skip', 'error')
			)
		)
	)
);

// ##### CREATEPHRASE #############################################
// # Create a new phrase                                          #
// ################################################################

function vbhms_do_createphrase($action)
{
	global $DB_site;
	static $groupidcache;

	vbhms_print_info_line_start("Creating new phrase '{$action[attrs][handler]}'... ");

	if (!isset($groupidcache["{$action['attrs']['group']}"]))
	{
		$groupid = $DB_site->query_first("SELECT phrasetypeid FROM " . TABLE_PREFIX . "phrasetype WHERE fieldname='" . addslashes($action['attrs']['group']) . "'");
		if (intval($groupid['phrasetypeid']) < 1)
		{
			vbhms_print_fatal_error("The phrasegroup {$action['attrs']['group']} does not exist.");
		}
		$groupidcache["{$action['attrs']['group']}"] = $groupid['phrasetypeid'];
	}
	
	vbhms_insert_new_phrase($action['attrs']['handler'], $action['data'], $groupidcache["{$action['attrs']['group']}"]);
	
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('createphrase', 'vbhms_do_createphrase',
	array
	(
		'possibledata' => 'ANY',
		'attributes' => array
		(
			'group' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			),
			'handler' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			)
		)
	)
);

// ##### RENAMEPHRASE #############################################
// # Rename a new phrase                                          #
// ################################################################

function vbhms_do_renamephrase($action)
{
	global $DB_site;
	static $groupidcache;

	vbhms_print_info_line_start("Renaming phrase '{$action['attrs']['oldhandler']}' to '{$action['attrs']['newhandler']}'... ");

	if (!isset($groupidcache["{$action['attrs']['group']}"]))
	{
		$groupid = $DB_site->query_first("SELECT phrasetypeid FROM " . TABLE_PREFIX . "phrasetype WHERE fieldname='" . addslashes($action['attrs']['group']) . "'");
		if (intval($groupid['phrasetypeid']) < 1)
		{
			vbhms_print_fatal_error("The phrasegroup {$action['attrs']['group']} does not exist.");
		}
		$groupidcache["{$action['attrs']['group']}"] = $groupid['phrasetypeid'];
	}
	
	$DB_site->query("UPDATE " . TABLE_PREFIX . "phrase SET varname='" . addslashes($action['attrs']['newhandler']) . "' WHERE varname='" . addslashes($action['attrs']['oldhandler']) . "' AND phrasetypeid=" . $groupidcache["{$action['attrs']['group']}"]);
	
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('renamephrase', 'vbhms_do_renamephrase',
	array
	(
		'possibledata' => 'NONE',
		'attributes' => array
		(
			'group' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			),
			'oldhandler' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			),
			'newhandler' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			)
		)
	)
);

// ##### DROPPHRASEGROUP ##########################################
// # Remove a phrase group and the phrases it contains            #
// ################################################################

function vbhms_do_dropphrasegroup($action)
{
	global $DB_site;

	vbhms_print_info_line_start("Removing phrasegroup '{$action['attrs']['handler']}'... ");

	$phrasegroupinfo = $DB_site->query_first("SELECT phrasetypeid FROM " . TABLE_PREFIX . "phrasetype WHERE fieldname='". addslashes($action['attrs']['handler']) ."'");
	$phrasegroupid = $phrasegroupinfo['phrasetypeid'];
	if (intval($phrasegroupid) < 1)
	{
		vbhms_print_info_line_end('phrasegroup does not exist.');
		return;
	}
	
	$phrases = $DB_site->query("SELECT varname FROM " . TABLE_PREFIX . "phrase WHERE languageid=0 AND phrasetypeid={$phrasegroupid}");
	while($phrase = $DB_site->fetch_array($phrases)){
		vbhms_delete_phrase($phrase['varname'], $phrasegroupid);
	}

	$DB_site->query("DELETE FROM " . TABLE_PREFIX . "phrasetype WHERE phrasetypeid={$phrasegroupid}");
	$DB_site->query("ALTER TABLE " . TABLE_PREFIX . "language DROP phrasegroup_" . addslashes($action['attrs']['handler']));
	
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('dropphrasegroup', 'vbhms_do_dropphrasegroup',
	array
	(
		'possibledata' => 'NONE',
		'attributes' => array
		(
			'handler' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			)
		)
	)
);

// ##### DROPPHRASE ###############################################
// # Remove a phrase                                              #
// ################################################################

function vbhms_do_dropphrase($action)
{
	global $DB_site;
	
	vbhms_print_info_line_start("Removing phrase '{$action['attrs']['handler']}'... ");
	
	$phrasegroupinfo = $DB_site->query_first("SELECT phrasetypeid FROM " . TABLE_PREFIX . "phrasetype WHERE fieldname='". addslashes($action['attrs']['group']) ."'");
	$phrasegroupid = $phrasegroupinfo['phrasetypeid'];
	vbhms_delete_phrase($action['attrs']['handler'], $phrasegroupid);
	
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('dropphrase', 'vbhms_do_dropphrase',
	array
	(
		'possibledata' => 'NONE',
		'attributes' => array
		(
			'group' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			),
			'handler' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			)
		)
	)
);

// ##### REBUILDLANGUAGE ##########################################
// # Rebuild all phrases                                          #
// ################################################################

function vbhms_do_rebuildlanguage($action)
{
	$languageid = intval($action['attrs']['languageid']);
	if ($languageid < 1)
	{
		$languageid = -1;
	}
	
	vbhms_print_info_line_start('Rebuilding phrases... ');
	build_language($languageid);
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('rebuildlanguage', 'vbhms_do_rebuildlanguage',
	array
	(
		'possibledata' => 'NONE',
		'attributes' => array
		(
			'languageid' => array
			(
				'musthave' => false,
				'possiblevalues' => 'INT'
			)
		)
	)
);

// ##### CREATESETTINGGROUP #######################################
// # Create a new setting group                                   #
// ################################################################

function vbhms_do_createsettinggroup($action)
{
	global $DB_site;

	if (empty($action['data']))
	{
		$action['data'] = $action['attrs']['handler'];
	}
	
	vbhms_print_info_line_start("Creating new settinggroup '{$action['data']}' ({$action['attrs']['handler']})... ");
	
	if ($DB_site->query_first("SELECT * FROM " . TABLE_PREFIX . "settinggroup WHERE grouptitle='" . addslashes($action['attrs']['handler']) . "'"))
	{
		if ($action['attrs']['onduplicate'] == 'replace')
		{
			$DB_site->query("DELETE FROM " . TABLE_PREFIX . "settinggroup WHERE grouptitle='" . addslashes($action['attrs']['handler']) . "'");
			vbhms_delete_phrase('settinggroup_' . addslashes($action['attrs']['handler']), PHRASETYPEID_SETTING);
		}
		elseif ($action['attrs']['onduplicate'] == 'skip')
		{
			vbhms_print_info_line_end('skipped (already exists).');
			return;
		}
		else
		{
			vbhms_print_fatal_error("The settinggroup {$action['attrs']['handler']} does already exist.");
		}
	}
	
	$DB_site->query("INSERT INTO " . TABLE_PREFIX . "settinggroup (grouptitle, volatile, displayorder) VALUES ('" . addslashes($action['attrs']['handler']) . "', 0, 10000)");
	vbhms_insert_new_phrase('settinggroup_' . addslashes($action['attrs']['handler']), $action['data'], PHRASETYPEID_SETTING);
	
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('createsettinggroup', 'vbhms_do_createsettinggroup',
	array
	(
		'possibledata' => 'STR_NOHTML',
		'attributes' => array
		(
			'handler' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			),
			'onduplicate' => array
			(
				'musthave' => true,
				'possiblevalues' => array('skip', 'replace', 'error')
			)
		)
	)
);

// ##### CREATESETTING ############################################
// # Create a new setting                                         #
// ################################################################

function vbhms_do_createsetting($action)
{
	global $DB_site;

	if (empty($action['data']))
	{
		$action['data'] = $action['attrs']['handler'];
	}
	
	if (intval($action['attrs']['displayorder']) < 1)
	{
		$action['attrs']['displayorder'] = 10;
	}
	
	$value = $action['attrs']['default'];

	vbhms_print_info_line_start("Creating new setting '{$action['attrs']['handler']}'... ");
	
	if ($currentsetting = $DB_site->query_first("SELECT value FROM " . TABLE_PREFIX . "setting WHERE varname='" . addslashes($action['attrs']['handler']) . "'"))
	{
		if ($action['attrs']['onduplicate'] == 'updatevalue')
		{
			$DB_site->query("UPDATE " . TABLE_PREFIX . "setting SET value='" . addslashes($action['attrs']['default']) . "' WHERE varname='" . addslashes($action['attrs']['handler']) . "'");
			vbhms_print_info_line_end('ok (updated value).');
			return;
		}
		elseif ($action['attrs']['onduplicate'] == 'updatesetting')
		{
			$value = $currentsetting['value'];
			$DB_site->query("DELETE FROM " . TABLE_PREFIX . "setting WHERE varname='" . addslashes($action['attrs']['handler']) . "'");
			vbhms_delete_phrase("setting_" . addslashes($action['attrs']['handler']) . "_title", PHRASETYPEID_SETTING);
			vbhms_delete_phrase("setting_" . addslashes($action['attrs']['handler']) . "_desc", PHRASETYPEID_SETTING);
		}
		elseif ($action['attrs']['onduplicate'] == 'replace')
		{
			$DB_site->query("DELETE FROM " . TABLE_PREFIX . "setting WHERE varname='" . addslashes($action['attrs']['handler']) . "'");
			vbhms_delete_phrase("setting_" . addslashes($action['attrs']['handler']) . "_title", PHRASETYPEID_SETTING);
			vbhms_delete_phrase("setting_" . addslashes($action['attrs']['handler']) . "_desc", PHRASETYPEID_SETTING);
		}
		elseif ($action['attrs']['onduplicate'] == 'skip')
		{
			vbhms_print_info_line_end('skipped (already exists).');
			return;
		}
		else
		{
			vbhms_print_fatal_error("The setting {$action['attrs']['handler']} does already exist.");
		}
	}
	
	$DB_site->query("INSERT INTO " . TABLE_PREFIX . "setting 
	(varname, grouptitle, value, defaultvalue, optioncode, displayorder, volatile)
	VALUES 
	(
		'" . addslashes($action['attrs']['handler']) . "', 
	 	'" . addslashes($action['attrs']['group']) . "', 
		'" . addslashes($value) . "',
		'" . addslashes($action['attrs']['default']) . "',
		'" . addslashes($action['attrs']['optioncode']) . "',
		{$action['attrs']['displayorder']},
		0
	)");

	vbhms_insert_new_phrase("setting_" . addslashes($action['attrs']['handler']) . "_title", $action['attrs']['title'], PHRASETYPEID_SETTING);
	vbhms_insert_new_phrase("setting_" . addslashes($action['attrs']['handler']) . "_desc", $action['data'], PHRASETYPEID_SETTING);
	
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('createsetting', 'vbhms_do_createsetting',
	array
	(
		'possibledata' => 'STR',
		'attributes' => array
		(
			'onduplicate' => array
			(
				'musthave' => true,
				'possiblevalues' => array('skip', 'updatevalue', 'updatesetting', 'replace', 'error')
			),
			'handler' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			),
			'group' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			),
			'title' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			),
			'displayorder' => array
			(
				'musthave' => false,
				'possiblevalues' => 'STR_NOHTML'
			),
			'default' => array
			(
				'musthave' => false,
				'possiblevalues' => 'ANY'
			),
			'optioncode' => array
			(
				'musthave' => true,
				'possiblevalues' => array('', 'yesno', 'textarea', 'cpstylefolder')
			)
		)
	)
);

// ##### DROPSETTINGGROUP #########################################
// # Remove a setting group                                       #
// ################################################################

function vbhms_do_dropsettinggroup($action)
{
	global $DB_site;

	vbhms_print_info_line_start("Removing settinggroup '{$action['attrs']['handler']}'... ");
	
	$settings = $DB_site->query("SELECT varname FROM " . TABLE_PREFIX . "setting WHERE grouptitle='" . addslashes($action['attrs']['handler']) . "'");
	while($setting = $DB_site->fetch_array($settings)){
		$DB_site->query("DELETE FROM " . TABLE_PREFIX . "setting WHERE varname='" . addslashes($setting['varname']) . "'");
		vbhms_delete_phrase("setting_{$setting['varname']}_title", PHRASETYPEID_SETTING);
		vbhms_delete_phrase("setting_{$setting['varname']}_desc", PHRASETYPEID_SETTING);
	}
	
	$DB_site->query("DELETE FROM " . TABLE_PREFIX . "settinggroup WHERE grouptitle='" . addslashes($action['attrs']['handler']) . "'");
	vbhms_delete_phrase("settinggroup_" . addslashes($action['attrs']['handler']), PHRASETYPEID_SETTING);
	
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('dropsettinggroup', 'vbhms_do_dropsettinggroup',
	array
	(
		'possibledata' => 'NONE',
		'attributes' => array
		(
			'handler' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			)
		)
	)
);

// ##### DROPSETTING ##############################################
// # Remove a setting                                             #
// ################################################################

function vbhms_do_dropsetting($action)
{
	global $DB_site;

	vbhms_print_info_line_start("Removing setting '{$action['attrs']['handler']}'... ");
	
	$DB_site->query("DELETE FROM " . TABLE_PREFIX . "setting WHERE varname='" . addslashes($action['attrs']['handler']) . "'");
	vbhms_delete_phrase("setting_{$action['attrs']['handler']}_title", PHRASETYPEID_SETTING);
	vbhms_delete_phrase("setting_{$action['attrs']['handler']}_desc", PHRASETYPEID_SETTING);
	
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('dropsetting', 'vbhms_do_dropsetting',
	array
	(
		'possibledata' => 'STR',
		'attributes' => array
		(
			'handler' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			)
		)
	)
);

// ##### REBUILDSETTINGS ##########################################
// # Rebuild the setting cache                                    #
// ################################################################

function vbhms_do_rebuildsettings($action)
{
	global $DB_site;

	vbhms_print_info_line_start('Rebuilding settings... ');
	build_options();
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('rebuildsettings', 'vbhms_do_rebuildsettings',
	array
	(
		'possibledata' => 'NONE'
	)
);

// ##### CREATESTYLE ##############################################
// # Create a style and return the new styleid                    #
// ################################################################

function vbhms_do_createstyle($action)
{
	global $DB_site;
	
	$parentid = intval($action['attrs']['parentid']);
	if ($parentid == 0)
	{
		$parentid = -1;
	}
	
	vbhms_print_info_line_start("Inserting new style '{$action['data']}'... ");

	$DB_site->query("INSERT INTO " . TABLE_PREFIX . "style (title, parentid, userselect, displayorder) VALUES ('" . addslashes($action['data']) . "', $parentid, 0, 1)");
	
	if (!empty($action['attrs']['resultvar']))
	{
		global ${$action['attrs']['resultvar']};
		${$action['attrs']['resultvar']} = $DB_site->insert_id();
	}

	build_style_datastore();
	build_template_parentlists();
	
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('createstyle', 'vbhms_do_createstyle',
	array
	(
		'possibledata' => 'STR_NOHTML',
		'attributes' => array
		(
			'parentid' => array
			(
				'musthave' => false,
				'possiblevalues' => 'INT'
			),
			'resultvar' => array
			(
				'musthave' => false,
				'possiblevalues' => 'STR'
			)
		)
	)
);

// ##### REBUILDSTYLE #############################################
// # Rebuild a style                                              #
// ################################################################

function vbhms_do_rebuildstyle($action)
{
	$styleid = intval($action['attrs']['styleid']);
	if ($styleid == 0)
	{
		$styleid = -1;
	}
	print_rebuild_style($styleid, $action['attrs']['title'], 1, 1, 1, 1);
}

vbhms_add_executefunction('rebuildstyle', 'vbhms_do_rebuildstyle',
	array
	(
		'possibledata' => 'NONE',
		'attributes' => array
		(
			'styleid' => array
			(
				'musthave' => true,
				'possiblevalues' => 'INT'
			)
		)
	)
);

// ##### CREATEREPLACEMENT ########################################
// # Create a new replacement variable in a known style           #
// ################################################################

function vbhms_do_createreplacement($action)
{
	global $DB_site, $hackinfo;
	
	vbhms_print_info_line_start("Creating replacment for '{$action['attrs']['findtext']}'... ");

	$styleid = intval($action['attrs']['styleid']);
	if ($styleid == 0)
	{
		$styleid = -1;
	}
	
	$DB_site->query("REPLACE INTO " . TABLE_PREFIX . "template (styleid, title, template, templatetype, dateline, username) VALUES ({$styleid}, '" . addslashes($action['attrs']['findtext']) . "', '" . addslashes($action['data']) . "', 'replacement', " . TIMENOW . ", '" . addslashes($hackinfo['autor']['name']) . "')");

	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('createreplacement', 'vbhms_do_createreplacement',
	array
	(
		'possibledata' => 'ANY',
		'attributes' => array
		(
			'styleid' => array
			(
				'musthave' => true,
				'possiblevalues' => 'INT'
			),
			'findtext' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR'
			)
		)
	)
);

// ##### CREATETEMPLATE ###########################################
// # Create a new template in a known style                       #
// ################################################################

function vbhms_do_createtemplate($action)
{
	global $DB_site;
	vbhms_print_info_line_start("Creating new template '{$action[attrs][handler]}'... ");
	
	$styleid = intval($action['attrs']['styleid']);
	if ($styleid < 1)
	{
		$styleid = -1;
	}
	
	$template_un = $action['data'];
	$template = compile_template($template_un);
	
	// check if template already exists
	if (!$DB_site->query_first("SELECT templateid FROM " . TABLE_PREFIX . "template WHERE title = '" . addslashes($action['attrs']['handler']) . "' AND styleid = {$styleid}"))
	{
		$result = $DB_site->query("INSERT INTO " . TABLE_PREFIX . "template (styleid, title, template, template_un, dateline, username) VALUES ({$styleid}, '" . addslashes($action['attrs']['handler']) . "', '" . addslashes($template) . "', '" . addslashes($template_un) . "', " . TIMENOW . ", '" . addslashes($hackinfo['autor']['name']) . "')");
	}
	else
	{
		$DB_site->query("UPDATE " . TABLE_PREFIX . "template SET template = '" . addslashes($template) . "', template_un = '" . addslashes($template_un) . "', dateline = " . TIMENOW . ", username = '" . addslashes($hackinfo['autor']['name']) . "' WHERE styleid = {$styleid} AND title = '" . addslashes($action['attrs']['handler']) . "'");
	}
	
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('createtemplate', 'vbhms_do_createtemplate',
	array
	(
		'possibledata' => 'ANY',
		'attributes' => array
		(
			'styleid' => array
			(
				'musthave' => true,
				'possiblevalues' => 'INT'
			),
			'handler' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			)
		)
	)
);

// ##### DROPTEMPLATE #############################################
// # Drop a template                                              #
// ################################################################

function vbhms_do_droptemplate($action)
{
	global $DB_site;
	vbhms_print_info_line_start("Removing template '{$action[attrs][handler]}'... ");
	
	$styleid = intval($action['attrs']['styleid']);
	if ($styleid < 1)
	{
		$styleid = -1;
	}
	
	$DB_site->query("DELETE FROM " . TABLE_PREFIX . "template WHERE title = '" . addslashes($action['attrs']['handler']) . "' AND styleid={$styleid}");
	
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('droptemplate', 'vbhms_do_droptemplate',
	array
	(
		'possibledata' => 'NONE',
		'attributes' => array
		(
			'styleid' => array
			(
				'musthave' => true,
				'possiblevalues' => 'INT'
			),
			'handler' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			)
		)
	)
);

// ##### ALTERTEMPLATE ############################################
// # Alter an existing template in a known style                  #
// ################################################################

function vbhms_do_altertemplate($action)
{
	global $DB_site, $stylecache, $vboptions;
	
	vbhms_print_info_line_start("Altering template '{$action['attrs']['handler']}'... ");
	
	$styleid = intval($action['attrs']['styleid']);
	if ($styleid < 1)
	{
		$styleid = -1;
		$oldtemplate = $DB_site->query_first("SELECT template_un FROM " . TABLE_PREFIX . "template WHERE styleid=-1 AND title='{$action['attrs']['handler']}'");
	}
	else
	{
		cache_styles();
		
		$templatelist = unserialize($stylecache[$styleid]['templatelist']);
		$oldtemplateid = $templatelist["{$action['attrs']['handler']}"];
		
		$oldtemplate = $DB_site->query_first("SELECT template_un FROM " . TABLE_PREFIX . "template WHERE templateid={$oldtemplateid}");
	}

	$newtemplate = $oldtemplate['template_un'];
	
	$lastelement = 'replace';
	$findtext = '';
	$lasterror = '';
	for ($i=0; $i<count($action['subelements']); $i++)
	{
		$element = $action['subelements'][$i];
		if ($element['do'] == 'find' && $lastelement == 'replace' && isset($element['data']))
		{
			$findtext = $element['data'];
			$lastelement = 'find';
		}
		elseif ($element['do'] == 'replace' && $lastelement == 'find')
		{
			$lastelement = 'replace';
			if (!empty($element['attrs']['ifcontains']) && !strstr($newtemplate, $element['attrs']['ifcontains']))
			{
				continue;
			}
			if (!empty($element['attrs']['ifnotcontains']) && strstr($newtemplate, $element['attrs']['ifnotcontains']))
			{
				continue;
			}
			$newtemplate = str_replace($findtext, $element['data'], $newtemplate);
		}
		else
		{
			vbhms_print_info_line_end('<b>Error: Invalid template replacement section</b>');
			return;
		}
	}
	
	if ($newtemplate == $oldtemplate['template_un'])
	{
		vbhms_print_info_line_end('<b>Warning: Haven\'t changed anything</b>');
		return;
	}
	
	$template_un = $newtemplate;
	$template = compile_template($template_un);
	
	// check if template already exists
	if (!$DB_site->query_first("SELECT templateid FROM " . TABLE_PREFIX . "template WHERE title = '" . addslashes($action['attrs']['handler']) . "' AND styleid = $styleid"))
	{
		$result = $DB_site->query("INSERT INTO " . TABLE_PREFIX . "template (styleid, title, template, template_un, dateline, username) VALUES ($styleid, '" . addslashes($action['attrs']['handler']) . "', '" . addslashes($template) . "', '" . addslashes($template_un) . "', " . TIMENOW . ", '" . addslashes($hackinfo['autor']['name']) . "')");
	}
	else
	{
		$DB_site->query("UPDATE " . TABLE_PREFIX . "template SET template = '" . addslashes($template) . "', template_un = '" . addslashes($template_un) . "', dateline = " . TIMENOW . ", username = '" . addslashes($hackinfo['autor']['name']) . "' WHERE styleid = $styleid AND title = '" . addslashes($action['attrs']['handler']) . "'");
	}
	
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('altertemplate', 'vbhms_do_altertemplate',
	array
	(
		'possibledata' => 'NONE',
		'attributes' => array
		(
			'styleid' => array
			(
				'musthave' => true,
				'possiblevalues' => 'INT'
			),
			'handler' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			)
		),
		'subelements' => array
		(
			'find' => array
			(
				'musthave' => true,
				'possibledata' => 'ANY'
			),
			'replace' => array
			(
				'musthave' => true,
				'possibledata' => 'ANY',
				'attributes' => array
				(
					'ifcontains' => array
					(
						'musthave' => false,
						'possiblevalues' => 'ANY'
					),
					'ifnotcontains' => array
					(
						'musthave' => false,
						'possiblevalues' => 'ANY'
					)
				)
			)
		)
	)
);

// ##### INPUTFORM ################################################
// # Show a form to collect data from the user                    #
// ################################################################

function vbhms_do_inputform($action)
{
	global $do, $hack, $step;
	
	print_form_header(str_replace('.php', '', THIS_SCRIPT), $do);
	construct_hidden_code('hack', $hack);
	construct_hidden_code('step', ($step + 1));
	print_table_header($action['attrs']['title']);
	
	for ($i=0; $i<count($action['subelements']); $i++)
	{
		$element = $action['subelements'][$i];
		switch ($element['do'])
		{
			case 'inputcustom':
				if (!empty($element['data']))
				{
					print_description_row($element['data']);
				}
				if (!empty($element['attrs']['sourcefile']))
				{
					require_once($element['attrs']['sourcefile']);
				}
				vbhms_run_custom_function($element['attrs']['function'], $element['attrs']['arguments']);
				break;
		}
	}
	
	print_submit_row('Continue', 'Reset');

	define('NONEXTSTEP', true);
}

vbhms_add_executefunction('inputform', 'vbhms_do_inputform',
	array
	(
		'possibledata' => 'NONE',
		'attributes' => array
		(
			'title' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR'
			)
		),
		'subelements' => array
		(
			'inputcustom' => array
			(
				'musthave' => false,
				'possibledata' => 'ANY',
				'attributes' => array
				(
					'sourcefile' => array
					(
						'musthave' => false,
						'possiblevalues' => 'STR_NOHTML'
					),
					'function' => array
					(
						'musthave' => true,
						'possiblevalues' => 'STR_NOHTML'
					),
					'arguments' => array
					(
						'musthave' => false,
						'possiblevalues' => 'STR'
					)
				)
			)
		)
	)
);

// ##### QUERY ####################################################
// # Replace {{{TABLE_PREFIX}}} and then run the query            #
// ################################################################

function vbhms_do_query($action)
{
	global $DB_site, $hacktemp;
	
	vbhms_print_info_line_start(vbhms_replace_table_prefix($action['attrs']['description']) . '... ');
	
	$res = $DB_site->query(vbhms_replace_table_prefix($action['data']));
	if (!empty($action['attrs']['returnvar']))
	{
		$hacktemp[$action['attrs']['returnvar']] = $DB_site->insert_id($res);
	}
	
	vbhms_print_info_line_end('ok.');
}

vbhms_add_executefunction('query', 'vbhms_do_query',
	array
	(
		'possibledata' => 'STR',
		'attributes' => array
		(
			'description' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			),
			'returnvar' => array
			(
				'musthave' => false,
				'possiblevalues' => 'STR_NOHTML'
			)
		)
	)
);

// ##### EDITFILE #################################################
// # Give instructions to edit a file                             #
// ################################################################

function vbhms_do_editfile($action)
{
	print_table_start();
	print_table_header('Download the file <b>' . $action['attrs']['filename'] . '</b> (and create a backup)', 2, 0, '', 'left', 0);
	
	$subelements = $action['subelements'];
	$isfirst = true;
	
	for ($i=0; $i<count($subelements); $i++)
	{
		$subelement = $subelements[$i];
		if ($subelement['do'] == 'find')
		{
			if (!$isfirst)
			{
				print_hr_row();
			}
			$isfirst = false;
			print_label_row('<b>Find ' . iif($subelement['attrs']['times'] > 1, "({$subelement['attrs']['times']} times)", 'once') . '</b>');
			print_description_row("<pre>{$subelement['data']}</pre>");
		}
		elseif ($subelement['do'] == 'edit')
		{
			switch($subelement['attrs']['action'])
			{
				case 'under':
					$desc = 'Under it add';
					break;
				case 'above':
					$desc = 'Above it add';
					break;
				case 'replace':
					$desc = 'Replace it with';
					break;
				case 'remove':
					$desc = 'Simply remove this content';
					break;
				default:
					$desc = $subelement['attrs']['action'];
					break;
			}
			print_label_row("<b>{$desc}</b>");
			if ($subelement['attrs']['action'] != 'remove')
			{
				print_description_row("<pre>{$subelement['data']}</pre>");
			}
		}
	}

	print_table_footer();
}

vbhms_add_executefunction('editfile', 'vbhms_do_editfile',
	array
	(
		'possibledata' => 'NONE',
		'attributes' => array
		(
			'filename' => array
			(
				'musthave' => true,
				'possiblevalues' => 'STR_NOHTML'
			)
		),
		'subelements' => array
		(
			'find' => array
			(
				'musthave' => true,
				'possibledata' => 'STR_NOHTML',
				'attributes' => array
				(
					'times' => array
					(
						'musthave' => false,
						'possiblevalues' => 'INT'
					)
				)
			),
			'edit' => array
			(
				'musthave' => true,
				'possibledata' => 'STR_NOHTML',
				'attributes' => array
				(
					'action' => array
					(
						'musthave' => true,
						'possiblevalues' => array('under', 'above', 'replace', 'remove')
					)
				)
			)
		)
	)
);

?>