<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created: 11/16/2014
// 
	
	include ("check_session.php");

	$file_name = $_POST['file_name'];
	$folder = $_POST["folder"];
	$file_content = $_POST['file_content'];
	$action = $_REQUEST['action'];
	
	if (!isset($action))	// Something went foobar.  Don't do anything and bale out.
	{
		echo "Error: Action not defined.";
		exit;
	}
	
	$document_root = $_SERVER['DOCUMENT_ROOT'];
	if ($folder == "pages")
	{
		if ((BWB_BASE_DIR == '') && (BWB_WEBPAGE_DIR == ''))
			$path = $document_root . "/";
		elseif (BWB_BASE_DIR == '')
			$path = $document_root . "/" . BWB_WEBPAGE_DIR . "/";
		else
			$path = $document_root . "/" . BWB_BASE_DIR . "/" . BWB_WEBPAGE_DIR . "/";
	}
	elseif ($folder == "scripts")
	{
		if (BWB_BASE_DIR == '')
			$path = $document_root . "/" . BWB_SCRIPTS_DIR . "/";
		else
			$path = $document_root . "/" . BWB_BASE_DIR . "/" . BWB_SCRIPTS_DIR . "/";
	}
	elseif ($folder == "php")
		$path = $document_root . "/php/";
	else
	{
		echo "Error: no folder specified";
		exit;
	}
	
	// Save last revision to backup file.
	$source = $path . $file_name;
	$dest = $path . "." . $file_name . time();
	copy($source, $dest);
	
	// Whether saving draft of publishing, save latest revision to save file.
	$save_file_path = $path . "." . $file_name . "_save";
	$fh = fopen($save_file_path, 'w') or die("Can't create $save_file_path: $php_errormsg");
	$result = (fputs($fh, $file_content));
	fclose($fh) or die($php_errormsg);
	@chmod($save_file_path, 0644);
	
	if ($action == "publish")	// Publish latest changes.
	{
		$file_path = $path . $file_name;
		$fh = fopen($file_path, 'w') or die("Can't create $file_path: $php_errormsg");
		$result = (fputs($fh, $file_content));
		fclose($fh) or die($php_errormsg);
		@chmod($file_path, 0644);
	}
	
	if ($action == "publish")
		echo "File content has been published.";
	else
		echo "File content has been saved.";
	
?>
