<?php

/**
 * \file Exploitations.class.inc
 * \class Exploitations
 *
 * \author Yoann Perollet <yoann.perollet@veremes.com>.
 *
 * 	\brief This file contains the Exploitations php class
 *
 * This class defines Rest Api to Vitis exploitations
 * 
 */
require_once 'Vitis.class.inc';
require_once __DIR__ . '/../../class/vitis_lib/Connection.class.inc';
require_once(__DIR__ . '/../../class/vmlib/BdDataAccess.inc');

class Exploitations extends Vitis {
    /**
     * @SWG\Definition(
     *   definition="/exploitations",
     *   allOf={
     *     @SWG\Schema(ref="#/definitions/exploitations")
     *   }
     * )
     * * @SWG\Tag(
     *   name="Exploitations",
     *   description="Operations about Exploitations"
     * )
     */

    /**
     * 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) {
        parent::__construct($aPath, $aValues, $properties, $bShortcut, $oConnection);
        $this->aSelectedFields = Array();
    }

    /**
     * @SWG\Get(path="/exploitations/SharedDirectory",
     *   tags={"Exploitations"},
     *   summary="Get shared directory tree",
     *   description="Request to get the shared directory tree",
     *   operationId="GET",
     *   produces={"application/json", "application/x-vm-json"},
     *   @SWG\Parameter(
     *     name="token",
     *     in="query",
     *     description="user token",
     *     required=true,
     *     type="string"
     *   ),
     *   @SWG\Response(
     *         response=200,
     *         description="Poprerties Response",
     *         @SWG\Schema(ref="#/definitions/exploitations")
     *     )
     *  )
     */

    /**
     * get Exploitations
     * @return  Exploitations
     */
    function GET() {
        // Arborescence du répertoire partagé.
        if (strtolower($this->aPath[2]) == 'shareddirectory') {
            $aTreeview = $this->getDirectoryTree($this->aProperties['shared_dir']);
            if (!empty($aTreeview["data"][0]["nodes"]))
                $this->aFields['tree']['data'] = $aTreeview["data"][0]["nodes"];
            else
                $this->aFields['tree']['data'] = [];
        }
        //
        $aXmlRacineAttribute['status'] = 1;
        $sMessage = $this->asDocument('', 'vitis', $this->aValues['sEncoding'], True, $aXmlRacineAttribute, $this->aValues['sSourceEncoding'], $this->aValues['output']);
        return $sMessage;
    }

    /**
     * Get directory tree.
     */
    function getDirectoryTree($sDirectoryPath) {
        $aReturn = array('status' => 1, 'message' => '');
        // Création de l'arborescence des fichiers du répertoire.
        if (!empty($sDirectoryPath)) {
            $sDirectoryName = 'Downloads';
            if (is_string($sDirectoryPath)) {
                if (is_dir($sDirectoryPath)) {
                    $aDirStructure = $this->getDirStructure($sDirectoryPath, $sDirectoryName, $sDirectoryName, "");
                    $aTreeview["data"][] = $aDirStructure["data"];
                    if (!empty($aDirStructure["files"])) {
                        foreach ($aDirStructure["files"] as $aFiles) {
                            $aTreeview["files"][] = $aFiles;
                        }
                    }
                } else
                    writeToErrorLog('scandir(' . $sDirectoryPath . '): failed to open dir');
            }
        }
        return $aTreeview;
    }

    /*
     * Retourne l'arborescence d'un répertoire formaté pour "bootstrap-treeview".
     */

