<?php
if($_SERVER["HTTP_USER_AGENT"] == "Tasker Photo Upload") {
  $target_dir = "phone/new/";
  $target_file = $target_dir . basename($_GET["name"]);
  $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
  $uploadOk = 1;
  $tempfile = tempnam("/tmp","upld");
  
  if(isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] == 'application/octet-stream') {
    $out_fd = fopen("$tempfile", "w");
    $in_fd  = fopen("php://input", "r");
    while($data = fgets($in_fd)) {
      fputs($out_fd, $data);
    }
    echo "saved: " . filesize($tempfile) . "\n";
  } else {
    die("malformed request");
  }

  // Check if image file is a actual image or fake image
  if($imageFileType != "mp4") {
    $check = getimagesize($tempfile);
    if($check !== false) {
      echo "File is an image - " . $check["mime"] . ".";
      $uploadOk = 1;
    } else {
      echo "File is not an image.";
      $uploadOk = 0;
    }
  }
  // Check if file already exists
  if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
  }
  // Check file size
  if (filesize($tempfile) > 100000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
  }
  // Allow certain file formats
  if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "mp4" ) {
    echo "Sorry, only JPG, JPEG, PNG, GIF, and MP4 files are allowed.";
    $uploadOk = 0;
  }
  // Check if $uploadOk is set to 0 by an error
  if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
    unlink($tempfile);
  // if everything is ok, try to upload file
  } else {
    if (rename($tempfile, $target_file)) {
      echo "The file " . $_GET["name"] . " has been uploaded.";
    } else {
      echo "Sorry, there was an error uploading your file.";
    }
  }
}
?>
