Source for file modulo.classe.php

Documentation is available at modulo.classe.php

  1. <?php
  2.     /**
  3.      * modulo.classe.php
  4.      * 
  5.      * Faz inclusão de módulos validando e limpando $_REQUEST
  6.      *
  7.      * @copyright 2008 Soomp
  8.      * @author Marcio Merlone <mmerlone@gmail.com>
  9.      * @version 1.0
  10.      * @since 11/12/2006
  11.      * @package Soomp
  12.      */
  13.     /* $Id: modulo.classe.php,v 1.34 2007/05/29 20:38:34 mmerlone Exp $ */
  14.  
  15.     require_once(CFG_LOCAL_FRAMEWORK.'stdio.classe.php');
  16.     /**
  17.      * Faz a pré-carga de módulos, verifica permissões e executa o módulo
  18.      */
  19.     class modulo extends stdio{
  20.  
  21.         /**
  22.          * @var array $arrModulos Armazena os módulos disponíveis cfme. $CFG_MODULOS.
  23.          */
  24.         protected $arrModulos = array();
  25.         /**
  26.          * @var string $strModule Armazena o nome do modulo $_GET['m'] solicitado
  27.          */
  28.         protected $strModule = null;
  29.         /**
  30.          * @var object $objConfig Objeto de configuração do módulo
  31.          */
  32.         protected $objConfig;
  33.         /**
  34.          * @var string $strAcao Define a ação para a qual desejamos saber se há permissão
  35.          */
  36.         protected $strAcao = '';
  37.         /**
  38.          * @var string $strPath Nome completo do arquivo do módulo
  39.          */
  40.         protected $strPath = null;
  41.         /**
  42.          * @var array $arrStylesScripts Armazena as folhas de estilo (css)
  43.          *  e scripts (js) de cada módulo/ação
  44.          */
  45.         protected $arrStylesScripts = array('css' => array()'js' => array());
  46.         /**
  47.          * @var array $arrInstances Armazena os objetos de módulos controladores já instanciados
  48.          *  <code>
  49.          *  $this->arrInstances = array('usuario' => (object) $usuario, 'grupo' => (object) $grupo, ...);
  50.          *  </code>
  51.          */
  52.         protected $arrInstances = array();
  53.         /**
  54.          * @var string $template_dir Caminho para os templates do módulo
  55.          */
  56.         private $template_dir null;
  57.         /**
  58.          * @var string $compile_dir Caminho para compilação dos templates
  59.          */
  60.         private $compile_dir null;
  61.         /**
  62.          * @var string $prev_template_dir Caminho para os templates anterior ao módulo
  63.          */
  64.         private $prev_template_dir null;
  65.         /**
  66.          * @var string $prev_compile_dir Caminho para compilação dos templates anterior ao módulo
  67.          */
  68.         private $prev_compile_dir null;
  69.  
  70.         /**
  71.          * Construtor.
  72.          * @param array $CFG_MODULOS array com os modulos ativos no sistema (config.php)
  73.          */
  74.         public function __construct(&$CFG_MODULOS false){
  75.             if($CFG_MODULOS){
  76.                 $this->arrModulos = $CFG_MODULOS;
  77.             }
  78.         }
  79.  
  80.         /**
  81.          * Processa a requisição executando o método com nome $_GET['a'] definido
  82.          * na classe controladora do módulo $_GET['m'] solicitado.
  83.          */
  84.         protected function run(){
  85.  
  86.             $this->setModule();
  87.             $this->loadConfig();
  88.             $this->_setAction();
  89.  
  90.             if(!empty($this->strModule&& !empty($this->strAcao)){
  91.                 if(!$this->endRequest($this->_runModule())){
  92.                     $this->msg(0'Erro ao executar o módulo.''erro');
  93.                 }
  94.  
  95.             }else{
  96.                 switch($this->strAcao){
  97.                     case 'login';
  98.                         $this->_login();
  99.                         break;
  100.  
  101.                     case 'logindo':
  102.                         $this->_logindo();
  103.                         break;
  104.  
  105.                     case 'logout':
  106.                         $this->_logout();
  107.                         break;
  108.  
  109.                     default:
  110.                         $this->_outputIndex();
  111.                         break;
  112.                 }
  113.                 exit;
  114.             }
  115.         }
  116.  
  117.         /**
  118.          * Exibe o formulário de login
  119.          */
  120.         private function _login(){
  121.             if($this->_smarty()){
  122.                 $this->outputHead();
  123.                 $this->smarty->assign('username'isset($_SESSION['wronglogin']$_SESSION['wronglogin'null);
  124.                 $this->smarty->display('usuarioLogin.tpl');
  125.                 $this->outputFoot();
  126.                 unset($_SESSION['wronglogin']);
  127.             }
  128.         }
  129.  
  130.         /**
  131.          * Encerra a sessão autenticada
  132.          */
  133.         protected function _logout(){
  134.             if (isset($_COOKIE[session_name()])){
  135.                 setcookie(session_name()session_id()time()-42000'/');
  136.             }
  137.             session_destroy();
  138.             session_name(CFG_PROJETO);
  139.             session_start();
  140.             session_regenerate_id();
  141.             $_SESSION array();
  142.  
  143.             if(is_object($this->objUser&& $this->objUser->{CFG_USUARIO_DB_PK>= 0){
  144.                 $this->msg(0'Logout efetuado com sucesso.''sucesso');
  145.                 $this->objUser new usuario();
  146.             }else{
  147.                 $this->msg(0'Sessão expirada.''sucesso');
  148.             }
  149.             $this->endRequest('index.php');
  150.             break;
  151.         }
  152.  
  153.         /**
  154.          * Processa os dados de autenticação do formulário de login
  155.          */
  156.         private function _logindo(){
  157.             $u new usuario();
  158.             $u->Load($_POST[CFG_USUARIO_DB_USERNAME]);
  159.     
  160.             if($u->Auth($_POST[CFG_USUARIO_DB_SENHA])){
  161.                 $this->objUser $u;
  162.                 $this->objUser->ip $_SERVER['REMOTE_ADDR'];
  163.  
  164.                 if(property_exists($this->objUser'TS_LOGIN')){
  165.                     if($this->objUser->TS_LOGIN == '0000-00-00 00:00:00'){
  166.                         $strWelcome 'Este é seu primeiro acesso. Bem vindo.';
  167.                     }else{
  168.                         $strWelcome 'Seu último acesso foi em '.strftime('%c'strtotime($this->objUser->TS_LOGIN)).'.';
  169.                     }
  170.                 }
  171.  
  172.                 $this->msg(0'Login efetuado com sucesso. '.$strWelcome'sucesso');
  173.                 $this->objUser->TS_LOGIN date('Y-m-d H:i:s'time())// 2007-02-23 11:42:51
  174.                 $this->objUser->Save();
  175.     
  176.                 if(!is_null(CFG_MODULE_LOGIN_MODULE&& CFG_MODULE_LOGIN_MODULE!= '' && !is_null(CFG_MODULE_LOGIN_ACTION&& CFG_MODULE_LOGIN_ACTION != ''){
  177.                     $this->endRequest('index.php?m='.CFG_MODULE_LOGIN_MODULE.'&a='.CFG_MODULE_LOGIN_ACTION);
  178.                 }else{
  179.                     $this->endRequest('index.php');
  180.                 }
  181.     
  182.             }else{
  183.                 $this->msg(0'Usuario desconhecido ou senha incorreta.''erro');
  184.                 $_SESSION['wronglogin'$_POST[CFG_USUARIO_DB_USERNAME];
  185.                 $this->endRequest('index.php?a=login&s=401');
  186.             }
  187.             break;
  188.         }
  189.  
  190.         /**
  191.          * Exibe o template index.tpl
  192.          */
  193.         private function _outputIndex(){
  194.             if($this->_smarty()){
  195.                 $this->outputHead();
  196.                 $this->smarty->display('index.tpl')// Se não pediu nada mostra o index
  197.                 $this->outputFoot();
  198.             }
  199.         }
  200.         /**
  201.          * Exibe o cabeçalho HTML como DTD e etc.
  202.          * Caso exista, exibirá o css e/ou js do módulo/ação solicitados.
  203.          * Por ex.: index.php?m=usuario&a=lista irá exibir
  204.          * - usuario.lista.[css|js]
  205.          * - lista.[css|js]
  206.          * - usuario.[css|js]
  207.          */
  208.         public function outputHead(){
  209.  
  210.             if(isset($_GET['s'])){
  211.                 switch((int) $_GET['s']){
  212.  
  213.                     case 401:
  214.                         header('HTTP/1.0 401 Unauthorized');
  215.                         break;
  216.  
  217.                     case 404:
  218.                         header('HTTP/1.1 404 Not Found');
  219.                         header('Status: 404 Not Found');
  220.                         break;
  221.                 }
  222.             }
  223.  
  224.             if($this->_smarty()){
  225.                 $this->smarty->assign('USER',    $this->objUser);
  226.                 $this->smarty->assign('acao',    $this->strAcao);
  227.                 $this->smarty->assign('modulo',  $this->strModule);
  228.                 $this->smarty->assign('debugged'isset($_SESSION['debugged']$_SESSION['debugged'false);
  229.                 $this->smarty->display('head.tpl');
  230.                 $_SESSION['debugged'true;
  231.                 ob_flush()// Força o output dos buffers para o browser
  232.                 flush();
  233.             }
  234.         }
  235.  
  236.         /**
  237.          * Exibe o rodapé HTML, fecha tags, exibe mensagens de sistema, etc.
  238.          */
  239.         public function outputFoot(){
  240.             if($this->_smarty()){
  241.                 $this->smarty->outputMsgs();
  242.                 $this->smarty->display('foot.tpl');
  243.             }
  244.         }
  245.  
  246.         /**
  247.          * Define $this->strModule
  248.          * @param string $strModule nome do módulo
  249.          */
  250.         public function setModule($strModule false){
  251.  
  252.             if($strModule){
  253.                 if(isset($this->arrModulos[$strModule])){
  254.                     $this->strModule $strModule;
  255.                 }else{
  256.                     $this->strModule null;
  257.                     $this->msg(0'Modulo desconhecido: "'.$strModule.'"''erro');
  258.                 }
  259.  
  260.             }elseif(isset($_GET['m']&& !empty($_GET['m'])){
  261.                 if(isset($this->arrModulos[$_GET['m']])){
  262.                     $this->strModule $_GET['m'];
  263.                 }else{
  264.                     header('HTTP/1.1 404 Not Found');
  265.                     header('Status: 404 Not Found');
  266.                     $this->strModule null;
  267.                     $this->msg(0'Modulo desconhecido: "'.$_GET['m'].'"''erro');
  268.                 }
  269.  
  270.             }elseif(!is_null(CFG_MODULE_DEFAULT_MODULE)){
  271.                 if(isset($this->arrModulos[CFG_MODULE_DEFAULT_MODULE])){
  272.                     $this->strModule CFG_MODULE_DEFAULT_MODULE;
  273.                 }else{
  274.                     header('HTTP/1.1 404 Not Found');
  275.                     header('Status: 404 Not Found');
  276.                     $this->strModule null;
  277.                     $this->msg(0'Erro de configuração, modulo "'.CFG_MODULE_DEFAULT_MODULE.'" desconhecido. Verifique CFG_MODULE_DEFAULT_MODULE no config.php do módulo.''erro');
  278.                 }
  279.  
  280.             }else{
  281.                 $this->strModule null;
  282.             }
  283.             $this->strPath !is_null($this->strModule&& isset($this->arrModulos[$this->strModule]$this->arrModulos[$this->strModulenull;
  284.         }
  285.  
  286.         /**
  287.          * Lê a configuração do módulo
  288.          * @param string $strPath caminho para o módulo com o config.php
  289.          */
  290.         public function loadConfig($strPath false){
  291.             if($strPath){
  292.                 $this->strPath $strPath;
  293.             }
  294.             if($this->strPath){
  295.                 require_once($this->strPath.'/config.php');
  296.                 $strConfName $this->strModule.'_conf';
  297.                 $this->objConfig new $strConfName();
  298.                 require_once(CFG_LOCAL_FRAMEWORK.'idioma.classe.php');
  299.                 $idioma  idioma::getInstance();
  300.                 foreach($this->objConfig->actions as &$action){
  301.                     if(is_array($action[1])){
  302.                         $action[1convertCharset($idioma->getString($action[1]));
  303.                     }
  304.                 }
  305.                 if(!$this->objConfig->active){
  306.                     $this->objConfig $this->strPath $this->strModule null;
  307.                     $this->msg(0'Módulo indisponível. Contate o administrador do sistema.''erro');
  308.                 }
  309.                 return $this->objConfig;
  310.             }
  311.         }
  312.  
  313.         /**
  314.          * Overload de propriedades privadas
  315.          * @param string $var nome da propriedade
  316.          * @param mixed $value valor da propriedade
  317.          */
  318.         private function __set($var$value){
  319.             $this->$var $value;
  320.         }
  321.         
  322.         /**
  323.          * Overload de propriedades privadas
  324.          * @param string $var nome da propriedade
  325.          * @return mixed valor da propriedade
  326.          */
  327.         private function __get($var){
  328.             return $this->$var;
  329.         }
  330.  
  331.         /**
  332.          * Define $this->strAcao
  333.          */
  334.         private function _setAction(){
  335.             if(isset($_GET['a']&& !empty($_GET['a'])){
  336.  
  337.                 $arrAcoesAuth array('login' => 1'logindo' => 1'logout' => 1);
  338.                 
  339.                 if(isset($arrAcoesAuth[$_GET['a']]|| ($this->strPath && isset($this->objConfig->actions[$_GET['a']]))){
  340.                     $this->strAcao $_GET['a'];
  341.                 }else{
  342.                     header('HTTP/1.1 404 Not Found');
  343.                     header('Status: 404 Not Found');
  344.                     $this->strAcao $this->strModule null;
  345.                     $this->msg(0'Ação desconhecida: "'.$_GET['a'].'"''erro');
  346.                 }
  347.  
  348.             }elseif(!is_null(CFG_MODULE_DEFAULT_ACTION)){
  349.                 if(isset($this->objConfig->actions[CFG_MODULE_DEFAULT_ACTION])){
  350.                     $this->strAcao CFG_MODULE_DEFAULT_ACTION;
  351.                 }else{
  352.                     header('HTTP/1.1 404 Not Found');
  353.                     header('Status: 404 Not Found');
  354.                     $this->strAcao $this->strModule null;
  355.                     $this->msg(0'Erro de configuração, ação "'.CFG_MODULE_DEFAULT_ACTION.'" desconhecida. Verifique CFG_MODULE_DEFAULT_ACTION no config.php do módulo.''erro');
  356.                 }
  357.  
  358.             }else{
  359.                 $this->strAcao 'lista';
  360.             }
  361.         }
  362.  
  363.         /**
  364.          * Procura e carrega arquivos css, js, etc em CFG_PATH.'web/*'
  365.          * Busca por arquivos no padrão <strModule>.<strAcao>.<tipo>, onde <tipo>
  366.          * pode ser 'js' ou 'css'
  367.          * Por ex.: index.php?m=usuario&a=lista deverá possuir um arquivo <tipo>
  368.          * no mesmo dir especificado com os nomes (em ordem):
  369.          * - usuario.lista.xxx
  370.          * - usuario.xxx
  371.          * - lista.xxx
  372.          * Serão usados TODOS OS ARQUIVOS encontrados.
  373.          */
  374.         private function _loadScriptsStyles(){
  375.  
  376.             if(isset($this->strModule&& isset($this->strAcao&& $this->_smarty()){
  377.  
  378.                 foreach(array('js''css'as $strTipo){
  379.  
  380.                     switch($strTipo){
  381.  
  382.                         case 'js':
  383.                             $strDir        CFG_PATH.'/web/j/';
  384.                             break;
  385.  
  386.                         case 'css':
  387.                             $strDir        CFG_PATH.'/web/c/';
  388.                             break;
  389.                     }
  390.     
  391.                     $arrFiles array($this->strModule.'.'.$this->strAcao.'.'.$strTipo,
  392.                                       $this->strModule.'.'.$strTipo,
  393.                                       $this->strAcao.'.'.$strTipo);
  394.  
  395.                     foreach($arrFiles as $file){
  396.                         if(!isset($this->arrStylesScripts[$strTipo][$this->strModule][$this->strAcao][$file])){
  397.                             if(is_file($strDir.$file)){
  398.                                 $this->arrStylesScripts[$strTipo][$this->strModule][$this->strAcao][$file$file;
  399.                             }
  400.                         }
  401.                     }
  402.                 }
  403.             }
  404.  
  405.         }
  406.  
  407.         /**
  408.          * Reconfigura os diretórios do smarty para o módulo
  409.          * Pode-se criar um diretório 't' no mesmo diretório do módulo para os
  410.          * templates do módulo.
  411.          * Pode-se criar um diretório 'templates_c' no mesmo diretório do módulo
  412.          * para os templates compilados do módulo
  413.          */
  414.         private function _configSmarty(){
  415.             if($this->_smarty()){
  416.                 $this->smarty->assign('modulo'$this->strModule);
  417.                 $dir dirname($this->strPath);
  418.     
  419.                 $this->prev_compile_dir $this->smarty->compile_dir
  420.                 if(is_dir($dir.'/templates_c')){
  421.                     $this->smarty->compile_dir $this->compile_dir $dir.'/templates_c/';
  422.                 }
  423.     
  424.                 $this->prev_template_dir $this->smarty->template_dir
  425.                 if(is_dir($dir.'/t')){
  426.                     $this->smarty->template_dir $this->template_dir $dir.'/t/';
  427.                 }
  428.                 $this->smarty->assign('csss',    isset($this->arrStylesScripts['css'][$this->strModule][$this->strAcao]&& !empty($this->arrStylesScripts['css'][$this->strModule][$this->strAcao]$this->arrStylesScripts['css'][$this->strModule][$this->strAcaoarray());
  429.                 $this->smarty->assign('scripts'isset($this->arrStylesScripts['js'][$this->strModule][$this->strAcao]&& !empty($this->arrStylesScripts['js'][$this->strModule][$this->strAcao]$this->arrStylesScripts['js'][$this->strModule][$this->strAcaoarray());
  430.             }
  431.         }
  432.  
  433.         /**
  434.          * Restaura as configurações prévias do smarty
  435.          */
  436.         private function _restoreSmarty(){
  437.             if($this->_smarty()){
  438.                 $this->smarty->compile_dir    $this->prev_compile_dir;
  439.                 $this->smarty->template_dir    $this->prev_template_dir;
  440.             }
  441.         }
  442.  
  443.         /**
  444.          * Carrega o módulo, verifica existência dos arrays de permissões
  445.          */
  446.         private function _runModule(){
  447.  
  448.             if($this->strModule){
  449.  
  450.                 $strModuleController 'c'.$this->strModule;
  451.  
  452.                 /**
  453.                  * Instancia o controlador caso ainda não esteja e o armazena em
  454.                  * $this->arrInstances[this->strModule]
  455.                  */
  456.                 if(!isset($this->arrInstances[$this->strModule]|| !is_object($this->arrInstances[$this->strModule])){
  457.                     require_once($this->strPath.'/'.$strModuleController.'.modulo.php');
  458.                     $this->arrInstances[$this->strModulenew $strModuleController();
  459.                 }
  460.  
  461.                 /**
  462.                  * Verifica se o módulo possui a propriedade $acoes
  463.                  */
  464.                 if($this->_checkModulo()){
  465.  
  466.                     require_once(CFG_LOCAL_FRAMEWORK.'perms.classe.php');
  467.                     $perms new perms();
  468.                     $bitsPermsModule = isset($this->objConfig->actions->permissions$this->objConfig->actions->permissions $perms->getBitsPerm($this->strModule);
  469.                     $perms->setBitsUser($this->objUser$bitsPermsModule);
  470.  
  471.                     $this->_loadScriptsStyles();
  472.  
  473.                     /**
  474.                      * Verifica nos grupos do usuário se o $acoes do modulo permite
  475.                      * acesso
  476.                      */
  477.                     if($perms->checkUser($this->objConfig->actions[$this->strAcao][0])){
  478.  
  479.                         /**
  480.                          * GO! GO! GO!
  481.                          * É aqui que o módulo é executado.
  482.                          */
  483.                         $this->_configSmarty();
  484.                         $retorno $this->arrInstances[$this->strModule]->{$this->strAcao}($this);
  485.                         $this->_restoreSmarty();
  486.  
  487.                     }else{
  488.                         if(defined('INDEX')){
  489.                             if (isset($_COOKIE[session_name()])){
  490.                                 $this->msg(0'Sem permissão para este recurso.''erro');
  491.                             }else{
  492.                                 $this->msg(0'Sessão expirada, favor efetuar novo login.''erro');
  493.                             }
  494.                             header('HTTP/1.0 401 Unauthorized');
  495.                             $this->redireciona(401)// Manda para o index.
  496.  
  497.                         }else{
  498.                             /**
  499.                              * @todo verificar se é interessante definir códigos
  500.                              * de erro para o ajax
  501.                              */
  502.                             $retorno false;
  503.                         }
  504.                     }
  505.  
  506.                     if(defined('AJAX')){
  507.                         require_once(CFG_LOCAL_FRAMEWORK.'/terceiros/json.classe.php');
  508.                         $objJsonConverter new Services_JSON();
  509.                         echo $objJsonConverter->encode($retorno);
  510.                         exit;
  511.                     }
  512.                     return $retorno;
  513.  
  514.                 }else{
  515.                     $this->msg(0'Modulo "'.$this->strModule.'" não implementa a ação solicitada, permissões ou nenhuma ação!'E_USER_NOTICE);
  516.                     $this->strModule null;
  517.                     return false;
  518.                 }
  519.             }else{
  520.                 return false;
  521.             }
  522.         }
  523.  
  524.         /**
  525.          * Verifica se a configuração da classe controladora do módulo está habilitada
  526.          * ($this->objConfig->active) e se possui as propriedades necessárias para execução:
  527.          * - Se possui ações (!empty($this->objConfig->actions))
  528.          * - Se existe $this->objConfig->actions[$_GET['a']]
  529.          * - Se existe o método $_GET['a'] em $this->arrInstances[$this->strModule]
  530.          */
  531.         private function _checkModulo(){
  532.             if($this->objConfig->active
  533.             && is_array($this->objConfig->actions)
  534.             && isset($this->objConfig->actions[$this->strAcao])
  535.             && method_exists($this->arrInstances[$this->strModule]$this->strAcao)){
  536.                 return true;
  537.             }else{
  538.                 $this->arrInstances[$this->strModulenull;
  539.                 return false;
  540.             }
  541.         }
  542.  
  543.     }
  544. ?>

Documentation generated on Sun, 09 Mar 2008 23:52:36 -0300 by phpDocumentor 1.4.0

SourceForge.net Logo Support This Project