<?php

Goweb::loadClass('Goweb_Controller_Action_Admin');

/**
 * Goweb Sitemanager 5 Framework
 * @version    5.0.19.2
 * @category   Backoffice
 * @package    Cms
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2010 (c) Goweb (http://www.goweb.pt)
 */
class Cms_GenericController 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;

    /**
     * Objecto Cms_Model_Pagina
     * @var Cms_Model_Pagina
     */
    protected $_paginaModel = null;

    /**
     * Parametros para a criacao da arvore
     *
     * @var array
     */
    protected $_paginasTreeParams = array('target'         => null,
                                          'folderLinks'    => true,
                                          'useSelection'   => true,
                                          'useCookies'     => true,
                                          'useLines'       => true,
                                          'useIcons'       => true,
                                          'useStatusText'  => false,
                                          'closeSameLevel' => false,
                                          'inOrder'        => false);

    /**
     * Parametros para a criacao dos n&oacute;s da arvore
     *
     * @var array
     */
    protected $_paginasNodesParams = array('rootName'   => 'Raiz',
                                           'id'         => 'id',
                                           'pid'        => 'pai_id',
                                           'name'       => 'titulo',
                                           'url'        => '/cms/edit/section/paginas/id/',
                                           'urlId'      => 'id',
                                           'target'     => null,
                                           'title'      => null,
                                           'icon'       => null,
                                           'iconOpen'   => null,
                                           'open'       => null,
                                           'url_1'      => '/cms/add/section/paginas/pai_id/',
                                           'url_1_icon' => '/media/images/icon_add.png');

    /**
     * @var array
     */
    protected $_rootPaginasNodeParams = null;

    /**
     * Mensagem de Erro
     * @var string
     */
    protected $_error = null;

    /**
     * Mensagem de Sucesso
     * @var string
     */
    protected $_message = null;

    /**
     * Construtor da classe
     */
    public function init() {
        parent::init();
        $this->_paginasNodesParams['rootName'] = translateAdmin('Raiz');
        /*$this->_paginasNodesParams['url'] = '/cms/edit/section/paginas/id/';
		$this->_paginasNodesParams['url_1'] = '/cms/add/section/paginas/pai_id/';
		$this->_paginasNodesParams['url_1_icon'] = '/media/images/icon_add.png';*/
        if (!$this->_session) $this->_session = Goweb::registry('session');
        $this->_title = translateAdmin('CMS');
        $this->_sections = array(array('title'   => translateAdmin('P&aacute;ginas'),
                                       'section' => 'paginas',
                                       'link'    => '/cms/list/'));

        //parent::__construct();
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_paginaModel = Goweb::getModelInstance('Cms_Model_Pagina', 'db');
        $this->_paginatorParams = array('rows_per_page' => 5, 'links_per_page' => 10);
        if ($this->_request->pai_id) {
            $this->_parentUrl = 'pai_id/' . $this->_request->pai_id . '/';
        }
        $this->view->sections = $this->_sections;
    }
    

    /**
     * Devolve um object Goweb_Tree
     *
     * @param boolean
     *
     * @return Goweb_Tree
     */
    protected function _getTree() {
        // cria o objecto Goweb_Js_Tree
        //    $tree->setTitle(translateAdmin('P&aacute;ginas'));

        $nodesParams = $this->_paginasNodesParams;

        // valida se foram passados os campos necesserio para o node
        if (!array_key_exists('id', $nodesParams)) {
            throw new Goweb_Exception("O campo  'id' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('pid', $nodesParams)) {
            throw new Goweb_Exception("O campo  'pid' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('name', $nodesParams)) {
            throw new Goweb_Exception("O campo  'name' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('urlId', $nodesParams)) {
            throw new Goweb_Exception("O campo  'urlId' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }

        $idCol = $nodesParams['id'];
        $pidCol = $nodesParams['pid'];
        $nameCol = $nodesParams['name'];
        Goweb::loadClass('Goweb_Tree');
        $tree = new Goweb_Tree($idCol, $pidCol);
        $this->_paginaModel->order('ordem'); // ordena as paginas pelo campo ordem da bd

        // n&atilde;o carregar as chaves estrangeiras
        $this->_paginaModel->loadForeigns(false);

        $rowset = $this->_paginaModel->fetchAll(array($idCol, $pidCol, $nameCol, 'redireccionar'));

        //$tree->addElement($node);
        if ($rowset) {
            foreach ($rowset as $row) {
                $node = array($idCol => $row->{$idCol},
                $pidCol => $row->{$pidCol},
                $nameCol => $row->{$nameCol});

                // adiciona o node
                $tree->addElement($node);
            }
        }

        // retorna o Goweb_Js_Tree
        return $tree;
    }

    /**
     * Metodo chamado quando nenhuma action &eacute; fornecida
     */
    public function indexAction() {
        $this->_forward('list');
    }

    /**
     * Este Metodo &eacute; executado quando a action fornecida n&atilde;o
     * &eacute; encontrada
     */
    public function __call($action, $arguments) {
        $this->_forward('list');
    }

    /**
     * Listagem das Paginas
     */
    public function listAction() {
        if ($this->_getParam('message')){
            $this->_message = $this->_getParam('message');
        }
        if ($this->_getParam('error')){
            $this->_error = $this->_getParam('error');
        }
        $this->_links['edit'] = '/cms/edit/section/paginas/id/' . $this->_getParam('id') .'/';
        $this->_links['save'] = '/cms/save/section/paginas/id/' . $this->_getParam('id') .'/';
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('P&aacute;ginas'));
        $section->setTitleSingular(translateAdmin('P&aacute;gina'));
        $this->_paginaModel->where($this->_paginaModel->getTableName() . '.sistema=?', '0');
        $section->setModel($this->_paginaModel);
        $section->setListCols(array('titulo', 'criado'));
        $section->setSearchCols(array('titulo'));
        $section->setOrdering('criado');
        $tree = $this->_getTreeObject(false);
        $pid = $this->_getParam('id');
        if ($tree instanceof Goweb_Js_Dhtmlx_Tree && $this->_paginaModel->find($this->_getParam('id'))){
            if ($pid > 0){
                $treeModel = $this->_paginaModel;
                $treeModel->loadForeigns(false);
                $cats = $treeModel->getPais($pid);
                $cats = array_reverse($cats, true);
                $treeModel->loadForeigns(true);
                $tree->setOpenTo($cats);
            } else {
                $tree->setOpenTo($pid);
            }
        } else {
            $tree->setOpenTo($pid);
        }
        $section->setTreeObject($tree);
        $this->view->action  = translateAdmin('Listagem');
        $this->view->title   = $this->_title;
        $this->view->output = $this->_treeGeneric($section, $this->view, false);
        $this->view->section_title = $section->getTitle();
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Adiciona uma pagina
     *
     * @param boolean
     */
    public function addAction($cleanValues = false) {
        $this->_links['edit'] = '/cms/edit/section/paginas/';
        $this->_links['save'] = '/cms/save/section/paginas/';
        $cmsPermissaoModel = Goweb::getModelInstance('Sistema_Model_CmsPermissao', 'db', false);
        $cmsPermissaoModel->where('pagina_id=?', $this->_getParam('pai_id'));
        $cmsPermissaoModel->where('perfil_id=?', $this->_session->utilizador['perfil_id']);


        if ($this->_session->utilizador['perfil']['superuser'] == '0' && $cmsPermissaoModel->count('id') == '0') {
            $this->_error = translateAdmin('O seu utilizador n&atilde;o possui previl&eacute;gios para esta opera&ccedil;&atilde;o.');
            return $this->listAction();
        }

        Goweb::loadClass('Form_Pagina', ADMIN_PATH . DIRECTORY_SEPARATOR . 'Cms');
        $form = new Form_Pagina($this->_section, Goweb::link($this->_links['save']));
        $form->setModel($this->_paginaModel);
        $form->setup($this->_getParam('pai_id'));
        $form->render();
        $this->view->form = $form;
        $this->_paginaModel->where($this->_paginaModel->getTableName() . '.sistema=?', '0');
        $tree = $this->_getTreeObject(false);
        if ($this->_getParam('pai_id') > 0) {
            if ($tree instanceof Goweb_Js_Dhtmlx_Tree){
                $cats = $this->_paginaModel->getPais($this->_getParam('pai_id'));
                $cats = array_reverse($cats, true);
                $tree->setOpenTo($cats);
            } else {
                $tree->setOpenTo($this->_getParam('pai_id'));
            }
        }

        $this->view->id      = null;
        $this->view->tree    = $tree;
        $this->view->action  = translateAdmin('Inser&ccedil;&atilde;o');
        $this->view->title   = $this->_title;
        $this->view->section = translateAdmin('P&aacute;ginas');
        $this->view->section_singular = translateAdmin('P&aacute;gina');
        $this->view->error = $this->_error;
        $this->view->message = $this->_message;
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->view->render('form.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->view->section_title = translateAdmin('P&aacute;ginas');
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Editar pagina
     */
    public function editAction() {
        $this->_links['edit'] = '/cms/edit/section/paginas/id/' . $this->_getParam('id') .'/';
        $this->_links['save'] = '/cms/save/section/paginas/id/' . $this->_getParam('id') .'/';
        $this->_links['delete'] = '/cms/delete/section/paginas/id/' . $this->_getParam('id') .'/';

        if (!$this->_validateId($this->_getParam('id')) || !$this->_paginaModel->find($this->_getParam('id'))) {
            return $this->listAction();
        }

        // permissoes backoffice
        $cmsPermissaoModel = Goweb::getModelInstance('Sistema_Model_CmsPermissao', 'db', false);
        $cmsPermissaoModel->where('pagina_id=?', $this->_getParam('id'));
        $cmsPermissaoModel->where('perfil_id=?', $this->_session->utilizador['perfil_id']);

        if ($this->_session->utilizador['perfil']['superuser'] == '0' && $cmsPermissaoModel->count('id') == '0') {
            $this->_error = translateAdmin('O seu utilizador n&atilde;o possui previl&eacute;gios para esta opera&ccedil;&atilde;o.');
            return $this->listAction();
        }

        $permissoes = array();
        $permissaoModel = Goweb::getModelInstance('Cms_Model_Permissao', 'db', false);
        $permissaoModel->where("pagina_id=?", $this->_getParam('id'));
        $permissaoRowset = $permissaoModel->fetchAll();
        if ($permissaoRowset) {
            foreach ($permissaoRowset as $row) {
                $permissoes[] = $row->perfil_id;
            }
        }

        Goweb::loadClass('Form_Pagina', ADMIN_PATH . DIRECTORY_SEPARATOR . 'Cms');
        $form = new Form_Pagina($this->_section, Goweb::link($this->_links['save']));
        $form->setModel($this->_paginaModel);
        $form->setup($this->_getParam('pai_id'));
        $form->perfis->value        = $permissoes;
        foreach ($form->getElementsNames() as $element){
            if (!$this->_paginaModel->colExists($element)) {
                continue;
            }
            $form->{$element}->value        = $this->_paginaModel->{$element};
        }
        $form->render();
        $this->view->form = $form;
        $this->view->id = $this->_paginaModel->id;
        $this->_paginaModel->where($this->_paginaModel->getTableName() . '.sistema=?', '0');
        $tree = $this->_getTreeObject(false);
        if ($tree instanceof Goweb_Js_Dhtmlx_Tree){
            if ($this->_paginaModel->id > 0){
                $cats = $this->_paginaModel->getPais($this->_paginaModel->id);
                $cats = array_reverse($cats, true);
                $tree->setOpenTo($cats);
            } else {
                $tree->setOpenTo($this->_paginaModel->id);
            }
        } else {
            $tree->setOpenTo($this->_paginaModel->id);
        }
        $this->view->tree = $tree;
        $this->view->action  = translateAdmin('Edi&ccedil;&atilde;o');
        $this->view->title   = $this->_title;
        $this->view->section = translateAdmin('P&aacute;ginas');
        $this->view->section_singular = translateAdmin('P&aacute;gina');
        $this->view->error = $this->_error;
        $this->view->message = $this->_message;
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->links = $this->_links;
        $this->view->output = $this->view->render('form.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->view->section_title = translateAdmin('P&aacute;ginas');
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Salvar pagina
     */
    public function saveAction() {
        $cmsPermissaoModel = Goweb::getModelInstance('Sistema_Model_CmsPermissao', 'db', false);
        if ($this->_validateId($this->_getParam('id'))) {
            // permissoes backoffice
            $cmsPermissaoModel = Goweb::getModelInstance('Sistema_Model_CmsPermissao', 'db', false);
            $cmsPermissaoModel->where('perfil_id=?', $this->_session->utilizador['perfil']['id']);
            $cmsPermissaoModel->where('pagina_id=?', $this->_getParam('id'));
            if ($this->_session->utilizador['perfil']['superuser'] == '0' && $cmsPermissaoModel->count('id') == '0') {
                $this->_error = translateAdmin('O seu utilizador n&atilde;o possui previl&eacute;gios para esta opera&ccedil;&atilde;o.');
                return $this->listAction();
            }
            // --
        }

        $this->_links['edit'] = '/cms/edit/section/paginas/id/' . $this->_getParam('id') .'/';
        $this->_links['save'] = '/cms/save/section/paginas/id/' . $this->_getParam('id') .'/';
        $this->_links['delete'] = '/cms/delete/section/paginas/id/' . $this->_getParam('id') .'/';

        Goweb::loadClass('Form_Pagina', ADMIN_PATH . DIRECTORY_SEPARATOR . 'Cms');
        $form = new Form_Pagina($this->_section, Goweb::link($this->_links['save']));
        $form->setModel($this->_paginaModel);
        $form->setup();

        if (!$form->validate()) {
            if (count($form->getErrorMessages()) > 1) {
                $this->_error = translateAdmin('Corrija por favor os erros no formul&aacute;rio');
            } else {
                $this->_error = translateAdmin('Corrija por favor o erro no formul&aacute;rio');
            }
        } else {
            $perfilModel = Goweb::getModelInstance('Sistema_Model_CmsPermissao', 'db', false);
            $perfilModel->reset();
            $perfilModel->where('pagina_id=?', $form->pai_id->value);
            $perfis = $perfilModel->fetchAll();
            $podegravar=false;
            if ($this->_validateId($this->_getParam('id')) && $this->_paginaModel->find($this->_getParam('id')) && ($this->_paginaModel->pai_id && $this->_paginaModel->pai_id != $form->pai_id->value)){
                if ($perfis && $this->_session->utilizador['perfil']['superuser'] == '0') {
                    foreach ($perfis as $perfil) {
                        if ($this->_session->utilizador['perfil']['id']==$perfil->perfil_id){
                            $podegravar=true;
                        }
                    }
                    if (!$podegravar) {
                        $this->_error = translateAdmin('O seu utilizador n&atilde;o possui previl&eacute;gios para esta opera&ccedil;&atilde;o.');
                        return $this->listAction();;
                    }
                }
            }
            if ($this->_session->utilizador['perfil']['superuser'] == '1') $podegravar = true;
            if ($this->_paginaModel->pai_id && ($this->_paginaModel->pai_id != $form->pai_id->value) && (!is_numeric($form->pai_id->value) || !$podegravar)){
                $this->_error = translateAdmin('O seu utilizador n&atilde;o possui previl&eacute;gios para esta opera&ccedil;&atilde;o.');
                return $this->listAction();;
            }
            $insert = false;

            if (!$this->_validateId($this->_getParam('id')) || !$this->_paginaModel->find($this->_getParam('id'))) {
                if ($this->_session->utilizador['perfil']['superuser'] == '0'){
                    $podegravar=false;
                    foreach ($perfis as $perfil) {
                        if ($form->pai_id->value==$perfil->pagina_id){
                            $podegravar=true;
                        }
                    }
                    if (!$podegravar) {
                        $this->_error = translateAdmin('O seu utilizador n&atilde;o possui previl&eacute;gios para esta opera&ccedil;&atilde;o.');
                        return $this->listAction();;
                    }
                }
                $this->_message = translateAdmin('A P&aacute;gina foi inserida com sucesso.');
                $insert = true;
            } else {
                $this->_message = translateAdmin('A P&aacute;gina foi actualizada com sucesso.');
            }
            foreach ($form->getElementsNames() as $element){
                if (!$this->_paginaModel->colExists($element)) {
                    continue;
                }
                $this->_paginaModel->{$element} = $form->{$element}->value;
            }
            if ($form->homepage->value == '1') {
                $langs = $this->_paginaModel->getLangs();
                if ($langs) {
                    foreach ($langs as $lang) {
                        $lang = preg_replace('/([^a-z0-9_])/i', '_', $lang);
                        $table = $this->_paginaModel->getTablePrefix() . '_' . $lang;
                        $this->_paginaModel->getAdapter()->query($this->_getUpdateHomepage($table, $this->_paginaModel->pai_id));
                    }
                } else {
                    $this->_paginaModel->getAdapter()->query($this->_getUpdateHomepage($this->_paginaModel->getTableName(), $this->_paginaModel->pai_id));
                }
            }
            $this->_paginaModel->save();
            
            $files = glob(CACHE_PATH . "/zend/paginas*");
            if ($files && is_array($files) && count($files) > 0){
                foreach ($files as $file){
                    if(file_exists($file) && is_writable($file)) {
                        unlink($file);
                    }
                }
            }

            // remove o ficheiro em cache se este existir
            if (!is_null($this->_session->lang)) {
                $cacheFilename = ROOT_PATH . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'cms' . DIRECTORY_SEPARATOR . 'cms_' . $this->_paginaModel->id . '_' . $this->_session->lang . '.tpl';
                if(file_exists($cacheFilename) && is_writable($cacheFilename)) {
                    unlink($cacheFilename);
                }
            }

            // permissoes
            $permissaoModel = Goweb::getModelInstance('Cms_Model_Permissao', 'db', false);
            if ($this->_request->privado) {
                $permissoes = array();
                $permissaoModel->where("pagina_id=?", $this->_paginaModel->id);
                $permissaoRowset = $permissaoModel->fetchAll();

                if ($permissaoRowset) {
                    foreach ($permissaoRowset as $row) {
                        $permissoes[] = $row->perfil_id;
                    }
                }

                if ($this->_request->perfis) {
                    foreach ($this->_request->perfis as $perfil) {
                        if (!in_array($perfil, $permissoes)) {
                            $permissaoModel->reset();
                            $permissaoModel->pagina_id = $this->_paginaModel->id;
                            $permissaoModel->perfil_id = $perfil;
                            $permissaoModel->save();
                        }
                    }

                    foreach ($form->perfis->options as $key => $value) {
                        if (!in_array($key, $this->_request->perfis)) {
                            $permissaoModel->deleteWhere("pagina_id='{$this->_paginaModel->id}' && perfil_id='$key'");
                        }
                    }
                } else {
                    // limpa permissoes
                    foreach ($permissoes as $permissao) {
                        $permissaoModel->delete($permissao);
                    }
                }
            } else {
                $permissaoModel->deleteWhere("pagina_id='" . $this->_getParam('id') . "'");
            }

            // permissoes backoffice
            if ($insert) {
                $perfilModel = Goweb::getModelInstance('Sistema_Model_CmsPermissao', 'db', false);
                $perfilModel->reset();
                $perfilModel->where('pagina_id=?', $form->pai_id->value);
                $perfis = $perfilModel->fetchAll();
                if ($perfis) {
                    foreach ($perfis as $perfil) {
                        $cmsPermissaoModel->reset();
                        $cmsPermissaoModel->perfil_id = $perfil->perfil_id;
                        $cmsPermissaoModel->pagina_id = $this->_paginaModel->id;
                        $cmsPermissaoModel->save();
                    }
                }
            }

            if ($this->_request->submit) {
                $model = $this->_paginaModel;
                $this->_request->setParam($model->getPrimary(), $model->{$model->getPrimary()});
                return $this->listAction();
            }
            if ($this->_request->submit_and_continue) {
                $model = $this->_paginaModel;
                if (!$this->_getParam($model->getPrimary())){
                    $this->_request->setParam($model->getPrimary(), $model->{$model->getPrimary()});
                    $this->_links['save'] .= $model->getPrimary() . '/' . $model->{$model->getPrimary()} . '/';
                }
                return $this->editAction();
            }
            if ($this->_request->submit_and_new) {
                return $this->addAction(true);
            }
        }
        
        $form->render();
        $this->view->form = $form;
        $this->view->id = $this->_getParam('id');
        $this->_paginaModel->where($this->_paginaModel->getTableName() . '.sistema=?', '0');
        $tree = $this->_getTreeObject(false);
        if ($this->_getParam('id') > 0) {
            $tree->setOpenTo($this->_getParam('id'));
        } elseif ($this->_getParam('pai_id') > 0) {
            $tree->setOpenTo($this->_getParam('pai_id'));
        } elseif ($this->_request->pai_id > 0) {
            $tree->setOpenTo($this->_request->pai_id);
        }

        $this->view->tree = $tree;
        if (!$this->_getParam('id')){
            $this->view->action  = translateAdmin('Inser&ccedil;&atilde;o');
        } else {
            $this->view->action  = translateAdmin('Edi&ccedil;&atilde;o');
        }
        $this->view->title   = $this->_title;
        $this->view->section = translateAdmin('P&aacute;ginas');
        $this->view->section_singular = translateAdmin('P&aacute;gina');
        $this->view->section = translateAdmin('P&aacute;ginas');
        $this->view->section_singular = translateAdmin('P&aacute;gina');
        $this->view->error   = $this->_error;
        $this->view->message = $this->_message;
        $this->view->links = $this->_links;
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->view->render('form.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->view->section_title = translateAdmin('P&aacute;ginas');
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Remover pagina
     */
    public function deleteAction() {
        if (!$this->_validateId($this->_getParam('id')) || !$this->_paginaModel->find($this->_getParam('id'))) {
            return $this->listAction();
        }

        // permissões
        $cmsPermissaoModel = Goweb::getModelInstance('Sistema_Model_CmsPermissao', 'db', false);
        $cmsPermissaoModel->where('pagina_id=?', $this->_getParam('id'));
        $cmsPermissaoModel->where('perfil_id=?', $this->_session->utilizador['perfil']['id']);
        if ($this->_session->utilizador['perfil']['superuser'] == '0' && $cmsPermissaoModel->count('id') == '0') {
            $this->_error = translateAdmin('O seu utilizador n&atilde;o possui previl&eacute;gios para esta opera&ccedil;&atilde;o.');
            return $this->listAction();
        }
        // --

        $this->_paginaModel->where($this->_paginaModel->getTableName() . '.pai_id=?', $this->_getParam('id'));
        if ($this->_paginaModel->count('id') > 0) {
            $this->_error = translateAdmin('A P&aacute;gina tem sub-p&aacute;ginas e n&atilde;o pode removida.');
            return $this->editAction();
        }

        // remocao de permissões do frontoffice
        $permissaoModel = Goweb::getModelInstance('Cms_Model_Permissao', 'db', false);
        $permissaoModel->deleteWhere("pagina_id='" . $this->_getParam('id') . "'");

        // remocao de permissoes backoffice
        $cmsPermissaoModel->deleteWhere("pagina_id='" . $this->_getParam('id') . "'");

        $this->_message = translateAdmin('A P&aacute;gina foi removida com sucesso.');
        $this->_request->setParam($this->_paginaModel->getPrimary(), $this->_paginaModel->pai_id);

        $this->_paginaModel->delete();
        return $this->listAction();
        //$this->_forward('list', null, null, array('message' => $this->_message));
    }


    /**
     * Remover lista de Páginas de sistema
     */
    public function advlinkAction() {
        $this->_paginaModel->where($this->_paginaModel->getTableName() . '.sistema=?', '0');
        $tree = $this->_getAdvLinkTreeObject(false);
        $tree->setExpand(true);
        $this->view->tree = $tree;
        $this->view->title = translateAdmin('Gest&atilde;o');
        $this->view->action = translateAdmin('Links Internos');
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->_helper->viewRenderer->setRender('advlink');
    }

    /**
     * Metodo que trata dos componentes inseridos no RTE
     */
    public function componentAction() {
        /**
         * /admin/cms/component/controller/nome_do_controller
         */
        $error = '';
        $onload = '';
        $moduloPermissaoModel = Goweb::getModelInstance('Sistema_Model_Permissao', 'db');
        $modulosModel = Goweb::getModelInstance('Sistema_Model_Modulo', 'db');
        $moduloModel = Goweb::getModelInstance('Sistema_Model_Modulo', 'db');
        $modulos = array();
        $moduloModel->where("componente='1'");
        $moduloModel->where('permissao = ?', '1');
        $moduloModel->order('titulo');
        $moduloRowset = $moduloModel->fetchAll();
        if ($this->_session->utilizador['perfil']['superuser'] == 0) {
            if ($this->_getParam('controller')) {
                /*$moduloModel->findBy('nome', $this->_getParam('controller'));
                if ($moduloPermissaoModel->findBy('modulo_id', $moduloModel->id))*/
                $user = $this->_auth->getIdentity();
                if(is_object($user)) {
                    $role = $this->_auth->getIdentity()->role;
                }elseif (is_array($user)){
                    $auth = $this->_auth->getIdentity();
                    $role = $auth['role'];
                }
                if ($this->_helper->acl->isAllowed($role, $this->_getParam('controller')))
                    $hasPermission=true;
            }
        }
        // módulos
        $modulos = array();
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        if (($this->_session->utilizador['perfil']['superuser'] > 0) || isset($hasPermission) && $hasPermission) {
            if ($this->_getParam('component_controller')) {
                $controller = ucfirst(strtolower($this->_getParam('component_controller')));
                $this->view->controller = strtolower($controller);
                if (Goweb::isReadable($controller . '_Component', APPLICATION_PATH)) {
                    Goweb::loadClass($controller . '_Component', APPLICATION_PATH);
                    $class = $controller . '_Component';
                    $componentObject = new $class($this->_request, $this->_response);
                    if ($this->_getParam('component_action')) {
                        $method = $this->_getParam('component_action').'Action';
                        if (method_exists($componentObject, $method)) {
                            $form = $componentObject->{$method}();
                            if ($form) {
                                /**
                                 * sucatisse por causa do onload
                                 */
                                $form->setAction('');
                                if ($this->_request->isPost()) {
                                    if ($form->validate()) {
                                        $onload = '/' . strtolower($controller) . '/' . $this->_getParam('component_action') . '/';
                                        $encodeElements = $componentObject->getEncodeElements();
                                        foreach ($form->getElementsNames() as $element) {
                                    		$value = $form->{$element}->value;
                                            if (in_array($element, $encodeElements)) {
                                                $onload .= $element . '/' . urlencode($value) . '/';
                                            } else {
                                                $onload .= $element . '/' . $value . '/';
                                            }
                                        }
                                    } else {
                                        if (count($form->getErrorMessages()) > 1) {
                                            $error = translateAdmin('Corrija por favor os erros no formul&aacute;rio');
                                        } else {
                                            $error = translateAdmin('Corrija por favor o erro no formul&aacute;rio');
                                        }
                                    }
                                }
                                $form->render();
                                $this->view->form = $form;
                                $this->view->error = $error;
                                $this->view->onload = $onload;
                                $this->view->modulos = $moduloRowset;
                                $this->view->output = $this->view->render('form_component.tpl');
                                $this->_helper->viewRenderer->setNoController(true);
                                $this->_helper->viewRenderer->setRender('componentes');
                                return true;
                            }
                        }
                    }

                    $this->view->error = $error;
                    $this->view->onload = $onload;
                    $this->view->modulos = $moduloRowset;
                    $this->view->actions = $componentObject->getActions();
                    $this->view->output = $this->view->render('list_component_actions.tpl');
                    $this->_helper->viewRenderer->setNoController(true);
                    $this->_helper->viewRenderer->setRender('componentes');
                    return true;
                }
            }
        }

        $this->view->modulos = $moduloRowset;
        $this->view->error = $error;
        $this->view->onload = $onload;
        $this->view->output = null;
        $this->_helper->viewRenderer->setNoController(true);
        $this->_helper->viewRenderer->setRender('componentes');
    }

    /**
     * Devolve um object Goweb_Js_Tree
     *
     * @param boolean
     *
     * @return Goweb_Js_Tree
     */
    protected function _getTreeObject($cleanModelParts = true) {
        if (is_dir(WWW_PATH.'/admin/media/js/dhtmlx/')){
            Goweb::loadClass('Goweb_Js_Dhtmlx_Tree');
            $tree = new Goweb_Js_Dhtmlx_Tree('paginas');
            $tree->setLink('/cms/treeDhtmlx/');
            $tree->setTitle(translateAdmin('P&aacute;ginas'));
            goweb::loadCss('/admin/media/js/dhtmlx/dhtmlx.css');
            goweb::loadCss('/admin/media/css/dhtmlx.css');
            goweb::loadJavascript('/admin/media/js/dhtmlx/dhtmlx.js');
            goweb::loadJavascript('/admin/media/js/dhtmlx/connector.js');
            return $tree;
        }
        // cria o objecto Goweb_Js_Tree
        Goweb::loadClass('Goweb_Js_Tree');
        $tree = new Goweb_Js_Tree('paginas');
        $tree->setTitle(translateAdmin('P&aacute;ginas'));

        // adiciona os paremetros
        foreach ($this->_paginasTreeParams as $param => $value) {
            $tree->{$param} = $value;
        }

        $nodesParams = $this->_paginasNodesParams;

        // valida se foram passados os campos necesserio para o node
        if (!array_key_exists('id', $nodesParams)) {
            throw new Goweb_Exception("O campo  'id' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('pid', $nodesParams)) {
            throw new Goweb_Exception("O campo  'pid' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('name', $nodesParams)) {
            throw new Goweb_Exception("O campo  'name' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('urlId', $nodesParams)) {
            throw new Goweb_Exception("O campo  'urlId' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }

        $idCol = $nodesParams['id'];
        $pidCol = $nodesParams['pid'];
        $nameCol = $nodesParams['name'];
        $this->_paginaModel->order('ordem'); // ordena as paginas pelo campo ordem da bd

        // n&atilde;o carregar as chaves estrangeiras
        $this->_paginaModel->loadForeigns(false);
        // limpa todas as partes do SELECT
        if ($cleanModelParts) {
            $this->_paginaModel->cleanParts();
        }

        $rowset = $this->_paginaModel->fetchAll(array($idCol, $pidCol, $nameCol, 'redireccionar', 'activo'));
        $urlBase = Zend_Controller_Front::getInstance()->getRequest()->getBaseUrl();
        
        unset($nodesParams['id']);
        unset($nodesParams['pid']);
        unset($nodesParams['name']);
        if (strpos($nodesParams['url'], $urlBase) === false) $nodesParams['url'] = $urlBase . $nodesParams['url'];
        $node = new Goweb_Js_Tree_Node('0', '-1', '', $nodesParams['url'] . '0/');
        if (array_key_exists('rootName', $nodesParams)) {
            $node->name = $nodesParams['rootName'];
            unset($nodesParams['rootName']);
        }

        if ($this->_rootPaginasNodeParams) {
            $rootNodeParams = $this->_rootPaginasNodeParams;
        } else {
            $rootNodeParams = $nodesParams;
        }
        if (strpos($rootNodeParams['url'], $urlBase) === false) $rootNodeParams['url'] = $urlBase . $rootNodeParams['url'];

        // configura os links e icons extra
        for ($i=1; $i<=5; $i++) {
            $param = 'url_' . $i . '_icon';
            if  (array_key_exists($param, $rootNodeParams)) {
                if (strpos($rootNodeParams[$param], str_replace('/index.php', '', $urlBase)) === false){
                    $rootNodeParams[$param] = str_replace('/index.php', '', $urlBase) . $rootNodeParams[$param];
                }
                $node->{$param} = $rootNodeParams[$param];
                $param = 'url_' . $i;
                if (array_key_exists($param, $rootNodeParams)) {
                    if (strpos($rootNodeParams[$param], $urlBase) === false) $rootNodeParams[$param] = $urlBase . $rootNodeParams[$param];
                    $node->{$param} = $rootNodeParams[$param] . '0/';
                }
            }
        }

        $tree->addNode($node);
        if ($rowset) {
            // permissoes
            $cmsPermissaoModel = Goweb::getModelInstance('Sistema_Model_CmsPermissao', 'db', false);
            if ($this->_session->utilizador['perfil']['superuser'] == 0) {
                $cmsPermissaoModel->where('perfil_id=?', $this->_session->utilizador['perfil_id']);
            }
            $permissoesRowset = $cmsPermissaoModel->fetchAll();
            $permissoes = array();
            if ($permissoesRowset) {
                foreach ($permissoesRowset as $permissao) {
                    $permissoes[] = $permissao->pagina_id;
                }
            }

            foreach ($rowset as $row) {
                $titulo = $row->{$nameCol};
                if (!$row->activo){
                    $titulo = '<span class="disabled_page">' . $titulo . '</span>';
                }
                
                $node = new Goweb_Js_Tree_Node($row->{$idCol},
                $row->{$pidCol},
                $titulo,
                $nodesParams['url'] . $row->{$idCol} . '/',
                $nodesParams['urlId'],
                $nodesParams['target'],
                $nodesParams['title'],
                $nodesParams['icon'],
                $nodesParams['iconOpen'],
                $nodesParams['open']);

                // configura os links e icons extra
                for ($i=1; $i<=5; $i++) {
                    $param = 'url_' . $i . '_icon';
                    if  (array_key_exists($param, $nodesParams)) {
                        if (strpos($nodesParams[$param], str_replace('/index.php', '', $urlBase)) === false) {
                            $nodesParams[$param] = str_replace('/index.php', '', $urlBase) . $nodesParams[$param];
                        }
                        $node->{$param} = $nodesParams[$param];
                        $param = 'url_' . $i;
                        if (array_key_exists($param, $nodesParams)) {
                            if (strpos($nodesParams[$param], $urlBase) === false) $nodesParams[$param] = $urlBase . $nodesParams[$param];
                            $node->{$param} = $nodesParams[$param] . $row->{$idCol} . '/';
                        }
                    }
                }

                if ($row->redireccionar) {
                    $node->url_2 = '';
                    $node->url_2_icon = str_replace('/index.php', '', $urlBase) . '/media/images/icon_redirect.gif';
                }

                if (!in_array($row->{$idCol}, $permissoes) && $this->_session->utilizador['perfil']['superuser'] == 0) {
                    $node->disabled = true;
                }

                // adiciona o node
                $tree->addNode($node);
            }
        }

        // retorna o Goweb_Js_Tree
        return $tree;
    }

    /**
     * Devolve um objecto Goweb_Js_Tree
     *
     * @param boolean
     *
     * @return Goweb_Js_Tree
     */
    protected function _getAdvLinkTreeObject($cleanModelParts = true) {
        // cria o objecto Goweb_Js_Tree
        Goweb::loadClass('Goweb_Js_Tree');
        $tree = new Goweb_Js_Tree('paginas');
        $tree->setTitle(translateAdmin('P&aacute;ginas'));

        // adiciona os paremetros
        foreach ($this->_paginasTreeParams as $param => $value) {
            $tree->{$param} = $value;
        }

        $nodesParams = $this->_paginasNodesParams;

        // valida se foram passados os campos necesserio para o node
        if (!array_key_exists('id', $nodesParams)) {
            throw new Goweb_Exception("O campo  'id' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('pid', $nodesParams)) {
            throw new Goweb_Exception("O campo  'pid' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('name', $nodesParams)) {
            throw new Goweb_Exception("O campo  'name' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('urlId', $nodesParams)) {
            throw new Goweb_Exception("O campo  'urlId' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        $urlBase = Zend_Controller_Front::getInstance()->getRequest()->getBaseUrl();
        if (strpos($nodesParams['url'], $urlBase) === false) $nodesParams['url'] = $urlBase . $nodesParams['url'];

        $idCol = $nodesParams['id'];
        $pidCol = $nodesParams['pid'];
        $nameCol = $nodesParams['name'];
        $this->_paginaModel->order('ordem'); // ordena as paginas pelo campo ordem da bd

        // n&atilde;o carregar as chaves estrangeiras
        $this->_paginaModel->loadForeigns(false);
        // limpa todas as partes do SELECT
        if ($cleanModelParts) {
            $this->_paginaModel->cleanParts();
        }

        $rowset = $this->_paginaModel->fetchAll(array($idCol, $pidCol, $nameCol, 'redireccionar'));

        unset($nodesParams['id']);
        unset($nodesParams['pid']);
        unset($nodesParams['name']);
        $node = new Goweb_Js_Tree_Node('0', '-1', '', $nodesParams['url'] . '0/');
        if (array_key_exists('rootName', $nodesParams)) {
            $node->name = $nodesParams['rootName'];
            unset($nodesParams['rootName']);
        }

        if ($this->_rootPaginasNodeParams) {
            $rootNodeParams = $this->_rootPaginasNodeParams;
        } else {
            $rootNodeParams = $nodesParams;
        }
        if (strpos($rootNodeParams['url'], $urlBase) === false) $rootNodeParams['url'] = $urlBase . $rootNodeParams['url'];

        // configura os links e icons extra
        for ($i=1; $i<=5; $i++) {
            $param = 'url_' . $i . '_icon';
            if  (array_key_exists($param, $rootNodeParams)) {
                if (strpos($rootNodeParams[$param], str_replace('/index.php', '', $urlBase)) === false) {
                    $rootNodeParams[$param] = str_replace('/index.php', '', $urlBase) . $rootNodeParams[$param];
                }
                $node->{$param} = $rootNodeParams[$param];
                $param = 'url_' . $i;
                if (array_key_exists($param, $rootNodeParams)) {
                    if (strpos($rootNodeParams[$param], $urlBase) === false) $rootNodeParams[$param] = $urlBase . $rootNodeParams[$param];
                    $node->{$param} = $rootNodeParams[$param] . '0/';
                }
            }
        }

        $tree->addNode($node);
        if ($rowset) {
            if (strpos($nodesParams['url'], $urlBase) === false) $nodesParams['url'] = $urlBase . $nodesParams['url'];
            // permissoes
            $cmsPermissaoModel = Goweb::getModelInstance('Sistema_Model_CmsPermissao', 'db', false);
            if ($this->_session->utilizador['perfil']['superuser'] == 0) {
                $cmsPermissaoModel->where('perfil_id=?', $this->_session->utilizador['perfil_id']);
            }
            $permissoesRowset = $cmsPermissaoModel->fetchAll();
            $permissoes = array();
            if ($permissoesRowset) {
                foreach ($permissoesRowset as $permissao) {
                    $permissoes[] = $permissao->pagina_id;
                }
            }

            foreach ($rowset as $row) {
                $node = new Goweb_Js_Tree_Node($row->{$idCol},
                $row->{$pidCol},
                $row->{$nameCol},
    			"onclick=\"AdvLinkDialogue.setFilenameAndClose(\'" . str_replace('/admin', '', $this->view->link("/cms/view/id/" . $row->{$idCol})) . "/\');\"",
                $nodesParams['urlId'],
                $nodesParams['target'],
                $nodesParams['title'],
                $nodesParams['icon'],
                $nodesParams['iconOpen'],
                $nodesParams['open']);

                // adiciona o node
                $tree->addNode($node);
            }
        }

        // retorna o Goweb_Js_Tree
        return $tree;
    }

    /**
     * Criação dinâmica da àrvore, componente dhtmlx
     *
     */
    public function treeDhtmlxAction(){
        $this->_helper->viewRenderer->setNoRender();

        $idCat = $this->_request->id;
        if (!is_numeric($idCat)) {
            $idCat = 0;
        }
        $nodesParams = $this->_paginasNodesParams;
        
        // valida se foram passados os campos necessário para o node
        if (!array_key_exists('id', $nodesParams)) {
            throw new Goweb_Exception("O campo 'id' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('pid', $nodesParams)) {
            throw new Goweb_Exception("O campo 'pid' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('name', $nodesParams)) {
            throw new Goweb_Exception("O campo 'name' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('urlId', $nodesParams)) {
            throw new Goweb_Exception("O campo 'urlId' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }

        $idCol = $nodesParams['id'];
        $pidCol = $nodesParams['pid'];
        $nameCol = $nodesParams['name'];
        $this->_paginaModel->where($this->_paginaModel->getTableName() . '.' . $pidCol . ' = ?', $idCat);
        $this->_paginaModel->order('ordem');
        $rowset = $this->_paginaModel->fetchAll();

        $data = array('id' => $idCat, 'item' => array());
        if ($idCat == 0){
            $data['item'][0] = array(
                        'id' => 'root', 
                        'text' => $this->_addTreeOptions($this->_paginasNodesParams['rootName'], 0, $nodesParams),
                        'item' => array());
        }
        if ($rowset){
            $items = array();
            foreach ($rowset as $item){
                $childs = $this->_paginaModel->getCountFilhos($item->{$idCol});
                $titulo = $item->{$nameCol};
                if (!$item->activo){
                    $titulo = '<span class="disabled_page">' . $titulo . '</span>';
                }
                $currentNodesParams = $nodesParams;
                if ($item->redireccionar) {
                    $currentNodesParams['url_2'] = '';
                    $currentNodesParams['url_2_icon'] = $this->view->urlBase . '/media/images/icon_redirect.gif';
                }
                $items[] = array(
                            'id' => $item->{$idCol}, 
                            'text' => $this->_addTreeOptions($titulo, $item->{$idCol}, $currentNodesParams), 
                            'child' => $childs);
            }
            if ($idCat == 0){
                $data['item'][0]['item'] = $items;
            } else {
                $data['item'] = $items;
            }
        }

        if ($this->_getParam('format') == 'xml'){
            throw new Goweb_Exception('not completed');
            $this->getResponse()->setHeader('Content-Type', 'text/xml; charset=' . CHARSET);
            $output = '<tree id=\'' . $idCat . '\'>' . "\n";
            foreach ($data['item'] as $item){
                $output .= "<item ";
                foreach ($item as $key => $value){
                    if ($key != 'text'){
                        $output .= $key . "='" . $value . "' ";
                    } else {
                        $output .= $key . "='" . htmlspecialchars($value, ENT_QUOTES, CHARSET, false) . "' ";
                    }
                }
                $output .= '></item>' . "\n";
            }
            $output .= '</tree>' . "\n";
            $this->view->output = $output;
            $this->view->setViewsPath(VIEWS_PATH);
            $this->_helper->viewRenderer->setRender('vazia');
            $this->_helper->viewRenderer->setNoRender(false);

        } else {
            $this->_helper->json($data);
        }

    }
    
    /**
     * Obter a query para actualizar a homepage, útil para o funcionamento com micro-sites
     *
     * @param string $table
     * @param int|string $id
     * @param int|string $pai_id
     * @return string
     */
    protected function _getUpdateHomepage($table, $pai_id = null){
        return "UPDATE " . $table . " SET homepage='0'";
    }
}