<?php
  require_once('../../autoload.php');

  session_write_close();

  $docid = $_GET['docid'];

  $conn = get_dbconnection();

  if ( $conn )
  {
      $result = pg_prepare($conn, "query", "select folder||'/'||file, realfilename from document where id = $1");
      if ( $query = pg_execute($conn, "query", array($docid)) )
      {
        if ( $row = pg_fetch_row($query) )
        {
          $filepath = $GLOBALS ["document_storage"] . "/" . $row[0];

          error_log ( "filepath : " .$filepath );

          if ( file_exists($filepath) )
          {
              $fp = fopen("{$filepath}","r");
              if ( $fp )
              {
                $fs = filesize("{$filepath}");

                set_time_limit(0);
                header("Content-Disposition: attachment; filename={$row[1]}");
                header("Content-Type: application/octet-stream");
                header("Content-Length: {$fs}");
                header("Pragma: no-cache");
                header("Expires: 0");

		            ob_clean();

		            while (!feof($fp) && !(connection_aborted() || connection_status() == 1))
		            {
                  echo fread($fp, 8192);
                }

                fclose($fp);
              }
          }
          else
          {
            die ( "File $filepath doesn't exist !!!" );
          }
        }
      }
    }
  
    exit;
 ?>
