<?php
/**
 * Any service can be built, but certain rules must be followed:
 * Read in POST params 'markdown' and 'filename'
 * Convert 'filename' to lowercase
 * Filter out relative paths (../) from 'filename'
 * Only allow .md extensions to be written
 * Any sub-folders must be created before attempting to write the file
 * On success, return JSON success message 
 * 
 **/


$newMarkdown = $_POST['markdown'];
$wikifilepath = $_POST['filename'];

$filenameNoRelativePath = str_ireplace("../", "", strtolower($wikifilepath));
$file = basename($filenameNoRelativePath);
$fileBreakdown = explode(".", $file);
$extension = $fileBreakdown[count($fileBreakdown) - 1];

$path = dirname($filenameNoRelativePath);

if($extension == "md") {
	$markdownPath = dirname(__FILE__). "/../markdown";
	if (!is_dir($markdownPath . $path)) {
		mkdir($markdownPath . $path, 0755, true);
	}

	$absoluteFile = $markdownPath . $filenameNoRelativePath;

	//TODO: make a history file
		//mkdir folder with the filename
		//copy current file contents into unique hash filename
		//add unique hash to the manifest file

	file_put_contents($absoluteFile, $newMarkdown);

	$response = array("status" => "success", "message" => "Saved " . $filenameNoRelativePath);
} else {
	$response = array("status" => "error", "message" => "Invalid filename " . $filenameNoRelativePath);
}
header('Content-Type: application/json');
echo json_encode($response);
