<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright EB Dynamics, Inc., 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.
//

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

	if ($page_name == "")
	{
		echo "Oops! You forgot to enter a page name.  Click <a href=\"main.php?mode=$mode\" 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 = mysql_query($query, $bwb_link);
	$row = mysql_fetch_array($result);
	$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 = mysql_query($query, $bwb_link);
	$row = mysql_fetch_array($result);
	$page_name_retrieved = $row["page_name"];
	if ($page_name_retrieved)
	{
		echo "$file_name already exists in database.  Click <a href=\"main.php?mode=$mode\" 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=\"main.php?mode=$mode\" 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 = mysql_query($query, $bwb_link);
		$row = mysql_fetch_array($result);
		$head_code = $row["head_code"];
		$head_html = $row["head_html"];
		$body_code = $row["body_code"];
		$body_html = $row["body_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'";
	$result = mysql_query($query, $bwb_link);
//	echo $query;
//	exit;
// 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";
	$result = mysql_query($query, $bwb_link);

	//Get template from database.
	$query = "SELECT `page_template` FROM `" . BWB_TABLE_PREFIX . "template` WHERE `template_name` = '$template_name'";
	$result = mysql_query($query, $bwb_link);
	$row = mysql_fetch_array($result);
	$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 = mysql_query($query, $bwb_link);
	$row = mysql_fetch_array($result);
	$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 put HTML head  holder with head code snippet.
	if (($plugin != "-not selected-") && ($head_html != ""))
	{
		// Get last head name.
		$query = "SELECT head_name FROM " . BWB_TABLE_PREFIX . "head ORDER BY head_name DESC";
		$result = mysql_query($query, $bwb_link);
		$row = mysql_fetch_array($result);
		$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 = mysql_query($query, $bwb_link);
		$row = mysql_fetch_array($result);
		$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 = mysql_fetch_array($result))
			{
				$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 . "')";
		}
		$result = mysql_query($query, $bwb_link);
//		echo "<br><br>$query<br>\n";
		
		// 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);
	}
			
	// 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 plugen 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 = mysql_query($query, $bwb_link);
			if (mysql_num_rows($result) < 1)
			{
				$query = "SELECT MAX(sort_order) AS sort_order FROM " . BWB_TABLE_PREFIX . "style_sheets";
				$result = mysql_query($query, $bwb_link);
				$row = mysql_fetch_array($result);
				$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;
				$result = mysql_query($query, $bwb_link);
			}
		}
		
		if (isset($class_sql) && ($class_sql != ""))
		{
			$table = $style_sheet . "_classes";
			copy_table_structure($table, BWB_TABLE_PREFIX, $bwb_link, $bwb_database);
			$result = mysql_query($class_sql, $bwb_link);
		}
		
		if (isset($css_sql) && ($css_sql != ""))
		{
			$table = $style_sheet . "_css";
			copy_table_structure($table, BWB_TABLE_PREFIX, $bwb_link, $bwb_database);
			$result = mysql_query($css_sql, $bwb_link);
		}
		
		if (isset($plugin_sql) && ($plugin_sql != ""))
		{
			$result = mysql_query($plugin_sql, $bwb_link);
		}
		
		$query = "UPDATE " . BWB_TABLE_PREFIX . "plugins SET `deployed`=1 WHERE `id`=$plugin";
		$result = mysql_query($query, $bwb_link);
	}	
	
	//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&first_open=1";
	header("Location: $edit_page");
	
	exit;
	////////////////////////////////////////////////////////////////////////////////////////////////
	function copy_table_structure($table, $table_prefix, $link, $database)
	{
		$query = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '" . $database . "' AND table_name = '" . $table_prefix . $table . "'";
		$result = mysql_query($query, $link);
		$row = mysql_fetch_array($result);
		$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;
			$result = mysql_query($query, $link);
			
			$query = " ALTER TABLE `" . $table_prefix . $table . "` ADD PRIMARY KEY (`class`)";
			$result = mysql_query($query, $link);
		}
		
		$query = "TRUNCATE TABLE `" . $table_prefix . $table . "`";
		$result = mysql_query($query, $link);
			
		return "";
	}
	
?>
