<?php

Goweb::loadClass('Goweb_Controller_Action_Admin');

/**
 * Goweb Sitemanager 4 Framework
 * @version    4.0.0
 * @category   Backoffice
 * @package    Filemanager
 * @author     I&D <dev@goweb.pt>
 * @copyright  2006 (c) Goweb (http://www.goweb.pt)
*/
class Filemanager_Controller extends Goweb_Controller_Action_Admin {

    /**
     * Titulo do Modulo
     * @var string
    */
    protected $_title;
    
    /**
     * Controller do Modulo
     * @var string
    */
    protected $_controller = 'cms';
    
    /**
     * Seccoes do Modulo
     * @var array
    */
    protected $_sections;

    /**
     * Seccao default do modulo
     * @var string
    */
    protected $_section = 'ficheiros';

    /**
     * Objecto Goweb_View
     * @var Goweb_View
    */
    protected $_view = null;
    
    /**
     * Caminho absoluto do upload
     * @var string
    */
    protected $_uploadPath = '';
    
    /**
     * Caminho relativo do upload
     * @var string
    */
    protected $_uploadRelativePath = '';
    
    /**
     * Caminho base do upload
     * @var string
    */
    protected $_uploadBasePath = '/uploads/cms';
    
    /**
     * Caminho dos thumbnails
     * @var string
    */
    protected $_thumbnailsPath = '';
    
    /**
     * Caminho
     * @var string
    */
    protected $_path = '';
    
    /**
     * Directorios
     * @var array
    */
    protected $_dirs = array();
    
    /**
     * Ficheiros
     * @var array
    */
    protected $_files = array();
    
    /**
     * Ficheiros ordenados
    */
    protected $_filesOrdered = array();
    
    /**
     * Objecto Goweb_Request
     * @var Goweb_Request
    */
    protected $_request = null;
    
