<?php

Goweb::loadClass('Goweb_Db_Model');

/**
 * Goweb Sitemanager 5 Framework
 * @version    5.0.0
 * @category   Frontoffice
 * @package    Cms
 * @subpackage Model
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2009 (c) Goweb (http://www.goweb.pt)
*/
class Cms_Model_Pagina extends Goweb_Db_Model {
    
    /**
     * Nome da Tabela
     *
     * @var string
    */
    protected $_table = 'cms_pagina';
    
    /**
     * Chave Primaria
     * 
     * @var string
    */
    protected $_primary = 'id';
    
    /**
     * Campo que sera retornado se um
     * echo do objecto for chamado
     *
     * @var string
    */
    protected $_toString = 'titulo';
    
    
    /**
     * Metodo obrigatorio. Informa a definicao da tabela
     * referente ao Model em questao.
    */
    protected function _setup() {
        $this->initLang();
        $this->setSyncCols(array('slug', 'ordem', 'canal', 'homepage', 'privado'));
        $this->setUseSearchIndex();
        $this->setSearchCols(array('titulo', 'titulo_site', 'texto', 'keywords'));
        $this->_link = '/go/{{url}}';
        $this->pai_id         = $this->SelfKey(array('alias' => 'pagina_pai', 'label' => translate('P&aacute;gina Pai'), 'where' => 'sistema = 0', 'default' => '0'));
        $this->ordem          = $this->Integer(array('default' => 0, 'label' => translate('Ordem')));
        $this->titulo         = $this->Char(array('maxlength' => 200, 'notnull' => true, 'label' => translate('T&iacute;tulo Sec&ccedil;&atilde;o')));
        $this->titulo_site    = $this->Char(array('maxlength' => 200, 'label' => translate('T&iacute;tulo Site')));
        $this->slug           = $this->Char(array('maxlength' => 50, 'notnull' => true, 'on_update' => '_slugFromTitulo'));
        $this->redireccionar  = $this->Char(array('maxlength' => 200, 'label' => translate('Redireccionar')));
        $this->canal          = $this->Char(array('maxlength' => 50, 'options' => $this->_getChannelViews(), 'label' => translate('Canal'), 'default' => 'base.tpl'));
        $this->homepage       = $this->Boolean(array('default' => '0', 'label' => translate('Homepage'), 'help' => translate('Define esta p&aacute;gina como p&aacute;gina inicial')));
        $this->texto          = $this->Text(array('form' => 'Rte', 'label' => translate('Texto'), 'css' => '/media/css/cms.css'));
        $this->texto_stripped = $this->Text(array('coltype' => 'text', 'show' => false, 'label' => translate('Texto Stripped')));
        $this->menu           = $this->Boolean(array('default' => '1', 'label' => translate('Pertence a um menu')));
        $this->sem_url        = $this->Boolean(array('default' => '0', 'label' => translate('Sem Url Amig&aacute;vel')));
        $this->semlink        = $this->Boolean(array('default' => '0', 'label' => translate('Sem link')));
        $this->popup          = $this->Boolean(array('default' => '0', 'label' => translate('Abre em PopUp')));
        $this->privado        = $this->Boolean(array('default' => '0', 'label' => translate('Privado')));
        $this->keywords       = $this->Text(array('maxlength' => 500, 'label' => translate('Keywords'), 'rows' => 3, 'cols' => 50));
        $this->url            = $this->Url(array('label' => translate('Url Amig&aacute;vel'), 'on_update' => '_urlFromTitulo'));
        $this->activo         = $this->Boolean(array('default' => '1', 'label' => translate('Activo')));
        $this->sistema        = $this->Boolean(array('default' => '0', 'show' => false));
        $this->modulo         = $this->Char(array('show' => false));
        $this->timestamp      = $this->Integer(array('on_update' => time()));
        $this->actualizado    = $this->Datetime(array('on_update' => '_currentDatetime', 'label' => translate('Actualizado em')));
        $this->criado         = $this->Datetime(array('on_insert' => '_currentDatetime', 'label' => translate('Criado em')));
        $this->ip             = $this->IpAddress(array('on_update' => '_remoteAddress', 'label' => translate('Endere&ccedil;o IP')));
    }

