<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Revised: 6/15/2007
// Fixed bug of missing calendar flag.
// Revised: 8/13/2008	ELL
// Added force page names to lower case if that option is selected.
// Revised: 8/28/2009	ELL
// Changed from adding HTML head code to page template to setting up with new head content so user could possibly modify it in head content editor.
// Revised: 9/27/2010 ELL
// Added mode follow-thru such that returning to main menu after editing pages, border areas, or creating pages brings up the same mode in the main menu.
// Revised: 10/12/2010	ELL
// Changed timestamping of `revised` field due to change from VARCHAR to DATETIME in table structure.
// Revised: 11/9/2010	ELL
// Fixed looming bug where sort of head names would keep finding head9 and last head.  (This fix is similar to that done for adding border areas.)
// Also fixed bug of head not getting incremented to head1.  (It worked for head1 to head2, etc, but somehow left out default case.
// Revised: 11/13/2010	ELL
// Added flag to signify first entering editor.
// Revised: 1/12/2/12	ELL
// Added saving to page_data_draft table to accomodate new upgrade for save to draft mode.
// Added default stirng for body HTML.  It has been noticed that the tew CKEditor won't allow typing very easily without content, so we add starter text.
// Revised: 2/7/2012	ELL
// Added table prefix handling.  Added reference to user files folder constant.
// Revised: 4/26/2012	ELL
// Added special-case checking of existence of index.php at webroot level with website setup to run web pages at webroot.  This automatically deletes
// stock forwarded so index.php home page can be created.
// Revised: 10/11/2012	ELL
// Revamped handlng of plugins to include creation of class and css tables as well as deployment of DB tables and button for backend console.
// Revised: 5/10/2013	ELL
// Added handing of plugin code for new header and footer areas.
// Revised: 12/1/2013	ELL
// Modifed for compatibility with BWB version 5.0.
// Revised: 12/13/2013	ELL
// Added refresh of main menu to update buttons and set to last selections.
// Revised: 3/6/2014	ELL
// Fixed bug with plugins creating addtional head1, header1 and footer1 records whenever a user friendly named area was already created.  i.e. head_home
// This also automatically creates user-friendly speceal areas names based on the page name you just created.
// Revised: 4/3/2014	ELL
// Revamped plugin insertion to look for comments that may be left in such that plugins may be installed on existing pages.  Also added hooks for adding
// plugin code to top, bottom, left and right areas for maximum flexibility.
// Revised: 6/16/2014	ELL
// Added storing of plugin ID's into page data to facilitate content sensitive help for relevant plugins in page editor.
// Revised: 10/16/2014	ELL
// Added setting of disable_site_styles for HTML message page plugins.
// ADded copying of use_table_structure and use_table_structure_mobile flages from selected options to page data for modal switching of use of page table structure
// when page is viewed.
// Revised: 1/10/2015	ELL
// Fixed bug with single quotes in plugin HTML doubling up in border areas and content.
// Revised: 5/1/2015	ELL
// Converted from inline RunSQL function to included library RunSQL function.
// Revised: 8/19/2015	ELL
// Added handling of new plugin feature body_onload field.
// Revised: 10/2/2015	ELL
// Added missing language defines.
// Modified to set template field in page data record instead of pulling specific template.
// Modified to set border area and head fields in page data record instead of parsing template layout file to insert custom border area references.
// Added setting of body_onload function name as attribute it the page data table.
// Revised: 5/26/2016	ELL
// Added function string checking to standardize entry of function call.
// Revised: 6/11/2016	ELL
// Modified template minimum requirements checking to include header and footer.
// Added simultaneous deployment of mobile styles for plugin if provided.
// Revised: 8/15/2016	ELL
// Added ability to adapt script and css folders in head HTML to config file settings.
// Revised: 11/11/2016	ELL
// Implemented new plugin field custom_css_sql.
// Revised: 1/9/2017	ELL
// Added hook to allow to be called without going to editor.  This facilitates creating child plugin pages when creating a group of pages out of a plugin group.
// Revised: 6/19/2017	ELL
// Moved 'deployed' field to new table plugins_deployed.
// Revised: 9/27/2018	ELL
// Added addition of touchscreen styles to style sheet list.
// Revised: 3/29/2019	ELL
// Added ability to set $show_custom_styles = 1 even if there is no custom SQL in the plugin by looking for 1@@@@ in $custom_css_sql.
// Added ability to set $show_custom_styles = 0 even if there is custom SQL in the plugin by looking for 0@@@@ in $custom_css_sql.
// Revised: 4/29/2019	ELL
// Converted referenceing of deployed plugins from using 'plugin_id' to 'name'. This is because the SQL REPLACE command used to update aftermarket plugin records 
// causes the id field to increment in the 'plugins' table only, making it out-of-sync with the 'plugins_deployed' table.
// Revised: 7/13/2019	ELL
// Added reading of option of how to handle file aready exists error from options and either dissallowing creation of page (default),
// keeping existing file and continuing, or overwriting existing file and continuing.
// Added creation of touchscreen only CSS files for plugins.
// Revised:	10/2/2019	ELL
// Changed "parent" from using parent plugin name to using parent plugin ID.
// Added checking for parent plugin deployed if any child plugin has been selected.  If the parent plugin has NOT been deployed, then run any CSS SOL it has, 
// any plugin SQL it has, and marked it as deployed.
// Modified: 11/26/2019	ELL
// Added creation of sitemap.xml and robots.txt file upon creating page.
// Modified: 1/30/2020	ELL
// Added handling of plugin field 'cookie_session_code'.
// Modified: 7/7/2020	ELL
// Added ability to detect and treat custom (advanced) plugin CSS as either CSS or SQL.  This was added to allow web developers to paste CSS directly into
// Plugin SDK plugin record tool directly without forming into SQL statement.
// Revised: 11/10/2020	ELL
// Added handling of new plugin fields "version" and "css_important_sql".
//

include ("check_session.php");
		
$page_name = $_POST['createPage'];
$plugin = $_POST['plugin'];
$template_name = $_POST['template_name'];
$mode = $_REQUEST['mode'];
$no_edit = $_REQUEST['no_edit'];

include("lib/run_sql.php");
include ("lib/build_css_string.php");

////////////////////////////////////////////////////////////////////////////////////////////////
function copy_table_structure($table, $table_prefix, $dbh, $database, $source_table = "", $copy_data = false)
{
	$query = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '" . $database . "' AND table_name = '" . $table_prefix . $table . "'";
	$result = $dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);
	$table_count = $row['COUNT(*)'];
	if ($table_count < 1)
	{
		// Must be a missing menu table, find suffix.
		if ($source_table == "")	{
			if (strpos($table, "_classes") > 0)
				$source_table = $table_prefix . "site_classes";
			else
				$source_table = $table_prefix . "site_css";
		}
		else
			$source_table = $table_prefix . $source_table;

		$query = "CREATE TABLE " . $table_prefix . $table . " LIKE " . $source_table;
		$cnt = $dbh->exec($query);
		if ($copy_data === true)	{
			$query = "INSERT " . $table_prefix . $table . " SELECT * FROM " . $source_table;
			$cnt = $dbh->exec($query);
		}
	}
		
	return 1;
}

