<?php

Goweb::loadClass('Index_Controller', ADMIN_PATH);

/**
 * Goweb Sitemanager 5 Framework
 * @version    5.0.13
 * @category   Backoffice
 * @package    PainelGoweb
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2009 (c) Goweb (http://www.goweb.pt)
*/
class PainelGoweb_GenericController extends Index_Controller {

    /**
     * Titulo do Modulo
     * @var string
    */
    protected $_title;
    
    /**
     * Nomes das linguas
     * @var string
    */
    protected $_langsNames;
    /**
     * Controller do Modulo
     * @var string
    */
    protected $_controller = 'painel_goweb';
    
    /**
     * Seccoes do Modulo
     * @var array
    */
    protected $_sections;
    
    /**
     * Objecto Goweb_Config_Ini
     * @var Goweb_Config_Ini
    */
    protected $_configModel = null;
    
    /**
     * Objecto Sistema_Model_Utilizador
     * @var Sistema_Model_Utilizador
    */
    protected $_utilizadorModel = null;
    
    /**
     * Objecto Sistema_Model_Perfil
     * @var Sistema_Model_Perfil
    */
    protected $_perfilModel = null;
    
    /**
     * Objecto Sistema_Model_Permissao
     * @var Sistema_Model_Permissao
    */
    protected $_permissaoModel = null;
    
    /**
     * Objecto Sistema_Model_Modulo
     * @var Sistema_Model_Modulo
    */
    protected $_moduloModel = null;
    
    /**
     * Objecto Sistema_Model_CmsPermissao
     * @var Sistema_Model_CmsPermissao
    */
    protected $_cmsPermissaoModel = null;
    
    /**
     * Objecto Cms_Model_Pagina
     * @var Cms_Model_Pagina
    */
    protected $_paginaModel = null;

    /**
     * Mensagem de erro
     *
     * @var strint
    */
    protected $_error = null;
    
    /**
     * Mensagem de sucesso
     *
     * @var strint
    */
    protected $_message = null;

