<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created: 11/16/2014
// Modified: 9/14/2016	ELL
// Added ability to handle sub folders within folders.
// 
	
	include ("check_session.php");

	$file_name = $_POST['file_name'];
	$folder = $_POST["folder"];
	
	if (strpos($file_name, "/") === 0)
		$file_name = substr($file_name, 1);
	if (strpos($folder, "/") === 0)
		$folder = substr($folder, 1);

	$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'];	
	$path = $document_root . "/" . $folder . "/";

	// Save last revision to backup file.
	$source = $path . $file_name;
	$sub_path = "";
	if (strpos($file_name, "/") !== false)	{
		$file_name_arr = explode("/", $file_name);
		for ($i = 0; $i < count($file_name_arr) - 1; $i++)	{
			$sub_path .= $file_name_arr[$i] . "/";
		}
		$file_name = $file_name_arr[count($file_name_arr) - 1];
	}
	if (file_exists($source))	{	// Won't exist if save as.
		$dest = $path . $sub_path . "." . $file_name . time();
		copy($source, $dest);
	}
	
	// Whether saving draft of publishing, save latest revision to save file.
	$save_file_path = $path . $sub_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 . $sub_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 (strtolower(substr($file_name, strlen($file_name) - strlen(".js"))) == ".js")
		{
			$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "options_selected WHERE option_name = 'MinifyJSOnSave'";
			$result = $bwb_dbh->query($query);
			$row = $result->fetch(PDO::FETCH_ASSOC);
			$MinifyJSOnSave = $row['option_value'];
			if ($MinifyJSOnSave == 1)	{
				$_REQUEST['file_name'] = $file_name;
				$supress_msg = 1;
				include("minify_js.php");
			}
		}
	}
	
	if ($action == "publish")
		echo EDIT_FILE_FILE_PUBLISHED;
	else
		echo EDIT_FILE_FILE_SAVED;
	
?>
