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

set_include_path(get_include_path() . PATH_SEPARATOR . '../../app');

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

class CertFileManagerController extends BaseController {

  protected function signinRequired() {
    return true;
  }
  protected function adminRequired() {
    return true;
  }
  
  private function certDir() {
    $curPath = dirname(__FILE__);
    $uploadDir = $curPath . DIRECTORY_SEPARATOR . "uploads";
    if (!is_dir($uploadDir))
      mkdir($uploadDir, 0777, true);

    $certDir = $uploadDir . DIRECTORY_SEPARATOR . "certs";
    if (!is_dir($certDir))
      mkdir($certDir, 0700, true);

    return $certDir;
  }
  
  protected function doAjaxGet() {
    $response = array();
    //GOTCHA: php on FW does not support glob with GLOB_BRACE option
    // $pattern = $this->certDir() . DIRECTORY_SEPARATOR . "*.{png,jpg,jpeg,gif}";
    $pattern = $this->certDir() . DIRECTORY_SEPARATOR . "*";
    $rootPath = $_SERVER['DOCUMENT_ROOT'];
    foreach(glob($pattern) as $filename)
    {
      // if(endsWith($filename, ".png") || endsWith($filename, ".jpg") || endsWith($filename, ".jpeg") || endsWith($filename, ".gif"))
        $response[] = '{"path": "' . basename($filename) . '", "size": ' . filesize($filename) . '}';
    }
    die('{"response": {"files": [' . implode(",", $response) . ']}}');
  }
  
  protected function doAjaxPost() {
    if (isset($_POST['action']) && $_POST['action'] == "delete")
      $this->deleteFile();
    else
      $this->uploadFile();
  }
  
  protected function uploadFile() {
    if (empty($_FILES)) {
      http_response_code(400);
      exit(L('No file specified'));
    }
    
    $response = array();
    $tempFile = $_FILES['file']['tmp_name'];
    $fileName = $_FILES['file']['name'];
    $fileName = str_replace("../", "", $fileName);
    $targetFilePath = $this->certDir() . DIRECTORY_SEPARATOR . $fileName;

    //check free disk space
    $freeSpace = disk_free_space($this->certDir());
    if (filesize($tempFile)+500*1024 > $freeSpace) {
      http_response_code(400);
      exit(L('No disk space specified'));
    }

    move_uploaded_file($tempFile, $targetFilePath);
    $response['file_path'] = $targetFilePath;
    die('{"response": ' . map2json($response) . '}');
  }

  protected function deleteFile() {
    $response = array();
    $name = $_POST['name'];
    $certDir = $this->certDir();
    $targetFilePath = realpath($certDir . DIRECTORY_SEPARATOR . $name);
    if (!startsWith($targetFilePath, $certDir))
      $this->renderAjaxError($response, L('invalid file name'));
    
    unlink($targetFilePath)
    $this->renderAjaxSuccess($response);
  }
}

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

?>