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

include_once "../app/db.php";
include_once "../app/base_controller.php";

class FileUploadController extends BaseController {

  protected function signinRequired() {
    return true;
  }
  
  private function uploadDir() {
    $curPath = dirname(__FILE__);
    $uploadDir = $curPath . DIRECTORY_SEPARATOR . "uploads";
    if (!is_dir($uploadDir))
      mkdir($uploadDir, 0777, true);
    return $uploadDir;
  }
  
  protected function doAjaxGet() {
    $response = array();
    //GOTCHA: php on FW does not support glob with GLOB_BRACE option
    // $pattern = $this->uploadDir() . DIRECTORY_SEPARATOR . "*.{png,jpg,jpeg,gif}";
    $pattern = $this->uploadDir() . 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[] = '{"url": "' . substr($filename, strlen($rootPath)). '", "size": ' . filesize($filename) . '}';
    }
    //TODO: get all images under uploads folder  
    die('{"response": {"images": [' . 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->uploadDir() . DIRECTORY_SEPARATOR . $fileName;

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

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

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

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

?>