<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright EB Dynamics, Inc., Edward Lemmers, P.E.
// For licensing, see license.txt.
// Revised: 8/13/2008
// Revised: 4/11/09	ELL
//	Fixed bug with not updating from preview.
// Revised: 6/2/09 ELL
//  Added source field to backup table to fix bug of restore not knowing anything about special pages.
// Revised: 6/18/09	ELL
//  Changed CKeditor height from 500 pixels to 93%.
// Revised: 6/24/09	ELL
//	Added encupusalation of template table and divs to apply built-in template styles to create a true WYSISWYG editing environment.
// Revised: 6/27/09	ELL
//	Added image optimization and image restoration.
// Revised: 6/29/09	ELL
//	Fixed bug caused by the encapsulation of built-in template styles performed on 6/24/09.
// Revised: 7/14/09	ELL
//	Fixed bug with encapsulation with CKeditor in IE.  It turns out that CKeditor automatically puts the "class" attribute before
//  the "valign" attribute if running in IE.
// Revised: 8/24/09	ELL
//	Added button to bring up CSS editor for sites CSS only.
// Revised: 9/3/09	ELL
//	Added "Live View" for pop open new window for viewing actual page.
//	Added page name being edited to title and in bottom button bar.
// Revised: 2/11/10	ELL
//	Fixed bug with data not being saved from preview.  (Problem caused by single quotes not being escaped in sValue.)
//	Renamed buttons and added "Clear Content" button.
// Revised:	2/14/10	ELL
//	Modified style application to look for alternate border areas, i.e. right1, right2, etc.
// Revised: 3/11/10	ELL
//	Modified redirection to go to preview_page.php instead of save_page.php for previewing.
/////////////////////////////////////////////////////////////////////////
// Revised: 4/2/10	ELL
//	Upgraded from FCKEditor 2.6 to CKEditor 3.2
// Revised: 4/17/10	ELL
//	Fixed window height problem for Opera.
// Revised: 4/20/10 ELL
//	Added modality of "Edit Styles" button based on access level.  Restricted users can't see this button. 
//	Fixed bug of lossing unsaved changed when optimizing images.
// 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
// Modified to inject new id attributes into surrounding table and div structure for WYSIWYG experience.
// Added persitence of last page edited or last border area edited.
// Revised: 11/13/2010	ELL
// Added checking for save button being pressed on CKEditor so that page can be saved rather than loosing changes.
// Revised: 4/24/2010	ELL
// Removed line referencing CKFinder.
// Revised: 12/27/2011	ELL
// Made changes to handle upgrade from CKEditor version 3.4 to version 3.6.
//	1) Changed CKEDITOR.config.stylesCombo_stylesSet to CKEDITOR.config.stylesSet
//	2) Modifed CKEDITOR.config.contentsCss line to have array of all CSS files rather than just site.css
// Revised: 12/28/2011	ELL
// Added startup folder for file, image or flash when calling KFM.
// Revised: 1/12/2/12	ELL
// Added saving of drafts.  In fact, draft becomes the default for "Save".  The button that actually saves the page for the site is 
// now called "Publish".
// Revised: 2/8/2012	ELL
// Added table prefix handling.  Added references to website files, images, CSS, scripts, media and Flash folder configurations.
// Revised: 2/28/2012	ELL
// Added stray paragraph nuker to deal with CKEditor breaking pages by adding paragraph to end of HTML.
// Revised: 7/10/2012	ELL
// Added handling of blogging.


	include ("check_session.php");
		
	$preview = $_POST['preview'];
	$save_draft = $_POST['save_draft'];
	$publish = $_POST['publish'];
	$revert = $_POST['revert'];
	$optimize = $_POST['optimize'];
	$reset = $_POST['reset'];
	$clear = $_GET['clear'];
	$mode = $_REQUEST['mode'];
	$sValue = stripslashes( $_POST['CKeditor1'] ) ;
	$update_from_preview = $_POST['update_from_preview'];
	if (!isset($save_draft))	// Check for click of save button on CKEditor.
	{
		$first_open = $_REQUEST['first_open'];
		if ( (!isset($preview)) && (!isset($optimize)) && (!isset($reset)) && (!isset($clear)) && (!isset($update_from_preview)) && (!isset($revert)) && (!isset($first_open)) )
			$save_draft = "Save";
	}
	
	include ("lib/image_processing.php");
	
	$page_name = $_REQUEST['page_name'];
	$blog_id = $_REQUEST['blog_id'];
	$special = $_REQUEST['special'];	//Flag to tell if editing special page (header, footer, side panel...).
	if ($mode == "blog")
	{
		$_SESSION['last_blog_edited'] = $blog_id;
		$_SESSION['last_page_edited'] = $page_name;
		$special = 0;
	}
	elseif (!isset($special))
	{
		$_SESSION['last_page_edited'] = $page_name;
		$special = 0;
	}
	else
		$_SESSION['last_border_edited'] = $page_name;
	
	$prepend = stripslashes($_POST['prepend']);
	$postpend = stripslashes($_POST['postpend']);
	
	$encap_delim = "<!-- WYSIWYG Encapsulation. Modify HTML inside of these comments only.  All code outside of these comments is discarded. -->";
	if ($mode == "blog")
		$post_locate_string = "<!-- Post locate string for blog ID " . $blog_id . ". Do not remove this line. -->";
	
	if (BWB_BASE_DIR == '')
		$userfiles = '';
	else
		$userfiles = "/" . BWB_BASE_DIR;
		
	if (BWB_WEBPAGE_DIR == '')
		$website_folder = '';
	else
		$website_folder = "/" . BWB_WEBPAGE_DIR;
	
	// If Revert clicked, then clean out draft so editor will use last published page.
	if (($revert == "Revert") && ($mode != "blog"))
	{
		$query = "DELETE FROM " . BWB_TABLE_PREFIX . "page_data_draft WHERE page_name='$page_name'";
		$result = mysql_query($query, $bwb_link);
		unset($sValue);
	}
	elseif (($revert == "Revert") && ($mode == "blog"))
	{
		$query = "DELETE FROM " . BWB_TABLE_PREFIX . "blog_draft WHERE blog_id='$blog_id'";
		$result = mysql_query($query, $bwb_link);
		unset($sValue);
	}
	
	if ((isset($sValue)) && isset($prepend))
	{
		$sValue_arr = explode($encap_delim, $sValue);
		$sValue = $sValue_arr[1];
		
		// Because of unpredictable behavior as to where CKeditor allows added on content for new pages, need to dig content out of top of page.
		$count = 1;
		$sValue_arr[0] = str_replace("<div class='wrap' id='wrap'>", "", $sValue_arr[0], $count);
		$sValue_arr[0] = str_replace("<div class=\"wrap\" id=\"wrap\">", "", $sValue_arr[0], $count);
		$sValue_arr[0] = str_replace("<div id='wrap' class='wrap'>", "", $sValue_arr[0], $count);
		$sValue_arr[0] = str_replace("<div id=\"wrap\" class=\"wrap\">", "", $sValue_arr[0], $count);
		$sValue_arr[0] = str_replace("<table width='100%' height='100%'>", "", $sValue_arr[0], $count);
		$sValue_arr[0] = str_replace("<table width=\"100%\" height=\"100%\">", "", $sValue_arr[0], $count);
		$sValue_arr[0] = str_replace("<table height='100%' width='100%'>", "", $sValue_arr[0], $count);
		$sValue_arr[0] = str_replace("<table height=\"100%\" width=\"100%\">", "", $sValue_arr[0], $count);
		$sValue_arr[0] = str_replace("<tbody>", "", $sValue_arr[0], $count);
		$sValue_arr[0] = str_replace("<tr>", "", $sValue_arr[0], $count);
		if (($special != 1) || ($mode == "blog"))
		{
			$sValue_arr[0] = str_replace("<td valign='top' class='content_td' id='content_td'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign=\"top\" class=\"content_td\" id=\"content_td\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td class='content_td' id='content_td' valign='top'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td class=\"content_td\" id=\"content_td\" valign=\"top\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div class='content_div' id='content_div'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div class=\"content_div\" id=\"content_div\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign='top' id='content_td' class='content_td'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign=\"top\" id=\"content_td\" class=\"content_td\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td id='content_td' class='content_td' valign='top'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td id=\"content_td\" class=\"content_td\" valign=\"top\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div id='content_div' class='content_div'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div id=\"content_div\" class=\"content_div\">", "", $sValue_arr[0], $count);
		}
		elseif (substr($page_name, 0, 3) == "top")
		{
			$sValue_arr[0] = str_replace("<td valign='top' class='top_td' id='top_td'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign=\"top\" class=\"top_td\" id=\"top_td\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td class='top_td' id='top_td' valign='top'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td class=\"top_td\" id=\"top_td\" valign=\"top\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td class='top_td' id='top_td'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td class=\"top_td\" id=\"top_td\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div class='top_div' id='top_div'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div class=\"top_div\" id=\"top_div\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign='top' id='top_td' class='top_td'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign=\"top\" id=\"top_td\" class=\"top_td\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td id='top_td' class='top_td' valign='top'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td id=\"top_td\" class=\"top_td\" valign=\"top\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td id='top_td' class='top_td'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td id=\"top_td\" class=\"top_td\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div id='top_div' class='top_div'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div id=\"top_div\" class=\"top_div\">", "", $sValue_arr[0], $count);
		}
		elseif (substr($page_name, 0, 6) == "bottom")
		{
			$sValue_arr[0] = str_replace("<td valign='top' class='bottom_td' id='bottom_td'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign=\"top\" class=\"bottom_td\" id=\"bottom_td\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td class='bottom_td' id='bottom_td' valign='top'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td class=\"bottom_td\" id=\"bottom_td\" valign=\"top\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td class='bottom_td' id='bottom_td'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td class=\"bottom_td\" id=\"bottom_td\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div class='bottom_div' id='bottom_div'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div class=\"bottom_div\" id=\"bottom_div\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign='top' id='bottom_td' class='bottom_td'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign=\"top\" id=\"bottom_td\" class=\"bottom_td\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td id='bottom_td' class='bottom_td' valign='top'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td id=\"bottom_td\" class=\"bottom_td\" valign=\"top\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td id='bottom_td' class='bottom_td'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td id=\"bottom_td\" class=\"bottom_td\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div id='bottom_div' class='bottom_div'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div id=\"bottom_div\" class=\"bottom_div\">", "", $sValue_arr[0], $count);
		}
		elseif (substr($page_name, 0, 4) == "left")
		{
			$sValue_arr[0] = str_replace("<td valign='top' class='left_td' id='left_td'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign=\"top\" class=\"left_td\" id=\"left_td\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td class='left_td' id='left_td' valign='top'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td class=\"left_td\" id=\"left_td\" valign=\"top\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div class='left_div' id='left_div'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div class=\"left_div\" id=\"left_div\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign='top' id='left_td' class='left_td'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign=\"top\" id=\"left_td\" class=\"left_td\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td id='left_td' class='left_td' valign='top'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td id=\"left_td\" class=\"left_td\" valign=\"top\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div id='left_div'> class='left_div'", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div id=\"left_div\" class=\"left_div\">", "", $sValue_arr[0], $count);
		}
		elseif (substr($page_name, 0, 5) == "right")
		{
			$sValue_arr[0] = str_replace("<td valign='top' class='right_td' id='right_td'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign=\"top\" class=\"right_td\" id=\"right_td\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td class='right_td' id='right_td' valign='top'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td class=\"right_td\" id=\"right_td\" valign=\"top\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div class='right_div' id='right_div'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div class=\"right_div\" id=\"right_div\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign='top' id='right_td' class='right_td'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td valign=\"top\" id=\"right_td\" class=\"right_td\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td id='right_td' class='right_td' valign='top'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<td id=\"right_td\" class=\"right_td\" valign=\"top\">", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div id='right_div' class='right_div'>", "", $sValue_arr[0], $count);
			$sValue_arr[0] = str_replace("<div id=\"right_div\" class=\"right_div\">", "", $sValue_arr[0], $count);
		}
		$sValue_arr[0] = trim($sValue_arr[0]);
		$sValue = $sValue_arr[0]. $sValue;
		
		// Because of unpredictable behavior as to where CKeditor allows added on content for new pages, need to dig content out of bottom of page.
		// Note: The order with which items are replaced is very important.  Note that the string is being worked on from the end as the order is reversed.
		$sValue_arr[2] = strrev($sValue_arr[2]);
		// Search for extraneous paragraphs that CKEditor adds to the bottom from time to time.
		$pos = strpos($sValue_arr[2], ">", 0);
		if (substr($sValue_arr[2], $pos + 1, 1) == "p")	// Found pesky paragraph.  Nuke it!!!
		{
			$sValue_arr[2] = str_replace(">p/<", "", $sValue_arr[2], $count);
			$sValue_arr[2] = str_replace(";psbn&", "", $sValue_arr[2], $count);
			$sValue_arr[2] = str_replace(">p<", "", $sValue_arr[2], $count);
		}
		$sValue_arr[2] = str_replace(">vid/<", "", $sValue_arr[2], $count);
		$sValue_arr[2] = str_replace(">elbat/<", "", $sValue_arr[2], $count);
		$sValue_arr[2] = str_replace(">ydobt/<", "", $sValue_arr[2], $count);
		$sValue_arr[2] = str_replace(">rt/<", "", $sValue_arr[2], $count);
		$sValue_arr[2] = str_replace(">dt/<", "", $sValue_arr[2], $count);
		$sValue_arr[2] = str_replace(">vid/<", "", $sValue_arr[2], $count);
		$sValue_arr[2] = strrev($sValue_arr[2]);
		$sValue_arr[2] = trim($sValue_arr[2]);
		$sValue .= $sValue_arr[2];
	}
	
	////////////////////////////////////////////////////////////
	if (isset($optimize))	// Parse sValue for images.
		$num_of_images_optimized = OptimizeImages($sValue, $userfiles, BWB_IMAGE_DIR);
	
	if (isset($reset))	// Replace modified images with original images.
		$num_of_images_reset = ResetImages($sValue, $userfiles, BWB_IMAGE_DIR);
	////////////////////////////////////////////////////////////
	
	// If Save clicked then save draft and stay in editor. (Also update draft if publishing to keep in synch.)
	if (($save_draft == "Save") || ($publish == "Publish"))
	{
		$page_name=addslashes($page_name);
		$sValue=addslashes($sValue);
		$today = date("Y-m-d H:i:s");
		
		if ($mode == "blog")
		{
			$query = "SELECT blog_id FROM " . BWB_TABLE_PREFIX . "blogs_draft WHERE blog_id='$blog_id'";
			$result = mysql_query($query, $bwb_link);
			if (mysql_num_rows($result) > 0)	
				$query = "UPDATE " . BWB_TABLE_PREFIX . "blogs_draft SET post='$sValue', revised='$today' WHERE blog_id='$blog_id'";
			else
				$query = "INSERT INTO " . BWB_TABLE_PREFIX . "blogs_draft SET blog_id='$blog_id', post='$sValue', revised='$today'";

			$result = mysql_query($query, $bwb_link);
			
			$query = "TRUNCATE " . BWB_TABLE_PREFIX . "page_data_draft";
			$result = mysql_query($query, $bwb_link);
		}
		else
		{
			$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_draft WHERE page_name='$page_name'";
			$result = mysql_query($query, $bwb_link);
			if (mysql_num_rows($result) > 0)	
				$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data_draft SET page_content='$sValue', revised='$today', `source`=$special WHERE page_name='$page_name'";
			else
				$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_draft SET page_name='$page_name', page_content='$sValue', revised='$today', `source`=$special";
			$result = mysql_query($query, $bwb_link);
		}
	}
	
	// If Publish clicked then save page and stay in editor.
	if ($publish == "Publish")
	{
		$page_name=addslashes($page_name);
		$sValue=addslashes($sValue);
		$today = date("Y-m-d H:i:s");
		
		if ($special == 1)
		{
			$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name='$page_name'";
			$result = mysql_query($query, $bwb_link);
			if (mysql_num_rows($result) > 0)
				$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data_special SET page_content='$sValue', revised='$today' WHERE page_name='$page_name'";
			else
				$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_special SET page_name='$page_name', page_content='$sValue', revised='$today'";
		}
		elseif ($mode == "blog")
		{
			$query = "SELECT `id` FROM " . BWB_TABLE_PREFIX . "blogs WHERE `id`='$blog_id'";
			$result = mysql_query($query, $bwb_link);
			$row_cnt = mysql_num_rows($result);
			if ($row_cnt > 0)
			{
				$query = "UPDATE " . BWB_TABLE_PREFIX . "blogs SET post='$sValue', revised='$today' WHERE blog_id='$blog_id'";
				$result = mysql_query($query, $bwb_link);
			}
			else
			{
				echo "ERROR: Did not find existing blog with ID $blog_id.  Inserting new blog.<br>";
				$query = "INSERT INTO " . BWB_TABLE_PREFIX . "blogs SET post='$sValue', page_name='$page_name', owner='$userid', revised='$today'";
				$result = mysql_query($query, $bwb_link);
			}
			$query = "SELECT page_content FROM " . BWB_TABLE_PREFIX . "page_data WHERE page_name='" . $page_name . "'";
			$result = mysql_query($query, $bwb_link);
			if (mysql_num_rows($result) < -1)
			{
				echo "ERROR: Can't find page content for page $pagename.<br/>";
				$page_content_append = "";
			}
			else
			{
				$row = mysql_fetch_array($result);
				$page_content_append = $row['page_content'];
			}
			if ($row_cnt > 0)
			{
				// Find existing post from page content, remove and replace with new.
				if (strpos($page_content_append, $post_locate_string) !== false)
				{
					$page_content_arr = explode($post_locate_string, $page_content_append);
					$page_content_w_blog = $page_content_arr[0] . $sValue . $page_content_arr[2]; 
				}
				else
					$page_content_w_blog = $sValue . $page_content_append;
			}
			else
				$page_content_w_blog = $sValue . $page_content_append;	// Prepend page with new post and publish.
			$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET page_content='$page_content_w_blog', revised='$today' WHERE page_name='$page_name'";	
		}
		else
		{
			$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data WHERE page_name='$page_name'";
			$result = mysql_query($query, $bwb_link);
			if (mysql_num_rows($result) > 0)
				$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data SET page_content='$sValue', revised='$today' WHERE page_name='$page_name'";
			else
				$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data SET page_name='$page_name', page_content='$sValue', revised='$today'";
		}
			
		$result = mysql_query($query, $bwb_link);
	}
	
	// If 'Update and Preview' clicked,  then pass data to save and preview page.
	if ($preview == "Preview")
	{
		$sValue=addslashes($sValue);
		$query = "TRUNCATE " . BWB_TABLE_PREFIX . "page_cache";
		$result = mysql_query($query, $bwb_link);
		$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_cache SET id = 1, tmp_page_data = '$sValue'";
		$result = mysql_query($query, $bwb_link);
		
		$preview_page_string = "preview_page.php?page_name=$page_name&special=$special&mode=$mode&blog_id=$blog_id";
			
		header("Location: $preview_page_string");
	}
	
?>
<html>
<head>
<title>Breeze Website Builder - Editing <?php echo $page_name; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="manager.css" type="text/css">
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon">

<script type="text/javascript" src="../ckeditor/ckeditor.js"></script>

<script language="javascript" type="text/javascript">
	function OpenHelpWindow()
	{
		window.open("http://breezewebsitebuilder.com/docs/cms/help.html#edit_page", "Help", "scrollbars=1,resizable=1,status=0,toolbar=0,menubar=0,location=0,height=700,width=800");
	}
</script>
</head>

<body>
<?php
	include_once("../ckeditor/ckeditor.php");
?>

<form action="edit_page.php" method="post" name="frmEditPage">
<?php
echo "<input type='hidden' name='page_name' value='$page_name' />\n";
echo "<input type='hidden' name='special' value='$special' />\n";
echo "<input type='hidden' name='blog_id' value='$blog_id' />\n";

	if (isset($optimize) || isset($reset))	// If resizing images, then don't want to loose any changes since last save.
		$page_content = $sValue;
	else
	{
		if ($mode == "blog")
		{
			$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "blogs_draft WHERE blog_id='$blog_id'";		
			$result = mysql_query($query, $bwb_link);
			if ($row = mysql_fetch_array($result))
				$page_content = $row["post"];
			else	// Some reason no draft exits.  Just use actual page data.
			{
				$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "blogs WHERE id='$blog_id'";
				$result = mysql_query($query, $bwb_link);
				$row = mysql_fetch_array($result);
				$page_content = $row["post"];
			}
		}
		else
		{
			$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "page_data_draft WHERE page_name='$page_name' AND `source`=$special";		
			$result = mysql_query($query, $bwb_link);
			if ($row = mysql_fetch_array($result))
				$page_content = $row["page_content"];
			else	// Some reason no draft exits.  Just use actual page data.
			{
				if ($special == 1)
					$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "page_data_special WHERE page_name='$page_name'";
				else
					$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "page_data WHERE page_name='$page_name'";
				$result = mysql_query($query, $bwb_link);
				$row = mysql_fetch_array($result);
				$page_content = $row["page_content"];
			}
		}
	}
			
	// Before we go any farther, back this puppy up!
	$revised = $row["revised"];
	if ($mode == "blog")
		$query = "INSERT INTO " . BWB_TABLE_PREFIX . "blogs_bkup SET blog_id='$blog_id', page_name='$page_name', post='$page_content', `owner`='$userid', revised='$revised'";
	else
		$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_bkup SET page_name='$page_name', page_content='$page_content', revised='$revised', `source`=$special";
	$result = mysql_query($query, $bwb_link);
	// Pull extra slashes so that slahes codes don't start adding up.
	if ($clear != 1)
		$page_content = stripslashes($page_content);
	elseif ($clear == 1)
		$page_content = "";
	
	// Encapsulate page data with template table cell and div so that built-in styles will se seen in the editing environment as well.
	if ($special != 1)
		$prepend = "<div class='wrap' id='wrap'><table width='100%' height='100%'><tr><td valign='top' class='content_td' id='content_td'><div class='content_div' id='content_div'>";
	elseif (substr($page_name, 0, 3) == "top")
		$prepend = "<div class='wrap' id='wrap'><table width='100%' height='100%'><tr><td class='top_td' id='top_td'><div class='top_div' id='top_div'>";
	elseif (substr($page_name, 0, 6) == "bottom")
		$prepend = "<div class='wrap' id='wrap'><table width='100%' height='100%'><tr><td class='bottom_td' id='bottom_td'><div class='bottom_div' id='bottom_div'>";
	elseif (substr($page_name, 0, 4) == "left")
		$prepend = "<div class='wrap' id='wrap'><table width='100%' height='100%'><tr><td valign='top' class='left_td' id='left_td'><div class='left_div' id='left_div'>";
	elseif (substr($page_name, 0, 5) == "right")
		$prepend = "<div class='wrap' id='wrap'><table width='100%' height='100%'><tr><td valign='top' class='right_td' id='right_td'><div class='right_div' id='right_div'>";
	$postpend = "</div></td></tr></table></div>";
	$page_content = $prepend . $encap_delim . $page_content . $encap_delim . $postpend;	
?>

<div style="height:93%; width:100%;" id="editorContainer">
<?php
	$ckeditor = new CKEditor( );
	$ckeditor->basePath	= '../ckeditor/';
	$ckeditor->config['filebrowserBrowseUrl'] = '/kfm/index.php?startup_folder=' . BWB_WEBPAGE_DIR;
	$ckeditor->config['filebrowserImageBrowseUrl'] = '/kfm/index.php?startup_folder=' . BWB_IMAGE_DIR;
	$ckeditor->config['filebrowserFlashBrowseUrl'] = '/kfm/index.php?startup_folder=' . BWB_FLASH_DIR;
	$ckeditor->editor('CKeditor1', $page_content);

?>
</div>
	<script type="text/javascript" language="javascript">
    //<![CDATA[
		// If IE6 or IE7, can't apply CSS.
		if (!((navigator.appName == "Microsoft Internet Explorer") && ((navigator.appVersion.indexOf('MSIE 7') > 0) || (navigator.appVersion.indexOf('MSIE 6') > 0))))
		{
<?php 
	echo "\nCKEDITOR.config.contentsCss = [";
	$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "style_sheets";
	$result = mysql_query($query, $bwb_link);
	$delim ="";
	while ($row = mysql_fetch_array($result))
	{
		$style_sheet = $row["name"] . ".css";
		echo $delim . "'" . $userfiles . "/" . BWB_CSS_DIR . "/" . $style_sheet . "'";
		$delim = ",";
	}
	echo "];\n";
?>
		}
		CKEDITOR.config.stylesSet = 'eb_styles:/ckeditor/styles.js';
        var editorElem = document.getElementById("editorContainer");
        CKEDITOR.config.width = '100%';
		if (navigator.appName == "Microsoft Internet Explorer")
        	CKEDITOR.config.height = document.body.clientHeight - 200;
		else if (navigator.appName == "Opera")
			CKEDITOR.config.height = window.innerHeight - 210;
		else
			CKEDITOR.config.height = editorElem.clientHeight - 135;
        CKEDITOR.config.resize_enabled = false;
    //]]>
    </script>
            
      <br/>
	  <table width="90%" align="center"><tr>
	  <td align="left" class="small_message" width="9%">
      Page Name:<br/><?php echo $page_name; ?>
	  </td>
      <td align="center">
      <input type="submit" value="Preview" name="preview" />
      <input type="hidden" name="mode" id="mode" value="<?php echo $mode; ?>" />
	  </td>
      <td align="center">
      <input type="submit" value="Save" name="save_draft" />
	  </td>
	  <td align="center">
      <input type="submit" value="Publish" name="publish" />
	  </td>
      <td align="center">
      <input type="submit" value="Revert" name="revert" />
	  </td>
      <td align="center">
      <input type="button" value="See Site" name="live_view" 
<?php
		echo "onClick=\"window.open('..";
		echo $userfiles . $website_folder . "/";
      	if ($special == 1)
	  		echo "index";
		else
			echo $page_name;
		echo ".php', '_blank');\"";
?>
      />
	  </td>
      <td align="center"><input type="button" name="Clear" value="Clear" onClick="window.location.href='edit_page.php?page_name=<?php echo $page_name; ?>&special=<?php echo $special; ?>&clear=1&mode=<?php echo $mode; ?>';" /></td>
	  <td align="center">
	  <input type="button" name="Back" value="Back to Main Menu" onClick="window.location.href='main.php?mode=<?php echo $mode; ?>';" />
	  </td>
	  <td width="8%">
      &nbsp;
      <input type="hidden" name="prepend" value="<?php echo $prepend; ?>" />
      <input type="hidden" name="postpend" value="<?php echo $postpend; ?>" />
	  </td>
      <td align="center">
      <input type="submit" name="optimize" value="Optimize Images" />
      </td>
      <td align="center">
      <input type="submit" name="reset" value="Reset Images" />
      </td>
      <td>
<?php if ($access_level != "restricted") { ?>
      <input type="button" name="edit_styles" value="Edit Styles" onClick="window.open('edit_css.php?style_sheet=site','_blank');" />
<?php } else echo "&nbsp;"; ?>
      </td>
      <td width="8%">&nbsp;</td>
      <td align="center">
      <div id="help_button_sm" onClick="OpenHelpWindow();">
	    &nbsp;
      </div>
	  </td>
	  </tr></table>
    </form>

</body>
</html>

<?php
	exit;
	
	function OptimizeImages($sValue, $userfiles, $image_folder)
	{
		$result = 0;
		$doc_root = getenv('DOCUMENT_ROOT');
		$orig_image_path = $doc_root . $userfiles . "/" . $image_folder . "/orig";
			
		if (!file_exists($orig_image_path))
			mkdir($orig_image_path, 0755);
		
		$bad_chars = array("\"", "px", "%");
		$last_img_tag_pos = 0;
		while ((strpos($sValue, "<img ", $last_img_tag_pos)) > 1)
		{
			$img_tag_pos = strpos($sValue, "<img ", $last_img_tag_pos);
			$last_img_tag_pos = $img_tag_pos + strlen("<img ");
			
			$src_att_pos = strpos($sValue, "src=", $img_tag_pos);
			$end_src_pos = strpos($sValue, "\"", $src_att_pos + strlen("src=") + 2);
			$start_src_pos = $src_att_pos + strlen("src=") + 1;
			$src = substr($sValue, $start_src_pos, $end_src_pos - $start_src_pos);
			$tmp = substr($src, strlen($src) - strlen("jpg"));	//jpg, jpeg
			if (($tmp != "jpg") && ($tmp != "peg") && ($tmp != "JPG") && ($tmp != "PEG") && ($tmp != "Jpg"))
				continue;			//jpeg not found, can't process
			
			$height_att_pos = strpos($sValue, "height", $img_tag_pos);
			$end_height_pos_1 = strpos($sValue, "\"", $height_att_pos + strlen("height") + 2);
			$end_height_pos_2 = strpos($sValue, ";", $height_att_pos + strlen("height") + 2);
			if (($end_height_pos_1 === false))
				$end_height_pos = $end_height_pos_2;
			elseif (($end_height_pos_2 === false))
				$end_height_pos = $end_height_pos_1;
			elseif ($end_height_pos_1 <  $end_height_pos_2)
					$end_height_pos = $end_height_pos_1;
			else
				$end_height_pos = $end_height_pos_2;
			
			$start_height_pos = $height_att_pos + strlen("height") + 1;
			$height = substr($sValue, $start_height_pos, $end_height_pos - $start_height_pos);
			$height = str_replace($bad_chars, "", $height);
			
			$width_att_pos = strpos($sValue, "width", $img_tag_pos);
			$end_width_pos_1 = strpos($sValue, "\"", $width_att_pos + strlen("width") + 2);
			$end_width_pos_2 = strpos($sValue, ";", $width_att_pos + strlen("width") + 2);
			if (($end_width_pos_1 === false))
				$end_width_pos = $end_width_pos_2;
			elseif (($end_width_pos_2 === false))
				$end_width_pos = $end_width_pos_1;
			elseif ($end_width_pos_1 <  $end_width_pos_2)
					$end_width_pos = $end_width_pos_1;
			else
				$end_width_pos = $end_width_pos_2;
				
			$start_width_pos = $width_att_pos + strlen("width") + 1;
			$width = substr($sValue, $start_width_pos, $end_width_pos - $start_width_pos);
			$width = str_replace($bad_chars, "", $width);
			
			$src = str_replace("%20", " ", $src);	// The %20 substitution for spaces break it.
			$image_path = $doc_root . $src;
			$image_file = substr($src, strrpos($src, "/") + 1);
			$orig_image_path_file = $orig_image_path . "/" . $image_file;
			
			list($width_orig, $height_orig) = getimagesize($image_path);
			
			if (!file_exists($orig_image_path_file))
			{
				if (!copy($image_path, $orig_image_path_file))
				{
					echo "Failed to backup original image $image_path.  Skipping resize.<br>\n";
					contitue;
				}
			}
			
			if (resize_image($image_path, $width, $height, $image_path, 1))
			{
				echo "Resized $image_file from $width_orig wide by $height_orig tall to $width wide by $height tall.<br>\n";
				$result++;
			}
			else
				echo "Failed to resize image $image_file.<br>\n";
		}
		return($result);
	}
	
	function ResetImages($sValue, $userfiles, $image_folder)
	{
		$doc_root = getenv('DOCUMENT_ROOT');
		$orig_image_path = $doc_root . $userfiles . "/" . $image_folder . "/orig";
		if (!file_exists($orig_image_path))
		{
			echo "Original images do not exist.  Most likely they were never optimized.  Click <a href='main.php>here</a> to return the the main menu.";
			return -1;
			exit;
		}
		
		$success = 0;
		$fail = 0;
		$last_img_tag_pos = 0;
		while ((strpos($sValue, "<img ", $last_img_tag_pos)) > 1)
		{
			$img_tag_pos = strpos($sValue, "<img ", $last_img_tag_pos);
			$last_img_tag_pos = $img_tag_pos + strlen("<img ");
			
			$src_att_pos = strpos($sValue, "src=", $img_tag_pos);
			$end_src_pos = strpos($sValue, "\"", $src_att_pos + strlen("src=") + 2);
			$start_src_pos = $src_att_pos + strlen("src=") + 1;
			$src = substr($sValue, $start_src_pos, $end_src_pos - $start_src_pos);
			$tmp = substr($src, strlen($src) - strlen("jpg"));	//jpg, jpeg
			if (($tmp != "jpg") && ($tmp != "peg") && ($tmp != "JPG") && ($tmp != "PEG") && ($tmp != "Jpg"))
				continue;			//jpeg not found, image was never optimized.
			
			$src = str_replace("%20", " ", $src);	// The %20 substitution for spaces break it.
			$image_path = $doc_root . $src;
			$image_file = substr($src, strrpos($src, "/") + 1);
			$orig_image_path_file = $orig_image_path . "/" . $image_file;
			
			if (file_exists($orig_image_path_file))
			{
				if (!copy($orig_image_path_file, $image_path))
				{
					echo "Failed to restore original image $orig_image_path_file.";
					$fail++;
				}
				else
					$success++;
			}
		}
		if (($fail == 0) && ($success > 0))
			echo "All of the images have been restored to their original resolution, but they will appear unchanged.  To enlarge the images, right click on them and select 'Image Properties'.  Then click on the 'Reset Size' button.<br>\n";
		elseif(($fail > 0) && ($success == 0))
			echo "WARNING: None of the images have been restored to their original resolution.<br>\n";
		elseif(($fail > 0) && ($success> 0))
			echo "Some of the images have been restored to their original resolution, but they will appear unchanged.  To enlarge the images, right click on them and select 'Image Properties'.  Then click on the 'Reset Size' button.<br>\n";
			
		return ($success);
	}
	
?>
