<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created: 4/3/2014	ELL
// 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: 1/12/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
// Modified to get template from field in page data record instead of parsing page file.
// Modified to get border area names and head name from fields in page data record instead of parsing page file.
// Revised: 5/26/2016	ELL
// Added function string checking to standardize entry of function call.
// Added simultaneous deployment of mobile styles for plugin if provided.
// 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: 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.
// Fixed bug with mobile style sheet description not getting updated to say "Mobile".
// 

include ("check_session.php");
		
$page_name = $_POST['page_name'];
$plugin = $_POST['plugin'];

include("lib/run_sql.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;
}

///////////////////////////////////////////////////////////////////////////////

	if (($page_name == "-not selected-") || ($plugin == "-not selected-") || ($page_name == "") || ($plugin == ""))
	{
		echo ADD_PLUGIN_TO_PAGE_PAGE_OR_PLUGIN_NOT_SELECTED_1_MSG . " " . CLICK_WORD . " <a href=\"add_plugin_to_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " .  ADD_PLUGIN_TO_PAGE_PAGE_OR_PLUGIN_NOT_SELECTED_2_MSG;
		exit;
	}
	
	$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"];
	$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"];
	$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"];
	$plugin_sql = $row["plugin_sql"];
	$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";
	$result = $bwb_dbh->query($query);
	if ($result->rowCount() > 0)	{
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$deployed = $row["deployed"];
	}
	else
		$deployed = 0;
	
	//Get page content from database.
	$today = date("Y-m-d H:i:s");
	$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "page_data WHERE page_name='$page_name'";
	$result = $bwb_dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);
	$page_content = addslashes(stripslashes($row["page_content"]));
	$existing_plugins = $row["plugins"];
	$page_content .= "\n\n" . addslashes(stripslashes($content_html));
	$template = $row["template"];
	$head_name = $row["head_name"];
	$header_name = $row["header_name"];
	$top_name = $row["top_name"];
	$left_name = $row["left_name"];
	$right_name = $row["right_name"];
	$bottom_name = $row["bottom_name"];
	$footer_name = $row["footer_name"];
	
	if ((isset($existing_plugins)) && ($existing_plugins != ""))
		$plugin_ids = $existing_plugins . "," . $plugin_id;
	else
		$plugin_ids = $plugin_id;
	
	//Update page content in database.
	$today = date("Y-m-d H:i:s");
	if ($body_onload == 1)
		$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET page_content='$page_content', revised='$today', plugins='$plugin_ids', body_onload=1, body_onload_function='$body_onload_function' WHERE page_name='$page_name'";
	else
		$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET page_content='$page_content', revised='$today', plugins='$plugin_ids' WHERE page_name='$page_name'";
//	echo $query;
	$cnt = $bwb_dbh->exec($query);

// Copy page data to draft table.
	$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "page_data_draft WHERE page_name='$page_name'";
	$result = $bwb_dbh->query($query);
	if ($result->rowCount() < 1)
		$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_draft SET page_name='$page_name', page_content='$page_content', revised='$today', `source`=0";
	else
		$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data_draft SET page_content='$page_content', revised='$today', `source`=0 WHERE page_name='$page_name'";