////////////////////////////////////////////////////////////////////////////////////////////////
function CheckForSQL($sql_string)
{
	$line_arr = array();
	// Split SQL input into lines.
	$line_arr = preg_split("[\n|\r]", $sql_string);
	
	// Search for INSERT or REPLACE commands.
	for ($i = 0; $i < count($line_arr); $i++)
	{
		// Test for comment line.
		$curr_line = trim($line_arr[$i]);
		$first_chars = substr($curr_line, 0, 2);
		if (($first_chars == "--") || ($first_chars == "//") || ($first_chars == "/*") || ($first_chars == ""))
			continue;
		elseif ((substr($curr_line, 0, 6) == "INSERT") || (substr($curr_line, 0, 7) == "REPLACE"))
			return true;
		else
			return false;
	}
}
		
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
	if ($page_name == "")
	{
		echo CREATE_PAGE_PAGE_NAME_BLANK_1_ERR . " " . CLICK_WORD . " <a href=\"create_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . CREATE_PAGE_PAGE_NAME_BLANK_2_ERR;
		exit;
	}
	
	//Remove Unix incompatible characters.
	$page_name = preg_replace("/(?:\s|&nbsp;)+/", "_", $page_name, -1);
	$page_name = preg_replace("/[^A-Za-z0-9_.-]/", "", $page_name, -1);
	$query = "SELECT `option_value` FROM `" . BWB_TABLE_PREFIX . "options_selected` WHERE `option_name`='ForcePageNameToLowerCase'";
	$result = $bwb_dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);
	$ForcePageNameToLowerCase = $row["option_value"];
	if ($ForcePageNameToLowerCase == 1)
		$page_name = strtolower($page_name);
	
	$page_name = addslashes($page_name);
	
	// Get default use of table structure from selected options.
	$query = "SELECT `option_value` FROM `" . BWB_TABLE_PREFIX . "options_selected` WHERE `option_name`='UseTableStructure'";
	$result = $bwb_dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);
	$UseTableStructure = $row["option_value"];
	$query = "SELECT `option_value` FROM `" . BWB_TABLE_PREFIX . "options_selected` WHERE `option_name`='UseTableStructureMobile'";
	$result = $bwb_dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);
	$UseTableStructureMobile = $row["option_value"];
	// Check if OK to continue to cerate page if page template file already exists, an whether to keep existing or overwrite.
	// Useful if creating new pages on second inactive site, but don't want to change folder of page files, .i.e. webroot.
	$query = "SELECT `option_value` FROM `" . BWB_TABLE_PREFIX . "options_selected` WHERE `option_name`='CreatePageFileExistsHandling'";
	$result = $bwb_dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);
	$CreatePageFileExistsHandling = $row["option_value"];
	
	//First check to see if page is already in database.
	$query = "SELECT `page_name` FROM `" . BWB_TABLE_PREFIX . "page_data` WHERE `page_name`='$page_name'";
	$result = $bwb_dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);
	$page_name_retrieved = $row["page_name"];
	if ($page_name_retrieved)
	{
		echo $file_name . " " . CLASSES_ADD_CLASS_ADD_ERR . " " . CLICK_WORD . " <a href=\"create_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . CREATE_PAGE_PAGE_ALREADY_EXISTS_ERR;
		exit;
	}
	
	//Test to see if file already exists.
	$document_root = $_SERVER['DOCUMENT_ROOT'];
	if (BWB_BASE_DIR == '')
		$file_name = $document_root . "/" . BWB_WEBPAGE_DIR . "/" . $page_name . ".php";
	else
		$file_name = $document_root . "/" . BWB_BASE_DIR . "/" . BWB_WEBPAGE_DIR . "/" . $page_name . ".php";