    /**
     * Construtor da classe
    */
    public function __construct() {
        $this->_title = translateAdmin('CMS');
        $this->_sections = array('ficheiros' => translateAdmin('Imagens'));
        
        $this->_view = new Goweb_View(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->_request = Goweb::registry('request');
        $this->_uploadPath = PUBLIC_UPLOAD_PATH . DIRECTORY_SEPARATOR . 'cms';
        $this->_thumbnailsPath = DIRECTORY_SEPARATOR . '.thumbnails';
    }

    /**
     * Metodo chamado quando nenhuma action &eacute; fornecida
    */
    public function indexAction() {
        $this->browseAction();
    }
    
    /**
     * Este Metodo &eacute; executado quando a action fornecida n&atilde;o
     * &eacute; en&atilde;ontrada
    */
    public function __call($action, $arguments) {
        $this->browseAction();
    }
    
    /**
     * Este metodo valida e cria as pastas necessarias ao upload do ficheiro
    */
    public function browseAction() {
        $path = $this->_request->path;        
        $path = DIRECTORY_SEPARATOR . trim($path, '/');
        $this->_path = $path;

        $type = 'images';
        if($this->_getParam('section') == 'file'){
                $this->_uploadPath =  PUBLIC_UPLOAD_PATH . DIRECTORY_SEPARATOR . "user_id_" . Goweb::registry('session')->utilizador['perfil_id'];
                $this->_uploadBasePath =  "/uploads/user_id_" . Goweb::registry('session')->utilizador['perfil_id'];
                $this->_thumbnailsPath = "";
                $this->_request->files = "ficheiro";
                $type = 'file';
            }
            
        $this->_initBaseUploadPath($type);
        $this->_uploadPath .= DIRECTORY_SEPARATOR . $type;
        $this->_uploadRelativePath .= DIRECTORY_SEPARATOR . $type;

        if (is_dir($this->_uploadPath . $path)) {
            $this->_uploadPath .= ($path == '/') ? '' : $path;
            $this->_uploadRelativePath .= ($path == '/') ? '' : $path;
        } else {
            $this->_path = '/';
        }

        $this->_checkThumbnailsPath();

        // Criaecao de pasta
        
        Goweb::loadClass('Form_Pasta', dirname(__FILE__));
        $formPasta = new Form_Pasta('form_pasta', '/admin' . $_SERVER['REQUEST_URI']);        
        $formPasta->render();
        
        if ($this->_request->pasta != null && $this->_request->submit != null) {
            if ($formPasta->validate()) {
                if (file_exists($this->_uploadPath . '/' . $this->_request->pasta)) {
                    $formPasta->pasta->setErrorMessage(translateAdmin('J&aacute; existe uma pasta com o nome da <b>{{campo}}</b>.', $this->_request->pasta));
                } else {
                    mkdir($this->_uploadPath . '/' . $this->_request->pasta);
                    chmod($this->_uploadPath . '/' . $this->_request->pasta, 0777);
                }
            }
        }
        
        $this->_view->form_pasta = $formPasta;

        // ---
        
        $method = '_' . $type . 'Browse';
        $this->{$method}();        
    }
    
    /**
     * Remove ficheiro
    */
    public function deleteAction() {
        $path = $this->_request->path;        
        $path = DIRECTORY_SEPARATOR . trim($path, '/');
        $this->_path = $path;

        if ($this->_getParam('section') == 'image') {
            $type = 'images';
        }else{
            $type = 'file';
            $this->_uploadPath = PUBLIC_UPLOAD_PATH . DIRECTORY_SEPARATOR . "user_id_" . Goweb::registry('session')->utilizador['perfil_id'];
            $this->_uploadBasePath =  "/uploads/user_id_" . Goweb::registry('session')->utilizador['perfil_id'];
        }
        
        $this->_initBaseUploadPath($type);
        $this->_uploadPath .= DIRECTORY_SEPARATOR . $type;
        $this->_uploadRelativePath .= DIRECTORY_SEPARATOR . $type;

        if (is_dir($this->_uploadPath . $path)) {
            $this->_uploadPath .= ($path == '/') ? '' : $path;
            $this->_uploadRelativePath .= ($path == '/') ? '' : $path;
        } else {
            $this->_path = '/';
        }
                
        $this->_checkThumbnailsPath();
        
        if ($this->_request->file) {           
            $file = $this->_uploadPath . DIRECTORY_SEPARATOR . $this->_request->file;
            if ($type = 'images') {
                $thumbnail = $this->_uploadPath . $this->_thumbnailsPath . DIRECTORY_SEPARATOR .$this->_request->file;
                if (file_exists($file) && is_writable($file)) {
                    unlink($file);
                }
                
                if (file_exists($thumbnail) && is_writable($thumbnail)) {
                    unlink($thumbnail);
                }
            }
        }
        
        $this->_imagesBrowse();
    }
    
    /**
     * Retira caracteres invalidos de uma string
     *
     * @param string
     *
     * @return string
    */
    private function _clearString($str) {
        $strFromArray = str_split(html_entity_decode("&atilde;&Atilde;&aacute;&Aacute;&agrave;&Agrave;&eacute;&Eacute;&iacute;&Iacute;&otilde;&oacute;&ocirc;&otilde;&Oacute;&Ocirc;&uacute;&Uacute;&ccedil;&Ccedil;"));
        $strToArray = str_split("aAaAaAeEiIoooOOOuUcC");
        
        for ($i = 0; $i < (count($strFromArray) - 1); $i++) {
            $str = str_replace($strFromArray[$i], $strToArray[$i], $str);
        }
        
        $str = str_replace(" ", "_", $str);
        
        return $str;
        
    }
    
    /**
     * Visualiza imagem
    */
    private function _imagesBrowse() {
        Goweb::loadClass('Form_Imagem', dirname(__FILE__));
        $form = new Form_Imagem('form_imagem', '/admin' . $_SERVER['REQUEST_URI']);
        $form->render();

        if ($this->_request->files('ficheiro')) {
            if ($form->validate()) {
                if (is_writable($this->_uploadPath)) {
                    if (!file_exists($this->_uploadPath . $this->_thumbnailsPath)) {
                        try {
                            mkdir($this->_uploadPath . $this->_thumbnailsPath);
                            chmod($this->_uploadPath . $this->_thumbnailsPath, 0777);
                        } catch (Exception $e) {
                            throw new Goweb_Exception('N&atilde;o e poss&iacute;vel criar a directoria: "' . $this->_uploadPath . $this->_thumbnailsPath . '".');
                        }
                    }
                    $filename = date("YmdHis") . '_' . $this->_clearString($form->ficheiro->value['name']);
                    move_uploaded_file($form->ficheiro->value['tmp_name'], $this->_uploadPath . DIRECTORY_SEPARATOR . $filename);
                    chmod($this->_uploadPath . DIRECTORY_SEPARATOR . $filename, 0777);

                    // thumbnail
                    Goweb::loadClass('Goweb_Image_Resize');
                    $imageResize = new Goweb_Image_Resize();
                    $imageResize->resizeMaintainRatio($this->_uploadPath . DIRECTORY_SEPARATOR . $filename,
                                                      $this->_uploadPath . $this->_thumbnailsPath . DIRECTORY_SEPARATOR . $filename,
                                                      100, 100, 100);
                    chmod($this->_uploadPath . $this->_thumbnailsPath . DIRECTORY_SEPARATOR . $filename, 0777);
                } else {
                    throw new Goweb_Exception('N&atilde;o e poss&iacute;vel escrever na directoria: "' . $this->_uploadPath . '".');
                }
            }           
        }

        $this->_readDir($this->_uploadPath);
        $this->_view->dirs = $this->_dirs;
        // $this->_view->files = $this->_files; // alteracao tbrito 2007-06-22 16:28
        $this->_view->files = $this->_filesOrdered;
        $parentArr = explode('/', trim($this->_path, '/'));
        $parent = '/';
        if (count($parentArr) == 1) {
            if ($parentArr[0] == '') {
                $parent = '';
            } else {
                $parent = '/';
            }
        } else {
            for ($i=0; $i<count($parentArr) - 1; $i++) {
                $parent .= $parentArr[$i];
            }
        }
        
        Goweb::loadClass('Form_Pasta', dirname(__FILE__));
        $formPasta = new Form_Pasta('form_pasta', '/admin' . $_SERVER['REQUEST_URI']);        
        $formPasta->render();
        
        $this->_view->form_pasta = $formPasta;
        $this->_view->path = $this->_path;
        $this->_view->relative_path = $this->_uploadRelativePath;
        $this->_view->base_path = $this->_uploadBasePath;
        $this->_view->full_path = $this->_uploadPath;
        $this->_view->thumbnails_path = $this->_thumbnailsPath;
        $this->_view->parent = $parent;
        $this->_view->title = translateAdmin('Gest&atilde;o');
        $this->_view->action = translateAdmin('Imagens');        
        $this->_view->form = $form;
        $this->_view->output = $this->_view->render('images.tpl');
        $this->_helper->viewRenderer->setRender('base');
    }
    
    /**
     * Valida as permissoes de escrita
    */
    private function _initBaseUploadPath($dir) {
        $path = $this->_uploadPath . DIRECTORY_SEPARATOR . $dir;
        if (!is_dir($path)) {
            if (!is_dir($this->_uploadPath)) {
                try {
                    mkdir($this->_uploadPath);
                    chmod($this->_uploadPath, 0777);
                } catch (Goweb_Exception $e) {
                    throw new Goweb_Exception('A pasta "' . $this->_uploadPath . '" n&atilde;o tem permiss&otilde;es de escrita.');
                }
            }
            try {
                mkdir($path);
                chmod($path, 0777);
            } catch (Goweb_Exception $e) {
                throw new Goweb_Exception('A pasta "' . $path . '" n&atilde;o tem permiss&otilde;es de escrita.');
            }
        }
    }

    /**
     * Verifica as permissoes de escrita na pasta destinada aos Thumbnails
    */
    private function _checkThumbnailsPath() {
        if (!file_exists($this->_uploadPath . $this->_thumbnailsPath)) {
            try {
                mkdir($this->_uploadPath . $this->_thumbnailsPath);
                chmod($this->_uploadPath . $this->_thumbnailsPath, 0777);
            } catch (Goweb_Exception $e) {
                throw new Goweb_Exception('A pasta "' . $this->_uploadPath . $this->_thumbnailsPath . '" n&atilde;o tem permiss&otilde;es de escrita.');
            }
        }        
    }      
    
    /**
     * Verifica o tamanho de um directorio
     *
     * @param string
    */
    protected function _readDir($path) {
        if (is_dir($path)) {
            if ($handler = opendir($path)) {
                while (($file = readdir($handler)) !== false) {
                    if ($file != '.' && $file != '..') {
                        if (filetype($path . DIRECTORY_SEPARATOR . $file) == 'dir') {
                            $this->_dirs[] = $file;
                        } else {
                            $size = filesize($path . DIRECTORY_SEPARATOR . $file);
                            if ($size < 1024) {
                                $size .= ' bytes';
                            } elseif ($size < 1024 * 1024) {
                                $size = number_format(round($size / 1024, 0), 0, '.', '') . ' Kb';
                            } else {
                                $size = number_format($size / (1024 * 1024), 3, '.', '') . ' Mb';
                            }
                            $this->_files[] = array('name' => $file,
                                                    'size' => $size);
                        }
                    }
                }
                closedir($handler);
            }
        }
        
        if (count($this->_files) > 0) {
            foreach ($this->_files as $files) {
                $this->_filesOrdered[]['name'] = $files['name'];
            }
        }
        
        sort($this->_filesOrdered);
        rsort($this->_filesOrdered);
    }
    
}

?>