    function getDirStructure($sDirectoryPath, $sSubDirectoryName, $sDirectoryName, $sFolder) {
        $aFilteredDir['data'] = array('text' => $sSubDirectoryName, 'selectable' => true, 'path' => $sFolder . '/' . $sSubDirectoryName);
        $aDir = scandir($sDirectoryPath);
        // Les répertoires sont affichés avant les fichiers (idem windows).
        $aSortedDir = array();
        $aSortedFiles = array();
        foreach ($aDir as $sName) {
            $sPath = $sDirectoryPath . '/' . $sName;
            $sFileType = filetype($sPath);
            if ($sFileType == 'dir')
                $aSortedDir[] = $sName;
            else
                $aSortedFiles[] = $sName;
        }
        sort($aSortedDir, SORT_STRING|SORT_FLAG_CASE);
        sort($aSortedFiles, SORT_STRING|SORT_FLAG_CASE);
        $aDir = array_merge($aSortedDir, $aSortedFiles);
        //
        if ($sSubDirectoryName !== $sDirectoryName)
            $sFolder .= '/' . $sSubDirectoryName;

        foreach ($aDir as $sName) {
            $sPath = $sDirectoryPath . '/' . $sName;
            $sFileType = filetype($sPath);
            // Répertoire ?
            if ($sFileType == 'dir') {
                if ($sName != '.' && $sName != '..') {
                    if (is_dir($sPath)) {
                        $aDirStructure = $this->getDirStructure($sPath . '/', $sName, $sDirectoryName, $sFolder);
                        //if (!empty($aDirStructure['data']['nodes'])) {
                            // Structure du répertoire.
                            $aFilteredDir['data']['nodes'][] = $aDirStructure['data'];
                            // Liste des fichiers du répertoire.
                            if (!empty($aDirStructure["files"])) {
                                foreach ($aDirStructure["files"] as $aFiles) {
                                    $aFilteredDir["files"][] = $aFiles;
                                }
                            }
                        //}
                    } else
                        writeToErrorLog('scandir(' . $sPath . '): failed to open dir');
                }
            }
            // fichier ?
            if ($sFileType == 'file') {
                // Taille + unité du fichier.
                //$iFileSize = filesize($sPath);
                $aFileInfos = stat($sPath);
                $iFileSizeLabel = $aFileInfos['size'];
                $aFileSizeUnity = array('o', 'Ko', 'Mo', 'Go', 'To');
                $i = 0;
                while ($iFileSizeLabel > 1024) {
                    $iFileSizeLabel /= 1024;
                    $i++;
                }
                // Sauve la structure du fichier pour le treeview.
                $sFileLabel = $sName . ' (' . round($iFileSizeLabel) . ' ' . $aFileSizeUnity[$i] . ')';
                $aFilteredDir['data']['nodes'][] = array(
                    'folder' => $sFolder,
                    'directory' => $sDirectoryName,
                    'name' => $sName,
                    'text' => $sFileLabel,
                    'icon' => 'glyphicon glyphicon-file',
                    'path' => str_replace('//', '/', $sFolder . '/' . '/' . $sName),
                    //'tags' => array('<span class="glyphicon glyphicon-trash"></span>'),
                    'size' => $aFileInfos['size'],
                    'selectable' => false
                );
                // Sauve le nom et la date du fichier.
                $aFilteredDir['files'][] = array(
                    'path' => str_replace('//', '/', $sFolder . '/' . '/' . $sName),
                    //'last_modif' => floor((time() - $aFileInfos['mtime']) / (24 * 3600))    // dernière modif. (Nb jours). 
                );
            }
        }
        return $aFilteredDir;
    }
    
    /**
     * @SWG\Post(path="/exploitations/SharedDirectory/Directory",
     *   tags={"Exploitations"},
     *   summary="Create directory",
     *   description="Request to create a directory",
     *   operationId="POST",
     *   produces={"application/xml", "application/json"},
     *   @SWG\Parameter(
     *     name="token",
     *     in="formData",
     *     description="user token",
     *     required=true,
     *     type="string"
     *   ),
     *  @SWG\Parameter(
     *     name="directory_path",
     *     in="formData",
     *     description="path of the directory",
     *     required=true,
     *     type="string"
     *   ),
     *   @SWG\Response(
     *         response=200,
     *         description="Poprerties Response",
     *         @SWG\Schema(ref="#/definitions/exploitations/SharedDirectory")
     *    )
     *  )
     */

    /**
     * @SWG\Post(path="/exploitations/SharedDirectory/File",
     *   tags={"Exploitations"},
     *   summary="Ulpload file",
     *   description="Request to upload a file",
     *   operationId="POST",
     *   produces={"application/xml", "application/json"},
     *   @SWG\Parameter(
     *     name="token",
     *     in="formData",
     *     description="user token",
     *     required=true,
     *     type="string"
     *   ),
     *  @SWG\Parameter(
     *     name="directory_path",
     *     in="formData",
     *     description="path of the directory",
     *     required=true,
     *     type="string"
     *   ),
     *   @SWG\Response(
     *         response=200,
     *         description="Poprerties Response",
     *         @SWG\Schema(ref="#/definitions/exploitations/SharedDirectory")
     *    )
     *  )
     */
    
