<?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.
//

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

////////////////////////////////////////////////////////////////////////////////////////////////
function copy_table_structure($table, $table_prefix, $dbh, $database)
{
	$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 (strpos($table, "_classes") > 0)
			$source_table = $table_prefix . "site_classes";
		else
			$source_table = $table_prefix . "site_css";
		$query = "CREATE TABLE IF NOT EXISTS " . $table_prefix . $table . " SELECT * FROM " . $source_table;
		$cnt = $dbh->exec($query);
		
		$query = " ALTER TABLE `" . $table_prefix . $table . "` ADD PRIMARY KEY (`class`)";
		$cnt = $dbh->exec($query);
	}
	
	$query = "TRUNCATE TABLE `" . $table_prefix . $table . "`";
	$cnt = $dbh->exec($query);
		
	return "";
}
	
///////////////////////////////////////////////////////////////////////////////
function RunSQL($sql_string, $table_prefix, $dbh)
{
	$sql_string = stripslashes($sql_string);
	$sql_string_arr = array();
	$line_arr = array();
	// Split SQL input into lines.
	$line_arr = preg_split("[\n|\r]", $sql_string);
	$sql_string_arr[0] = "";
	$j = 0;
	$find_start = true;
	$got_script = false;
	$got_php = false;
	$got_style = false;
	// Search for commands and assemble into SQL command array.
	for ($i = 0; $i < count($line_arr); $i++)
	{
		// Test for comment line.
		$curr_line = trim($line_arr[$i]);
		if ($find_start)
		{
			$first_chars = substr($curr_line, 0, 2);
			if (($first_chars == "--") || ($first_chars == "//"))
				continue;
		}
		$find_start = false;
		
		// It is possible for a line to end with a semicolon (;) if records contain JavaScript or PHP.  Need to turn off looking end of SQL command
		// if script or PHP is found until end of script or PHP is also found.  Otherwise we run the risk of trying to run only part of a record insert
		// which usually results in an SQL syntax error.
		if (!$got_script)
		{
			if (stripos($curr_line, "<script") !== false)
				$got_script = true;
		}
		if ($got_script)
		{
			if (stripos($curr_line, "</script>") !== false)
				$got_script = false;
		}
		
		if (!$got_php)
		{
			if (stripos($curr_line, "<?php") !== false)
				$got_php = true;
		}
		if ($got_php)
		{
			if (stripos($curr_line, "?>") !== false)
				$got_php = false;
		}
		
		if (!$got_style)
		{
			if (stripos($curr_line, "<style") !== false)
				$got_style = true;
		}
		if ($got_style)
		{
			if (stripos($curr_line, "</style>") !== false)
				$got_style = false;
		}
		
		// Build SQL command.
		$sql_string_arr[$j] = $sql_string_arr[$j] . $line_arr[$i];
		
		// Look for end of command.
		if ((!$got_script) && (!$got_php) && (!$got_style))
		{
			$last_char = substr($curr_line, (strlen($curr_line) - 1), 1);
			if ($last_char == ";")	// Got end of SQL command.
			{
				// Check for other possible reasons that ; is at end of line.
				$last_6_chars = substr($curr_line, (strlen($curr_line) - 7), 6);
				if (stripos($curr_line, "&") === false) // Looks like ; is not do to & code, good to go.
				{
					$j++;
					$sql_string_arr[$j] = "";
					$find_start = true;
				}
			}
		}
	}
	// Run SQL commands one at a time.
	for ($i = 0; $i < count($sql_string_arr); $i++)
	{
		if (strlen($sql_string_arr[$i]) > 2)
		{
			if ($table_prefix != "bwb_")
			{
				$sql_string_arr[$i] = str_replace("bwb_link", "@@@link_retention@@@", $sql_string_arr[$i]);
				$sql_string_arr[$i] = str_replace("bwb_", $table_prefix, $sql_string_arr[$i]);
				$sql_string_arr[$i] = str_replace("@@@link_retention@@@", "bwb_link", $sql_string_arr[$i]);
			}
//			echo $sql_string_arr[$i] . "<br><br>\n";

			try	{
				$cnt = $dbh->exec($sql_string_arr[$i]);
			} catch (Exception $e) {
				echo $e->getMessage() . "<br>\n";
			}
			
//			if (is_array($cnt))
//			{
//				echo "<pre>\n";
//				print_r($cnt);
//				echo "</pre>\n";
//			}
//			elseif ($cnt > 0)
//				echo $cnt . " row(s) affected.<br>\n";
//			else
//				echo $bwb_dbh->errorInfo() . "<br>\n";
				
//			if ($i < (count($sql_string_arr) - 1))
//				echo "<br>-------------------------------------------------------------------------------<br>\n";
		}
	}
}

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

	if ($page_name == "")
	{
		echo "Oops! You forgot to enter a page name.  Click <a href=\"create_page_select.php\" title=\"here\">here</a> and enter a page name.";
		exit;
	}
	
	//Remove Unix incompatible characters.
	$page_name = ereg_replace("[[^[:space:]]", "_", $page_name);
	$page_name = ereg_replace("[^a-zA-Z0-9\(\)\s_.-]", "", $page_name);
	$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);
	
	//First check to see if file is alrready 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 already exists in database.  Click <a href=\"create_page_select.php\" title=\"here\">here</a> to enter a different page name.";
		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>";
	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
		{
			echo "$file_name already exists.  Click <a href=\"create_page_select.php\" title=\"here\">here</a> to enter a different page name.";
			exit;
		}
	}
	
	// If plugin code selected, then get plugin code snippet.
	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);
		$head_code = $row["head_code"];
		$head_html = $row["head_html"];
		$header_code = $row["header_code"];
		$header_html = $row["header_html"];
		$body_code = $row["body_code"];
		$body_html = $row["body_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"];
		$plugin_sql = $row["plugin_sql"];
		$deployed = $row["deployed"];
	}
	else
		$body_html = "\n<p>Enter your content here.</p>\n";
	
	//Add page name to database.
	$today = date("Y-m-d H:i:s");
	$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data SET page_name='$page_name', page_content='$body_html', revised='$today'";
