<?php
//vim: ts=2 sw=2

include_once "db.php";
include_once "base_controller.php";

class NoteController extends BaseController {

  protected function signinRequired() {
    return true;
  }
  protected function sanitizeData() {
  }

  protected function noteFilePath($notePath) {
    // process $notePath to prevent file access outside of 'CPT/user_data/notes' folder
    $notePath = str_replace("../", "", $notePath);

    return build_file_path(cptBaseDir(), 'user_data', 'notes', $notePath);
  }

  protected function doAjaxGet() {
    $response = array();
    $path = $this->sanitizeParam($_GET['path']);
    $full_path = $this->noteFilePath($path);
    if (!file_exists($full_path) || !startsWith(realpath($full_path), cptBaseDir())) 
      $this->renderAjaxError($response, sprintf(L("can not find note at %s"), $path));

    $content = file_get_contents($full_path)
    $response['content'] = addcslashes($content, "\"");
    $this->renderAjaxSuccess($response, false);
  }

  protected function doAjaxPost() {
    $response = array();
    $path = $this->sanitizeParam($_POST['path']);
    if (empty($path))
      $this->renderAjaxError($response, L("invalid note path"));

    $full_path = $this->noteFilePath($path);
    $content = $_POST['content'];
    file_force_contents($full_path, $content);
    $this->renderAjaxSuccess($response);
  }

}

$controller = new NoteController();
$controller->run();

?>