<?php

$webdoc["page_title"].=" - Connected files";

if ($webdoc["main_table"]=="test") $person_role = 4;
elseif ($webdoc["main_table"]=="test_run") $person_role = 5;
else $person_role = 2;
if (!auth($person_role)) 
{
  $webdoc["message"][]=database_get_message("no_permission");
  $template->template_assign("no_display",true);
  return;
}

if ($webdoc["main_table"]=="test")
{
  $webdoc["test_id"]=$_REQUEST["test_id"];
  $result=database_query("SELECT * FROM test WHERE test_id LIKE '$webdoc[test_id]'");
  $result_db=database_fetch_array($result);
  $webdoc["sequence_id"]=$result_db["sequence_id"];
}

if ($webdoc["main_table"]=="test_run")
{
  $webdoc["test_run_id"]=$_REQUEST["test_run_id"];
  $webdoc["sequence_id"]=$webdoc["test_run_id"];
}

if (isset($_POST["save_file"]))
{
  
  if ($_FILES["soubor"]["name"]<>"") 
  {      
      $soubor_name = $webdoc["auth"] . "_" . $_FILES["soubor"]["name"]; // priprava jmena souboru
      $result=database_query("SELECT * FROM file_list WHERE file_name LIKE '$soubor_name'"); // existuje takovy soubor v db?
      if (database_num_rows($result)==0)
      {
        if (!move_uploaded_file($_FILES["soubor"]["tmp_name"],"../files/$soubor_name")) // upload souboru s puvodnim nazvem
        {
          $webdoc["message"][]=database_get_message("no_upload");
          return false;
        }
      }
      else
      {
        $soubor_name = rand(0,999) . "_" . $soubor_name; // doplneni nazvu o vygenerovane cislo - predejiti prepsani
        if (!move_uploaded_file($_FILES["soubor"]["tmp_name"],"../files/$soubor_name"))
        {
          $webdoc["message"][]=database_get_message("no_upload");
          return false;
        }
      }
      if (!database_query("INSERT INTO file_list (table_id, record_id, creator_id, created, file_name) VALUES ('$webdoc[main_table]', '$webdoc[sequence_id]', '$webdoc[auth]', now(), '$soubor_name')")) // vlozeni zaznamu do db
      {
        $webdoc["message"][]=database_get_message("error_saving");
        return false;
      }      
  }
    
  else
  {
    $webdoc["message"]["form_error"][]=database_get_message("no_file");
  }
}

if (isset($_POST["delete_file"]))
{
  if (!database_query("UPDATE file_list SET remover_id='$webdoc[auth]', removed=now() WHERE file_list_id=$_POST[file_list_id]"))
  {
    $webdoc["message"][]=database_get_message("error_saving");
    return false;
  }
}

?>
