<?php

/**
 * \file File_downloader.class.inc
 * \class File_downloader
 *
 * \author Anthony Borghi <anthony.borghi@veremes.com>.
 *
 * 	\brief This file contains the access file php class
 *
 * This class defines Rest Api to Access file
 *
 */
require_once 'Vitis.class.inc';
require_once ("aws_sdk/aws-autoloader.php");
require_once ("vmlib/phpUtil.inc");

class File_downloader extends Vitis {
    /**
     * @SWG\Definition(
     *   definition="/file_downloader",
     *   allOf={
     *     @SWG\Schema(ref="#/definitions/file_downloader")
     *   }
     * )
     * * @SWG\Tag(
     *   name="File_downloader",
     *   description="Download a file"
     * )
     */

    /**
     * construct
     * @param type $aPath url of the request
     * @param type $aValues parameters of the request
     * @param type $properties properties
     * @param type $bShortcut false to reinit variables
     * @param type $oConnection connection object
     */
    function __construct($aPath, $aValues, $properties, $bShortcut = false, $oConnection = false) {
      $this->aValues = $aValues;
      $this->aProperties = $properties;
    }

    /**
     * @SWG\Get(path="/file_downloader",
     *   tags={"File_downloader"},
     *   summary="Get File Content",
     *   description="Request to get File",
     *   operationId="GET",
     *   produces={"application/xml", "application/json", "application/x-vm-json"},
     *   @SWG\Parameter(
     *     name="token",
     *     in="query",
     *     description="group token",
     *     required=true,
     *     type="string"
     *   ),
     * @SWG\Parameter(
     *     name="key",
     *     in="query",
     *     description="File Path or s3 key",
     *     required=false,
     *     type="string"
     *   ),
     * @SWG\Parameter(
     *     name="eTag",
     *     in="query",
     *     description="Hash of content file",
     *     required=false,
     *     type="string"
     *   ),
     *   @SWG\Response(
     *         response=200,
     *         description="Blob of the file",
     *         @SWG\Schema(ref="#/definitions/file_downloader")
     *     )
     *  )
     */

    /**
     * get File
     * @return  $sMessage Json or blob
     */
    function GET() {
        $sMessage = array("status" => 0, "sMessage" => "");
        $bReturnFile = true;
        // si un paramètre est manquant on coupe
        if ((!empty($this->aValues["key"])) && (!empty($this->aValues["eTag"]))){
          $sPath = "";
          if ($this->aProperties["fileS3Uploader"]){
            $sPath = $this->aProperties['extract_dir'] . "/" . getUniqRandomId();
            // traitement du bucket et de ses sous-dossiers
            $sBucket = $this->aProperties['fileS3UploaderBucket'];
            $sPrefix = "";

            if (strpos($sBucket, "/") > -1){
                $aBucket = explode("/", $sBucket );
                $sBucket = $aBucket[0];
                $sPrefix = implode("/", array_slice($aBucket, 1));
            }
            // Création du client S3
            $s3 = new Aws\S3\S3Client(array(
                'version'=>'latest',
                'region'=> $this->aProperties['fileS3UploaderRegion'],
                'profile'=> $this->aProperties['fileS3UploaderProfil'],
                'debug' => false
            ));

            if(strpos($this->aValues['key'], $sPrefix) === 0){
              // récupération du fichier sur le serveur pour le téléchargement si le Etag correspond avec celui de s3
              try{
                $s3->getObject(array(
                  'Bucket' => $sBucket,
                  'Key' => $this->aValues['key'],
                  'IfMatch' => $this->aValues['eTag'],
                  'SaveAs' => $sPath
                ));
              }catch(Aws\S3\Exception\S3Exception $e){
                error_log($e->getMessage());
                $bReturnFile = false;
                $sMessage = array("status" => 0, "sMessage" => "This file doesn't exist or the Etag doesn't match");
              }
            } else {
              $bReturnFile = false;
              $sMessage = array("status" => 0, "sMessage" => "You can't access to this object");
            }

          } else {
            // modification de $sPath pour aller chercher le fichier dans ws_data
            $sPath = $this->aProperties["ws_data_dir"] . "/" . $this->aValues["key"];
            // check eTag
            $sEtag = sha1(file_get_contents($sPath), false);

            if ($sEtag != $this->aValues['eTag']){
              $bReturnFile = false;
              $sMessage = array("status" => 0, "sMessage" => "This file doesn't exist or the Etag doesn't match");
            }
          }

          if($bReturnFile){
            session_write_close();
            $this->getFile($sPath, end(explode("/", $this->aValues["key"])));
            if ($this->aProperties["fileS3Uploader"]){
              unlink($sPath);
            }
          }

        } else {
            $sMessage = array("status" => 0, "sMessage" => "Missing Parameter");
        }

        return json_encode($sMessage);
    }

    function getFile($sFilePath, $sFileName) {
      // Le fichier existe ?
      if (file_exists($sFilePath)) {
        $sContentType = mime_content_type($sFilePath);
        header("Content-Type: " . $sContentType);
        header("Content-disposition: attachment; filename=\"" . $sFileName . "\"");
        header('Content-Length: ' . filesize($sFilePath));
        if ($sContentType === "application/octet-stream") {
          header("Content-Transfer-Encoding: Binary");
        }
        readfile($sFilePath);
      }
    }


}

?>