//	echo $query;
	$cnt = $bwb_dbh->exec($query);
	
	
	///////////////////////////////////////////////////////////////////////////////////////
	// Get page file content.
	$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>";
	if (file_exists($file_name))
	{
		if (!($fh = fopen($file_name, 'r'))) {
			echo ADD_PLUGIN_TO_PAGE_ERROR_OPENING_PAGE_FILE_ERR . " " . CLICK_WORD . " <a href=\"add_plugin_to_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . ADD_PLUGIN_TO_PAGE_RETURN_TO_INSERT_PLUGIN_INTO_PAGE_CONSOLE_MSG . "\n$php_errormsg";
			exit;
		}
		
		$contents = (fread($fh, filesize($file_name)));
		
		if (!fclose($fh)) {
			echo ADD_PLUGIN_TO_PAGE_ERROR_CLOSING_PAGE_FILE_ERR . " " . CLICK_WORD . " <a href=\"add_plugin_to_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . ADD_PLUGIN_TO_PAGE_RETURN_TO_INSERT_PLUGIN_INTO_PAGE_CONSOLE_MSG . "\n$php_errormsg";
			exit;
		}
	}
		
	//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-->", $contents, 2);
		$contents = $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-->", $contents, 5);
		$contents = $page_temp_arr[0] . $content_code . "\n\n<!--content_code-->\n" . $page_temp_arr[1];
		if (isset($page_temp_arr[2]))
			$contents .= $content_code . "\n\n<!--content_code-->\n" . $page_temp_arr[2];
		if (isset($page_temp_arr[3]))
			$contents .= $content_code . "\n\n<!--content_code-->\n" . $page_temp_arr[3];
		if (isset($page_temp_arr[4]))
			$contents .= $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-->", $contents, 2);
		$contents = $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-->", $contents, 2);
		$contents = $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 != ""))
	{
		if (strpos($page_template, "<!--top_code-->") > 0)
		{
			$page_temp_arr = explode("<!--top_code-->", $contents, 4);
			$contents = $page_temp_arr[0] . $top_code . "\n\n<!--top_code-->\n" . $page_temp_arr[1];
			if (isset($page_temp_arr[2]))
				$contents .= $top_code . "\n\n<!--top_code-->\n" . $page_temp_arr[2];
			if (isset($page_temp_arr[3]))
				$contents .= $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 != ""))
	{
		if (strpos($page_template, "<!--left_code-->") > 0)
		{
			$page_temp_arr = explode("<!--left_code-->", $contents, 4);
			$contents = $page_temp_arr[0] . $left_code . "\n\n<!--left_code-->\n" . $page_temp_arr[1];
			if (isset($page_temp_arr[2]))
				$contents .= $left_code . "\n\n<!--left_code-->\n" . $page_temp_arr[2];
			if (isset($page_temp_arr[3]))
				$contents .= $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 != ""))
	{
		if (strpos($page_template, "<!--right_code-->") > 0)
		{
			$page_temp_arr = explode("<!--right_code-->", $contents, 4);
			$contents = $page_temp_arr[0] . $right_code . "\n\n<!--right_code-->\n" . $page_temp_arr[1];
			if (isset($page_temp_arr[2]))
				$contents .= $right_code . "\n\n<!--right_code-->\n" . $page_temp_arr[2];
			if (isset($page_temp_arr[3]))
				$contents .= $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 != ""))
	{
		if (strpos($page_template, "<!--bottom_code-->") > 0)
		{
			$page_temp_arr = explode("<!--bottom_code-->", $contents, 4);
			$contents = $page_temp_arr[0] . $bottom_code . "\n\n<!--bottom_code-->\n" . $page_temp_arr[1];
			if (isset($page_temp_arr[2]))
				$contents .= $bottom_code . "\n\n<!--bottom_code-->\n" . $page_temp_arr[2];
			if (isset($page_temp_arr[3]))
				$contents .= $bottom_code . "\n\n<!--bottom_code-->\n" . $page_temp_arr[3];
			unset($page_temp_arr);
		}
	}
	
	if (!($fh = fopen($file_name, 'w'))) {
		echo ADD_PLUGIN_TO_PAGE_ERROR_OPENING_PAGE_FILE_ERR . " " . CLICK_WORD . " <a href=\"add_plugin_to_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . ADD_PLUGIN_TO_PAGE_RETURN_TO_INSERT_PLUGIN_INTO_PAGE_CONSOLE_MSG . "\n$php_errormsg";
		exit;
	}
	if (!fwrite($fh, $contents)) {
		echo ADD_PLUGIN_TO_PAGE_ERROR_UPDATING_PAGE_FILE_ERR . " " . CLICK_WORD . " <a href=\"add_plugin_to_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . ADD_PLUGIN_TO_PAGE_RETURN_TO_INSERT_PLUGIN_INTO_PAGE_CONSOLE_MSG . "\n$php_errormsg";
		exit;
	}
	if (!fclose($fh)) {
		echo ADD_PLUGIN_TO_PAGE_ERROR_CLOSING_PAGE_FILE_ERR . " " . CLICK_WORD . " <a href=\"add_plugin_to_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . ADD_PLUGIN_TO_PAGE_RETURN_TO_INSERT_PLUGIN_INTO_PAGE_CONSOLE_MSG . "\n$php_errormsg";
		exit;
	}
	@chmod($file_name, 0644);

	/////////////////////////////////////////////////////////////////////////////////////////
	// 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_name . "'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$head_content = $row["head_content"];
		
		// If head is default head, then create a new head based on page name.
		$new = false;
		if ($head_name == "head")
		{
			$head_name .= "_" . $page_name;
			$query = "SELECT head_name FROM " . BWB_TABLE_PREFIX . "head WHERE head_name = '" . $head_name . "'";
			$result = $bwb_dbh->query($query);
			if ($result->rowCount() > 0)
				$head_name .= time();
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET head_name='" . $head_name. "' WHERE page_name='" . $page_name . "'";
			$cnt = $bwb_dbh->exec($query);
			$new = true;
		}
		
		// 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));
		
		// Insert new head into table.
		if ($new === true)
			$query = "INSERT INTO " . BWB_TABLE_PREFIX . "head SET head_content = '" . $head_content . "', `revised` = '" . $today . "', plugins = '" . $plugin_ids . "', head_name = '" . $head_name . "'";
		else
			$query = "UPDATE " . BWB_TABLE_PREFIX . "head SET head_content = '" . $head_content . "', `revised` = '" . $today . "', plugins = '" . $plugin_ids . "' WHERE head_name = '" . $head_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_name . "'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$header_content = $row["page_content"];
		
		// If header is default header, then create a new header based on page name.
		$new = false;
		if ($header_name == "header")
		{
			$header_name .= "_" . $page_name;
			$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = '" . $header_name . "'";
			$result = $bwb_dbh->query($query);
			if ($result->rowCount() > 0)
				$header_name .= time();
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET header_name='" . $header_name . "' WHERE page_name='" . $page_name. "'";
			$cnt = $bwb_dbh->exec($query);
			$new = true;
		}
		
		// Combine HTML (Javascript) code with default header content.
		$header_content = $header_content . "\n\n\n" . $header_html;
		$header_content = addslashes(stripslashes($header_content));
		
		// Insert new header into table.
		if ($new === true)
			$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special SET page_content = '" . $header_content . "', `revised` = '" . $today . "', plugins = '" . $plugin_ids . "', page_name = '" . $header_name . "'";
		else
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data_special SET page_content = '" . $header_content . "', `revised` = '" . $today . "', plugins = '" . $plugin_ids . "' WHERE page_name = '" . $header_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_name . "'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$footer_content = $row["page_content"];
		
		// If footer is default footer, then create a new footer based on page name.
		$new = false;
		if ($footer_name == "footer")
		{
			$footer_name .= "_" . $page_name;
			$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = '" . $footer_name . "'";
			$result = $bwb_dbh->query($query);
			if ($result->rowCount() > 0)
				$footer_name .= time();
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET footer_name='" . $footer_name . "' WHERE page_name='" . $page_name. "'";
			$cnt = $bwb_dbh->exec($query);
			$new = true;
		}
		
		// Combine HTML (Javascript) code with default footer content.
		$footer_content = $footer_content . "\n\n\n" . $footer_html;
		$footer_content = addslashes(stripslashes($footer_content));
		
		// Insert new footer into table.
		if ($new === true)
			$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special SET page_content = '" . $footer_content . "', `revised` = '" . $today . "', plugins = '" . $plugin_ids . "', page_name = '" . $footer_name . "'";
		else
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data_special SET page_content = '" . $footer_content . "', `revised` = '" . $today . "', plugins = '" . $plugin_ids . "' WHERE page_name = '" . $footer_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_name . "'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$top_content = $row["page_content"];
		
		// If top is default top, then create a new top based on page name.
		$new = false;
		if ($top_name == "top")
		{
			$top_name .= "_" . $page_name;
			$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = '" . $top_name . "'";
			$result = $bwb_dbh->query($query);
			if ($result->rowCount() > 0)
				$top_name .= time();
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET top_name='" . $top_name . "' WHERE page_name='" . $page_name. "'";
			$cnt = $bwb_dbh->exec($query);
			$new = true;
		}
		
		// Combine HTML (Javascript) code with default top content.
		$top_content = $top_content . "\n\n\n" . $top_html;
		$top_content = addslashes(stripslashes($top_content));
		
		// Insert new top into table.
		if ($new === true)
			$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special SET page_content = '" . $top_content . "', `revised` = '" . $today . "', plugins = '" . $plugin_ids . "', page_name = '" . $top_name . "'";
		else
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data_special SET page_content = '" . $top_content . "', `revised` = '" . $today . "', plugins = '" . $plugin_ids . "' WHERE page_name = '" . $top_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_name . "'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$left_content = $row["page_content"];
		
		// If left is default left, then create a new left based on page name.
		$new = false;
		if ($left_name == "left")
		{
			$left_name .= "_" . $page_name;
			$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = '" . $left_name . "'";
			$result = $bwb_dbh->query($query);
			if ($result->rowCount() > 0)
				$left_name .= time();
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET left_name='" . $left_name . "' WHERE page_name='" . $page_name. "'";
			$cnt = $bwb_dbh->exec($query);
			$new = true;
		}
		
		// Combine HTML (Javascript) code with default left content.
		$left_content = $left_content . "\n\n\n" . $left_html;
		$left_content = addslashes(stripslashes($left_content));
		
		// Insert new top into table.
		if ($new === true)
			$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special SET page_content = '" . $left_content . "', `revised` = '" . $today . "', plugins = '" . $plugin_ids . "', page_name = '" . $left_name . "'";
		else
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data_special SET page_content = '" . $left_content . "', `revised` = '" . $today . "', plugins = '" . $plugin_ids . "' WHERE page_name = '" . $left_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_name . "'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$right_content = $row["page_content"];
		
		// If right is default right, then create a new right based on page name.
		$new = false;
		if ($right_name == "right")
		{
			$right_name .= "_" . $page_name;
			$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = '" . $right_name . "'";
			$result = $bwb_dbh->query($query);
			if ($result->rowCount() > 0)
				$right_name .= time();
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET right_name='" . $right_name . "' WHERE page_name='" . $page_name. "'";
			$cnt = $bwb_dbh->exec($query);
			$new = true;
		}
		
		// Combine HTML (Javascript) code with default right content.
		$right_content = $right_content . "\n\n\n" . $right_html;
		$right_content = addslashes(stripslashes($right_content));
		
		// Insert new top into table.
		if ($new === true)
			$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special SET page_content = '" . $right_content . "', `revised` = '" . $today . "', plugins = '" . $plugin_ids . "', page_name = '" . $right_name . "'";
		else
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data_special SET page_content = '" . $right_content . "', `revised` = '" . $today . "', plugins = '" . $plugin_ids . "' WHERE page_name = '" . $right_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_name . "'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$bottom_content = $row["page_content"];
		
		// If bottom is default bottom, then create a new bottom based on page name.
		$new = false;
		if ($bottom_name == "bottom")
		{
			$bottom_name .= "_" . $page_name;
			$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name = '" . $bottom_name . "'";
			$result = $bwb_dbh->query($query);
			if ($result->rowCount() > 0)
				$bottom_name .= time();
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET bottom_name='" . $bottom_name . "' WHERE page_name='" . $page_name. "'";
			$cnt = $bwb_dbh->exec($query);
			$new = true;
		}
		
		// Combine HTML (Javascript) code with default bottom content.
		$bottom_content = $bottom_content . "\n\n\n" . $bottom_html;
		$bottom_content = addslashes(stripslashes($bottom_content));
		
		// Insert new top into table.
		if ($new === true)
			$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special SET page_content = '" . $bottom_content . "', `revised` = '" . $today . "', plugins = '" . $plugin_ids . "', page_name = '" . $bottom_name . "'";
		else
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data_special SET page_content = '" . $bottom_content . "', `revised` = '" . $today . "', plugins = '" . $plugin_ids . "' WHERE page_name = '" . $bottom_name . "'";
		$cnt = $bwb_dbh->exec($query);
	}
	
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 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)
			{
				$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 != ""))
				 	$show_custom_styles = 1;
				else
					$show_custom_styles = 0;
				
				$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);
			}
		}
		
		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 != ""))
		{
			$result = RunSQL($css_sql, $bwb_dbh, BWB_TABLE_PREFIX, false, UPLOAD_TEMPLATE_ROWS_AFFECTED_MSG);
		}
				
		if (isset($custom_css_sql) && ($custom_css_sql != ""))
		{
			$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 != "")))
		{	
			include ("lib/build_css_string.php");
			$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 ADD_PLUGIN_TO_PAGE_COULD_NOT_RENAME_MSG . " $file_name " . TO_WORD . " $bkup_file_name.<br>";
				@chmod($bkup_file_name, 0644);
			}
			
			// Create file.
			$fh = fopen($file_name, 'x') or die("Can't create $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);
		}
		
		if (isset($plugin_sql) && ($plugin_sql != ""))
		{
			$result = RunSQL($plugin_sql, $bwb_dbh, BWB_TABLE_PREFIX, false, UPLOAD_TEMPLATE_ROWS_AFFECTED_MSG);
		}
		
		$query = "REPLACE INTO " . BWB_TABLE_PREFIX . "plugins_deployed SET `plugin_id`=$plugin, `deployed`=1";
		$cnt = $bwb_dbh->exec($query);
	}
	
	///////////////////////////////////////////////////////////////
	// Change page-template layout if needed.
	$query = "SELECT template FROM " . BWB_TABLE_PREFIX . "page_data WHERE page_name = '" . $page_name . "'";
	$result = $bwb_dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);
	$template_name = $row['template'];
	
	// 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'];
			
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET template = '" . $template_name . "' WHERE page_name = '" . $page_name . "'";
			$cnt = $bwb_dbh->exec($query);
		}
	}
	
	//Go to edit page.
	$domain = $_SERVER['HTTP_HOST'];
	if (BWB_REQUIRE_SSL == 1)
		$web_path = "https://" . $domain;
	else
		$web_path = "http://" . $domain;
	$php_self = $_SERVER['PHP_SELF'];
	$this_file = substr(strrchr($php_self, "/"), 1);
	$app_dir = substr($php_self, 0, (strlen($php_self)- strlen($this_file)));
	$redirect = $web_path . $app_dir . "add_plugin_to_page_select.php?page_name=$page_name&plugin_name=$plugin_name";
	if ($deployed != 1)
		$redirect .= "&refresh_buttons=1";
	header("Location: $redirect");
	
?>
