<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created:	11/16/2014	ELL
// Modified: 9/14/2016	ELL
// Modified to accomodate file name that are actually paths.
// Revised: 10/27/2016	ELL
// Modified to compare file dates of draft and published files and to not use draft if older than published.
// 

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);

$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];
}
$draft_file_name = "." . $file_name . "_save";

if (strpos($file_name, "untitled", 0) === 0)	{
	echo "";
	exit;
}

$document_root = $_SERVER['DOCUMENT_ROOT'];
$file_path_draft = $document_root . "/" . $folder . "/" . $sub_path . $draft_file_name;
$file_path = $document_root . "/" . $folder . "/" . $sub_path . $file_name;

if (file_exists($file_path_draft))	{
	if (filemtime($file_path_draft) < filemtime($file_path))
		$file_path_draft = $file_path;
}
elseif ((strtolower(substr($file_name, strlen($file_name) - strlen(".js"))) == ".js") && (substr($folder, strlen($folder) - strlen(BWB_SCRIPTS_DIR)) == BWB_SCRIPTS_DIR) && ($sub_path == "") && file_exists($document_root . "/" . $folder . "/src/" . $file_name))
{
	$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)
		$file_path_draft = $document_root . "/" . $folder . "/src/" . $file_name;
}
else
	$file_path_draft = $file_path;

if (!($fh = fopen($file_path_draft, 'r')))
{	
	if (!($fh = fopen($file_path, 'r'))) {
		echo "Error opening file.  Please contact your system administrator.\n$php_errormsg";
		exit;
	}
}
else
	$file_path = $file_path_draft;

$contents = (fread($fh, filesize($file_path)));
fclose($fh);

echo $contents;
?>