<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created: 6/15/2007
// Revised: 11/23/2008	ELL
// Added code to change page name within file.  (Without this, page re-naming was in affect not working.)
// Revised: 6/5/2009	ELL
// Added copy mode.
// Revised: 6/19/2009	ELL
// Added contigency for copying to existing file and prompt for overwrite.
// Also added options to copy content only and re-use destination template, or copy content to freshly created template.
// Revised: 8/25/2009	ELL
// Added blanking of plugin markers.
// Revised: 10/13/2009	ELL
// Added ability to handle multiple menu-items tables and removed reference to obsolute menu-item file generator.
// Revised: 8/30/2010	ELL
// Fixed bug with renaming menu items upon renaming pages.
// Revised: 11/11/2010	ELL
// Fixed bug with GetNewTemplateContentFromSiteOptions function not always having $link resource available by passing $link to function.
// Revised: 2/7/2012	ELL
// Added table prefix handling.  Added reference to user files folder constant.
// Revised: 5/10/2013``	ELL
// Added handling of footer and header replace strings in new layout templates.
// Revised: 2/2/2014	ELL
// Added protection from corrupting file when file is index.php.
// Revised: 6/16/2014	ELL
// Added tracking of plugin ID's associated with page data to facilitate content sensitive help for relevant plugins in page editor.
// Revised: 12/5/2014	ELL
// Fixed bug of having border areas not retaining custom assignments when not refreshing page lapout template and using border area
// with page name in it.
// Revised: 1/12/2015	ELL
// Added retention of custom head and border areas assignments for copy with template layout refresh.
// Revised:	2/2/2015	ELL
// Added handling of use_table_structure and use_table_structure_mobile flags for copyig pages: If basic copy, then copy from
// page, otherwise get from site options.
// Fixed bug of "Save As" not creating new file.
// Revised: 2/15/2015	ELL
// Added handling of page_onload bit.
// Revised: 4/20/2015	ELL
// Added updating of 'pagename_load' function call.
// Revised: 6/10/2015	ELL
// Fixed bug with refreshing page template file under condition of no plugins on page.
//

include ("check_session.php");
		
$page_name = $_REQUEST['page_name'];
$new_name = $_REQUEST['new_name'];
$copy_mode = $_REQUEST['copy_mode'];
$overwrite = $_REQUEST['overwrite'];
$overwrite_content_only = $_REQUEST['overwrite_content_only'];
$create_new_template = $_REQUEST['create_new_template'];

	if ($page_name == "")
	{
		echo COPY_RENAME_PAGE_FORGOT_TO_SELECT_PAGE_TO_RENAME_1_MSG . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php?mode=copy\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_FORGOT_TO_SELECT_PAGE_TO_RENAME_2_MSG;
		exit;
	}
	if ($new_name == "")
	{
		echo COPY_RENAME_PAGE_FORGOT_TO_ENTER_NEW_PAGE_NAME_1_MSG . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php?mode=copy\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_FORGOT_TO_ENTER_NEW_PAGE_NAME_2_MSG;
		exit;
	}