//	echo "File Name: $file_name<br>";
	$skip_file_create = false;
	if (file_exists($file_name))
	{
		if ((BWB_BASE_DIR == '') && (BWB_WEBPAGE_DIR == '') && ($page_name == "index"))	// Special case, getting rid of stock forwarder to /userfiles/file/
			unlink($file_name);
		else
		{
			if ((strpos($CreatePageFileExistsHandling, "Keep") === false) && (strpos($CreatePageFileExistsHandling, "Overwrite") === false))	{
				echo $file_name . " " . MANAGE_CUSTOM_FONTS_ADDING_FONT_2_ERR . " " . CLICK_WORD . " <a href=\"create_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . CREATE_PAGE_PAGE_ALREADY_EXISTS_ERR;
				exit;
			}
			elseif (strpos($CreatePageFileExistsHandling, "Overwrite") !== false)
				unlink($file_name);
			elseif (strpos($CreatePageFileExistsHandling, "Keep") !== false)
				$skip_file_create = true;
		}
	}
	
	$page_content_divider = "<!-- Page Content Divider -->";
	// If plugin code selected, then get plugin code snippet.
	if ((!isset($plugin)) || ($plugin == ""))
		$plugin = "-not selected-";
		
	if ($plugin != "-not selected-")
	{
		$query = "SELECT * FROM `" . BWB_TABLE_PREFIX . "plugins` WHERE `id` = $plugin";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$plugin_id = $row["id"];
		$plugin_name = $row["name"];
		$plugin_version = $row["version"];
		$parent = $row["parent"];
		$cookie_session_code = $row["cookie_session_code"];
		$head_code = $row["head_code"];
		$head_html = $row["head_html"];
		$header_code = $row["header_code"];
		$header_html = $row["header_html"];
		$top_code = $row["top_code"];
		$top_html = $row["top_html"];
		$left_code = $row["left_code"];
		$left_html = $row["left_html"];
		$content_code = $row["content_code"];
		if (strpos($row["content_html"], $page_content_divider) === false)
			$content_html = $page_content_divider . "\n" . $row["content_html"];
		else
			$content_html = $row["content_html"];
		$right_code = $row["right_code"];
		$right_html = $row["right_html"];
		$bottom_code = $row["bottom_code"];
		$bottom_html = $row["bottom_html"];
		$footer_code = $row["footer_code"];
		$footer_html = $row["footer_html"];
		$style_sheet = $row["style_sheet"];
		$style_sheet_description = $row["style_sheet_description"];
		$class_sql = $row["class_sql"];
		$css_sql = $row["css_sql"];
		$custom_css_sql = $row["custom_css_sql"];
		$css_important_sql = $row["css_important_sql"];
		$plugin_sql = $row["plugin_sql"];
		$disable_site_styles = $row["disable_site_styles"];
		$body_onload = $row["body_onload"];
		if (isset($row["body_onload_function"]) && ($row["body_onload_function"] != ""))	{
			$body_onload_function = $row["body_onload_function"];
			$funct_str_len = strlen($body_onload_function);
			$funct_str_end = substr($body_onload_function, $funct_str_len - 3);
			if (strpos($funct_str_end, "();") === false)	{
				if (strpos($funct_str_end, ")") == 2)
					$body_onload_function .= ";";
				elseif (strpos($funct_str_end, ");") != 1)
					$body_onload_function .= "();";
			}
		}
		else
			$body_onload_function = $page_name . "_load();";
			
		$query = "SELECT * FROM `" . BWB_TABLE_PREFIX . "plugins_deployed` WHERE (`plugin_id` = $plugin) OR (`name` = '$plugin_name')";
		$result = $bwb_dbh->query($query);
		if ($result->rowCount() > 0)	{
			$row = $result->fetch(PDO::FETCH_ASSOC);
			$deployed = $row["deployed"];
		}
		else
			$deployed = 0;
			
		$parent_deployed = -1;
		if (isset($parent) && ($parent!= "") && ($parent != $plugin_name))	{
			$query = "SELECT * FROM `" . BWB_TABLE_PREFIX . "plugins_deployed` WHERE (`plugin_id` = '$parent')";
			$result = $bwb_dbh->query($query);
			if ($result->rowCount() > 0)	{
				$row = $result->fetch(PDO::FETCH_ASSOC);
				$parent_deployed = $row["deployed"];
			}
			else
				$parent_deployed = 0;
	
			if ($parent_deployed == 0)	{
				$query = "SELECT * FROM `" . BWB_TABLE_PREFIX . "plugins` WHERE `id` = $parent";
				$result = $bwb_dbh->query($query);
				$row = $result->fetch(PDO::FETCH_ASSOC);
				$parent_name = $row["name"];
				$parent_style_sheet = $row["style_sheet"];
				$parent_style_sheet_description = $row["style_sheet_description"];
				$parent_class_sql = $row["class_sql"];
				$parent_css_sql = $row["css_sql"];
				$parent_custom_css_sql = $row["custom_css_sql"];
				$parent_plugin_sql = $row["plugin_sql"];
			}
		}
		
		// Check template compatibility with plugin.
		if (strpos($template_name, "header_footer_top_bottom_left_right") === false)
		{
			$need_header = false;
			$need_footer = false;
			$need_top = false;
			$need_left = false;
			$need_right = false;
			$need_bottom = false;
			$need_alt = false;
			$need_alt2 = false;
			$dont_want_header = false;
			$dont_want_footer = false;
			$dont_want_top = false;
			$dont_want_left = false;
			$dont_want_right = false;
			$dont_want_bottom = false;
			
			if ((isset($header_code) && ($header_code != "")) || (isset($header_html) && ($header_html != "")) && (strpos($template_name, "header") === false))
				$need_header = true;
			if ((isset($footer_code) && ($footer_code != "")) || (isset($footer_html) && ($footer_html != "")) && (strpos($template_name, "footer") === false))
				$need_footer = true;
			if ((isset($top_code) && ($top_code != "")) || (isset($top_html) && ($top_html != "")) && (strpos($template_name, "top") === false))
				$need_top = true;
			if ((isset($left_code) && ($left_code != "")) || (isset($left_html) && ($left_html != "")) && (strpos($template_name, "left") === false))
				$need_left = true;
			if ((isset($right_code) && ($right_code != "")) || (isset($right_html) && ($right_html != "")) && (strpos($template_name, "right") === false))
				$need_right = true;
			if ((isset($bottom_code) && ($bottom_code != "")) || (isset($bottom_html) && ($bottom_html != "")) && (strpos($template_name, "bottom") === false))
				$need_bottom = true;
				
			if (strpos($template_name, "header") === false)
				$dont_want_header = true;
			if (strpos($template_name, "footer") === false)
				$dont_want_footer = true;
			if (strpos($template_name, "top") === false)
				$dont_want_top = true;
			if (strpos($template_name, "left") === false)
				$dont_want_left = true;
			if (strpos($template_name, "right") === false)
				$dont_want_right = true;
			if (strpos($template_name, "bottom") === false)
				$dont_want_bottom = true;
				
			if (strpos($template_name, "alt2") !== false)
				$need_alt2 = true;
			elseif (strpos($template_name, "alt") !== false)
				$need_alt = true;
				
			if (($need_header === true) || ($need_footer === true) || ($need_top === true) || ($need_left === true) || ($need_right === true) || ($need_bottom === true))
			{
				$where = "";
				if ($need_header === true)
					$where .= " AND option_value LIKE '%header%'";
				elseif (($dont_want_header === true) && ($need_footer !== true))
					$where .= " AND option_value NOT LIKE '%header%'";
				if ($need_footer === true)
					$where .= " AND option_value LIKE '%footer%'";
				elseif ($dont_want_footer === true)
					$where .= " AND option_value NOT LIKE '%footer%'";
				if ($need_top === true)
					$where .= " AND option_value LIKE '%top%'";
				elseif (($dont_want_top === true) && ($need_bottom !== true))
					$where .= " AND option_value NOT LIKE '%top%'";
				if ($need_left === true)
					$where .= " AND option_value LIKE '%left%'";
				elseif (($dont_want_left === true) && ($need_right !== true))
					$where .= " AND option_value NOT LIKE '%left%'";
				if ($need_right === true)
					$where .= " AND option_value LIKE '%right%'";
				elseif ($dont_want_right === true)
					$where .= " AND option_value NOT LIKE '%right%'";
				if ($need_bottom === true)
					$where .= " AND option_value LIKE '%bottom%'";
				elseif ($dont_want_bottom === true)
					$where .= " AND option_value NOT LIKE '%bottom%'";
					
				if ($need_alt2 === true)
					$where .= " AND option_value LIKE '%alt2%'";
				elseif ($need_alt === true)
					$where .= " AND option_value LIKE '%alt%' AND NOT LIKE '%alt2%'";
					
				$query = "SELECT option_value FROM " . BWB_TABLE_PREFIX . "options WHERE option_name = 'Template'" . $where . " ORDER BY dropdown_sort_order";
				$result = $bwb_dbh->query($query);
				$row = $result->fetch(PDO::FETCH_ASSOC);
				$template_name = $row['option_value'];
			}
		}
	}
	else
	{
		$content_html = "\n<p>" . CREATE_PAGE_DEFAULT_CONTENT . "</p>\n" . $page_content_divider . "\n";
		$plugin_id = "";
		$body_onload = 0;
		$body_onload_function = $page_name . "_load();";
		$disable_site_styles = 0;
	}
	
	//Add page name to database.
	$page_content = addslashes(stripslashes($content_html));
		
	$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data SET page_name='$page_name', page_content='$page_content', template='$template_name', plugins='$plugin_id', disable_site_styles='$disable_site_styles', body_onload='$body_onload', body_onload_function='$body_onload_function', use_table_structure='$UseTableStructure', use_table_structure_mobile='$UseTableStructureMobile'";
//	echo $query;
	$cnt = $bwb_dbh->exec($query);

// Copy page data to draft table.
	$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_draft SET page_name='$page_name', page_content='$page_content', `source`=0";
//	echo $query;
	$cnt = $bwb_dbh->exec($query);

	//Get template from database.
	$query = "SELECT `page_template` FROM `" . BWB_TABLE_PREFIX . "template` WHERE `template_name` = 'all'";
	$result = $bwb_dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);
	$page_template = $row["page_template"];

