<?php
require 'DropboxUploader.php';


function trimds($s) {
  return rtrim($s, DIRECTORY_SEPARATOR);
}

function joinpaths() {
  $trimmed = array_map('trimds',  func_get_args());
  return implode(DIRECTORY_SEPARATOR, $trimmed);
}

function upload($src, $filename, $directory, $email, $password) {
  $subdir = basename($directory);
  $dest = joinpaths("Server", "inbox", $subdir);

  try {
    if ($filename === "") {
      throw new Exception('File name not supplied by the browser.');
    }


    $uploader = new DropboxUploader($email, $password);
    $uploader->upload($src, $dest, $filename);
  } catch (Exception $e) {
    $stored_exc = $e; // workaround missing finally-block
  }

  if (isset($stored_exc)) {
    throw($stored_exc);
  }
};

if ($_POST) {
  try {
    if (isset($_POST['dest'])) {
      $dest = $_POST['dest'];
    } else {
      $dest = "";
    }
    $file = "../../dropbox-secret.ini";
    if (file_exists($file) && is_readable($file)) {
      $secret = parse_ini_file($file);
      $email = $secret["email"];
      $password = $secret["password"];
      upload($_POST['file_path'], $_POST['file_name'], $dest,
        $email, $password);
      echo 'File successfully uploaded to your Dropbox!';
    } else {
      echo("$file not readable");
    }
  } catch(Exception $e) {
    #http_response_code(404);
    echo 'Error: ' . htmlspecialchars($e->getMessage());
  }

  if (isset($file) && file_exists($file)) {
    unlink($file);
  }
}
?>