//	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='$body_html', revised='$today', `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` = '$template_name'";
	$result = $bwb_dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);
	$page_template = $row["page_template"];
	
	//Insert page name into template.
	$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 plugin is selected, then replace aaa holder with head code snippet.
	if (($plugin != "-not selected-") && ($head_code != ""))
		$page_template = str_replace("aaa", $head_code, $page_template);
	//else, replace aaa with nothing.
	else
		$page_template = str_replace("aaa", "", $page_template);
	
	//If plugin is selected, then replace yyy holder with body code snippet.
	if (($plugin != "-not selected-") && ($body_code != ""))
		$page_template = str_replace("yyy", $body_code, $page_template);
	//else, replace yyy with nothing.
	else
		$page_template = str_replace("yyy", "", $page_template);
		
	//If plugin is selected, then replace hhh holder with header code snippet. (not to be confused with head)
	if (($plugin != "-not selected-") && ($header_code != ""))
		$page_template = str_replace("hhh", $header_code, $page_template);
	//else, replace hhh with nothing.
	else
		$page_template = str_replace("hhh", "", $page_template);
		
	//If plugin is selected, then replace fff holder with footer code snippet.
	if (($plugin != "-not selected-") && ($footer_code != ""))
		$page_template = str_replace("fff", $footer_code, $page_template);
	//else, replace fff with nothing.
	else
		$page_template = str_replace("fff", "", $page_template);
		
	//If plugin is selected, then replace HTML head holder with head code snippet.
	if (($plugin != "-not selected-") && (isset($head_html)) && ($head_html != ""))
	{
		// Get last head name.
		$query = "SELECT head_name FROM " . BWB_TABLE_PREFIX . "head ORDER BY head_name DESC";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$head_name = $row["head_name"];
		
		// 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"];
		
		// Combine HTML (Javascript) code with default head content.
		$head_content = $head_content . "\n\n\n" . $head_html;
		$head_content = addslashes($head_content);
		
		// Insert new head into table.
		$head_index = 1;
		if ($head_name == "head")
			$query = "INSERT INTO " . BWB_TABLE_PREFIX . "head (head_name, head_content, `revised`) VALUES ('head1', '" . $head_content . "', '" . $today. "')";
		else
		{
			$index = array();
			$i = 1;
			$index[0] = substr($head_name, strlen("head"));
			while ($row = $result->fetch(PDO::FETCH_ASSOC))
			{
				$head_name = $row["head_name"];
				$index[$i] = substr($head_name, strlen("head"));
				$i++;
			}
			sort($index);
			$head_index = $index[$i-1] + 1;
			$query = "INSERT INTO " . BWB_TABLE_PREFIX . "head (head_name, head_content, `revised`) VALUES ('head" . $head_index . "', '" . $head_content . "', '" . $today . "')";
		}
//		echo "<br><br>$query<br>\n";
		$cnt = $bwb_dbh->exec($query);
		
		// Replace reference to head content in template.
		$head_str = "head_name='head" . $head_index . "'";
		$page_template = str_replace("head_name='head'", $head_str, $page_template);
	}
	
	//If plugin is selected, then replace HTML header holder with header HTML code snippet.
	if (($plugin != "-not selected-") && (isset($header_html)) && ($header_html != ""))
	{
		// Get last header name.
		$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name LIKE 'header%' ORDER BY page_name DESC";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$header_name = $row["page_name"];
		
		// 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 = $footer_content . "\n\n\n" . $header_html;
		$header_content = addslashes($header_content);
		
		// Insert new header into table.
		$header_index = 1;
		unset($index);
		if ($header_name == "header")
			$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special (page_name, page_content, `revised`) VALUES ('header1', '" . $header_content . "', '" . $today. "')";
		else
		{
			$index = array();
			$i = 1;
			$index[0] = substr($header_name, strlen("header"));
			while ($row = $result->fetch(PDO::FETCH_ASSOC))
			{
				$header_name = $row["page_name"];
				$index[$i] = substr($header_name, strlen("header"));
				$i++;
			}
			sort($index);
			$header_index = $index[$i-1] + 1;
			$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special (page_name, page_content, `revised`) VALUES ('header" . $header_index . "', '" . $header_content . "', '" . $today . "')";
		}
//		echo "<br><br>$query<br>\n";
		$cnt = $bwb_dbh->exec($query);
		
		// Replace reference to header content in template.
		$header_str = "page_name='header" . $header_index . "'";
		$page_template = str_replace("page_name='header'", $header_str, $page_template);
	}
	
	//If plugin is selected, then replace HTML footer holder with footer HTML code snippet.
	if (($plugin != "-not selected-") && (isset($footer_html)) && ($footer_html != ""))
	{
		// Get last footer name.
		$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name LIKE 'footer%' ORDER BY page_name DESC";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$footer_name = $row["page_name"];
		
		// 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($footer_content);
		
		// Insert new footer into table.
		$footer_index = 1;
		unset($index);
		if ($footer_name == "footer")
			$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special (page_name, page_content, `revised`) VALUES ('footer1', '" . $footer_content . "', '" . $today. "')";
		else
		{
			$index = array();
			$i = 1;
			$index[0] = substr($footer_name, strlen("footer"));
			while ($row = $result->fetch(PDO::FETCH_ASSOC))
			{
				$footer_name = $row["page_name"];
				$index[$i] = substr($footer_name, strlen("footer"));
				$i++;
			}
			sort($index);
			$footer_index = $index[$i-1] + 1;
			$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special (page_name, page_content, `revised`) VALUES ('footer" . $footer_index . "', '" . $footer_content . "', '" . $today . "')";
		}
		$cnt = $bwb_dbh->exec($query);
//		echo "<br><br>$query<br>\n";
		
		// Replace reference to footer content in template.
		$footer_str = "page_name='footer" . $footer_index . "'";
		$page_template = str_replace("page_name='footer'", $footer_str, $page_template);
	}
			
	// Create file.
	$fh = fopen($file_name, 'x') or die("Can't create $file_name: $php_errormsg");
	$result = (fputs($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)
			{
				$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;
				
				$query = "INSERT INTO " . BWB_TABLE_PREFIX . "style_sheets SET `name`='" . $style_sheet . "', `description`='" . $style_sheet_description . "', `sort_order`=" . $sort_order;
				$cnt = $bwb_dbh->exec($query);
			}
		}
		
		if (isset($class_sql) && ($class_sql != ""))
		{
			$table = $style_sheet . "_classes";
			copy_table_structure($table, BWB_TABLE_PREFIX, $bwb_dbh, $bwb_database);
			$result = $bwb_dbh->query($class_sql);
		}
		
		if (isset($css_sql) && ($css_sql != ""))
		{
			$table = $style_sheet . "_css";
			copy_table_structure($table, BWB_TABLE_PREFIX, $bwb_dbh, $bwb_database);
			$result = $bwb_dbh->query($css_sql);
		}
		
		if (isset($plugin_sql) && ($plugin_sql != ""))
		{
//			$result = $bwb_dbh->query($plugin_sql);
			RunSQL($plugin_sql, BWB_TABLE_PREFIX, $bwb_dbh);
		}
		
		$query = "UPDATE " . BWB_TABLE_PREFIX . "plugins SET `deployed`=1 WHERE `id`=$plugin";
		$cnt = $bwb_dbh->exec($query);
	}	
	
	//Go to edit page.
	$domain = $_SERVER['HTTP_HOST'];
	$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)));
	$edit_page = $web_path . $app_dir . "edit_page.php?page_name=$page_name&mode=$mode";
	if (($plugin != "-not selected-") && ($deployed != 1))
		$edit_page .= "&refresh_buttons=1";
	header("Location: $edit_page");
	
?>