//Insert page name into template.
	$zzz_found = false;
	if ($page_name == "zzz")	{
		$page_template = str_replace("xxx", "-ZZZ-", $page_template);
		$zzz_found = true;
	}
	else
		$page_template = str_replace("xxx", $page_name, $page_template);
	
	//Get meta-tags template from database.
	$query = "SELECT `meta_tags_template` FROM `" . BWB_TABLE_PREFIX . "meta_tags_template`";
	$result = $bwb_dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);
	$meta_tags_template = $row["meta_tags_template"];
	
	//Insert page name into meta-tags template.
	$meta_tags_template = str_replace("xxx", $page_name, $meta_tags_template);
	
	//Insert meta-tags template into page template.
	$page_template = str_replace("zzz", $meta_tags_template, $page_template);
	
	if ($zzz_found === true)
		$page_template = str_replace("-ZZZ-", $page_name, $page_template);
		
	//If plugin is selected, then insert cookie/session code snippet after //cookie_session_code// comment.
	if (($plugin != "-not selected-") && ($cookie_session_code != ""))
	{
		$page_temp_arr = explode("//cookie_session_code//", $page_template, 2);
		$page_template = $page_temp_arr[0] . $cookie_session_code . "\n\n//cookie_session_code//\n" . $page_temp_arr[1];
		unset($page_temp_arr);
	}
		
	//If plugin is selected, then insert head code snippet after <!--head_code--> comment.
	if (($plugin != "-not selected-") && ($head_code != ""))
	{
		$page_temp_arr = explode("<!--head_code-->", $page_template, 2);
		$page_template = $page_temp_arr[0] . $head_code . "\n\n<!--head_code-->\n" . $page_temp_arr[1];
		unset($page_temp_arr);
	}
	
	//If plugin is selected, then insert content code snippet after <!--content_code--> comment.
	if (($plugin != "-not selected-") && ($content_code != ""))
	{
		$page_temp_arr = explode("<!--content_code-->", $page_template, 5);
		$page_template = $page_temp_arr[0] . $content_code . "\n\n<!--content_code-->\n" . $page_temp_arr[1];
		if (isset($page_temp_arr[2]))
			$page_template .= $content_code . "\n\n<!--content_code-->\n" . $page_temp_arr[2];
		if (isset($page_temp_arr[3]))
			$page_template .= $content_code . "\n\n<!--content_code-->\n" . $page_temp_arr[3];
		if (isset($page_temp_arr[4]))
			$page_template .= $content_code . "\n\n<!--content_code-->\n" . $page_temp_arr[4];
		unset($page_temp_arr);
	}
		
	//If plugin is selected, then insert header code snippet after <!--header_code--> comment. (not to be confused with head)
	if (($plugin != "-not selected-") && ($header_code != ""))
	{
		$page_temp_arr = explode("<!--header_code-->", $page_template, 2);
		$page_template = $page_temp_arr[0] . $header_code . "\n\n<!--header_code-->\n" . $page_temp_arr[1];
		unset($page_temp_arr);
	}
		
	//If plugin is selected, then insert footer code snippet after <!--footer_code--> comment.
	if (($plugin != "-not selected-") && ($footer_code != ""))
	{
		$page_temp_arr = explode("<!--footer_code-->", $page_template, 2);
		$page_template = $page_temp_arr[0] . $footer_code . "\n\n<!--footer_code-->\n" . $page_temp_arr[1];
		unset($page_temp_arr);
	}

	//If plugin is selected, then insert top code snippet after <!--top_code--> comment.
	if (($plugin != "-not selected-") && ($top_code != ""))
	{
		$page_temp_arr = explode("<!--top_code-->", $page_template, 4);
		$page_template = $page_temp_arr[0] . $top_code . "\n\n<!--top_code-->\n" . $page_temp_arr[1];
		if (isset($page_temp_arr[2]))
			$page_template .= $top_code . "\n\n<!--top_code-->\n" . $page_temp_arr[2];
		if (isset($page_temp_arr[3]))
			$page_template .= $top_code . "\n\n<!--top_code-->\n" . $page_temp_arr[3];
		unset($page_temp_arr);
	}
	
	//If plugin is selected, then insert left code snippet after <!--left_code--> comment.
	if (($plugin != "-not selected-") && ($left_code != ""))
	{
		$page_temp_arr = explode("<!--left_code-->", $page_template, 4);
		$page_template = $page_temp_arr[0] . $left_code . "\n\n<!--left_code-->\n" . $page_temp_arr[1];
		if (isset($page_temp_arr[2]))
			$page_template .= $left_code . "\n\n<!--left_code-->\n" . $page_temp_arr[2];
		if (isset($page_temp_arr[3]))
			$page_template .= $left_code . "\n\n<!--left_code-->\n" . $page_temp_arr[3];
		unset($page_temp_arr);
	}
	
	//If plugin is selected, then insert right code snippet after <!--right_code--> comment.
	if (($plugin != "-not selected-") && ($right_code != ""))
	{
		$page_temp_arr = explode("<!--right_code-->", $page_template, 4);
		$page_template = $page_temp_arr[0] . $right_code . "\n\n<!--right_code-->\n" . $page_temp_arr[1];
		if (isset($page_temp_arr[2]))
			$page_template .= $right_code . "\n\n<!--right_code-->\n" . $page_temp_arr[2];
		if (isset($page_temp_arr[3]))
			$page_template .= $right_code . "\n\n<!--right_code-->\n" . $page_temp_arr[3];
		unset($page_temp_arr);
	}
	
	//If plugin is selected, then insert bottom code snippet after <!--bottom_code--> comment.
	if (($plugin != "-not selected-") && ($bottom_code != ""))
	{
		$page_temp_arr = explode("<!--bottom_code-->", $page_template, 4);
		$page_template = $page_temp_arr[0] . $bottom_code . "\n\n<!--bottom_code-->\n" . $page_temp_arr[1];
		if (isset($page_temp_arr[2]))
			$page_template .= $bottom_code . "\n\n<!--bottom_code-->\n" . $page_temp_arr[2];
		if (isset($page_temp_arr[3]))
			$page_template .= $bottom_code . "\n\n<!--bottom_code-->\n" . $page_temp_arr[3];
		unset($page_temp_arr);
	}

	//If plugin is selected, then replace HTML head holder with head code snippet.
	if (($plugin != "-not selected-") && (isset($head_html)) && ($head_html != ""))
	{
		// Get head content from main head.  Most likely that we want this as default.  Can edit later.
		$query = "SELECT head_content FROM " . BWB_TABLE_PREFIX . "head WHERE head_name = 'head'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$head_content = $row["head_content"];
		
		// Adjust path to any JavaScript includes, CSS, images, Flash or media to settings in config file.
		if ((BWB_BASE_DIR == '') && (BWB_WEBPAGE_DIR == ''))	{
			$scripts_dir_rel = BWB_SCRIPTS_DIR . "/";
			$flash_dir_rel = BWB_FLASH_DIR . "/";
			$media_dir_rel = BWB_MEDIA_DIR . "/";
			$image_dir_rel = BWB_IMAGE_DIR . "/";
			$css_dir_rel = BWB_CSS_DIR . "/";
		}
		elseif ((BWB_BASE_DIR == '') || (BWB_WEBPAGE_DIR == ''))
		{
			if (BWB_BASE_DIR == '')	{
				$scripts_dir_rel = "../" . BWB_SCRIPTS_DIR . "/";
				$flash_dir_rel = "../" . BWB_FLASH_DIR . "/";
				$media_dir_rel = "../" . BWB_MEDIA_DIR . "/";
				$image_dir_rel = "../" .BWB_IMAGE_DIR . "/";
				$css_dir_rel = "../" . BWB_CSS_DIR . "/";
			}
			elseif (BWB_WEBPAGE_DIR == '')	{
				$scripts_dir_rel = BWB_SCRIPTS_DIR . "/";
				$flash_dir_rel = BWB_FLASH_DIR . "/";
				$media_dir_rel = BWB_MEDIA_DIR . "/";
				$image_dir_rel = BWB_IMAGE_DIR . "/";
				$css_dir_rel = BWB_CSS_DIR . "/";
			}
		}
		else	{
			$scripts_dir_rel = "../" . BWB_SCRIPTS_DIR . "/";
			$flash_dir_rel = "../" . BWB_FLASH_DIR . "/";
			$media_dir_rel = "../" . BWB_MEDIA_DIR . "/";
			$image_dir_rel = "../" .BWB_IMAGE_DIR . "/";
			$css_dir_rel = "../" . BWB_CSS_DIR . "/";
		}
		$head_html = str_replace("scripts/", $scripts_dir_rel, $head_html);
		$head_html = str_replace("css/", $scripts_dir_rel, $head_html);
		$head_html = str_replace("images/", $scripts_dir_rel, $head_html);
		$head_html = str_replace("media/", $scripts_dir_rel, $head_html);
		$head_html = str_replace("flash/", $scripts_dir_rel, $head_html);
			
		// Combine HTML (Javascript) code with default head content.
		$head_content = $head_content . "\n\n\n" . $head_html;
		$head_content = addslashes(stripslashes($head_content));
		
		// Check to see if head record alread exists.
		$head_name = "head_" . $page_name;
		$query = "SELECT head_name FROM " . BWB_TABLE_PREFIX . "head WHERE head_name = '$head_name'";
		$result = $bwb_dbh->query($query);
		$row_cnt = $result->rowCount();
		if ($row_cnt > 0)
			$head_name .= time();
		
		// Insert new head into table.
		$query = "INSERT INTO " . BWB_TABLE_PREFIX . "head (head_name, head_content, plugins) VALUES ('" . $head_name . "', '" . $head_content . "', '" . $plugin_id . "')";
		$cnt = $bwb_dbh->exec($query);
		
		// Update head name in page record.
		$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET head_name='$head_name' WHERE page_name='$page_name'";
		$cnt = $bwb_dbh->exec($query);
	}
	
	//If plugin is selected, then replace HTML header holder with header HTML code snippet.
	if (($plugin != "-not selected-") && (isset($header_html)) && ($header_html != ""))
	{	
		// Get header content from main header.  Most likely that we want this as default.  Can edit later.
		$query = "SELECT page_content FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = 'header'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$header_content = $row["page_content"];
		
		// Combine HTML (Javascript) code with default header content.
		$header_content = $header_content . "\n\n\n" . $header_html;
		$header_content = addslashes(stripslashes($header_content));

		// Check to see if head record alread exists.
		$header_name = "header_" . $page_name;
		$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = '$header_name'";
		$result = $bwb_dbh->query($query);
		$row_cnt = $result->rowCount();
		if ($row_cnt > 0)
			$header_name .= time();

		// Insert new header into table.
		$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special (page_name, page_content, plugins) VALUES ('" . $header_name . "', '" . $header_content . "', '" . $plugin_id . "')";
		$cnt = $bwb_dbh->exec($query);
		
		// Update header name in page record.
		$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET header_name='$header_name' WHERE page_name='$page_name'";
		$cnt = $bwb_dbh->exec($query);
	}

	//If plugin is selected, then replace HTML footer holder with footer HTML code snippet.
	if (($plugin != "-not selected-") && (isset($footer_html)) && ($footer_html != ""))
	{
		// Get footer content from main footer.  Most likely that we want this as default.  Can edit later.
		$query = "SELECT page_content FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = 'footer'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$footer_content = $row["page_content"];
		
		// Combine HTML (Javascript) code with default footer content.
		$footer_content = $footer_content . "\n\n\n" . $footer_html;
		$footer_content = addslashes(stripslashes($footer_content));
		
		// Check to see if head record alread exists.
		$footer_name = "footer_" . $page_name;
		$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = '$footer_name'";
		$result = $bwb_dbh->query($query);
		$row_cnt = $result->rowCount();
		if ($row_cnt > 0)
			$footer_name .= time();
		
		// Insert new footer into table.
		$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special (page_name, page_content, plugins) VALUES ('" . $footer_name . "', '" . $footer_content . "', '" . $plugin_id . "')";
		$cnt = $bwb_dbh->exec($query);
		
		// Update footer name in page record.
		$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET footer_name='$footer_name' WHERE page_name='$page_name'";
		$cnt = $bwb_dbh->exec($query);
	}

	//If plugin is selected, then append HTML code snippet to top.
	if (($plugin != "-not selected-") && (isset($top_html)) && ($top_html != ""))
	{
		// Get footer content from main footer.  Most likely that we want this as default.  Can edit later.
		$query = "SELECT page_content FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = 'top'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$top_content = $row["page_content"];
		
		// Combine HTML (Javascript) code with default top content.
		$top_content = $top_content . "\n\n\n" . $top_html;
		$top_content = addslashes(stripslashes($top_content));
		
		// Check to see if head record alread exists.
		$top_name = "top_" . $page_name;
		$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = '$top_name'";
		$result = $bwb_dbh->query($query);
		$row_cnt = $result->rowCount();
		if ($row_cnt > 0)
			$top_name .= time();
		
		// Insert new top into table.
		$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special (page_name, page_content, plugins) VALUES ('" . $top_name . "', '" . $top_content . "', '" . $plugin_id . "')";
		$cnt = $bwb_dbh->exec($query);
		
		// Update top name in page record.
		$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET top_name='$top_name' WHERE page_name='$page_name'";
		$cnt = $bwb_dbh->exec($query);
	}
	
	//If plugin is selected, then append HTML code snippet to left.
	if (($plugin != "-not selected-") && (isset($left_html)) && ($left_html != ""))
	{
		// Get footer content from main footer.  Most likely that we want this as default.  Can edit later.
		$query = "SELECT page_content FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = 'left'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$left_content = $row["page_content"];
		
		// Combine HTML (Javascript) code with default left content.
		$left_content = $left_content . "\n\n\n" . $left_html;
		$left_content = addslashes(stripslashes($left_content));
		
		// Check to see if head record alread exists.
		$left_name = "left_" . $page_name;
		$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = '$left_name'";
		$result = $bwb_dbh->query($query);
		$row_cnt = $result->rowCount();
		if ($row_cnt > 0)
			$left_name .= time();
		
		// Insert new top into table.
		$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special (page_name, page_content, plugins) VALUES ('" . $left_name . "', '" . $left_content . "', '" . $plugin_id . "')";
		$cnt = $bwb_dbh->exec($query);
		
		// Update left name in page record.
		$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET left_name='$left_name' WHERE page_name='$page_name'";
		$cnt = $bwb_dbh->exec($query);
	}
	
	//If plugin is selected, then append HTML code snippet to right.
	if (($plugin != "-not selected-") && (isset($right_html)) && ($right_html != ""))
	{
		// Get footer content from main footer.  Most likely that we want this as default.  Can edit later.
		$query = "SELECT page_content FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = 'right'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$right_content = $row["page_content"];
		
		// Combine HTML (Javascript) code with default right content.
		$right_content = $right_content . "\n\n\n" . $right_html;
		$right_content = addslashes(stripslashes($right_content));
		
		// Check to see if head record alread exists.
		$right_name = "right_" . $page_name;
		$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = '$right_name'";
		$result = $bwb_dbh->query($query);
		$row_cnt = $result->rowCount();
		if ($row_cnt > 0)
			$right_name .= time();
		
		// Insert new top into table.
		$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special (page_name, page_content, plugins) VALUES ('" . $right_name . "', '" . $right_content . "', '" . $plugin_id . "')";
		$cnt = $bwb_dbh->exec($query);
		
		// Update right name in page record.
		$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET right_name='$right_name' WHERE page_name='$page_name'";
		$cnt = $bwb_dbh->exec($query);
	}
	
	//If plugin is selected, then append HTML code snippet to bottom.
	if (($plugin != "-not selected-") && (isset($bottom_html)) && ($bottom_html != ""))
	{
		// Get footer content from main footer.  Most likely that we want this as default.  Can edit later.
		$query = "SELECT page_content FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = 'bottom'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$bottom_content = $row["page_content"];
		
		// Combine HTML (Javascript) code with default bottom content.
		$bottom_content = $bottom_content . "\n\n\n" . $bottom_html;
		$bottom_content = addslashes(stripslashes($bottom_content));
		
		// Check to see if head record alread exists.
		$bottom_name = "bottom_" . $page_name;
		$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = '$bottom_name'";
		$result = $bwb_dbh->query($query);
		$row_cnt = $result->rowCount();
		if ($row_cnt > 0)
			$bottom_name .= time();
		
		// Insert new top into table.
		$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special (page_name, page_content, plugins) VALUES ('" . $bottom_name . "', '" . $bottom_content . "', '" . $plugin_id . "')";
		$cnt = $bwb_dbh->exec($query);
		
		// Update bottom name in page record.
		$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET bottom_name='$bottom_name' WHERE page_name='$page_name'";
		$cnt = $bwb_dbh->exec($query);
	}
			
	// Create file.
	if (!$skip_file_create)	{
		$fh = fopen($file_name, 'xb') or die("Can't create $file_name: $php_errormsg");
		$result = (fwrite($fh, $page_template));
		fclose($fh) or die($php_errormsg);
		@chmod($file_name, 0755);
	}
	
	// Create plugin tables if plugin selected and table not existing.
	if (($plugin != "-not selected-") && ($deployed != 1))
	{
		if (isset($style_sheet) && ($style_sheet != ""))
		{
			$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "style_sheets WHERE `name`='" . $style_sheet . "'";
			$result = $bwb_dbh->query($query);
			if ($result->rowCount() < 1)
			{
				$css_already_in_use = false;
				$query = "SELECT MAX(sort_order) AS sort_order FROM " . BWB_TABLE_PREFIX . "style_sheets";
				$result = $bwb_dbh->query($query);
				$row = $result->fetch(PDO::FETCH_ASSOC);
				$sort_order = $row['sort_order'] + 10;
				
				if ((isset($custom_css_sql) && ($custom_css_sql != "") && (strpos($custom_css_sql, "0@@@@@") === false)) || (strpos($custom_css_sql, "1@@@@@") == 0))
				 	$show_custom_styles = 1;
				elseif (!isset($custom_css_sql) || ($custom_css_sql == "") || (strpos($custom_css_sql, "0@@@@@") == 0))
				 	$show_custom_styles = 0;
				if (isset($custom_css_sql) && (strpos($custom_css_sql, "@@@@@") == 1))	{
					$custom_css_sql = str_replace("0@@@@@", "", $custom_css_sql);
					$custom_css_sql = str_replace("1@@@@@", "", $custom_css_sql);
				}
				
				$query = "INSERT INTO " . BWB_TABLE_PREFIX . "style_sheets SET `name`='" . $style_sheet . "', `description`='" . $style_sheet_description . "', `sort_order`=" . $sort_order . ", `show_custom_styles`='" . $show_custom_styles . "'";
				$cnt = $bwb_dbh->exec($query);
				
				$sort_order = $sort_order + 10;
				$style_sheet_desc_arr = explode("Styles", $style_sheet_description);
				if (count($style_sheet_desc_arr) > 1)	{
					$mobile_style_sheet_desc = $style_sheet_desc_arr[0] . "Mobile Styles" . $style_sheet_desc_arr[1];
					$touchscreen_style_sheet_desc = $style_sheet_desc_arr[0] . "Touchscreen Styles" . $style_sheet_desc_arr[1];
				}
				else	{
					$mobile_style_sheet_desc = $style_sheet_description . " Mobile Styles";
					$touchscreen_style_sheet_desc = $style_sheet_description . " Touchscreen Styles";
				}
				$query = "INSERT INTO " . BWB_TABLE_PREFIX . "style_sheets SET `name`='" . $style_sheet . "_mobile', `description`='" . $mobile_style_sheet_desc . "', `sort_order`=" . $sort_order . ", `show_custom_styles`='" . $show_custom_styles . "'";
				$cnt = $bwb_dbh->exec($query);
				
				$sort_order = $sort_order + 10;
				$query = "INSERT INTO " . BWB_TABLE_PREFIX . "style_sheets SET `name`='" . $style_sheet . "_touchscreen', `description`='" . $touchscreen_style_sheet_desc . "', `sort_order`=" . $sort_order . ", `show_custom_styles`='" . $show_custom_styles . "'";
				$cnt = $bwb_dbh->exec($query);
			}
			else
				$css_already_in_use = true;
			
			$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "plugins AS T1 INNER JOIN " . BWB_TABLE_PREFIX . "plugins_deployed AS T2 ON T1.id = T2.plugin_id WHERE T1.style_sheet = '" . $style_sheet . "' AND T2.deployed = 1";
			$result = $bwb_dbh->query($query);
			if ($result->rowCount() < 1)
			{
				if (isset($class_sql) && ($class_sql != ""))
				{
					$result = RunSQL($class_sql, $bwb_dbh, BWB_TABLE_PREFIX, false, UPLOAD_TEMPLATE_ROWS_AFFECTED_MSG);
				}
				
				if (isset($css_sql) && ($css_sql != "") && !$css_already_in_use)
				{
					$result = RunSQL($css_sql, $bwb_dbh, BWB_TABLE_PREFIX, false, UPLOAD_TEMPLATE_ROWS_AFFECTED_MSG);
				}
				
				if (isset($css_important_sql) && ($css_important_sql != "") && !$css_already_in_use)
				{
					$result = RunSQL($css_important_sql, $bwb_dbh, BWB_TABLE_PREFIX, false, UPLOAD_TEMPLATE_ROWS_AFFECTED_MSG);
				}
				
				if (isset($custom_css_sql) && ($custom_css_sql != "") && !$css_already_in_use)
				{
					if (!CheckForSQL($custom_css_sql))	{
						$sql = "INSERT INTO " . BWB_TABLE_PREFIX . "custom_site_css (`name`, `custom_css`) VALUES ('" . $style_sheet . "', '" . addslashes(stripslashes($custom_css_sql)) . "')";
						$result = $bwb_dbh->exec($sql);
						$sql = "INSERT INTO " . BWB_TABLE_PREFIX . "custom_site_css (`name`, `custom_css`) VALUES ('" . $style_sheet . "_mobile', '" . addslashes(stripslashes($custom_css_sql)) . "')";
						$result = $bwb_dbh->exec($sql);
						$sql = "INSERT INTO " . BWB_TABLE_PREFIX . "custom_site_css (`name`, `custom_css`) VALUES ('" . $style_sheet . "_touchscreen', '" . addslashes(stripslashes($custom_css_sql)) . "')";
						$result = $bwb_dbh->exec($sql);
					}
					else
						$result = RunSQL($custom_css_sql, $bwb_dbh, BWB_TABLE_PREFIX, false, UPLOAD_TEMPLATE_ROWS_AFFECTED_MSG);
				}
				
				if ((isset($css_sql) && ($css_sql != "")) || (isset($custom_css_sql) && ($custom_css_sql != "")))
				{	
					$css_string = BuildCSSString($style_sheet, $bwb_dbh, BWB_BASE_DIR, BWB_IMAGE_DIR, BWB_TABLE_PREFIX);
					////////////////////////////////////////////////////////
					/// Write menu items to menu.css file /////////////
					//Test to see if file already exists.
					if (BWB_BASE_DIR == '')
						$userfiles = '';
					else
						$userfiles = "/" . BWB_BASE_DIR;
						
					$css_file = $style_sheet . ".css";
					$file_name = $document_root . $userfiles . "/" . BWB_CSS_DIR . "/" . $css_file;
						
					if (file_exists($file_name))
					{
						$bkup_file_name = $file_name . time();
						if (!rename($file_name, $bkup_file_name))
							echo EDIT_CSS_COULD_NOT_RENAME_1_ERR . " $file_name " . EDIT_CSS_COULD_NOT_RENAME_2_ERR . " $bkup_file_name.<br>";
						@chmod($bkup_file_name, 0644);
					}
					
					// Create file.
					$fh = fopen($file_name, 'x') or die(EDIT_CSS_CANT_CREATE_ERR . " $file_name: $php_errormsg");
					$result = (fputs($fh, $css_string));
					fclose($fh) or die($php_errormsg);
					@chmod($file_name, 0644);
					
					/////////////////////////////////////////////////////
					// Build mobile style sheet
					$css_string = BuildCSSString($style_sheet . "_mobile", $bwb_dbh, BWB_BASE_DIR, BWB_IMAGE_DIR, BWB_TABLE_PREFIX);
					
					$css_file = $style_sheet . "_mobile.css";
					$file_name = $document_root . $userfiles . "/" . BWB_CSS_DIR . "/" . $css_file;
						
					if (file_exists($file_name))
					{
						$bkup_file_name = $file_name . time();
						if (!rename($file_name, $bkup_file_name))
							echo EDIT_CSS_COULD_NOT_RENAME_1_ERR . " $file_name " . EDIT_CSS_COULD_NOT_RENAME_2_ERR . " $bkup_file_name.<br>";
						@chmod($bkup_file_name, 0644);
					}
					
					// Create file.
					$fh = fopen($file_name, 'x') or die(EDIT_CSS_CANT_CREATE_ERR . " $file_name: $php_errormsg");
					$result = (fputs($fh, $css_string));
					fclose($fh) or die($php_errormsg);
					@chmod($file_name, 0644);
					
					/////////////////////////////////////////////////////
					// Build touchscreen only style sheet
					$css_string = BuildCSSString($style_sheet . "_touchscreen", $bwb_dbh, BWB_BASE_DIR, BWB_IMAGE_DIR, BWB_TABLE_PREFIX);
					
					$css_file = $style_sheet . "_touchscreen.css";
					$file_name = $document_root . $userfiles . "/" . BWB_CSS_DIR . "/" . $css_file;
						
					if (file_exists($file_name))
					{
						$bkup_file_name = $file_name . time();
						if (!rename($file_name, $bkup_file_name))
							echo EDIT_CSS_COULD_NOT_RENAME_1_ERR . " $file_name " . EDIT_CSS_COULD_NOT_RENAME_2_ERR . " $bkup_file_name.<br>";
						@chmod($bkup_file_name, 0644);
					}
					
					// Create file.
					$fh = fopen($file_name, 'x') or die(EDIT_CSS_CANT_CREATE_ERR . " $file_name: $php_errormsg");
					$result = (fputs($fh, $css_string));
					fclose($fh) or die($php_errormsg);
					@chmod($file_name, 0644);
				}
			}
		}
		if (isset($plugin_sql) && ($plugin_sql != ""))
		{
			$result = RunSQL($plugin_sql, $bwb_dbh, BWB_TABLE_PREFIX, false, UPLOAD_TEMPLATE_ROWS_AFFECTED_MSG);
		}
	
		if (isset($plugin_name) && ($plugin_name != ""))
			$query = "REPLACE INTO " . BWB_TABLE_PREFIX . "plugins_deployed SET `plugin_id`=$plugin, `name`='$plugin_name', `deployed`=1";
		else
			$query = "REPLACE INTO " . BWB_TABLE_PREFIX . "plugins_deployed SET `plugin_id`=$plugin, `deployed`=1";
		$cnt = $bwb_dbh->exec($query);
	}
	
	// Create parent plugin tables if plugin selected and table not existing.
	if (($plugin != "-not selected-") && ($parent_deployed < 1))
	{
		if (isset($parent_style_sheet) && ($parent_style_sheet != ""))
		{
			$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "style_sheets WHERE `name`='" . $parent_style_sheet . "'";
			$result = $bwb_dbh->query($query);
			if ($result->rowCount() < 1)
			{
				$css_already_in_use = false;
				$query = "SELECT MAX(sort_order) AS sort_order FROM " . BWB_TABLE_PREFIX . "style_sheets";
				$result = $bwb_dbh->query($query);
				$row = $result->fetch(PDO::FETCH_ASSOC);
				$sort_order = $row['sort_order'] + 10;
				
				if ((isset($parent_custom_css_sql) && ($parent_custom_css_sql != "") && (strpos($parent_custom_css_sql, "0@@@@@") === false)) || (strpos($parent_custom_css_sql, "1@@@@@") == 0))
				 	$show_custom_styles = 1;
				elseif (!isset($parent_custom_css_sql) || ($parent_custom_css_sql == "") || (strpos($parent_custom_css_sql, "0@@@@@") == 0))
				 	$show_custom_styles = 0;
				if (isset($parent_custom_css_sql) && (strpos($parent_custom_css_sql, "@@@@@") == 1))	{
					$parent_custom_css_sql = str_replace("0@@@@@", "", $parent_custom_css_sql);
					$parent_custom_css_sql = str_replace("1@@@@@", "", $parent_custom_css_sql);
				}
				
				$query = "INSERT INTO " . BWB_TABLE_PREFIX . "style_sheets SET `name`='" . $parent_style_sheet . "', `description`='" . $parent_style_sheet_description . "', `sort_order`=" . $sort_order . ", `show_custom_styles`='" . $show_custom_styles . "'";
				$cnt = $bwb_dbh->exec($query);
				
				$sort_order = $sort_order + 10;
				$style_sheet_desc_arr = explode("Styles", $parent_style_sheet_description);
				if (count($style_sheet_desc_arr) > 1)	{
					$mobile_style_sheet_desc = $style_sheet_desc_arr[0] . "Mobile Styles" . $style_sheet_desc_arr[1];
					$touchscreen_style_sheet_desc = $style_sheet_desc_arr[0] . "Touchscreen Styles" . $style_sheet_desc_arr[1];
				}
				else	{
					$mobile_style_sheet_desc = $parent_style_sheet_description . " Mobile Styles";
					$touchscreen_style_sheet_desc = $parent_style_sheet_description . " Touchscreen Styles";
				}
				$query = "INSERT INTO " . BWB_TABLE_PREFIX . "style_sheets SET `name`='" . $parent_style_sheet . "_mobile', `description`='" . $mobile_style_sheet_desc . "', `sort_order`=" . $sort_order . ", `show_custom_styles`='" . $show_custom_styles . "'";
				$cnt = $bwb_dbh->exec($query);
				
				$sort_order = $sort_order + 10;
				$query = "INSERT INTO " . BWB_TABLE_PREFIX . "style_sheets SET `name`='" . $parent_style_sheet . "_touchscreen', `description`='" . $touchscreen_style_sheet_desc . "', `sort_order`=" . $sort_order . ", `show_custom_styles`='" . $show_custom_styles . "'";
				$cnt = $bwb_dbh->exec($query);
			}
			else
				$css_already_in_use = true;
			
			$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "plugins AS T1 INNER JOIN " . BWB_TABLE_PREFIX . "plugins_deployed AS T2 ON T1.id = T2.plugin_id WHERE T1.style_sheet = '" . $parent_style_sheet . "' AND T2.deployed = 1";
			$result = $bwb_dbh->query($query);
			if ($result->rowCount() < 1)
			{
				if (isset($parent_class_sql) && ($parent_class_sql != ""))
				{
					$result = RunSQL($parent_class_sql, $bwb_dbh, BWB_TABLE_PREFIX, false, UPLOAD_TEMPLATE_ROWS_AFFECTED_MSG);
				}
				
				if (isset($parent_css_sql) && ($parent_css_sql != "") && !$css_already_in_use)
				{
					$result = RunSQL($parent_css_sql, $bwb_dbh, BWB_TABLE_PREFIX, false, UPLOAD_TEMPLATE_ROWS_AFFECTED_MSG);
				}
				
				if (isset($parent_custom_css_sql) && ($parent_custom_css_sql != "") && !$css_already_in_use)
				{
					if (!CheckForSQL($parent_custom_css_sql))	{
						$sql = "INSERT INTO " . BWB_TABLE_PREFIX . "custom_site_css (`name`, `custom_css`) VALUES ('" . $parent_style_sheet . "', '" . addslashes(stripslashes($parent_custom_css_sql)) . "')";
						$result = $bwb_dbh->exec($sql);
						$sql = "INSERT INTO " . BWB_TABLE_PREFIX . "custom_site_css (`name`, `custom_css`) VALUES ('" . $parent_style_sheet . "_mobile', '" . addslashes(stripslashes($parent_custom_css_sql)) . "')";
						$result = $bwb_dbh->exec($sql);
						$sql = "INSERT INTO " . BWB_TABLE_PREFIX . "custom_site_css (`name`, `custom_css`) VALUES ('" . $parent_style_sheet . "_touchscreen', '" . addslashes(stripslashes($parent_custom_css_sql)) . "')";
						$result = $bwb_dbh->exec($sql);
					}
					else
						$result = RunSQL($parent_custom_css_sql, $bwb_dbh, BWB_TABLE_PREFIX, false, UPLOAD_TEMPLATE_ROWS_AFFECTED_MSG);
				}
				
				if ((isset($parent_css_sql) && ($parent_css_sql != "")) || (isset($parent_custom_css_sql) && ($parent_custom_css_sql != "")))
				{	
					$css_string = BuildCSSString($parent_style_sheet, $bwb_dbh, BWB_BASE_DIR, BWB_IMAGE_DIR, BWB_TABLE_PREFIX);
					////////////////////////////////////////////////////////
					/// Write menu items to menu.css file /////////////
					//Test to see if file already exists.
					if (BWB_BASE_DIR == '')
						$userfiles = '';
					else
						$userfiles = "/" . BWB_BASE_DIR;
						
					$css_file = $parent_style_sheet . ".css";
					$file_name = $document_root . $userfiles . "/" . BWB_CSS_DIR . "/" . $css_file;
						
					if (file_exists($file_name))
					{
						$bkup_file_name = $file_name . time();
						if (!rename($file_name, $bkup_file_name))
							echo EDIT_CSS_COULD_NOT_RENAME_1_ERR . " $file_name " . EDIT_CSS_COULD_NOT_RENAME_2_ERR . " $bkup_file_name.<br>";
						@chmod($bkup_file_name, 0644);
					}
					
					// Create file.
					$fh = fopen($file_name, 'x') or die(EDIT_CSS_CANT_CREATE_ERR . " $file_name: $php_errormsg");
					$result = (fputs($fh, $css_string));
					fclose($fh) or die($php_errormsg);
					@chmod($file_name, 0644);
					
					/////////////////////////////////////////////////////
					// Build mobile style sheet
					$css_string = BuildCSSString($parent_style_sheet . "_mobile", $bwb_dbh, BWB_BASE_DIR, BWB_IMAGE_DIR, BWB_TABLE_PREFIX);
					
					$css_file = $parent_style_sheet . "_mobile.css";
					$file_name = $document_root . $userfiles . "/" . BWB_CSS_DIR . "/" . $css_file;
						
					if (file_exists($file_name))
					{
						$bkup_file_name = $file_name . time();
						if (!rename($file_name, $bkup_file_name))
							echo EDIT_CSS_COULD_NOT_RENAME_1_ERR . " $file_name " . EDIT_CSS_COULD_NOT_RENAME_2_ERR . " $bkup_file_name.<br>";
						@chmod($bkup_file_name, 0644);
					}
					
					// Create file.
					$fh = fopen($file_name, 'x') or die(EDIT_CSS_CANT_CREATE_ERR . " $file_name: $php_errormsg");
					$result = (fputs($fh, $css_string));
					fclose($fh) or die($php_errormsg);
					@chmod($file_name, 0644);
					
					/////////////////////////////////////////////////////
					// Build touchscreen only style sheet
					$css_string = BuildCSSString($parent_style_sheet . "_touchscreen", $bwb_dbh, BWB_BASE_DIR, BWB_IMAGE_DIR, BWB_TABLE_PREFIX);
					
					$css_file = $parent_style_sheet . "_touchscreen.css";
					$file_name = $document_root . $userfiles . "/" . BWB_CSS_DIR . "/" . $css_file;
						
					if (file_exists($file_name))
					{
						$bkup_file_name = $file_name . time();
						if (!rename($file_name, $bkup_file_name))
							echo EDIT_CSS_COULD_NOT_RENAME_1_ERR . " $file_name " . EDIT_CSS_COULD_NOT_RENAME_2_ERR . " $bkup_file_name.<br>";
						@chmod($bkup_file_name, 0644);
					}
					
					// Create file.
					$fh = fopen($file_name, 'x') or die(EDIT_CSS_CANT_CREATE_ERR . " $file_name: $php_errormsg");
					$result = (fputs($fh, $css_string));
					fclose($fh) or die($php_errormsg);
					@chmod($file_name, 0644);
				}
			}
		}
		if (isset($parent_plugin_sql) && ($parent_plugin_sql != ""))
		{
			$result = RunSQL($parent_plugin_sql, $bwb_dbh, BWB_TABLE_PREFIX, false, UPLOAD_TEMPLATE_ROWS_AFFECTED_MSG);
		}
	
		if (isset($parent_name) && ($parent_name != ""))
			$query = "REPLACE INTO " . BWB_TABLE_PREFIX . "plugins_deployed SET `plugin_id`=$parent, `name`='$parent_name', `deployed`=1";
		else
			$query = "REPLACE INTO " . BWB_TABLE_PREFIX . "plugins_deployed SET `plugin_id`=$parent, `deployed`=1";
		$cnt = $bwb_dbh->exec($query);
	}
	
	//Go to edit page.
	if (!isset($no_edit) || ($no_edit != 1))	{
		$edit_page = "edit_page.php?page_name=$page_name&mode=$mode";
		if (($plugin != "-not selected-") && ($deployed != 1))
			$edit_page .= "&refresh_buttons=1";
		try	{
			header("Location: $edit_page");
		} catch (Exception $e) {
			echo $e->getMessage();
		}
	}
	else
		echo "Child Plugin Page Created";
		
	// Re-write sitemap.xml for web crawlers.
	include("generate_site_map.php");
?>