    /**
     * insert user
     * @return id of the user created
     */
    function POST() {
        // Répertoire partagé.
        if (strtolower($this->aPath[2]) == 'shareddirectory') {
            // Création d'un répertoire.
            if (strtolower($this->aPath[3]) == 'directory') {
                if (!empty($this->aValues['directory_path'])) {
                    if (mkdir($this->aProperties['shared_dir'] . '/' . $this->aValues['directory_path'])) {
                        $aXmlRacineAttribute['status'] = 1;
                        $sMessage = $this->asDocument('', 'vitis', $this->aValues['sEncoding'], True, $aXmlRacineAttribute, $this->aValues['sSourceEncoding'], $this->aValues['output']);
                    }
                    else {
                        $oError = new VitisError(1, 'DIRECTORY_CREATION_ERROR_EXPLOITATION_EXPLOITATION');
                        $sMessage = $oError->asDocument('', 'vitis', $this->aValues['sEncoding'], True, $aXmlRacineAttribute, $this->aValues['sSourceEncoding'], $this->aValues['output']);
                    }
                }
            }
            // Upload d'un fichier.
            else if (strtolower($this->aPath[3]) == 'file') {
                if (!empty($_FILES["file"])) {
                    if (!empty($this->aValues['directory_path']))
                        $sFilePath = $this->aProperties['shared_dir'] . '/' . $this->aValues['directory_path'] . '/' . $_FILES["file"]["name"];
                    else
                        $sFilePath = $this->aProperties['shared_dir'] . '/' . $_FILES["file"]["name"];
                    if (!move_uploaded_file($_FILES['file']['tmp_name'], $sFilePath)) {
                        $oError = new VitisError(1, 'FILE_CREATION_ERROR_EXPLOITATION_EXPLOITATION');
                        $sMessage = $oError->asDocument('', 'vitis', $this->aValues['sEncoding'], True, $aXmlRacineAttribute, $this->aValues['sSourceEncoding'], $this->aValues['output']);
                    }
                    else {
                        $aXmlRacineAttribute['status'] = 1;
                        $sMessage = $this->asDocument('', 'vitis', $this->aValues['sEncoding'], True, $aXmlRacineAttribute, $this->aValues['sSourceEncoding'], $this->aValues['output']);
                    }
                }
            }
        }
        return $sMessage;
    }
    
    /**
     * @SWG\Delete(path="/exploitations/SharedDirectory",
     *   tags={"Exploitations"},
     *   summary="delete shared directory files",
     *   description="Request to delete shared directory files",
     *   operationId="DELETE",
     *   produces={"application/json", "application/x-vm-json"},
     *   @SWG\Parameter(
     *     name="token",
     *     in="query",
     *     description="user token",
     *     required=true,
     *     type="string"
     *   ),
     * * @SWG\Parameter(
     *     name="idList",
     *     in="query",
     *     description="path of the files",
     *     required=true,
     *     type="string"
     *   ),
     * @SWG\Response(
     *         response=200,
     *         description="Poprerties Response",
     *         @SWG\Schema(ref="#/definitions/exploitations/SharedDirectory")
     *     )
     *  )
     */

    /**
     * delete exploitation files
     */
    function DELETE() {
        // Verify connection.
        if (!empty($this->oConnection->oError)) {
            $oError = $this->oConnection->oError;
            $aXmlRacineAttribute['status'] = 0;
            $sMessage = $oError->asDocument('', 'vitis', $this->aValues['sEncoding'], True, $aXmlRacineAttribute, $this->aValues['sSourceEncoding'], $this->aValues['output']);
            return $sMessage;
        }
        // Privilège "vitis_admin" requis.
        if (!in_array('vitis_admin', $this->oConnection->aPrivileges)) {
            $oError = new VitisError(1, "Rights problem : you don't have right to delete shared directory files");
            $aXmlRacineAttribute['status'] = 0;
            $sMessage = $oError->asDocument('', 'vitis', $this->aValues['sEncoding'], True, $aXmlRacineAttribute, $this->aValues['sSourceEncoding'], $this->aValues['output']);
            return $sMessage;
        }
        // Suppression des fichiers.
        $aXmlRacineAttribute['status'] = 1;
        $sMessage = $this->asDocument('', 'vitis', $this->aValues['sEncoding'], True, $aXmlRacineAttribute, $this->aValues['sSourceEncoding'], $this->aValues['output']);
        if (!empty($this->aValues['idList'])) {
            $aPathsToDelete = explode('|', $this->aValues['idList']);
            $aDirToDelete = array();
            foreach ($aPathsToDelete as $sPath) {
                $sPath = str_replace('//', '/', $this->aProperties['shared_dir'] . $sPath);
                if (file_exists($sPath)) {
                    if (is_dir($sPath))
                        array_unshift($aDirToDelete, $sPath);
                    else
                        unlink($sPath);
                }
            }
        }
        // Suppression des répertoires.
        foreach ($aDirToDelete as $sPath) {
            rmdir($sPath);
        }
        //
        return $sMessage;
    }
}
?>