//Remove Unix incompatible characters.
//$new_name = ereg_replace("[[^[:space:]]", "_", $new_name);
//$new_name = ereg_replace("[^a-zA-Z0-9\(\)\s_.-]", "", $new_name);
$new_name = preg_replace("/(?:\s|&nbsp;)+/", "_", $new_name, -1);
$new_name = preg_replace("/[^A-Za-z0-9_.-]/", "", $new_name, -1);
	
	$page_name = addslashes($page_name);
	$document_root = $_SERVER['DOCUMENT_ROOT'];
	if ((BWB_BASE_DIR == '') && (BWB_WEBPAGE_DIR == ''))
	{
		$old_file_name = $document_root . "/" . $page_name . ".php";
		$new_file_name = $document_root . "/" . $new_name . ".php";
	}
	elseif (BWB_BASE_DIR == '')
	{
		$old_file_name = $document_root . "/" . BWB_WEBPAGE_DIR . "/" . $page_name . ".php";
		$new_file_name = $document_root . "/" . BWB_WEBPAGE_DIR . "/" . $new_name . ".php";
	}
	else
	{
		$old_file_name = $document_root . "/" . BWB_BASE_DIR . "/" . BWB_WEBPAGE_DIR . "/" . $page_name . ".php";
		$new_file_name = $document_root . "/" . BWB_BASE_DIR . "/" . BWB_WEBPAGE_DIR . "/" . $new_name . ".php";
	}
	
	//----------------------------------------------------------------------//
	if (($page_name == $new_name) && ($create_new_template != 1) && ($copy_mode == "copy"))
	{
		echo COPY_RENAME_PAGE_COPY_ONTO_SELF_1_MSG . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_COPY_ONTO_SELF_2_MSG;
		exit;
	}
	elseif (($page_name == $new_name) && ($create_new_template == 1) && ($copy_mode == "copy"))
	{	
		// Get new content based on selected site option for template.
		$contents = GetNewTemplateContentFromSiteOptions($new_name, $new_file_name, $page_name, $bwb_dbh);

		unlink($new_file_name);	// Delete 

		if (!($fh = fopen($new_file_name, 'x'))) {
			echo COPY_RENAME_PAGE_ERROR_OPENING_NEW_PAGE_ERR . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_TO_RETURN_TO_COPY_RENAME_CONSOLE . " \n" . $php_errormsg;
			exit;
		}
		if (!fwrite($fh, $contents)) {
			echo COPY_RENAME_PAGE_ERROR_UPDATING_PAGE_NAME_REFERENCES_ERR . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_TO_RETURN_TO_COPY_RENAME_CONSOLE . " \n" . $php_errormsg;
			exit;
		}
		if (!fclose($fh)) {
			echo COPY_RENAME_PAGE_ERROR_CLOSING_NEW_PAGE_AFETR_REFERENCE_UPDATE_ERR . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_TO_RETURN_TO_COPY_RENAME_CONSOLE . " \n" . $php_errormsg;
			exit;
		}
		@chmod($new_file_name, 0644);

		header("Location: copy_rename_page_select.php");
		exit;
	}
	//----------------------------------------------------------------------//
	
	if ($copy_mode == "rename")
	{
		//Check for existance of new page name first.
		$query = "SELECT * FROM `" . BWB_TABLE_PREFIX . "page_data` WHERE `page_name`='$new_name'";
		$result = $bwb_dbh->query($query);
		if ($result->rowCount() > 0) {
			echo COPY_RENAME_PAGE_RENAME_NEW_PAGE_ALREADY_EXISTS_1_ERR . " $new_name " . COPY_RENAME_PAGE_RENAME_NEW_PAGE_ALREADY_EXISTS_2_ERR . " $page_name " . TO_WORD . " $new_name.  " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_RENAME_NEW_PAGE_ALREADY_EXISTS_3_ERR;
			exit;
		}
		
		//Rename page in page_data table.
		$query = "UPDATE `" . BWB_TABLE_PREFIX . "page_data` SET `page_name`='$new_name' WHERE `page_name`='$page_name'";
		$cnt = $bwb_dbh->exec($query);

		// Clear any old junk in draft table.
		$query = "DELETE FROM `" . BWB_TABLE_PREFIX . "page_data_draft` WHERE `page_name`='$new_name'";
		$bwb_dbh->exec($query);
	}
	elseif ($copy_mode == "copy")
	{
		if (file_exists($new_file_name) && ($overwrite != 1) && ($overwrite_content_only != 1) && ($create_new_template != 1))
		{
?>
<!DOCTYPE html>
		<html>
        <head>
        <title>Breeze Website Builder</title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <link rel="stylesheet" href="theme/<?php echo $theme; ?>/manager.css" type="text/css">
        <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon">
        <script language="javascript" type="text/ecmascript">
		function OpenHelpWindow()
		{
			window.open("http://breezewebsitebuilder.com/docs/cms/help.html#copy_rename_page", "Help", "scrollbars=1,resizable=1,status=0,toolbar=0,menubar=0,location=0,height=700,width=800");
		}
		</script>
        </head>
        
        <body>
			<table border="0" cellspacing="0" cellpadding="0" align="center">
              <tr>
                <td class="bold" height="40"><?php echo $new_name; ?> <?php echo COPY_RENAME_PAGE_PAGE_ALREADY_EXISTS; ?></td>
                <td valign="top">
                  	<div id="help_button" class="help_button" onClick="OpenHelpWindow();">
                    &nbsp;
                    </div>
                </td>
              </tr>
              <tr>
                <td height="40">
                <div class='button_console' style="width:600px;" onClick="window.location='copy_rename_page.php?page_name=<?php echo $page_name; ?>&amp;new_name=<?php echo $new_name; ?>&amp;copy_mode=<?php echo $copy_mode; ?>&amp;overwrite=1';"><span class='button_console_text'><?php echo COPY_RENAME_PAGE_OVERWRITE_DESTINATION_BTN; ?></span></div>
                </td>
              </tr>
              <tr>
                <td height="40">
                <div class='button_console' style="width:600px;" onClick="window.location='copy_rename_page.php?page_name=<?php echo $page_name; ?>&amp;new_name=<?php echo $new_name; ?>&amp;copy_mode=<?php echo $copy_mode; ?>&amp;overwrite_content_only=1';"><span class='button_console_text'><?php echo COPY_RENAME_PAGE_OVERWRITE_DESTINATION_RETAIN_TEMPLATE_BTN; ?></span></div>
                </td>
              </tr>
              <tr>
                <td height="40">
                <div class='button_console' style="width:600px;" onClick="window.location='copy_rename_page.php?page_name=<?php echo $page_name; ?>&amp;new_name=<?php echo $new_name; ?>&amp;copy_mode=<?php echo $copy_mode; ?>&amp;create_new_template=1';"><span class='button_console_text'><?php echo COPY_RENAME_PAGE_OVERWRITE_DESTINATION_CREATE_NEW_TEMPLATE_BTN; ?></span></div>
                </td>
              </tr>
              <tr>
                <td height="40">
                <div class='button_console_cancel' style="width:600px;" onClick="window.location='copy_rename_page_select.php';"><span class='button_console_text_w_icon'><?php echo COPY_RENAME_PAGE_CANCEL_COPY_BTN; ?></span></div>
                </td>
              </tr>
            </table>

        </body>
		</html>
<?php
			exit;
		}
		else	// Copy to new file.
		{
			if (file_exists($new_file_name) && (($overwrite == 1) || ($create_new_template == 1)))
			{
				unlink($new_file_name);
			}

			//Copy page to new record.
			$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']));
			$revised = $row['revised'];
			$plugin_ids = $row['plugins'];
			$on_load = $row['on_load'];

			if ($create_new_template != 1)
			{
				$use_table_structure = $row['use_table_structure'];
				$use_table_structure_mobile = $row['use_table_structure_mobile'];
			}
			else
			{
				// Get default use of table structure from selected options.
				$query = "SELECT `option_value` FROM `" . BWB_TABLE_PREFIX . "options_selected` WHERE `option_name`='UseTableStructure'";
				$result = $bwb_dbh->query($query);
				$row = $result->fetch(PDO::FETCH_ASSOC);
				$use_table_structure = $row["option_value"];
				$query = "SELECT `option_value` FROM `" . BWB_TABLE_PREFIX . "options_selected` WHERE `option_name`='UseTableStructureMobile'";
				$result = $bwb_dbh->query($query);
				$row = $result->fetch(PDO::FETCH_ASSOC);
				$use_table_structure_mobile = $row["option_value"];
			}
			
			$query = "SELECT * FROM `" . BWB_TABLE_PREFIX . "page_data` WHERE `page_name`='$new_name'";
			$result = $bwb_dbh->query($query);
			if ($result->rowCount() > 0)
				$query = "UPDATE `" . BWB_TABLE_PREFIX . "page_data` SET `page_content`='$page_content', `revised`='$revised', `plugins`='$plugin_ids', `use_table_structure`=$use_table_structure, `use_table_structure_mobile`=$use_table_structure_mobile, `body_onload`='$on_load' WHERE `page_name`='$new_name'";
			else
				$query = "INSERT INTO `" . BWB_TABLE_PREFIX . "page_data` SET `page_name`='$new_name', `page_content`='$page_content', `revised`='$revised', `plugins`='$plugin_ids', `use_table_structure`=$use_table_structure, `use_table_structure_mobile`=$use_table_structure_mobile, `body_onload`='$on_load'";
			$cnt = $bwb_dbh->exec($query);
			
			// Clear any old junk in draft table.
			$query = "DELETE FROM `" . BWB_TABLE_PREFIX . "page_data_draft` WHERE `page_name`='$new_name'";
			$bwb_dbh->exec($query);
		}
	}
	else
	{
		echo COPY_RENAME_PAGE_UNKNOWN_ERROR_ERR;
		exit;
	}
	
	//Check for existance of file.
	if (!file_exists($old_file_name)) {
		echo "$old_file_name " . COPY_RENAME_PAGE_RENAME_OLD_PAGE_NOT_FOUND_ERR . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_TO_RETURN_TO_COPY_RENAME_CONSOLE . " \n" . $php_errormsg;
		exit;
	}
	
	if ($copy_mode == "rename")
	{
		//Rename page file name.
		if (!rename($old_file_name , $new_file_name)) {
			echo COPY_RENAME_PAGE_ERROR_RENAMING_PAGE_ERR . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_TO_RETURN_TO_COPY_RENAME_CONSOLE . " \n" . $php_errormsg;
			exit;
		}
		////////////////////////////////////////////////////////////
		// Read in file and change any references to page name to new name and re-save.
		if (!($fh = fopen($new_file_name, 'r'))) {
			echo COPY_RENAME_PAGE_ERROR_OPENING_NEW_PAGE_ERR . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_TO_RETURN_TO_COPY_RENAME_CONSOLE . " \n" . $php_errormsg;
			exit;
		}
		$contents = (fread($fh, filesize($new_file_name)));
		$search = array("page_name = '" . $page_name . "'", "page_name='" . $page_name . "'");
		$replace = "page_name = '" . $new_name . "'";
		$contents = str_replace($search, $replace, $contents);
		unset($search);
		$search = "onLoad='" . $page_name . "_load();'";
		$replace = "onLoad='" . $new_name . "_load();'";
		$contents = str_replace($search, $replace, $contents);
		if (!fclose($fh)) {
			echo COPY_RENAME_PAGE_ERROR_CLOSING_NEW_PAGE_AFETR_REFERENCE_UPDATE_ERR . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_TO_RETURN_TO_COPY_RENAME_CONSOLE . " \n" . $php_errormsg;
			exit;
		}
		if (!($fh = fopen($new_file_name, 'w'))) {
			echo COPY_RENAME_PAGE_ERROR_OPENING_NEW_PAGE_ERR . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_TO_RETURN_TO_COPY_RENAME_CONSOLE . " \n" . $php_errormsg;
			exit;
		}
		if (!fwrite($fh, $contents)) {
			echo COPY_RENAME_PAGE_ERROR_UPDATING_PAGE_NAME_REFERENCES_ERR . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_TO_RETURN_TO_COPY_RENAME_CONSOLE . " \n" . $php_errormsg;
			exit;
		}
		if (!fclose($fh)) {
			echo COPY_RENAME_PAGE_ERROR_CLOSING_NEW_PAGE_AFETR_REFERENCE_UPDATE_ERR . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_TO_RETURN_TO_COPY_RENAME_CONSOLE . " \n" . $php_errormsg;
			exit;
		}
		@chmod($new_file_name, 0644);
	}
	elseif ($overwrite_content_only != 1)	//Copy File
	{
		// Read in original file contents.
		if ($create_new_template != 1)
		{
			if (!($fh = fopen($old_file_name, 'r'))) {
				echo COPY_RENAME_PAGE_ERROR_OPENING_ORIGINAL_PAGE_ERR . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_TO_RETURN_TO_COPY_RENAME_CONSOLE . " \n" . $php_errormsg;
				exit;
			}
			// Copy template from source.
			$contents = (fread($fh, filesize($old_file_name)));
			fclose($fh);
			$search = array("page_name = '" . $page_name . "'", "page_name='" . $page_name . "'");
			$replace = "page_name = '" . $new_name . "'";
			$contents = str_replace($search, $replace, $contents);
			unset($search);
			$search = "onLoad='" . $page_name . "_load();'";
			$replace = "onLoad='" . $new_name . "_load();'";
			$contents = str_replace($search, $replace, $contents);
		}
		elseif ($create_new_template == 1)
			// Get new content based on selected site option for template.
			$contents = GetNewTemplateContentFromSiteOptions($new_name, $new_file_name, $page_name, $bwb_dbh);
		
		// Create new file.
		if (!($fh = fopen($new_file_name, 'x'))) {
			echo COPY_RENAME_PAGE_ERROR_OPENING_NEW_PAGE_ERR . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_TO_RETURN_TO_COPY_RENAME_CONSOLE . " \n" . $php_errormsg;
			exit;
		}
		if (!fwrite($fh, $contents)) {
			echo COPY_RENAME_PAGE_ERROR_WRITING_TO_NEW_PAGE_ERR . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_TO_RETURN_TO_COPY_RENAME_CONSOLE . " \n" . $php_errormsg;
			exit;
		}
		if (!fclose($fh)) {
			echo COPY_RENAME_PAGE_ERROR_CLOSING_NEW_PAGE_ERR . " " . CLICK_WORD . " <a href=\"copy_rename_page_select.php\" title=\"" . HERE_WORD . "\">" . HERE_WORD . "</a> " . COPY_RENAME_PAGE_TO_RETURN_TO_COPY_RENAME_CONSOLE . " \n" . $php_errormsg;
			exit;
		}
		@chmod($new_file_name, 0644);
	}
		
	
	if ($copy_mode == "rename")
	{
		////////////////////////////////////////////////////////////
		// Update menu items in menu_items table.
		$old_name = $page_name . ".php";
		$new_name = $new_name . ".php";
		
		$query2 = "SELECT * FROM " . BWB_TABLE_PREFIX . "menus";
		$result2 = $bwb_dbh->query($query2);
		while ($row2 = $result2->fetch(PDO::FETCH_ASSOC))
		{
			$menu = $row2['menu_name'];
			$menu_type = $row2['menu_type'];
			$tmp = str_replace("_mobile", "", $menu);
			$suffix = substr($tmp, 4);
			$query = "UPDATE `" . BWB_TABLE_PREFIX . "menu" . $suffix . "_items` SET `URL`='" . $new_name . "' WHERE `URL`='" . $old_name . "'";
			$cnt = $bwb_dbh->exec($query);
			
			////////////////////////////////////////////////////////////
			// Re-write menu_items.js with new references.
			if ($menu_type == 1)
				include("save_menu_items_file.php");
		}
	}
	
	///////////////////////////////////////////////////////////
	header("Location: copy_rename_page_select.php");
	exit;
	
	///////////////////////////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////////////
	function GetNewTemplateContentFromSiteOptions($pagename, $file_name, $old_page_name, $bwb_dbh)
	{
		/////////////////////////////////////////
		// Read file.
		$fh = fopen($file_name, 'r') or die(COPY_RENAME_PAGE_CANT_READ_ERR . $file_name . ": " . $php_errormsg);
		$contents = fread($fh, filesize($file_name));
		fclose($fh) or die($php_errormsg);
	
		$search_str_head = "head_name='head";
		$search_str_right = "page_name='right";
		$search_str_left = "page_name='left";
		$search_str_top = "page_name='top";
		$search_str_bottom = "page_name='bottom";
		$search_str_header = "page_name='header";
		$search_str_footer = "page_name='footer";
		
		$start_pos = strpos($contents, $search_str_head, 1);
		$end_pos = strpos($contents, "\"", $start_pos) - 1;
		$start_pos = $start_pos + strlen("head_name='");
		$head_str = substr($contents, $start_pos, $end_pos - $start_pos);
	
		$start_pos = strpos($contents, $search_str_right, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, "\"", $start_pos) - 1;
			$start_pos = $start_pos + strlen("page_name='");
			$right_str = substr($contents, $start_pos, $end_pos - $start_pos);
		}
		else
			$right_str = "right";
		
		$start_pos = strpos($contents, $search_str_left, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, "\"", $start_pos) - 1;
			$start_pos = $start_pos + strlen("page_name='");
			$left_str = substr($contents, $start_pos, $end_pos - $start_pos);
		}
		else
			$left_str = "left";
		
		$start_pos = strpos($contents, $search_str_top, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, "\"", $start_pos) - 1;
			$start_pos = $start_pos + strlen("page_name='");
			$top_str = substr($contents, $start_pos, $end_pos - $start_pos);
		}
		else
			$top_str = "top";
		
		$start_pos = strpos($contents, $search_str_bottom, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, "\"", $start_pos) - 1;
			$start_pos = $start_pos + strlen("page_name='");
			$bottom_str = substr($contents, $start_pos, $end_pos - $start_pos);
		}
		else
			$bottom_str = "bottom";
			
		$start_pos = strpos($contents, $search_str_header, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, "\"", $start_pos) - 1;
			$start_pos = $start_pos + strlen("page_name='");
			$header_str = substr($contents, $start_pos, $end_pos - $start_pos);
		}
		else
			$header_str = "header";
			
		$start_pos = strpos($contents, $search_str_footer, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, "\"", $start_pos) - 1;
			$start_pos = $start_pos + strlen("page_name='");
			$footer_str = substr($contents, $start_pos, $end_pos - $start_pos);
		}
		else
			$footer_str = "footer";
		////////////////////////////////////
		
		//Get selected template from options_selected table.
		$query = "SELECT `option_value` FROM `" . BWB_TABLE_PREFIX . "options_selected` WHERE `option_name` = 'Template'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$template_name = $row["option_value"];
	
		//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.
		$contents = str_replace("xxx", $pagename, $page_template);
		
		//Transfer original head and border area assignment to new page template.
		$search_str_right_menu = "border_area = \"right";
		$search_str_left_menu = "border_area = \"left";
		$search_str_top_menu = "border_area = \"top";
		$search_str_bottom_menu = "border_area = \"bottom";
		$search_str_header_menu = "border_area = \"header";
		$search_str_footer_menu = "border_area = \"footer";
		
		$new_contents = $contents;
	
		$start_pos = strpos($contents, $search_str_head, 1);
		$end_pos = strpos($contents, "\"", $start_pos);
		$search_str = substr($contents, $start_pos, $end_pos - $start_pos);
		$replace_str = "head_name='" . $head_str . "'";
		$new_contents = str_replace($search_str, $replace_str, $contents);
		
		$start_pos = strpos($contents, $search_str_right, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, "\"", $start_pos);
			$search_str = substr($contents, $start_pos, $end_pos - $start_pos);
			$replace_str = "page_name='" . $right_str . "'";
			$new_contents = str_replace($search_str, $replace_str, $new_contents);
		}
		
		$start_pos = strpos($contents, $search_str_left, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, "\"", $start_pos);
			$search_str = substr($contents, $start_pos, $end_pos - $start_pos);
			$replace_str = "page_name='" . $left_str . "'";
			$new_contents = str_replace($search_str, $replace_str, $new_contents);
		}
		
		$start_pos = strpos($contents, $search_str_top, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, "\"", $start_pos);
			$search_str = substr($contents, $start_pos, $end_pos - $start_pos);
			$replace_str = "page_name='" . $top_str . "'";
			$new_contents = str_replace($search_str, $replace_str, $new_contents);
		}
		
		$start_pos = strpos($contents, $search_str_bottom, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, "\"", $start_pos);
			$search_str = substr($contents, $start_pos, $end_pos - $start_pos);
			$replace_str = "page_name='" . $bottom_str . "'";
			$new_contents = str_replace($search_str, $replace_str, $new_contents);
		}
		
		$start_pos = strpos($contents, $search_str_header, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, "\"", $start_pos);
			$search_str = substr($contents, $start_pos, $end_pos - $start_pos);
			$replace_str = "page_name='" . $header_str . "'";
			$new_contents = str_replace($search_str, $replace_str, $new_contents);
		}
		
		$start_pos = strpos($contents, $search_str_footer, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, "\"", $start_pos);
			$search_str = substr($contents, $start_pos, $end_pos - $start_pos);
			$replace_str = "page_name='" . $footer_str . "'";
			$new_contents = str_replace($search_str, $replace_str, $new_contents);
		}
		/////////////////////////////////////
	
		$start_pos = strpos($contents, $search_str_right_menu, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, ";", $start_pos);
			$search_str = substr($contents, $start_pos, $end_pos - $start_pos);
			$replace_str = "border_area = \"" . $right_str . "\"";
			$new_contents = str_replace($search_str, $replace_str, $new_contents);
		}
		
		$start_pos = strpos($contents, $search_str_left_menu, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, ";", $start_pos);
			$search_str = substr($contents, $start_pos, $end_pos - $start_pos);
			$replace_str = "border_area = \"" . $left_str . "\"";
			$new_contents = str_replace($search_str, $replace_str, $new_contents);
		}
		
		$start_pos = strpos($contents, $search_str_top_menu, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, ";", $start_pos);
			$search_str = substr($contents, $start_pos, $end_pos - $start_pos);
			$replace_str = "border_area = \"" . $top_str . "\"";
			$new_contents = str_replace($search_str, $replace_str, $new_contents);
		}
		
		$start_pos = strpos($contents, $search_str_bottom_menu, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, ";", $start_pos);
			$search_str = substr($contents, $start_pos, $end_pos - $start_pos);
			$replace_str = "border_area = \"" . $bottom_str . "\"";
			$new_contents = str_replace($search_str, $replace_str, $new_contents);
		}
		
		$start_pos = strpos($contents, $search_str_header_menu, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, ";", $start_pos);
			$search_str = substr($contents, $start_pos, $end_pos - $start_pos);
			$replace_str = "border_area = \"" . $header_str . "\"";
			$new_contents = str_replace($search_str, $replace_str, $new_contents);
		}
		
		$start_pos = strpos($contents, $search_str_footer_menu, 1);
		if ($start_pos !== false)
		{
			$end_pos = strpos($contents, ";", $start_pos);
			$search_str = substr($contents, $start_pos, $end_pos - $start_pos);
			$replace_str = "border_area = \"" . $footer_str . "\"";
			$new_contents = str_replace($search_str, $replace_str, $new_contents);
		}

		//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", $pagename, $meta_tags_template);
		
		//Insert meta-tags template into page template.
		$new_contents = str_replace("zzz", $meta_tags_template, $new_contents);

		////////////////////////////////////////////////////////////
		// Get plugin code and add it to page file.
		$query = "SELECT `plugins` FROM `" . BWB_TABLE_PREFIX . "page_data` WHERE `page_name`='$old_page_name'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$plugins = array();
		$plugins = explode(",", $row['plugins']);

		if (count($plugins) > 0)
		{
			foreach ($plugins as $plugin)
			{
				if ($plugin != "")
				{
					$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"];
					$header_code = $row["header_code"];
					$top_code = $row["top_code"];
					$left_code = $row["left_code"];
					$content_code = $row["content_code"];
					$right_code = $row["right_code"];
					$bottom_code = $row["bottom_code"];
					$footer_code = $row["footer_code"];
					
					//If plugin is selected, then insert head code snippet after <!--head_code--> comment.
					if ($head_code != "")
					{
						$page_temp_arr = explode("<!--head_code-->", $new_contents, 2);
						$new_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 ($content_code != "")
					{
						$page_temp_arr = explode("<!--content_code-->", $new_contents, 2);
						$new_contents = $page_temp_arr[0] . $content_code . "\n\n<!--content_code-->\n" . $page_temp_arr[1];
						unset($page_temp_arr);
					}
						
					//If plugin is selected, then insert header code snippet after <!--header_code--> comment. (not to be confused with head)
					if ($header_code != "")
					{
						$page_temp_arr = explode("<!--header_code-->", $new_contents, 2);
						$new_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 ($footer_code != "")
					{
						$page_temp_arr = explode("<!--footer_code-->", $new_contents, 2);
						$new_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 ($top_code != "")
					{
						if (strpos($page_template, "<!--top_code-->") > 0)
						{
							$page_temp_arr = explode("<!--top_code-->", $new_contents, 2);
							$new_contents = $page_temp_arr[0] . $top_code . "\n\n<!--top_code-->\n" . $page_temp_arr[1];
							unset($page_temp_arr);
						}
					}
					
					//If plugin is selected, then insert left code snippet after <!--left_code--> comment.
					if ($left_code != "")
					{
						if (strpos($page_template, "<!--left_code-->") > 0)
						{
							$page_temp_arr = explode("<!--left_code-->", $new_contents, 2);
							$new_contents = $page_temp_arr[0] . $left_code . "\n\n<!--left_code-->\n" . $page_temp_arr[1];
							unset($page_temp_arr);
						}
					}
					
					//If plugin is selected, then insert right code snippet after <!--right_code--> comment.
					if ($right_code != "")
					{
						if (strpos($page_template, "<!--right_code-->") > 0)
						{
							$page_temp_arr = explode("<!--right_code-->", $new_contents, 2);
							$new_contents = $page_temp_arr[0] . $right_code . "\n\n<!--right_code-->\n" . $page_temp_arr[1];
							unset($page_temp_arr);
						}
					}
					
					//If plugin is selected, then insert bottom code snippet after <!--bottom_code--> comment.
					if ($bottom_code != "")
					{
						if (strpos($page_template, "<!--bottom_code-->") > 0)
						{
							$page_temp_arr = explode("<!--bottom_code-->", $new_contents, 2);
							$new_contents = $page_temp_arr[0] . $bottom_code . "\n\n<!--bottom_code-->\n" . $page_temp_arr[1];
							unset($page_temp_arr);
						}
					}
				}
			}
		}

		return ($new_contents);
	}
?>
