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

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 (isset($create_new_template))
	$create_new_template = 1;

	if ($page_name == "")
	{
		echo "Oops! You forgot to select a page to rename.  Click <a href=\"main.php?mode=copy\" title=\"here\">here</a> and select a page to rename.";
		exit;
	}
	if ($new_name == "")
	{
		echo "Oops! You forgot to enter a new page name.  Click <a href=\"main.php?mode=copy\" title=\"here\">here</a> and enter a new page name.";
		exit;
	}
//Remove Unix incompatible characters.
$new_name = ereg_replace("[[^[:space:]]", "_", $new_name);
$new_name = ereg_replace("[^a-zA-Z0-9\(\)\s_.-]", "", $new_name);
	
	$page_name = addslashes($page_name);
	$document_root = $_SERVER['DOCUMENT_ROOT'];
	if (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 "You cannot copy a page onto itself. (Unless you have selected to discard the old template and create a new one.)  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> and enter a new page name.";
		exit;
	}
	elseif (($page_name == $new_name) && ($create_new_template == 1) && ($copy_mode == "copy"))
	{
		unlink($new_file_name);	// Delete 
		
		// Get new content based on selected site option for template.
		$contents = GetNewTemplateContentFromSiteOptions($new_name, $bwb_dbh);

		if (!($fh = fopen($new_file_name, 'x'))) {
			echo "Error opening new page file.  Please contact your system administrator.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> to return to the copy/rename console.\n$php_errormsg";
			exit;
		}
		if (!fwrite($fh, $contents)) {
			echo "Error updating page name references in new page file.  Please contact your system administrator.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> to return to the copy/rename console.\n$php_errormsg";
			exit;
		}
		if (!fclose($fh)) {
			echo "Error closing page name references in new page file.  Please contact your system administrator.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> to return to the 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 "The page $new_name already exists.  You cannot rename $page_name to $new_name.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> and enter a different destination name.";
			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);
	}
	elseif ($copy_mode == "copy")
	{
		if (file_exists($new_file_name) && ($overwrite != 1) && ($overwrite_content_only != 1) && ($create_new_template != 1))
		{
?>
		<html>
        <head>
        <title>Breeze Website Builder</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 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; ?> already exists.  What do you want to do?</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'>Overwrite destination</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'>Overwrite destination content but retain destination template</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'>Overwrite destination with source content create new template per selected site options</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'>Cancel copy and return to the copy/rename console</span></div>
                </td>
              </tr>
            </table>

        </body>
		</html>
<?php
			exit;
		}
		else
		{
			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 = $row['page_content'];
			$revised = $row['revised'];
			
			$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' 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'";
			$cnt = $bwb_dbh->exec($query);
		}
	}
	else
	{
		echo "Some how we cannot determine if you want to copy or rename.  Please go back and select an operation from the list.";
		exit;
	}
	
	//Check for existance of file.
	if (!file_exists($old_file_name)) {
		echo "$old_file_name not found.  Please contact your system administrator.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> to return to the copy/rename console.\n$php_errormsg";
		exit;
	}
	
	if ($copy_mode == "rename")
	{
		//Rename page file name.
		if (!rename($old_file_name , $new_file_name)) {
			echo "Error renaming file.  Please contact your system administrator.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> to return to the 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 "Error opening new page file.  Please contact your system administrator.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> to return to the copy/rename console.\n$php_errormsg";
			exit;
		}
		$contents = (fread($fh, filesize($new_file_name)));
		$contents = str_replace("robots_index", "robots_iinnddeexx", $contents);	// Protection for renaming index page.
		$contents = str_replace($page_name, $new_name, $contents);
		$contents = str_replace("robots_iinnddeexx", "robots_index", $contents);	// Protection for renaming index page.
		if (!fclose($fh)) {
			echo "Error closing page name references in new page file.  Please contact your system administrator.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> to return to the copy/rename console.\n$php_errormsg";
			exit;
		}
		if (!($fh = fopen($new_file_name, 'w'))) {
			echo "Error opening new page file.  Please contact your system administrator.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> to return to the copy/rename console.\n$php_errormsg";
			exit;
		}
		if (!fwrite($fh, $contents)) {
			echo "Error updating page name references in new page file.  Please contact your system administrator.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> to return to the copy/rename console.\n$php_errormsg";
			exit;
		}
		if (!fclose($fh)) {
			echo "Error closing page name references in new page file.  Please contact your system administrator.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> to return to the 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 "Error opening original page file.  Please contact your system administrator.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> to return to the copy/rename console.\n$php_errormsg";
				exit;
			}
			// Copy template from source.
			$contents = (fread($fh, filesize($old_file_name)));
			fclose($fh);
			$contents = str_replace("robots_index", "robots_iinnddeexx", $contents);	// Protection for renaming index page.
			$contents = str_replace($page_name, $new_name, $contents);
			$contents = str_replace("robots_iinnddeexx", "robots_index", $contents);	// Protection for renaming index page.
		}
		elseif ($create_new_template == 1)
			// Get new content based on selected site option for template.
			$contents = GetNewTemplateContentFromSiteOptions($new_name, $bwb_dbh);
		
		// Create new file.
		if (!($fh = fopen($new_file_name, 'x'))) {
			echo "Error opening new page file.  Please contact your system administrator.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> to return to the copy/rename console.\n$php_errormsg";
			exit;
		}
		if (!fwrite($fh, $contents)) {
			echo "Error writing content to new page file.  Please contact your system administrator.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> to return to the copy/rename console.\n$php_errormsg";
			exit;
		}
		if (!fclose($fh)) {
			echo "Error closing new page file.  Please contact your system administrator.  Click <a href=\"copy_rename_page_select.php\" title=\"here\">here</a> to return to the 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_name = $row2['menu_name'];
			$menu_type = $row2['menu_type'];
			$suffix = substr($menu_name, 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, $bwb_dbh)
	{
		//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.
		$page_template = str_replace("xxx", $pagename, $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", $pagename, $meta_tags_template);
		
		//Insert meta-tags template into page template.
		$page_template = str_replace("zzz", $meta_tags_template, $page_template);
		
		return ($page_template);
	}
?>