    /**
     * Devolve o canal da view
     *
     * @return string
    */
    protected function _getChannelViews() {
        $channels = array();
        if (is_dir(VIEWS_PATH)) {            
            if ($handle = opendir(VIEWS_PATH)) {
                while (($file = readdir($handle)) !== false) {
                    if (is_file(VIEWS_PATH . DIRECTORY_SEPARATOR . $file)) {
                        $channels[$file] = $this->_formatViewName($file);
                    }
                }
                closedir($handle);
            }
        }
        return $channels;
    }

    /**
     * Formata o nome da view
     *
     * @param string
     *
     * @return string
    */
    protected function _formatViewName($unformatted) {
        $unformatted = substr($unformatted, 0, strlen($unformatted) - 4);
        $unformatted = str_replace(array('-', '_', '.'), ' ', strtolower($unformatted));
        $unformatted = preg_replace('[^a-z0-9 ]', '', $unformatted);
        return ucwords($unformatted);
    }

    protected function _urlFromTitulo() {
        if ($this->sem_url == 1) return '';
        if ($this->url == '') {
            $this->url = $this->_clearString($this->titulo);
            $this->url = $this->_getParents($this->id, $this->url);
        } else {
            $this->url = $this->_clearString($this->url);
        }
        $tmpModel = new Cms_Model_Pagina('db', false);
        $url = $this->url;
        $count = 0;
        if (file_exists(APPLICATION_PATH . '/Cms/Controller.php')){
            $methods = $this->_getClassActions(APPLICATION_PATH . '/Cms/Controller.php');
        }
        if (file_exists(APPLICATION_PATH . '/Cms/GenericController.php')){
            $methods =  array_merge($methods, $this->_getClassActions(APPLICATION_PATH . '/Cms/GenericController.php'));
        }
        
        //$methods = $this->_getClassActions(APPLICATION_PATH . '/Cms/Controller.php');
        $dispatcher = Zend_Controller_Front::getInstance()->getDispatcher();
        $actionName = $dispatcher->formatActionName($url);
        while (($tmpModel->findBy('url', $url) && $tmpModel->id != $this->id) || in_array($actionName, $methods)){
            $count++;
            if ($count == 1) $url .= '-';
            $url=$this->url . $count;
            $actionName = $dispatcher->formatActionName($url);
        }
        $this->url = $url;
        return $this->url;
    }
    
    protected function _getParents($pai_id = 0, $parents = ''){
        $categoriaModel = new Cms_Model_Pagina('db', false);
        
        if ($categoriaModel->find($pai_id)){
            while ($categoriaModel->find($categoriaModel->pai_id)){
                if ($categoriaModel->url && strpos($parents, $categoriaModel->url) === false){
                    if (strlen($parents) >0 && strlen($categoriaModel->url) > 0) $parents = "/" . $parents;
                    $parents = $categoriaModel->url . $parents;
                }
            }
        }
        return $parents;
    }
    
    /**
     * Gera uma string URL compativel
     *
     * @param   string  $string
     * @return  string  String formatada na forma URL compativel
     */
    protected function _slugFromTitulo() {
        if ($this->slug == '') {
            $alterList = array('/e/' => 'a',
                               '/e/' => 'a',
                               '/e/' => 'a',
                               '/e/' => 'e',
                               '/e/' => 'i',
                               '/e/' => 'o',
                               '/e/' => 'o',
                               '/e/' => 'u',
                               '/e/' => 'u',
                               '/e/' => 'c');
            
            $formatted = strtolower($this->titulo);
            $formatted = preg_replace(array_keys($alterList), array_values($alterList), $formatted);
            $formatted = trim($formatted); // limpa espacos antes e depois da string
            $formatted = preg_replace("/[^/\sa-z0-9]/", " ", $formatted);  // remove caracteres especiais
            $formatted = preg_replace('/\s+/', ' ', $formatted); // remove todos os espacos a mais
            $formatted = str_replace(' ', '-', $formatted); // substitui espacos por -
            return $formatted;
        }
        return $this->slug;
    }

    /**
     * Chama o metodo save da classe pai para salvar o texto
     */
    public function save() {
        $this->texto_stripped = strip_tags($this->texto);
        $this->texto_stripped = html_entity_decode($this->texto_stripped, ENT_COMPAT, CHARSET);
        return parent::save();
    }
}