    /**
     * Construtor da classe
    */
    public function init() {
        $this->_title = translateAdmin('Painel de Controlo Goweb');
        $this->_sections[] = array('title'   => translateAdmin('Dashboard'),
                                       'section' => 'dashboard',
                                       'link'    => '/painel_goweb/dashboard');
        parent::init();
        $this->_sections[] = array('title'   => translateAdmin('Tradu&ccedil;&otilde;es'),
                                       'section' => 'traducoes',
                                       'link'    => '/painel_goweb/translater');
        $this->_sections[] = array('title'   => translateAdmin('Tradu&ccedil;&otilde;es Backoffice'),
                                       'section' => 'traducoesAdmin',
                                       'link'    => '/painel_goweb/translaterAdmin');
        $this->_sections[] = array('title'   => translateAdmin('Access Control List'),
                                       'section' => 'acl',
                                       'link'    => '/painel_goweb/list_acl');

        
        $this->_langsNames = goweb::registry('langsNames');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_paginatorParams = array('rows_per_page' => 20, 'links_per_page' => 10);
        $this->_initDefaultLinks();
        $this->_configModel = Goweb::getModelInstance('Painel_Model_Config', 'db');
        $this->view->title    = $this->_title;
        $this->view->sections = $this->_sections;
        $this->_links['excel'] = $this->_links['xml'] = '';
    }
    public function dashboardAction(){
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Dashboard'));
        $section->setTitleSingular(translateAdmin('Dashboard'));
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->links            = $this->_links;
        $this->view->action           = translateAdmin('Dashboard');
        $this->view->sections         = $this->_sections;
        $this->view->section_title    = $section->getTitle();
        $this->view->section_singular = $section->getTitleSingular();
        $this->view->error            = $this->_error;
        $this->view->message          = $this->_message;
        $this->view->output           = $this->view->render('dashboard.tpl');        
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }
    public function mysqlAction(){
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('MySQL'));
        $section->setTitleSingular(translateAdmin('MySQL'));
        Goweb::loadClass('Form_Mysql', dirname(__FILE__));
        $form = new Form_Mysql('Form_Mysql', '/painel_goweb/mysql');
        $form->setup();
        $form->render();
        if ($this->_request->isPost() && $form->validate()){
            $this->_message = 'adicionar';
            return $this->dashboardAction();
        }
        $this->view->form = $form;
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->links            = $this->_links;
        $this->view->action           = translateAdmin('Dashboard');
        $this->view->sections         = $this->_sections;
        $this->view->section_title    = $section->getTitle();
        $this->view->section_singular = $section->getTitleSingular();
        $this->view->error            = $this->_error;
        $this->view->message          = $this->_message;
        $this->view->output           = $this->view->render('form.tpl');        
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }
    
   
    /**
     * LIstagem dos Perfis dos Utilizadores
     */
    public function listAclAction() {
        $this->_links['list'] = '/painel_goweb/list_acl/';
        $this->_links['add'] = null;
        $this->_links['edit'] = '/painel_goweb/edit_acl/id/';
        $this->_links['delete'] = '/painel_goweb/delete_acl/id/';
        $this->_links['deletelist'] = null;
        
        $this->_perfilModel = Goweb::getModelInstance('Utilizadores_Model_Perfil', 'db');    
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Access Control List'));
        $section->setTitleSingular(translateAdmin('Access Control List'));
        $section->setModel($this->_perfilModel);               
        $section->setListCols(array('nome', 'activo', 'criado'));
        $section->setSearchCols(array('nome'));
        $section->setOrdering('nome');
        
        $this->view->model  = $this->_configModel;
        $this->view->output = $this->_listGeneric($section, $this->view, false);        
        $this->_helper->viewRenderer->setRender('base');
    }
    

    public function editAclAction() {
        $this->_perfilModel = Goweb::getModelInstance('Utilizadores_Model_Perfil', 'db');
                
        $id = $this->_getParam('id');
        
        if (!$this->_validateId($id) || !$this->_perfilModel->find($id)) {            
            return $this->listPerfisAction();
        }

        $this->_links['edit'] = '/painel_goweb/edit_acl/id/' . $id . '/';
        $this->_links['save'] = '/painel_goweb/save_acl/id/' . $id . '/';
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Access Control List'));
        $section->setTitleSingular(translateAdmin('Access Control List'));
        $section->setModel($this->_perfilModel);
        $section->setTreeObject($this->_getPaginasTree($id));

        $this->view->modulos = $this->_getPaginasTreeModulos();
        
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->_editGeneric($section, $this->view, null, 0, true, true, 'form_acl.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }
    

    /**
     * Salva um perfil
    */
    public function saveAclAction() {
        $this->_utilizadorModel = Goweb::getModelInstance('Utilizadores_Model_Perfil', 'db');
        $perfil_id = $this->_getParam($this->_utilizadorModel->getPrimary());
        $this->_saveAcl();
        if ($this->_request->submit) {
            return $this->listAclAction();
        }
        if ($this->_request->submit_and_new) {
            return $this->addAclAction(true);
        }
        if ($this->_request->submit_and_continue) {

            $model = $this->_utilizadorModel;

            if (!$this->_getParam($model->getPrimary())){
                $this->_request->setParam($model->getPrimary(), $model->{$model->getPrimary()});
                $this->_links['save'] .= $model->getPrimary() . '/' . $model->{$model->getPrimary()} . '/';
            }
            return $this->editAclAction();
        }

    }

    /**
     * Editar Config
    */
    public function editGowebAction() {
        $sectionGoweb = $this->_getParam('sub_section');
        if ($sectionGoweb != 'config' && $sectionGoweb != 'meta' && $sectionGoweb != 'google') {
            $sectionGoweb = 'config';
        }

        if (!$this->_configModel->find('1')) {
            throw new Goweb_Exception('As configura&ccedil;&otilde;es do "Goweb" n&atilde;o existem no sistema.');
        }

        $this->_links['save'] = '/painel_goweb/savePainel/sub_section/' . $sectionPainel . '/';

        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Configura&ccedil;&otilde;es'));
        $section->setTitleSingular(translateAdmin('Configura&ccedil;&atilde;o'));
        $section->setModel($this->_configModel);               

        Goweb::loadClass('Form_Generic', ADMIN_PATH . DIRECTORY_SEPARATOR . 'Index');
        $form = new Form_Generic($section, Goweb::link($this->_links['save']));
        $form->setup($section, $section->getLabels(), $this->_configModel);
        $form->render();
        
        if ($sectionPainel == 'config') {
            $this->view->show_elements = array('linguas_activas');
        } elseif ($sectionPainel == 'meta') {
            $this->view->show_elements = array('title', 'meta_copyright', 'meta_keywords', 'meta_description', 'meta_extra');
        } elseif ($sectionPainel == 'google') {
            $this->view->show_elements = array('google_sitemap', 'google_analytics');
        }
        
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->links            = $this->_links;
        $this->view->action           = translateAdmin('Edi&ccedil;&atilde;o');
        $this->view->sections         = $this->_sections;
        $this->view->section_title    = $section->getTitle();
        $this->view->section_singular = $section->getTitleSingular();
        $this->view->model            = $this->_configModel;
        $this->view->error            = $this->_error;
        $this->view->message          = $this->_message;
        $this->view->form             = $form;
        $this->view->output           = $this->view->render('form.tpl');        
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Metodo de actualizacao da base de dados
    */
    public function savePainelAction() {
        $sectionPainel = $this->_getParam('sub_section');
        if ($sectionPainel != 'config' && $sectionPainel != 'meta' && $sectionPainel != 'google') {
            $sectionPainel = 'config';
        }
        
        if (!$this->_configModel->find('1')) {
            throw new Goweb_Exception('As configura&ccedil;&otilde;es n&atilde;o existem no sistema.');
        }

        $this->_links['save'] = '/painel_goweb/savePainel/sub_section/' . $sectionPainel . '/';

        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Configura&ccedil;&otilde;es'));
        $section->setTitleSingular(translateAdmin('Configura&ccedil;&atilde;o'));
        $section->setModel($this->_configModel);
        
        Goweb::loadClass('Form_Generic', ADMIN_PATH . DIRECTORY_SEPARATOR . 'Index');
        $form = new Form_Generic($section, Goweb::link($this->_links['save']));
        $form->setup($section, $section->getLabels(), $this->_configModel);

        $updateElements = array();
        if ($sectionPainel == 'config') {
            $updateElements = array('linguas_activas');
        } elseif ($sectionPainel == 'meta') {
            $updateElements = array('title', 'meta_copyright', 'meta_keywords', 'meta_description', 'meta_extra');
        } elseif ($sectionPainel == 'google') {
            $updateElements = array('google_sitemap', 'google_analytics');
        }
        
        if (!$form->validate()) {
            if (count($form->getErrorMessages()) > 1) {
                $this->_error = translateAdmin('Corrija por favor os erros no formul&aacute;rio');
                $this->_message = null;
            } else {
                $this->_error = translateAdmin('Corrija por favor o erro no formul&aacute;rio');
                $this->_message = null;
            }
        } else {
            $this->_error = null;
            $this->_message = translateAdmin('Configura&ccedil;&otilde;es gravas com sucesso');
            foreach ($updateElements as $element) {
                if (is_array($form->{$element}->value)) {
                    $this->_configModel->{$element} = serialize($form->{$element}->value);
                } else {
                    $this->_configModel->{$element} = $form->{$element}->value;
                }
            }
            $this->_configModel->save();            
        }

        $form->render();

        $this->view->show_elements = $updateElements;
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->links            = $this->_links;
        $this->view->action           = translateAdmin('Edi&ccedil;&atilde;o');
        $this->view->sections         = $this->_sections;
        $this->view->section_title    = $section->getTitle();
        $this->view->section_singular = $section->getTitleSingular();
        $this->view->model            = $this->_configModel;
        $this->view->error            = $this->_error;
        $this->view->message          = $this->_message;
        $this->view->form             = $form;
        $this->view->output           = $this->view->render('form.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');                
    }
    /**
     * Listagem de traduções
     */
    public function translaterAction(){
    	$this->_config22 = Goweb::registry('config');
    	$this->_links['list'] = '/painel_goweb/translater/';
        $this->_links['edit'] = null;
        $this->_links['save'] = '/painel_goweb/saveTranslater/';
        $this->_links['deletelist'] = null;
        
        $page = $this->_request->page > 0 ? $this->_request->page : '1';
        $letter = strlen($this->_request->letter) > 0 ? $this->_request->letter : '';  
        $row_por_pag = 20;
        $this->_translaterModel = Goweb::getModelInstance('Cms_Model_Translater', 'db');
        if ($letter){
            if (in_array($letter, range('A', 'Z'))){
                $this->view->letter_selected = $letter;
                $this->_links['save'] .= 'letter/'.$letter;
                $this->_translaterModel->orWhere($this->_translaterModel->getTableName().'.texto LIKE "'.$letter.'%"');
                $this->_translaterModel->orWhere($this->_translaterModel->getTableName().'.texto LIKE "'.strtolower($letter).'%"');
            } else {
                $letter = null;
            }
        }
        $db = $this->_translaterModel->getAdapter();
          
        foreach ($_POST as $key => $value) {
        	$key_temp = explode("_", $key);
        	if (strlen($this->_session->lang) > 2){
            	if (count($key_temp) == 4 && $key_temp[3] != 'change'){
            	    $key_temp[2] = $key_temp[2] . '_' . $key_temp[3];
            	    unset($key_temp[3]); 
            	} else if (count($key_temp) == 5 && $key_temp[4] == 'change'){
                    $key_temp[2] = $key_temp[2] . '_' . $key_temp[3];
                    $key_temp[3] = $key_temp[4];
                    unset($key_temp[4]); 
            	}
        	}
        	if(count($key_temp) == 3 && $key_temp[0] == 'texto') {
        		if ($_POST['texto_' . $key_temp[1] . '_' . $key_temp[2] . '_change'] == "true" && $this->_validateId($key_temp[1]) && $this->_translaterModel->find($key_temp[1])) {
        			$value = str_replace("'", "&#39;", $value);
        			$tabela = "cms_translater_" . $key_temp[2];
       				$sql = "UPDATE $tabela SET translater = '$value', actualizado = '" . date("Y-m-d H:i:s") . "' WHERE id = " . $key_temp[1];
       				//Goweb::dump($sql);
       				$db->query($sql);
        		}
        	}
        	
        }
        $this->view->links  =  $this->_links;
        $this->view->action  = translateAdmin('Tradu&ccedil;&otilde;es');
        $this->view->section_title = translateAdmin('Tradu&ccedil;&otilde;es');
        $this->view->section_singular = translateAdmin('Tradu&ccedil;&atilde;o');
        $this->view->model  = $this->_configModel;
        $link_paginator = $this->_links['list'];
        $this->view->letter = '#';
        if ($letter){
            $link_paginator .= 'letter/'.$letter;
        } else {
            $this->view->letter_selected = '#';
        }
        
  
       //goweb::dump($this->_translaterModel->getSelect()->__toString()); exit;
        $paginator = new Goweb_Paginator(Goweb::link( $link_paginator, 'page='),
                                         $this->_translaterModel->count(),
                                         $page,
                                         $row_por_pag,
                                         10);
                                                                     
        $this->view->paginator = $paginator;
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->view->paginator_output = $this->view->render('paginator.tpl');
        
        $langs = array();
        $traducoes_temp = array();
        $this->_langsNames = goweb::registry('langsNames');
        $available = explode(',', $this->_config22->languages->available);
       
        foreach ($available as $lang) {
            $lang = preg_replace('/([^a-z0-9_])/i', '_', $lang);
        	$traducoes_temp[$lang] = array();
        	$langs[$lang] = isset($this->_langsNames[$lang]) ? $this->_langsNames[$lang] : $lang;
        }
        if ($this->_request->isPost()){
            goweb::loadClass('Zend_Json');
            foreach (array_keys($langs) as $lang) {
                $file = WWW_PATH . '/media/js/lang/bd_' . $lang . '.js';
                if (!is_writable($file)) {
                    continue ;
                }
                $tabela = "cms_translater_$lang";
                $sql = "SELECT texto, translater FROM $tabela ";
                $rowset = $db->fetchAll($sql);
                $data = array();
                foreach ($rowset as $row) {
                    $data[html_entity_decode($row['texto'], null, CHARSET)] = html_entity_decode($row['translater'], null, CHARSET);
                }
                $file_contents = 'var Translator = new Translate(' . Zend_Json::encode($data). ');';
                file_put_contents($file, $file_contents);
            }
        }
        
       
       $orderBy = 'texto ASC';
       
       $i = 0;
       $lang_1 = 'pt';
       
       foreach ($langs as $lang => $value) {
       			$tabela = "cms_translater_$lang";
       			$sql = "SELECT id, texto, translater FROM $tabela ";
       			if ($letter){
       			    $sql .= ' where ';
                    $sql .= $tabela.'.texto LIKE "'.$letter.'%"';
                    $sql .= ' OR ';
                    $sql .= $tabela.'.texto LIKE "'.strtolower($letter).'%"';
       			}
       			
       			$sql .= " ORDER BY $orderBy LIMIT  " . ($paginator->getRowsPerPage() * $paginator->getPage() - $paginator->getRowsPerPage()) . ', ' . $paginator->getRowsPerPage();
       			$traducoes_temp[$lang] = $db->fetchAll($sql);
       			if($i == 0) $lang_1 = $lang;
       			$i++;
           	}
        $traducoes = array();
        for ($i = 0; $i < count($traducoes_temp[$lang_1]); $i++)
        {
        	//Goweb::dump($traducoes_temp[$lang_1][$i]);
        	$array_linha_temp = array();
        	
        	$array_linha_temp['texto'] =  html_entity_decode($traducoes_temp[$lang_1][$i]['texto'], ENT_NOQUOTES, CHARSET);
        	
        	foreach ($langs as $lang => $value){
        		if(isset($traducoes_temp[$lang][$i]['translater']))
    			$array_linha_temp[$lang] = html_entity_decode($traducoes_temp[$lang][$i]['translater'], ENT_NOQUOTES, CHARSET);
    			else
    			$array_linha_temp[$lang] = html_entity_decode($array_linha_temp['texto'], ENT_NOQUOTES, CHARSET);
        	}
        	
        	
        	$traducoes[$traducoes_temp[$lang_1][$i]['id']] = $array_linha_temp;
        }

        goweb::loadClass('Zend_Cache');
        $cache = Zend_Registry::get('cache');
        $cache->clean(Zend_Cache::CLEANING_MODE_ALL);

        $this->view->langs = $langs;
        $this->view->traducoes = $traducoes;
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->view->render('translater.tpl'); 
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
        
    }
    /**
     * Listagem de traduções Backoffice
     */
    public function translaterAdminAction(){
    	$this->_config22 = Goweb::registry('config');
    	$this->_links['list'] = '/painel_goweb/translaterAdmin/';
        $this->_links['edit'] = null;
        $this->_links['save'] = '/painel_goweb/saveTranslaterAdmin/';
        $this->_links['deletelist'] = null;
        
        $page = $this->_request->page > 0 ? $this->_request->page : '1';
        $row_por_pag = 20;
        $this->_translaterModel = Goweb::getModelInstance('Cms_Model_TranslaterAdmin', 'db'); 
        $letter = strlen($this->_request->letter) > 0 ? $this->_request->letter : '';  
        if ($letter){
            if (in_array($letter, range('A', 'Z'))){
                $this->view->letter_selected = $letter;
                $this->_links['save'] .= 'letter/'.$letter;
                $this->_translaterModel->orWhere($this->_translaterModel->getTableName().'.texto LIKE "'.$letter.'%"');
                $this->_translaterModel->orWhere($this->_translaterModel->getTableName().'.texto LIKE "'.strtolower($letter).'%"');
            } else {
                $letter = null;
            }
        }
        $db = $this->_translaterModel->getAdapter();
          
        foreach ($_POST as $key => $value) {
        	$key_temp = explode("_", $key);
        	if (strlen($this->_session->lang) > 2){
        	    if (count($key_temp) == 4 && $key_temp[3] != 'change'){
        	        $key_temp[2] = $key_temp[2] . '_' . $key_temp[3];
        	        unset($key_temp[3]);
        	    } else if (count($key_temp) == 5 && $key_temp[4] == 'change'){
        	        $key_temp[2] = $key_temp[2] . '_' . $key_temp[3];
        	        $key_temp[3] = $key_temp[4];
        	        unset($key_temp[4]);
        	    }
        	}
        	if(count($key_temp) == 3 && $key_temp[0] == 'texto') {
        		if ($_POST['texto_' . $key_temp[1] . '_' . $key_temp[2] . '_change'] == "true" && $this->_validateId($key_temp[1]) && $this->_translaterModel->find($key_temp[1])) {
        			$value = str_replace("'", "&#39;", $value);
        			$tabela = "cms_translater_admin_" . $key_temp[2];
       				$sql = "UPDATE $tabela SET translater = '$value', actualizado = '" . date("Y-m-d H:i:s") . "' WHERE id = " . $key_temp[1];
       				//Goweb::dump($sql);
       				$db->query($sql);
        		}
        	}
        	
        }
        $this->view->links  =  $this->_links;
        $this->view->action  = translateAdmin('Tradu&ccedil;&otilde;es Backoffice');
        $this->view->section_title = translateAdmin('Tradu&ccedil;&otilde;es BackOffice');
        $this->view->section_singular = translateAdmin('Tradu&ccedil;&atilde;o BackOffice');
        $this->view->model  = $this->_configModel;
        
        $link_paginator = $this->_links['list'];
        $this->view->letter = '#';
        if ($letter){
            $link_paginator .= 'letter/'.$letter;
        } else {
            $this->view->letter_selected = '#';
        }
  
       
        $paginator = new Goweb_Paginator(Goweb::link( $link_paginator, 'page='),
                                         $this->_translaterModel->count(),
                                         $page,
                                         $row_por_pag,
                                         10);
                                                                     
        $this->view->paginator = $paginator;
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->view->paginator_output = $this->view->render('paginator.tpl');
        
        $langs = array();
        $traducoes_temp = array();
        $available = explode(',', $this->_config22->languages->available);
       
        foreach ($available as $lang) {
            $lang = preg_replace('/([^a-z0-9_])/i', '_', $lang);
        	$traducoes_temp[$lang] = array();
            $langs[$lang] = isset($this->_langsNames[$lang]) ? $this->_langsNames[$lang] : $lang;
        }
        //Goweb::dump($langs);
       // $langs['en'] = "Inglês";
        //$langs['es'] = "Espanhol";
        //$langs['fr'] = "Francês";
        
       
       $orderBy = 'texto ASC';
       
       $i = 0;
       $lang_1 = 'pt';
       
       foreach ($langs as $lang => $value) {
       			$tabela = "cms_translater_admin_$lang";
       			//$sql = "SELECT id, texto, translater FROM $tabela ORDER BY $orderBy LIMIT  " . ($paginator->getRowsPerPage() * $paginator->getPage() - $paginator->getRowsPerPage()) . ', ' . $paginator->getRowsPerPage();
       			$sql = "SELECT id, texto, translater FROM $tabela ";
       			if ($letter){
       			    $sql .= ' where ';
                    $sql .= $tabela.'.texto LIKE "'.$letter.'%"';
                    $sql .= ' OR ';
                    $sql .= $tabela.'.texto LIKE "'.strtolower($letter).'%"';
       			}
       			
       			$sql .= " ORDER BY $orderBy LIMIT  " . ($paginator->getRowsPerPage() * $paginator->getPage() - $paginator->getRowsPerPage()) . ', ' . $paginator->getRowsPerPage();
       			
       			$traducoes_temp[$lang] = $db->fetchAll($sql);
       			if($i == 0) $lang_1 = $lang;
       			$i++;
           	}
        $traducoes = array();
        for ($i = 0; $i < count($traducoes_temp[$lang_1]); $i++)
        {
        	//Goweb::dump($traducoes_temp[$lang_1][$i]);
        	$array_linha_temp = array();
        	
        	$array_linha_temp['texto'] =  html_entity_decode($traducoes_temp[$lang_1][$i]['texto'], ENT_NOQUOTES, CHARSET);
        	
        	foreach ($langs as $lang => $value){
        		if(isset($traducoes_temp[$lang][$i]['translater']))
    			$array_linha_temp[$lang] = html_entity_decode($traducoes_temp[$lang][$i]['translater'], ENT_NOQUOTES, CHARSET);
    			else
    			$array_linha_temp[$lang] = html_entity_decode($array_linha_temp['texto'], ENT_NOQUOTES, CHARSET);
        	}
        	
        	
        	$traducoes[$traducoes_temp[$lang_1][$i]['id']] = $array_linha_temp;
        } 
        goweb::loadClass('Zend_Cache');
        $cache = Zend_Registry::get('cache');
        $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
        
        $this->view->langs = $langs;
        $this->view->traducoes = $traducoes;
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->view->render('translater.tpl'); 
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
        
    }
    /**
     * Listagem de Utilizadores do Sistema
     */
    public function listUtilizadoresAction() {
        $this->_links['list'] = '/painel_goweb/list_utilizadores/';
        $this->_links['add'] = '/painel_goweb/add_utilizador/';
        $this->_links['edit'] = '/painel_goweb/edit_utilizador/id/';
        $this->_links['delete'] = '/painel_goweb/delete_utilizador/id/';
        $this->_links['deletelist'] = null;
        
        $this->_utilizadorModel = Goweb::getModelInstance('Sistema_Model_Utilizador', 'db');    
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Utilizadores'));
        $section->setTitleSingular(translateAdmin('Utilizador'));
        $section->setModel($this->_utilizadorModel);               
        $section->setListCols(array('nome', 'username', 'perfil', 'activo', 'criado'));
        $section->setSearchCols(array('username', 'nome'));
        $section->setOrdering('nome');

        $this->view->model  = $this->_configModel;
        $this->view->output = $this->_listGeneric($section, $this->view, false);        
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Adiciona um utilizador do Sistema
    */
    public function addUtilizadorAction() {    
        $this->_utilizadorModel = Goweb::getModelInstance('Sistema_Model_Utilizador', 'db');
        
        $this->_links['add'] = '/painel_goweb/add_utilizador/';
        $this->_links['save'] = '/painel_goweb/save_utilizador/';
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Utilizadores'));
        $section->setTitleSingular(translateAdmin('Utilizador'));
        $this->_utilizadorModel->where('perfil_id <> ?', '1');
        $section->setModel($this->_utilizadorModel);

        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->view->output = $this->_addGeneric($section, $this->view);        
        $this->_helper->viewRenderer->setRender('base');
    }
    
    /**
     * Edita um utilizador do sistema
    */
    public function editUtilizadorAction() {    
        $this->_utilizadorModel = Goweb::getModelInstance('Sistema_Model_Utilizador', 'db');
        
        $id = $this->_getParam('id');

        if (!$this->_validateId($id) || !$this->_utilizadorModel->find($id)) {            
            return $this->listUtilizadoresAction();
        }        
        
        $this->_links['edit'] = '/painel_goweb/edit_utilizador/id/' . $id . '/';
        $this->_links['save'] = '/painel_goweb/save_utilizador/id/' . $id . '/';
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Utilizadores'));
        $section->setTitleSingular(translateAdmin('Utilizador'));        
        $section->setModel($this->_utilizadorModel);

        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->view->output = $this->_editGeneric($section, $this->view);
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Salva um utilizador do sistema
    */
    public function saveUtilizadorAction() {                
        $this->_utilizadorModel = Goweb::getModelInstance('Sistema_Model_Utilizador', 'db');

        $this->_links['save'] = '/painel_goweb/save_utilizador/';

        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Utilizadores'));
        $section->setTitleSingular(translateAdmin('Utilizador'));
        $section->setModel($this->_utilizadorModel);

        $output = $this->_saveGeneric($section, $this->view);
        if (is_bool($output)) {
            if ($this->_request->submit) {
                return $this->listUtilizadoresAction();
            }
            if ($this->_request->submit_and_new) {
                return $this->addUtilizadorAction(true);
            }
            
        }
        
        
        
        $this->view->output = $output;
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Remove um utilizador do sistema
    */
    public function deleteUtilizadorAction() {        
        $this->_utilizadorModel = Goweb::getModelInstance('Sistema_Model_Utilizador', 'db');
        if (!$this->_validateId($this->_getParam('id')) || $this->_getParam('id') == '1' || !$this->_utilizadorModel->find($this->_getParam('id'))) {
            $this->_error = translateAdmin('Este Utilizador n&atilde;o pode ser removido.');
            return $this->listUtilizadoresAction();
        }
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Utilizadores'));
        $section->setTitleSingular(translateAdmin('Utilizador'));
        $section->setModel($this->_utilizadorModel);
        $this->_deleteGeneric($section, $this->view);
        return $this->listUtilizadoresAction();
    }

    /**
     * LIstagem dos Perfis dos Utilizadores do Sistema
    */
    public function listPerfisAction() {
        $this->_links['list'] = '/painel_goweb/list_perfis/';
        $this->_links['add'] = '/painel_goweb/add_perfil/';
        $this->_links['edit'] = '/painel_goweb/edit_perfil/id/';
        $this->_links['delete'] = '/painel_goweb/delete_perfil/id/';
        $this->_links['deletelist'] = null;
        
        $this->_perfilModel = Goweb::getModelInstance('Sistema_Model_Perfil', 'db');    
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Perfis'));
        $section->setTitleSingular(translateAdmin('Perfil'));
        $section->setModel($this->_perfilModel);               
        $section->setListCols(array('nome', 'activo', 'criado'));
        $section->setSearchCols(array('nome'));
        $section->setOrdering('nome');
        
        $this->view->model  = $this->_configModel;
        $this->view->output = $this->_listGeneric($section, $this->view, false);        
        $this->_helper->viewRenderer->setRender('base');
    }
    
    /**
     * Adiciona Perfis dos Utilizadores do Sistema
    */
    public function addPerfilAction() {    
        $this->_perfilModel = Goweb::getModelInstance('Sistema_Model_Perfil', 'db');
        $this->_moduloModel = Goweb::getModelInstance('Sistema_Model_Modulo', 'db');
        
        $this->_links['add'] = '/painel_goweb/add_perfil/';
        $this->_links['save'] = '/painel_goweb/save_perfil/';        
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Perfis'));
        $section->setTitleSingular(translateAdmin('Perfil'));
        $section->setModel($this->_perfilModel);
        $section->setTreeObject($this->_getPaginasTree());
        
        $this->_moduloModel->where('permissao=?', '1');
        $this->view->modulos = $this->_moduloModel->fetchAll();
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->_addGeneric($section, $this->view, null, 0, false, true, true, 'form_perfil.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Edita Perfis dos Utilizadores do Sistema
     */
    public function editPerfilAction() {
        $this->_perfilModel = Goweb::getModelInstance('Sistema_Model_Perfil', 'db');
        $this->_moduloModel = Goweb::getModelInstance('Sistema_Model_Modulo', 'db');
        $this->_permissaoModel = Goweb::getModelInstance('Sistema_Model_Permissao', 'db');
                
        $id = $this->_getParam('id');
        
        if (!$this->_validateId($id) || !$this->_perfilModel->find($id)) {            
            return $this->listPerfisAction();
        }

        $this->_links['edit'] = '/painel_goweb/edit_perfil/id/' . $id . '/';
        $this->_links['save'] = '/painel_goweb/save_perfil/id/' . $id . '/';
        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Perfis'));
        $section->setTitleSingular(translateAdmin('Perfil'));
        $section->setModel($this->_perfilModel);
        $section->setTreeObject($this->_getPaginasTree($id));
        
        $this->_permissaoModel->where('perfil_id=?', $id);
        $modulosPermissao = array();
        $permissoesRowset = $this->_permissaoModel->fetchAll();
        if ($permissoesRowset) {
            foreach ($permissoesRowset as $permissao) {
                $modulosPermissao[] = $permissao->modulo_id;
            }
        }
        $this->_moduloModel->where('permissao=?', '1');
        //$this->view->modulos = $this->_moduloModel->fetchAll();
        $this->view->modulos = $this->_getPaginasTreeModulos('back');
        //goweb::dump($this->view->modulos);
        $this->view->modulos_permissao = $modulosPermissao;
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->_editGeneric($section, $this->view, null, 0, true, true, 'form_perfil.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }   
    
    /**
     * Insert ou Update de Perfil de Utilizadores do Sistema
     */
    public function savePerfilAction() {
        $this->_perfilModel = Goweb::getModelInstance('Sistema_Model_Perfil', 'db');
        $this->_moduloModel = Goweb::getModelInstance('Sistema_Model_Modulo', 'db');
        $this->_permissaoModel = Goweb::getModelInstance('Sistema_Model_Permissao', 'db');
        
        $this->_links['save'] = '/painel_goweb/save_perfil/';      
        
        $id = $this->_getParam('id');

        if (!$this->_validateId($id) || !$this->_perfilModel->find($id)) {            
            $id = 0;
        }

        $modulosAcesso = $this->_request->modulos_acesso;
        if (!is_array($modulosAcesso)) {
            $modulosAcesso = array();            
        }
        
        $paginasAcesso = $this->_request->paginas_acesso;
        if (!is_array($paginasAcesso)) {
            $paginasAcesso = array();
        }

        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Perfis'));
        $section->setTitleSingular(translateAdmin('Perfil'));
        $section->setModel($this->_perfilModel);
        $section->setTreeObject($this->_getPaginasTree($id, $paginasAcesso));

        $modulosPermissao = array();

        if ($id > 0) {
            $this->_permissaoModel->where('perfil_id=?', $id);        
            $permissoesRowset = $this->_permissaoModel->fetchAll();
            if ($permissoesRowset) {
                foreach ($permissoesRowset as $permissao) {
                    $modulosPermissao[] = $permissao->modulo_id;
                }
            }
        }
        
        $this->_moduloModel->where('menu=?', '1');
        $this->_moduloModel->orWhere('nome=?', 'Cms');
        $this->view->modulos = $this->_moduloModel->fetchAll();
        $this->view->modulos_permissao = $modulosAcesso;

        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $output = $this->_saveGeneric($section, $this->view, null, 0, false, true, false, 'form_perfil.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);

        if ($this->_error == null) {
            // modulos com acesso
            $this->_permissaoModel->setUseCache();
            foreach ($modulosAcesso as $moduloId) {
                if (!in_array($moduloId, $modulosPermissao)) {
                    $this->_permissaoModel->reset();
                    $this->_permissaoModel->modulo_id = $moduloId;
                    $this->_permissaoModel->perfil_id = $id;
                    $this->_permissaoModel->save();
                }
            }

            if ($id > 0) {
                foreach ($modulosPermissao as $moduloId) {
                    if (!in_array($moduloId, $modulosAcesso)) {
                        $this->_permissaoModel->deleteWhere("modulo_id=$moduloId AND perfil_id=$id");
                    }
                }
            }
            $this->_permissaoModel->setUseCache(false);
            $this->_utilizadorModel = Goweb::getModelInstance('Sistema_Model_Utilizador', 'db');
            $this->_saveAcl('back');
            // paginas com acesso
            $paginasPermissao = array();
            if ($id > 0) {
                $this->_cmsPermissaoModel->where('perfil_id=?', $id);                        
                $paginasRowset = $this->_cmsPermissaoModel->fetchAll();
                if ($paginasRowset) {
                    foreach ($paginasRowset as $permissao) {
                        $paginasPermissao[] = $permissao->pagina_id;
                    }
                }
            }
            
            foreach ($paginasAcesso as $paginaId) {
                //if (!in_array($paginaId, $paginasPermissao) && $paginaId > 0) {
                if (!in_array($paginaId, $paginasPermissao)) {
                    $this->_cmsPermissaoModel->reset();
                    $this->_cmsPermissaoModel->pagina_id = $paginaId;
                    $this->_cmsPermissaoModel->perfil_id = $id;
                    $this->_cmsPermissaoModel->save();
                }
            }
            if ($id > 0) {
                foreach ($paginasPermissao as $paginaId) {
                    if (!in_array($paginaId, $paginasAcesso)) {
                        $this->_cmsPermissaoModel->deleteWhere("pagina_id=$paginaId AND perfil_id=$id");
                    }
                }
            }
            $this->_cmsPermissaoModel->setUseCache(false);
        }
        
        if (is_bool($output)) {
            if ($this->_request->submit) {
                return $this->listPerfisAction();
            }
            if ($this->_request->submit_and_new) {
                return $this->addPerfilAction(true);
            }
            if ($this->_request->submit_and_continue) {

                $model = $this->_utilizadorModel;

                if (!$this->_getParam($model->getPrimary())){
                    $this->_request->setParam($model->getPrimary(), $model->{$model->getPrimary()});
                    $this->_links['save'] .= $model->getPrimary() . '/' . $model->{$model->getPrimary()} . '/';
                }
                return $this->editPerfilAction();
            }
        }
        
        $this->view->output = $output;
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Remover Perfis dos Utilizadores do Sistema
     */
    public function deletePerfilAction() {
        $this->_perfilModel = Goweb::getModelInstance('Sistema_Model_Perfil', 'db', false);
        $this->_permissaoModel = Goweb::getModelInstance('Sistema_Model_Permissao', 'db', false);
        $this->_cmsPermissaoModel = Goweb::getModelInstance('Sistema_Model_CmsPermissao', 'db', false);
        if (!$this->_validateId($this->_getParam('id')) || $this->_getParam('id') == '1' || !$this->_perfilModel->find($this->_getParam('id'))) {
            $this->_error = translateAdmin('Este Perfil n&atilde;o pode ser removido.');
            return $this->listPerfisAction();
        }
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Perfis'));
        $section->setTitleSingular(translateAdmin('Perfil'));
        $section->setModel($this->_perfilModel);
        $this->_permissaoModel->deleteWhere("perfil_id='" . $this->_getParam('id') . "'");
        $this->_cmsPermissaoModel->deleteWhere("perfil_id='" . $this->_getParam('id') . "'");
        $this->_deleteGeneric($section, $this->view);
        return $this->listPerfisAction();
    }

    /**
     * Remover Perfis dos Utilizadores do Sistema
     */
    public function configAction() {
        $this->_links['save'] = '/painel_goweb/config/';
        $this->_links['update'] = '/painel_goweb/update_file_contents/';

        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Ficheiros de Configura&ccedil;&atilde;o'));
        $section->setTitleSingular(translateAdmin('Ficheiros de Configura&ccedil;&atilde;o'));
        Goweb::loadClass('Form_Edit', dirname(__FILE__));
        $form = new Form_Edit('form_edit', $this->_links['save']);
        if ($this->_request->isPost()){
            $ficheiro = $this->_request->ficheiros;
            if (strpos($ficheiro, 'config.ini') === false) return false;
            if (file_exists(ROOT_PATH . '/' . $ficheiro)){
                $ficheiro = ROOT_PATH . '/' . $ficheiro;
            }elseif (file_exists(APPLICATION_PATH . '/' . $ficheiro)){
                $ficheiro = APPLICATION_PATH . '/' . $ficheiro;
            } else {
                return false;
            }
            if (is_writable($ficheiro)) {
                $writeFile = fopen($ficheiro, "w+");
                $saveData = $this->_request->edit;
                $saveData = stripslashes($saveData);
                if (fwrite($writeFile,$saveData)) {
                    fclose($writeFile);
                    $this->_message = translateAdmin('{{section}} foi actualizado(a) com sucesso.', $this->_request->ficheiros);
                } else {
                    $this->_error = translateAdmin('N&atilde;o foi poss&iacute;vel gravar o ficheiro {{ficheiro}}.', $this->_request->ficheiros);
                }
            } else {
                $this->_error = translateAdmin('O ficheiro {{ficheiro}} n&atilde;o tem permiss&otilde;es de escrita.', $this->_request->ficheiros);
            }
            $form->ficheiros->value = $this->_request->ficheiros;
            $form->edit->value = file_get_contents($ficheiro);
        } else {
            $ficheiro = 'config.ini';
            $form->ficheiros->value = $ficheiro;
            $ficheiro = ROOT_PATH . '/' . $ficheiro;
            $form->edit->value = file_get_contents($ficheiro);
        }
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->links            = $this->_links;
        $this->view->action           = translateAdmin('Dashboard');
        $this->view->sections         = $this->_sections;
        $this->view->section_title    = $section->getTitle();
        $this->view->section_singular = $section->getTitleSingular();
        $this->view->error            = $this->_error;
        $this->view->form             = $form;
        $this->view->message          = $this->_message;
        $this->view->output           = $this->view->render('config.tpl');        
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }
    
    /**
     * Actualizar conteúdo dos ficheiros config
     *
     */
    public function updateFileContentsAction(){
        $this->_helper->viewRenderer->setNoRender();
        if (!$this->_request->isAjax()) return false;
        if (!headers_sent()) { header('Content-Type:text/html; charset=' . CHARSET); }
        $ficheiro = $this->_request->ficheiro;
        if (strpos($ficheiro, 'config.ini') === false) return false;
        if (file_exists(ROOT_PATH . '/' . $ficheiro)){
            $ficheiro = ROOT_PATH . '/' . $ficheiro;
        }elseif (file_exists(APPLICATION_PATH . '/' . $ficheiro)){
            $ficheiro = APPLICATION_PATH . '/' . $ficheiro;
        } else {
            return false;
        }
       	goweb::loadClass('Zend_Form_Element_Textarea');
       	$edit = new Zend_Form_Element_Textarea('edit');
        $edit->label = translateAdmin('Ficheiro');
        $edit->value = file_get_contents($ficheiro);
        $edit->setDecorators(array('ViewHelper', array()));
       	echo $edit->render();
       	
    }
    
    /**
     * Importações de catalogo
     *
     */
    public function importCatalogoAction(){
        if (!goweb::isReadable('Catalogo_Model_Produto', APPLICATION_PATH)){
            return $this->_forward('list');            
        }
        $this->_links['save'] = '/painel_goweb/import_catalogo/';

        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Importar Cat&aacute;logo'));
        $section->setTitleSingular(translateAdmin('Importar Cat&aacute;logo'));
        Goweb::loadClass('Form_Import', dirname(__FILE__));
        $form = new Form_Import('form_import', $this->_links['save']);
        if ($this->_request->isPost()){
            $mtime = microtime();
            $mtime = explode(" ",$mtime);
            $mtime = $mtime[1] + $mtime[0];
            $starttime = $mtime;
            
            $produtosCount = 1;
            // importar ........
            $element = 'ficheiro_upload';
            if (!$form->{$element}->isReceived() && !$form->{$element}->receive()) {
                throw new Goweb_Exception("Ocorreu um erro a gravar o ficheiro");
            }
            $ficheiroFullPatch = $form->{$element}->getFileName();
            require_once LIBRARY_PATH . '/External/excel_reader2.php';
            $data = new Spreadsheet_Excel_Reader($ficheiroFullPatch);
            
            /**
             * Remover os notices, código de PHP4 tem muitas vezes este tipo de problemas :)
             */
            $save = error_reporting();
            error_reporting(E_ALL ^ E_NOTICE);

            
            //echo $data->dump(true,true);
            $colunas = array();
            foreach ($form->getElementsNames() as $element){
                $elementValue = "";
                if($form->{$element}->getBelongsTo() && $this->_request->{$form->{$element}->getBelongsTo()} && isset($this->_request->{$form->{$element}->getBelongsTo()}[$element])){
                    $elementValue = $this->_request->{$form->{$element}->getBelongsTo()}[$element];
                    if ($elementValue){
                        $colunas[strtoupper($elementValue)] = $element;
                    }

                } else if ($this->_request->{$element}){
                    $elementValue = $this->_request->{$element};
                }
                if ($elementValue) $form->{$element}->value = $elementValue;
            }
            
            $count = $data->rowcount();
            
            
            
            $startCount = 1;
            if ($this->_request->label_campos){
                $startCount = 2;
            }
            $catalogoModel = Goweb::getModelInstance('Catalogo_Model_Produto', 'db', false);
            $cache = Zend_Registry::get('cache');
            $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
            $line = $startCount;
            for ($line = $startCount; $line<=$count; $line++){
                if (in_array($catalogoModel->getPrimary(), $colunas) && $key = array_search($catalogoModel->getPrimary(), $colunas)){
                    $catalogoModel->find($data->val($line, $key));
                }
                if ($this->_request->referencia_as_key && in_array('referencia', $colunas) && $key = array_search('referencia', $colunas)){
                    $catalogoModel->findBy('referencia', $data->val($line, $key));
                }
                
                $ficha=false;
                $fichasModel=array();
                foreach ($colunas as $col => $key){
                    preg_match('/ficha_id(\d+)_element(\d+)/', $key, $matches);
                    if (count($matches) == 0){
                        $content = $data->val($line,$col);
                        if(!mb_check_encoding($content, 'UTF-8') || !($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {
                            $content = mb_convert_encoding($content, 'UTF-8');
                        }
                        $value = $this->_convertExcelLine($content, $this->_request->convert_html, $this->_request->convert_newline);
                        $catalogoModel->{$key} = $value;
                    } else {
                        $catalogoModel->ficha_id = $matches[1];
                    }
                }
                if ($catalogoModel->save()){
                    $produtosCount++;
                    $produtoId=$catalogoModel->{$catalogoModel->getPrimary()};
                } else {
                    continue;
                }
                
                foreach ($colunas as $col => $key){
                    preg_match('/ficha_id(\d+)_element(\d+)/', $key, $matches);
                    $value = $this->_convertExcelLine($data->val($line,$col), $this->_request->convert_html, $this->_request->convert_newline);
                    if ($value && count($matches) > 0){
                        $fichaId= $matches[1];
                        if (!array_key_exists($fichaId, $fichasModel)){
                            $fichasModel[$fichaId] = $this->_getFichaModel($fichaId);
                            $fichasModel[$fichaId]->where($fichasModel[$fichaId]->getTableName().'.ficha_id=?', $fichaId);
                            $fichasModel[$fichaId]->where($fichasModel[$fichaId]->getTableName().'.produto_id=?', $produtoId);
                            $result = $fichasModel[$fichaId]->fetchAll();
                            if ($result){
                                $fichasModel[$fichaId]->find($result->current()->{$fichasModel[$fichaId]->getPrimary()});
                            }
                            $fichasModel[$fichaId]->ficha_id = $fichaId;
                            $fichasModel[$fichaId]->produto_id = $produtoId;
                        }
                        $fichasModel[$fichaId]->{'element_' . $matches[2]} = $value;
                        
                    }
                    
                }
                if (count($fichasModel) > 0){
                    foreach ($fichasModel as $fichaModel){
                        $fichaModel->save();
                        $fichaModel->reset();
                    }
                }
                $catalogoModel->reset();
            }
            
            
            error_reporting($save);
            $cache = Zend_Registry::get('cache');
            $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
            $element = 'ficheiro_upload';
            unlink($form->{$element}->getFileName());
            $mtime = microtime();
            $mtime = explode(" ",$mtime);
            $mtime = $mtime[1] + $mtime[0];
            $endtime = $mtime;
            $totaltime = ($endtime - $starttime);
            $this->_message = translateAdmin('Demorou {{tempo}} segundos a importar {{produtos}} produtos', number_format($totaltime, 2, '.', ''), $produtosCount);
            
        }
        $form->render();
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->links            = $this->_links;
        $this->view->action           = translateAdmin('Dashboard');
        $this->view->sections         = $this->_sections;
        $this->view->section_title    = $section->getTitle();
        $this->view->section_singular = $section->getTitleSingular();
        $this->view->error            = $this->_error;
        $this->view->form             = $form;
        $this->view->message          = $this->_message;
        $this->view->output           = $this->view->render('form.tpl');        
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }

    protected function _convertExcelLine($string, $html = false, $newLine = false) {
        if ($html) $string = htmlentities($string, ENT_COMPAT, CHARSET, false);
        if ($newLine) $string = str_replace(array("\n\r","\r\n","\n","\r"), '<br />', $string);
        return $string;
    }
    
    /**
     * Obter o model duma ficha do catalogo
     *
     * @param int $fichaId
     * @return Goweb_Db_Model
     */
    protected function _getFichaModel($fichaId) {
        $bareboneModel = Goweb::getModelInstance('Catalogo_Model_Barebone', 'db');
        $bareboneModel->setTableName('catalogo_ficha_id_' . $fichaId . '_' . $bareboneModel->getLang());
        $bareboneModel->setTablePrefix('catalogo_ficha_id_' . $fichaId);
        $this->_elementModel = Goweb::getModelInstance('Catalogo_Model_Element', 'db', false);
        $this->_elementModel->where($this->_elementModel->getTableName() . '.ficha_id=?', $fichaId);
        $rowset = $this->_elementModel->fetchAll();
        if (!$rowset) {
            return $bareboneModel;
        }
        foreach ($rowset as $row) {
            $params = array();
            $nome = 'element_' . $row->id;
            $params['label'] = $row->label;
            $params['notnull'] = false;
            if ($row->element == 'text') {
                if ($row->size > 0) {
                    $params['maxlength'] = $row->size;
                }
                $bareboneModel->{$nome} = $bareboneModel->Char($params);
            } elseif ($row->element == 'textarea') {
                $bareboneModel->{$nome} = $bareboneModel->Text($params);
            } else {
                // no caso de ser checkbox, radio ou select é guardado apenas o valor
                $params['maxlength'] = '200';
                $bareboneModel->{$nome} = $bareboneModel->Char($params);
            }
        }
        return $bareboneModel;
    }
    
    
    /**
     * Devolve um objecto Goweb_Js_Tree - monta a arvore dos modulos
     *
     * @param integer
     * @param array
     *
     * @return Goweb_Js_Tree
    */
    protected function _getPaginasTreeModulos($type = 'front') {
        $this->_moduloModel = Goweb::getModelInstance('Sistema_Model_Modulo', 'db');
        
        
        Goweb::loadClass('Goweb_Js_Tree');
        Goweb::loadClass('Goweb_Js_Tree_Node');

        $tree = new Goweb_Js_Tree('modulos_acesso');
        $tree->useSelection = false;
        $tree->setExpand(false);
        

        $node = new Goweb_Js_Tree_Node(0, -1, translateAdmin('Raiz'));
        $tree->addNode($node);
        
        $paginas = $this->_moduloModel->fetchAll();
        $actionModel = Goweb::getModelInstance('Sistema_Model_Action', 'db', false);

        if ($paginas) {
            $treeValue = array();
            if ($this->_getParam('id') && $this->_validateId($this->_getParam('id'))){
                if (strcmp($type, 'back') == 0){
                    $aclModel = Goweb::getModelInstance('Acl_Model_Backoffice', 'db');
                } else {
                    $aclModel = Goweb::getModelInstance('Acl_Model_Frontoffice', 'db');
                }
                $aclModel->where('perfil_id = ?', $this->_getParam('id'));
                $aclResult = $aclModel->fetchAll();
                if ($aclResult){
                    foreach ($aclResult as $item){
                        $treeValue[] = 'controller_' . $item->controller . '_action_' . $item->action;
                    }
                }
            }

            foreach ($paginas as $pagina) {
                if (strcmp($type, 'back') == 0){
                    $controllerPath = ADMIN_PATH;
                } else {
                    $controllerPath = APPLICATION_PATH;
                }
                $accoes = array();
                if (file_exists($controllerPath . '/' . $pagina->nome . '/Controller.php')){
                    $accoes = $this->_getClassActions($controllerPath . '/' . $pagina->nome . '/Controller.php');
                }
                if (file_exists($controllerPath . '/' . $pagina->nome . '/GenericController.php')){
                    $accoes =  array_merge($accoes, $this->_getClassActions($controllerPath . '/' . $pagina->nome . '/GenericController.php'));
                }
                if (file_exists(APPLICATION_PATH . '/' . $pagina->nome . '/Admin.php')){
                    $accoes = array_merge($accoes, array('add', 'list', 'edit', 'save', 'delete', 'deletelist'));
                }
                if ($accoes && count($accoes)>1){
                    $node = new Goweb_Js_Tree_Node('controller_' . $pagina->nome, 0, $pagina->titulo);
                    $node->form_element = 'checkbox';
                    $tree->addNode($node);
                    foreach ($accoes as $accao){
                        $accaoTitulo = $accao;
                        $actionModel->where('modulo_id = ?', $pagina->id);
                        $actionModel->where('nome = ?', $accao);
                        $result = $actionModel->fetchAll();
                        if ($result){
                            $accaoTitulo = $result->current()->titulo;
                        }
                        $node = new Goweb_Js_Tree_Node(	'controller_' . $pagina->nome . '_action_' . $accao,
                            							'controller_' . $pagina->nome,
                                                        $accaoTitulo);
                        $node->form_element = 'checkbox';
                        if (in_array('controller_' . $pagina->nome . '_action_' . $accao, $treeValue)) {
                            $node->form_checked = true;
                        }
                        $tree->addNode($node);

                    }
                }
                }
            }


        return $tree;
    }
    
    /**
     * Obter as acções de um controller
     *
     * @param String $file controller
     * @return array com as acções de um controller
     */
    protected function _getClassActions($file){
        if (!file_exists($file)) return array();
        $arr_methods = array();
        $arr = file($file);
        foreach ($arr as $line)
        {
            if (ereg ('function ([_A-Za-z0-9]+)', $line, $regs)){
                /**
                 * ignorar metodos começados por _ e que não seja Action
                 */
                if (substr($regs[1],0,1) !== '_' && substr($regs[1],-6) === 'Action')
                $arr_methods[] = substr($regs[1],0,-6);
            }
        }
        return $arr_methods;
    }

    /**
     * Devolve um objecto Goweb_Js_Tree - monta a arvore
     *
     * @param integer
     * @param array
     *
     * @return Goweb_Js_Tree
    */
    protected function _getPaginasTree($perfilId = 0, $permissoes = array()) {
        $this->_cmsPermissaoModel = Goweb::getModelInstance('Sistema_Model_CmsPermissao', 'db', false);
        $this->_paginaModel = Goweb::getModelInstance('Cms_Model_Pagina', 'db', false);
        
        Goweb::loadClass('Goweb_Js_Tree');
        Goweb::loadClass('Goweb_Js_Tree_Node');

        $tree = new Goweb_Js_Tree('paginas_acesso');
        $tree->useLines = false;
        $tree->useSelection = false;
        $tree->setExpand(true);

        if ($perfilId > 0 && count($permissoes) == 0) {
            $this->_cmsPermissaoModel->where('perfil_id=?', $perfilId);
            $permissoesRowset = $this->_cmsPermissaoModel->fetchAll();
            if ($permissoesRowset) {
                foreach ($permissoesRowset as $permissao) {
                    $permissoes[] = $permissao->pagina_id;
                }
            }
        }
        $node = new Goweb_Js_Tree_Node(0, -1, translateAdmin('Raiz'));
        $node->form_element = 'checkbox';
        if (in_array("0", $permissoes)) {
            $node->form_checked = true;
        }
        $tree->addNode($node);
        
        $this->_paginaModel->where($this->_paginaModel->getTableName() . '.sistema=?', '0');        
        $paginas = $this->_paginaModel->fetchAll();

        if ($paginas) {
            foreach ($paginas as $pagina) {
                $node = new Goweb_Js_Tree_Node($pagina->id,
                                               $pagina->pai_id,
                                               $pagina->titulo);
                $node->form_element = 'checkbox';
                if (in_array($pagina->id, $permissoes)) {
                    $node->form_checked = true;
                }
                $tree->addNode($node);
            }
        }

        return $tree;
    }
    
    /**
     * Gravar ACL
     *
     * @param string $type front|back
     */
    protected function _saveAcl($type = 'front'){
        $perfil_id = $this->_getParam($this->_utilizadorModel->getPrimary());
        if (strcmp($type, 'back') == 0){
            $aclModel = Goweb::getModelInstance('Acl_Model_Backoffice', 'db');
        } else {
            $aclModel = Goweb::getModelInstance('Acl_Model_Frontoffice', 'db');
        }
        $aclModel->setUseCache();

        $aclModel->deleteWhere($aclModel->getAdapter()->quoteInto('perfil_id = ?', $perfil_id));
        if ($this->_request->modulos_acesso
                && is_array($this->_request->modulos_acesso)
                && count($this->_request->modulos_acesso)>0){

            $controllers = array();
            foreach ($this->_request->modulos_acesso as $acesso){
                preg_match_all("/controller_(.*)_action_(.*)/i", $acesso, $match);
                if (!isset($match[1][0]) || !isset($match[2][0])) continue;
                $controller = $match[1][0];
                $action = $match[2][0];

                $aclModel->perfil_id  = $perfil_id;
                $aclModel->controller = $controller;
                $aclModel->action     = $action;
                $aclModel->save();
                $aclModel->reset();

            }

        }
        $aclModel->setUseCache(true);
    }
    
    /**
     * Publicar Site pelo backoffice
     *
     */
    public function publicarSiteAction(){
        $this->_links['save'] = '/painel_goweb/publicar_site/';

        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Publicar Site'));
        $section->setTitleSingular(translateAdmin('Publicar Site'));
        if ($this->_request->isPost()){
            if ($this->_request->publicar){
                if (is_file(CACHE_PATH . '/hide_site')){
                    @unlink(CACHE_PATH . '/hide_site');
                }
            } else {
                if (!is_file(CACHE_PATH . '/hide_site')){
                    @touch(CACHE_PATH . '/hide_site');
                }
            }
        }
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->links            = $this->_links;
        $this->view->action           = translateAdmin('Dashboard');
        $this->view->sections         = $this->_sections;
        $this->view->section_title    = $section->getTitle();
        $this->view->section_singular = $section->getTitleSingular();
        $this->view->error            = $this->_error;
        $this->view->message          = $this->_message;
        $this->view->output           = $this->view->render('publicar-site.tpl');        
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }
    
    public function searchAction(){
        $this->_links['save'] = '/painel_goweb/search/';

        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Manuten&ccedil;&atilde;o de pesquisa'));
        $section->setTitleSingular(translateAdmin('Manuten&ccedil;&atilde;o de pesquisa'));
        Goweb::loadClass('Form_Model', dirname(__FILE__));
        $form = new Form_Model('form_model', $this->_links['save']);
        if ($this->_request->isPost()){
            ini_set("max_execution_time", "0");
            $mtime = microtime();
            $mtime = explode(" ",$mtime);
            $mtime = $mtime[1] + $mtime[0];
            $starttime = $mtime;
            $modelName = $this->_request->getPost('model');
            goweb::loadModel($modelName);
            $model = new $modelName();
            $rows_per_page = 100;
            $totalCount = $model->count();
            $totalPages=(int) ceil($totalCount / $rows_per_page);
        	
            for ($page = 1; $page<=$totalPages; $page++){
                $model->limitPage($page, $rows_per_page);
                $result = $model->fetchAll(array('id'));
                foreach ($result as $item){
                    $model->find($item->id);
                    $model->forceSearchRebuild();
                }
            }
            foreach ($this->_session->langs as $lang){
                try {
                    $gowebSearch = new Zend_Search_Lucene(ROOT_PATH. '/cache/search/' . $lang);
                } catch (Exception $e){
                    $gowebSearch = new Zend_Search_Lucene(ROOT_PATH. '/cache/search/' . $lang, true);
                }
                $gowebSearch->optimize();
            }
            $mtime = microtime();
            $mtime = explode(" ",$mtime);
            $mtime = $mtime[1] + $mtime[0];
            $endtime = $mtime;
            $totaltime = ($endtime - $starttime);
            $this->_message = 'Demorou ' . number_format($totaltime, 2) . ' segundos a actualizar os indices';
        }
        $this->view->form             = $form;
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->links            = $this->_links;
        $this->view->action           = translateAdmin('Dashboard');
        $this->view->sections         = $this->_sections;
        $this->view->section_title    = $section->getTitle();
        $this->view->section_singular = $section->getTitleSingular();
        $this->view->error            = $this->_error;
        $this->view->message          = $this->_message;
        $this->view->output           = $this->view->render('config.tpl');        
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }
    
    public function updateAction(){
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        //$this->_helper->viewRenderer->setNoRender();
        goweb::loadClass('Goweb_Updater');
        $updater = new Goweb_Updater();
        if ($updater->isToUpdate()){
            $updater->extract();
            $filesToUpdate = $updater->compareMd5($updater->getMd5(CACHE_PATH . '/update/tmp/'));
            if (isset($_GET['progress'])) {
                $this->noRender();
                set_error_handler(create_function('$errno,$errstr', 'return false;'));
                $updater->update($filesToUpdate);
                restore_error_handler();
                die();
            }
        }
        
    }

    /**
     * Acao executada se nenhuma outra acao for especificada
     */
    public function indexAction(){
        return $this->_forward('dashboard');
    }
    

}
