<?php
/*
  Uploads model from url to GUI server and adds model name etc. to DB
*/

require "../Pages/UserAdmin/super_secret_stuff.php";
require "CommonFunc.php";
if(!empty($_GET["auth"]) && !empty($_GET["mname"]) &&  
   !empty($_GET["FNP"])){
  $con = mysqli_connect($website,$mysqli_username,$pw,$dbase);

  // Input error checks
  $auth = $_GET["auth"];
  $user_id = userid($con,$auth);
  if($user_id <= 0)goto errormsg1;

  $mname = $_GET["mname"];
  if($mname == "")$mname = "cannot use blank model name";

  // try and upload the file
  $url = $_GET["FNP"];
  $filename_only = basename($url);
  $filename_only = strtok($filename_only, '?'); // Get everything before ? in case of get variables associated with url (typical for dropbox)
  if (strpos($url, 'file.io') !== false)$filename_only .= ".tar.gz"; // Get filename extension for file.io cloud location
  
  // Add model
  $user_id_comma = "," . $user_id . ",";
  $res = mysqli_query($con,"SELECT COUNT(id) FROM Projects WHERE shared_between LIKE '%{$user_id_comma}%'");
  $row = mysqli_fetch_array($res);
  $next_proj = (int)$row[0];
  upload_file:
  $next_proj++;
  $target_file = $user_id . "_" . $next_proj . "_" . $filename_only;
  $target_dir = $proj_file_path_deep;
  $target_file_n_path = $target_dir . $target_file;
  $uploadOk = true;
  if(file_exists($target_file_n_path)){
    goto upload_file;
  }else{
    file_put_contents($target_file_n_path,file_get_contents($url));
  }
 
  $md5sum = -1;
  if(file_exists($target_file_n_path))$md5sum = md5_file($target_file_n_path);
  //Add to calibro_projects
  mysqli_query($con,"INSERT INTO Calibro_projects(name,meas_perf,MD5tarball,shared_between)
                     VALUES('{$mname}' , '{$target_file}' , '{$md5sum}' , ',{$user_id},')");
  mysqli_close($con);
}else{
  echo ("ERROR in AddModel.php: authentication code or project id or new model name or its file name and path not provided!");
}
exit;

errormsg1:
echo ("ERROR in AddModel.php: bad authentication code");goto theend;
errormsg2:
echo ("ERROR in AddModel.php: RESTful call bad project id");goto theend;
errormsg3:
echo ("ERROR in AddModel.php: you have too many simulations running try adding model later");goto theend;
theend:
mysqli_close($con);
exit;
?>
