Commit 40a440bb61ee5710a9d727e8b52b9889df0d3ef2

Authored by Eduardo Heinske
1 parent 7e58c999

Correção dos bugs na lista de processos expedidos, na acentuação dos interessado…

…s no destinatário, referência cruzada e Exibição do Download de Recibods
LEIAME.txt
... ... @@ -147,5 +147,6 @@ PROCEDIMENTOS PARA INSTALAÇÂO:
147 147  
148 148 17) O Barramento de PEN ao calcular os hashs para gerar recibos de tramite, leva em consideração a data/horário. Portanto é importante que todos os nós da aplicação esteja sincronizados com o NTP.br.
149 149 Este link pode ajudar a configurar conforme o SO utilizado: https://www.vivaolinux.com.br/artigo/Servidor-NTP-Configuracao-e-ajuste-de-data-e-hora
150   -
  150 +
  151 + 18) É altamente aconselhável deixar o arquivo .pem do certificado digital fora do path do apache (var/www/html)
151 152  
... ...
pen_procedimento_expedido_listar.php
... ... @@ -20,7 +20,7 @@ try {
20 20 $objFiltroDTO = new ProtocoloDTO();
21 21 $objFiltroDTO->setStrStaEstado(ProtocoloRN::$TE_BLOQUEADO);
22 22 $objFiltroDTO->setNumIdTarefaAtividade(ProcessoEletronicoRN::$TI_PROCESSO_ELETRONICO_PROCESSO_EXPEDIDO);
23   - $objFiltroDTO->setDistinct(true);
  23 + // $objFiltroDTO->setDistinct(true);
24 24 $objFiltroDTO->retDblIdProtocolo();
25 25 $objFiltroDTO->retStrProtocoloFormatado();
26 26  
... ... @@ -53,7 +53,7 @@ try {
53 53 if(!empty($arrObjProcessoExpedidoDTO)) {
54 54  
55 55 $arrObjProcessoExpedidoDTO = InfraArray::distinctArrInfraDTO($arrObjProcessoExpedidoDTO, 'IdProtocolo');
56   -
  56 +
57 57 $numRegistros = count($arrObjProcessoExpedidoDTO);
58 58 }
59 59 }
... ...
rn/EnviarReciboTramiteRN.php
... ... @@ -94,9 +94,6 @@ class EnviarReciboTramiteRN extends InfraRN
94 94 if($objTramite->situacaoAtual != ProcessoEletronicoRN::$STA_SITUACAO_TRAMITE_COMPONENTES_RECEBIDOS_DESTINATARIO) {
95 95 return;
96 96 }
97   -
98   -
99   -
100 97  
101 98 //TODO: Verificar necessidade de dessa validação
102 99 //Verificar se todos os componentes digitais foram obtidos e validados
... ... @@ -119,94 +116,10 @@ class EnviarReciboTramiteRN extends InfraRN
119 116 //}
120 117  
121 118 //TODO: Analisar necessidade do tratamento de datas abaixo já que todos os servidores que integrarem ao PEN deverão estar sincronizados
122   - //com o
123 119 $dthRecebimentoComponentesDigitais = $this->obterDataRecebimentoComponentesDigitais($objTramite);
124 120 $dthRecebimentoComponentesDigitais = $dthRecebimentoComponentesDigitais ?: date();
125 121 $dthRecebimento = gmdate("Y-m-d\TH:i:s.000\Z", InfraData::getTimestamp($dthRecebimentoComponentesDigitais));
126 122  
127   -// if($parArrObjComponenteDigitalDTO == null) {
128   -// $parArrObjComponenteDigitalDTO = $this->listarComponenteDigitalDTO($parNumIdTramite);
129   -// }
130   -// $arrHashConteudo = InfraArray::converterArrInfraDTO($parArrObjComponenteDigitalDTO, 'HashConteudo', null);
131   -// sort($arrHashConteudo);
132   -//
133   -// // @join_tec US008.11 (#23092)
134   -// if(empty($arrHashConteudo)) {
135   -// // Caso de retrasmição os componentes digitais não são reenviados, então
136   -// // não é gravado o recibo. Adicionamos alguma possição no array para
137   -// // gravar pelo menos um recibo.
138   -// $arrHashConteudo[] = '';
139   -// }
140   -
141   - //Busca os metadados do processo
142   - /* $objMetaRetorno = $this->objProcessoEletronicoRN->solicitarMetadados($numIdTramite);
143   -
144   - //Obtem os dados necessários para consultar os trâmites relacionados a unidade destinatário e ao processo recebido
145   - $parProtocolo = $objMetaRetorno->metadados->processo->protocolo;
146   - $parNumeroUnidadeDestino = $objMetaRetorno->metadados->destinatario->numeroDeIdentificacaoDaEstrutura;
147   - $parNumeroRepositorioEstruturas = $objMetaRetorno->metadados->destinatario->identificacaoDoRepositorioDeEstruturas;
148   -
149   - //Consulta os trâmites relacionados
150   - $arrObjTramites = new $this->objProcessoEletronicoRN->consultarTramites($parNumIdTramite, null, null, $parNumeroUnidadeDestino, $parProtocolo, $parNumeroRepositorioEstruturas);
151   - $arrObjTramites = is_array($arrObjTramites->tramitesEncontrados->tramite) ? $arrObjTramites->tramitesEncontrados->tramite : array($arrObjTramites->tramitesEncontrados->tramite);
152   -
153   - $arrTramitesAnteriores = array();
154   -
155   - foreach($arrObjTramite as $tramiteAntigo){
156   - if($tramiteAntigo->IDT != $parNumIdTramite){
157   - $arrTramitesAnteriores[] = $tramiteAntigo;
158   - }
159   - }
160   -
161   - $arrHashTramitesAnteriores = array();
162   -
163   - foreach($arrTramitesAnteriores as $tramiteAntigo){
164   -
165   - //Solicita os metadados desse trâmite
166   - $objMetaTramiteAntigo = $this->objProcessoEletronicoRN->solicitarMetadados($tramiteAntigo);
167   -
168   - //Transforma os documento em um array
169   - $arrDocumentosTramiteAntigo = is_array($objMetaTramiteAntigo->metadados->processo->documento) ? $objMetaTramiteAntigo->metadados->processo->documento : array($objMetaTramiteAntigo->metadados->processo->documento);
170   -
171   -
172   - }
173   -
174   -
175   - */
176   -
177   - /*
178   - $arrStrHashConteudo = array();
179   -
180   - $objMetaRetorno = $this->objProcessoEletronicoRN->solicitarMetadados($numIdTramite);
181   -
182   - $objMetaProcesso = $objMetaRetorno->metadados->processo;
183   -
184   - $arrObjMetaDocumento = is_array($objMetaProcesso->documento) ? $objMetaProcesso->documento : array($objMetaProcesso->documento);
185   -
186   - $objDTO = new ComponenteDigitalDTO();
187   - $objBD = new ComponenteDigitalBD($this->inicializarObjInfraIBanco());
188   -
189   - foreach($arrObjMetaDocumento as $objMetaDocumento) {
190   -
191   - $strHashConteudo = ProcessoEletronicoRN::getHashFromMetaDados($objMetaDocumento->componenteDigital->hash);
192   -
193   - $objDTO->setStrHashConteudo($strHashConteudo);
194   -
195   - if($objBD->contar($objDTO) > 0) {
196   -
197   - $arrStrHashConteudo[] = $strHashConteudo;
198   - }
199   - }
200   -
201   - return $arrStrHashConteudo;*/
202   -
203   - //$arrHashConteudo = $this->gerarReciboTramite($parNumIdTramite);
204   -
205   - /* foreach($parArrayHash as $strHashConteudo) {
206   -
207   - // @join_tec R003 S001 US036 (#3869)
208   - $this->cadastrarReciboTramiteRecebimento($strNumeroRegistro, $parNumIdTramite, $strHashConteudo);
209   - }*/
210 123  
211 124 $strReciboTramite = "<recibo>";
212 125 $strReciboTramite .= "<IDT>$parNumIdTramite</IDT>";
... ... @@ -221,8 +134,10 @@ class EnviarReciboTramiteRN extends InfraRN
221 134 }
222 135 $strReciboTramite .= "</recibo>";
223 136  
  137 + //Envia o Recibo de salva no banco
  138 + $hashAssinatura = $this->objProcessoEletronicoRN->enviarReciboDeTramite($parNumIdTramite, $dthRecebimento, $strReciboTramite);
  139 + $this->cadastrarReciboTramiteRecebimento($strNumeroRegistro, $parNumIdTramite, $hashAssinatura);
224 140  
225   - $this->objProcessoEletronicoRN->enviarReciboDeTramite($parNumIdTramite, $dthRecebimento, $strReciboTramite);
226 141 }
227 142  
228 143 private function obterDataRecebimentoComponentesDigitais($parObjTramite){
... ...
rn/ProcessoEletronicoRN.php
... ... @@ -1069,7 +1069,7 @@ class ProcessoEletronicoRN extends InfraRN {
1069 1069 }
1070 1070 }
1071 1071  
1072   - public function enviarReciboDeTramite($parNumIdTramite, $parDthRecebimento, $parStrReciboTramite)
  1072 + public function enviarReciboDeTramite($parNumIdTramite, $parDthRecebimento, $parStrReciboTramite)
1073 1073 {
1074 1074 try
1075 1075 {
... ... @@ -1080,8 +1080,6 @@ class ProcessoEletronicoRN extends InfraRN {
1080 1080 throw new InfraException("Erro ao obter chave privada do certificado digital.");
1081 1081 }
1082 1082  
1083   - // $recibo = $parStrReciboTramite;
1084   -
1085 1083  
1086 1084 openssl_sign($parStrReciboTramite, $strHashAssinatura, $objPrivatekey, 'sha256');
1087 1085 $strHashDaAssinaturaBase64 = base64_encode($strHashAssinatura);
... ... @@ -1092,9 +1090,10 @@ class ProcessoEletronicoRN extends InfraRN {
1092 1090 $parametro->dadosDoReciboDeTramite->dataDeRecebimento = $parDthRecebimento;
1093 1091 $parametro->dadosDoReciboDeTramite->hashDaAssinatura = $strHashDaAssinaturaBase64;
1094 1092  
1095   - // throw new InfraException('TESTE '.var_export($parametro, true)." DELIMITADOR ".$recibo);
1096 1093  
1097   - return $this->getObjPenWs()->enviarReciboDeTramite($parametro);
  1094 + $this->getObjPenWs()->enviarReciboDeTramite($parametro);
  1095 +
  1096 + return $strHashDaAssinaturaBase64;
1098 1097  
1099 1098 } catch (\SoapFault $fault) {
1100 1099  
... ...
rn/ReceberProcedimentoRN.php
... ... @@ -887,7 +887,7 @@ class ReceberProcedimentoRN extends InfraRN
887 887 $objInteressado = $arrObjInteressados[$i];
888 888 $objParticipanteDTO = new ParticipanteDTO();
889 889 $objParticipanteDTO->setStrSiglaContato($objInteressado->numeroDeIdentificacao);
890   - $objParticipanteDTO->setStrNomeContato($objInteressado->nome);
  890 + $objParticipanteDTO->setStrNomeContato(utf8_decode($objInteressado->nome));
891 891 $objParticipanteDTO->setStrStaParticipacao(ParticipanteRN::$TP_INTERESSADO);
892 892 $objParticipanteDTO->setNumSequencia($i);
893 893 $arrObjParticipantesDTO[] = $objParticipanteDTO;
... ... @@ -1102,7 +1102,7 @@ class ReceberProcedimentoRN extends InfraRN
1102 1102 $objProtocoloDTO->setStrDescricao(utf8_decode($objDocumento->descricao));
1103 1103 $objDocumentoDTO->setStrNumero(utf8_decode($objDocumento->descricao));
1104 1104 }else{
1105   - $objProtocoloDTO->setStrDescricao("");
  1105 + $objProtocoloDTO->setStrDescricao("");
1106 1106 $objDocumentoDTO->setStrNumero("");
1107 1107 }
1108 1108 //TODO: Avaliar regra de formação do número do documento
... ...
sip_atualizar_versao_modulo_pen.php
1 1 <?php
2   -/**
3   - * Script para atualização do sistema SEI.
4   - *
5   - * Modificar o "short_open_tag" para "On" no php.ini
6   - *
7   - * PHP 5.3.3 (cli) (built: Jul 9 2015 17:39:00)
8   - * Copyright (c) 1997-2010 The PHP Group
9   - * Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
10   - *
11   - * @author Join Tecnologia
12   - */
  2 +require_once dirname(__FILE__).'/Sip.php';
13 3  
14 4 set_include_path(implode(PATH_SEPARATOR, array(
15   - realpath(__DIR__.'/../infra_php'),
  5 + realpath(__DIR__ . '/../infra_php'),
16 6 get_include_path(),
17 7 )));
18 8  
19   -try {
20 9  
21   - require_once __DIR__.'/../sei/SEI.php';
  10 +/**
  11 + * Mapeamento dos metadados sobre a estrutura do banco de dados
  12 + *
  13 + * @author Join Tecnologia
  14 + */
  15 +class PenMetaBD extends InfraMetaBD {
  16 +
  17 + const NNULLO = 'NOT NULL';
  18 + const SNULLO = 'NULL';
  19 +
  20 + /**
  21 + *
  22 + * @return string
  23 + */
  24 + public function adicionarValorPadraoParaColuna($strNomeTabela, $strNomeColuna, $strValorPadrao, $bolRetornarQuery = false){
  25 +
  26 + $objInfraBanco = $this->getObjInfraIBanco();
  27 +
  28 + $strTableDrive = get_parent_class($objInfraBanco);
  29 + $strQuery = '';
  30 +
  31 + switch($strTableDrive) {
  32 +
  33 + case 'InfraMySql':
  34 + $strQuery = sprintf("ALTER TABLE `%s` ALTER COLUMN `%s` SET DEFAULT '%s'", $strNomeTabela, $strNomeColuna, $strValorPadrao);
  35 + break;
  36 +
  37 + case 'InfraSqlServer':
  38 + $strQuery = sprintf("ALTER TABLE [%s] ADD DEFAULT('%s') FOR [%s]", $strNomeTabela, $strValorPadrao, $strNomeColuna);
  39 +
  40 + case 'InfraOracle':
  41 + break;
  42 + }
  43 +
  44 + if($bolRetornarQuery === false) {
  45 +
  46 + $objInfraBanco->executarSql($strQuery);
  47 + }
  48 + else {
  49 +
  50 + return $strQuery;
  51 + }
  52 + }
  53 +
  54 + /**
  55 + * Verifica se o usuário do drive de conexão possui permissão para criar/ remover
  56 + * estruturas
  57 + *
  58 + * @return PenMetaBD
  59 + */
  60 + public function isDriverPermissao(){
  61 +
  62 + $objInfraBanco = $this->getObjInfraIBanco();
  63 +
  64 + if(count($this->obterTabelas('sei_teste'))==0){
  65 + $objInfraBanco->executarSql('CREATE TABLE sei_teste (id '.$this->tipoNumero().' NULL)');
  66 + }
  67 +
  68 + $objInfraBanco->executarSql('DROP TABLE sei_teste');
  69 +
  70 + return $this;
  71 + }
  72 +
  73 + /**
  74 + * Verifica se o banco do SEI é suportador pelo atualizador
  75 + *
  76 + * @throws InfraException
  77 + * @return PenMetaBD
  78 + */
  79 + public function isDriverSuportado(){
  80 +
  81 + $strTableDrive = get_parent_class($this->getObjInfraIBanco());
  82 +
  83 + switch($strTableDrive) {
  84 +
  85 + case 'InfraMySql':
  86 + // Fix para bug de MySQL versão inferior ao 5.5 o default engine
  87 + // é MyISAM e não tem suporte a FOREING KEYS
  88 + $this->getObjInfraIBanco()->executarSql('SET STORAGE_ENGINE=InnoDB');
  89 + case 'InfraSqlServer':
  90 + case 'InfraOracle':
  91 + break;
  92 +
  93 + default:
  94 + throw new InfraException('BANCO DE DADOS NAO SUPORTADO: ' . $strTableDrive);
  95 +
  96 + }
  97 +
  98 + return $this;
  99 + }
  100 +
  101 + /**
  102 + * Verifica se a versão sistema é compativel com a versão do módulo PEN
  103 + *
  104 + * @throws InfraException
  105 + * @return PenMetaBD
  106 + */
  107 + public function isVersaoSuportada($strRegexVersaoSistema, $strVerMinRequirida){
  108 +
  109 + $numVersaoRequerida = intval(preg_replace('/\D+/', '', $strVerMinRequirida));
  110 + $numVersaoSistema = intval(preg_replace('/\D+/', '', $strRegexVersaoSistema));
  111 +
  112 + if($numVersaoRequerida > $numVersaoSistema){
  113 + throw new InfraException('VERSAO DO FRAMEWORK PHP INCOMPATIVEL (VERSAO ATUAL '.$strRegexVersaoSistema.', VERSAO REQUERIDA '.$strVerMinRequirida.')');
  114 + }
  115 +
  116 + return $this;
  117 + }
  118 +
  119 + /**
  120 + * Apaga a chave primária da tabela
  121 + *
  122 + * @throws InfraException
  123 + * @return PenMetaBD
  124 + */
  125 + public function removerChavePrimaria($strNomeTabela, $strNomeChave){
  126 +
  127 + if($this->isChaveExiste($strNomeTabela, $strNomeChave)) {
  128 +
  129 + $strTableDrive = get_parent_class($this->getObjInfraIBanco());
  130 +
  131 + switch($strTableDrive) {
  132 +
  133 + case 'InfraMySql':
  134 + $this->getObjInfraIBanco()->executarSql('ALTER TABLE '.$strNomeTabela.' DROP PRIMARY KEY');
  135 + break;
  136 +
  137 + case 'InfraSqlServer':
  138 + $this->getObjInfraIBanco()->executarSql('ALTER TABLE '.$strNomeTabela.' DROP CONSTRAINT '.$strNomeChave);
  139 + break;
  140 +
  141 + case 'InfraOracle':
  142 + break;
  143 + }
  144 + }
  145 + return $this;
  146 + }
  147 +
  148 + public function isChaveExiste($strNomeTabela = '', $strNomeChave = ''){
  149 +
  150 + $objInfraBanco = $this->getObjInfraIBanco();
  151 + $strTableDrive = get_parent_class($objInfraBanco);
  152 +
  153 + switch($strTableDrive) {
  154 +
  155 + case 'InfraMySql':
  156 + $strSql = " SELECT COUNT(CONSTRAINT_NAME) AS EXISTE
  157 + FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
  158 + WHERE CONSTRAINT_SCHEMA = '".$objInfraBanco->getBanco()."'
  159 + AND TABLE_NAME = '".$strNomeTabela."'
  160 + AND CONSTRAINT_NAME = '".$strNomeChave."'";
  161 + break;
  162 +
  163 + case 'InfraSqlServer':
  164 +
  165 + $strSql = " SELECT COUNT(CONSTRAINT_NAME) AS EXISTE
  166 + FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
  167 + WHERE CONSTRAINT_CATALOG = '".$objInfraBanco->getBanco()."'
  168 + AND TABLE_NAME = '".$strNomeTabela."'
  169 + AND CONSTRAINT_NAME = '".$strNomeChave."'";
  170 + break;
  171 +
  172 + case 'InfraOracle':
  173 + $strSql = "SELECT 0 AS EXISTE";
  174 + break;
  175 + }
  176 +
  177 + $strSql = preg_replace('/\s+/', ' ', $strSql);
  178 + $arrDados = $objInfraBanco->consultarSql($strSql);
  179 +
  180 + return (intval($arrDados[0]['EXISTE']) > 0) ? true : false;
  181 + }
  182 +
  183 + public function adicionarChaveUnica($strNomeTabela = '', $arrNomeChave = array()){
  184 +
  185 + $this->getObjInfraIBanco()
  186 + ->executarSql('ALTER TABLE '.$strNomeTabela.' ADD CONSTRAINT UK_'.$strNomeTabela.' UNIQUE('.implode(', ', $arrNomeChave).')');
  187 + }
  188 +
  189 + public function renomearTabela($strNomeTabelaAtual, $strNomeTabelaNovo){
  190 +
  191 + if($this->isTabelaExiste($strNomeTabelaAtual)) {
  192 +
  193 + $objInfraBanco = $this->getObjInfraIBanco();
  194 +
  195 + $strTableDrive = get_parent_class($objInfraBanco);
  196 + $strQuery = '';
  197 +
  198 + switch ($strTableDrive) {
  199 +
  200 + case 'InfraMySql':
  201 + $strQuery = sprintf("ALTER TABLE `%s` RENAME TO `%s`", $strNomeTabelaAtual, $strNomeTabelaNovo);
  202 + break;
  203 +
  204 + case 'InfraSqlServer':
  205 + $strQuery = sprintf("sp_rename '%s', '%s'", $strNomeTabelaAtual, $strNomeTabelaNovo);
  206 +
  207 + case 'InfraOracle':
  208 + $strQuery = sprintf("RENAME TABLE %s TO %s", $strNomeTabelaAtual, $strNomeTabelaNovo);
  209 + break;
  210 + }
  211 +
  212 + $objInfraBanco->executarSql($strQuery);
  213 + }
  214 + }
  215 +
  216 +
  217 + /**
  218 + * Verifica se uma tabela existe no banco
  219 + *
  220 + * @throws InfraException
  221 + * @return bool
  222 + */
  223 + public function isTabelaExiste($strNomeTabela = ''){
  224 +
  225 + $objInfraBanco = $this->getObjInfraIBanco();
  226 + $strTableDrive = get_parent_class($objInfraBanco);
  227 +
  228 + switch($strTableDrive) {
  229 +
  230 + case 'InfraMySql':
  231 + $strSql = "SELECT COUNT(TABLE_NAME) AS EXISTE
  232 + FROM INFORMATION_SCHEMA.TABLES
  233 + WHERE TABLE_SCHEMA = '".$objInfraBanco->getBanco()."'
  234 + AND TABLE_NAME = '".$strNomeTabela."'";
  235 + break;
  236 +
  237 + case 'InfraSqlServer':
  238 +
  239 + $strSql = "SELECT COUNT(TABLE_NAME) AS EXISTE
  240 + FROM INFORMATION_SCHEMA.TABLES
  241 + WHERE TABLE_CATALOG = '".$objInfraBanco->getBanco()."'
  242 + AND TABLE_NAME = '".$strNomeTabela."'";
  243 + break;
  244 +
  245 + case 'InfraOracle':
  246 + $strSql = "SELECT 0 AS EXISTE";
  247 + break;
  248 + }
  249 +
  250 + $strSql = preg_replace('/\s+/', ' ', $strSql);
  251 + $arrDados = $objInfraBanco->consultarSql($strSql);
  252 +
  253 + return (intval($arrDados[0]['EXISTE']) > 0) ? true : false;
  254 + }
  255 +
  256 + public function isColuna($strNomeTabela = '', $strNomeColuna = ''){
  257 +
  258 + $objInfraBanco = $this->getObjInfraIBanco();
  259 + $strTableDrive = get_parent_class($objInfraBanco);
  260 +
  261 + switch($strTableDrive) {
  262 +
  263 + case 'InfraMySql':
  264 + $strSql = "SELECT COUNT(TABLE_NAME) AS EXISTE
  265 + FROM INFORMATION_SCHEMA.COLUMNS
  266 + WHERE TABLE_SCHEMA = '".$objInfraBanco->getBanco()."'
  267 + AND TABLE_NAME = '".$strNomeTabela."'
  268 + AND COLUMN_NAME = '".$strNomeColuna."'";
  269 + break;
  270 +
  271 + case 'InfraSqlServer':
  272 +
  273 + $strSql = "SELECT COUNT(COLUMN_NAME) AS EXISTE
  274 + FROM INFORMATION_SCHEMA.COLUMNS
  275 + WHERE TABLE_CATALOG = '".$objInfraBanco->getBanco()."'
  276 + AND TABLE_NAME = '".$strNomeTabela."'
  277 + AND COLUMN_NAME = '".$strNomeColuna."'";
  278 + break;
  279 +
  280 + case 'InfraOracle':
  281 + $strSql = "SELECT 0 AS EXISTE";
  282 + break;
  283 + }
  284 +
  285 + $strSql = preg_replace('/\s+/', ' ', $strSql);
  286 + $arrDados = $objInfraBanco->consultarSql($strSql);
  287 +
  288 + return (intval($arrDados[0]['EXISTE']) > 0) ? true : false;
  289 +
  290 +
  291 + }
  292 +
  293 + /**
  294 + * Cria a estrutura da tabela no padrão ANSI
  295 + *
  296 + * @throws InfraException
  297 + * @return PenMetaBD
  298 + */
  299 + public function criarTabela($arrSchema = array()){
  300 +
  301 + $strNomeTabela = $arrSchema['tabela'];
  302 +
  303 +
  304 + if($this->isTabelaExiste($strNomeTabela)) {
  305 + return $this;
  306 + }
  307 +
  308 + $objInfraBanco = $this->getObjInfraIBanco();
  309 + $arrColunas = array();
  310 + $arrStrQuery = array();
  311 +
  312 + foreach($arrSchema['cols'] as $strNomeColuna => $arrColunaConfig) {
  313 +
  314 + list($strTipoDado, $strValorPadrao) = $arrColunaConfig;
  315 +
  316 + if($strValorPadrao != self::SNULLO && $strValorPadrao != self::NNULLO) {
  317 +
  318 + $arrStrQuery[] = $this->adicionarValorPadraoParaColuna($strNomeTabela, $strNomeColuna, $strValorPadrao, true);
  319 + $strValorPadrao = self::NNULLO;
  320 + }
  321 +
  322 + $arrColunas[] = $strNomeColuna.' '.$strTipoDado.' '.$strValorPadrao;
  323 + }
  324 +
  325 + $objInfraBanco->executarSql('CREATE TABLE '.$strNomeTabela.' ('.implode(', ', $arrColunas).')');
  326 +
  327 + if(!empty($arrSchema['pk'])) {
  328 +
  329 + $this->adicionarChavePrimaria($strNomeTabela, 'pk_'.$strNomeTabela, $arrSchema['pk']);
  330 +
  331 + if(count($arrSchema['pk']) > 1) {
  332 +
  333 + foreach($arrSchema['pk'] as $strPk) {
  334 +
  335 + $objInfraBanco->executarSql('CREATE INDEX idx_'.$strNomeTabela.'_'.$strPk.' ON '.$strNomeTabela.'('.$strPk.')');
  336 + }
  337 + }
  338 + }
  339 +
  340 + if(array_key_exists('uk', $arrSchema) && !empty($arrSchema['uk'])) {
  341 +
  342 + $this->adicionarChaveUnica($strNomeTabela, $arrSchema['uk']);
  343 + }
  344 +
  345 + if(!empty($arrSchema['fks'])) {
  346 +
  347 + foreach($arrSchema['fks'] as $strTabelaOrigem => $array) {
  348 +
  349 + $strNomeFK = 'fk_'.$strNomeTabela.'_'.$strTabelaOrigem;
  350 + $arrCamposOrigem = (array)array_shift($array);
  351 + $arrCampos = $arrCamposOrigem;
  352 +
  353 + if(!empty($array)) {
  354 + $arrCampos = (array)array_shift($array);
  355 + }
  356 +
  357 + $this->adicionarChaveEstrangeira($strNomeFK, $strNomeTabela, $arrCampos, $strTabelaOrigem, $arrCamposOrigem);
  358 + }
  359 + }
  360 +
  361 + if(!empty($arrStrQuery)) {
  362 +
  363 + foreach($arrStrQuery as $strQuery) {
  364 + $objInfraBanco->executarSql($strQuery);
  365 + }
  366 + }
  367 +
  368 + return $this;
  369 + }
  370 +
  371 + /**
  372 + * Apagar a estrutura da tabela no banco de dados
  373 + *
  374 + * @throws InfraException
  375 + * @return PenMetaBD
  376 + */
  377 + public function removerTabela($strNomeTabela = ''){
  378 +
  379 + $this->getObjInfraIBanco()->executarSql('DROP TABLE '.$strNomeTabela);
  380 + return $this;
  381 + }
  382 +
  383 + public function adicionarChaveEstrangeira($strNomeFK, $strTabela, $arrCampos, $strTabelaOrigem, $arrCamposOrigem) {
  384 +
  385 + if(!$this->isChaveExiste($strTabela, $strNomeFK)) {
  386 + parent::adicionarChaveEstrangeira($strNomeFK, $strTabela, $arrCampos, $strTabelaOrigem, $arrCamposOrigem);
  387 + }
  388 + return $this;
  389 + }
  390 +
  391 + public function adicionarChavePrimaria($strTabela, $strNomePK, $arrCampos) {
  392 +
  393 + if(!$this->isChaveExiste($strTabela, $strNomePK)) {
  394 + parent::adicionarChavePrimaria($strTabela, $strNomePK, $arrCampos);
  395 + }
  396 + return $this;
  397 + }
  398 +
  399 + public function alterarColuna($strTabela, $strColuna, $strTipo, $strNull = '') {
  400 + parent::alterarColuna($strTabela, $strColuna, $strTipo, $strNull);
  401 + return $this;
  402 + }
  403 +
  404 + public function excluirIndice($strTabela, $strIndex) {
  405 + if($this->isChaveExiste($strTabela, $strFk)) {
  406 + parent::excluirIndice($strTabela, $strIndex);
  407 + }
  408 + return $this;
  409 + }
  410 +
  411 + public function excluirChaveEstrangeira($strTabela, $strFk) {
  412 + if($this->isChaveExiste($strTabela, $strFk)) {
  413 + parent::excluirChaveEstrangeira($strTabela, $strFk);
  414 + }
  415 + return $this;
  416 + }
  417 +}
  418 +
  419 +abstract class PenAtualizadorRN extends InfraRN {
  420 +
  421 + const VER_NONE = '0.0.0'; // Modulo não instalado
  422 + const VER_001 = '0.0.1';
  423 + const VER_002 = '0.0.2';
  424 + const VER_003 = '0.0.3';
  425 + const VER_004 = '0.0.4';
  426 + const VER_005 = '0.0.5';
  427 +
  428 + protected $sei_versao;
  429 +
  430 + /**
  431 + * @var string Versão mínima requirida pelo sistema para instalação do PEN
  432 + */
  433 + protected $versaoMinRequirida;
  434 +
  435 + /**
  436 + * @var InfraIBanco Instância da classe de persistência com o banco de dados
  437 + */
  438 + protected $objBanco;
  439 +
  440 + /**
  441 + * @var InfraMetaBD Instância do metadata do banco de dados
  442 + */
  443 + protected $objMeta;
  444 +
  445 + /**
  446 + * @var InfraDebug Instância do debuger
  447 + */
  448 + protected $objDebug;
  449 +
  450 + /**
  451 + * @var integer Tempo de execução do script
  452 + */
  453 + protected $numSeg = 0;
  454 +
  455 + /**
  456 + * @var array Argumentos passados por linha de comando ao script
  457 + */
  458 + protected $arrArgs = array();
  459 +
  460 + /**
  461 + * Inicia a conexão com o banco de dados
  462 + */
  463 + protected function inicializarObjMetaBanco() {
  464 + if (empty($this->objMeta)) {
  465 + $this->objMeta = new PenMetaBD($this->inicializarObjInfraIBanco());
  466 + }
  467 + return $this->objMeta;
  468 + }
  469 +
  470 + /**
  471 + * Adiciona uma mensagem ao output para o usuário
  472 + *
  473 + * @return null
  474 + */
  475 + protected function logar($strMsg) {
  476 + $this->objDebug->gravar($strMsg);
  477 + }
  478 +
  479 + /**
  480 + * Inicia o script criando um contator interno do tempo de execução
  481 + *
  482 + * @return null
  483 + */
  484 + protected function inicializar($strTitulo) {
  485 +
  486 + $this->numSeg = InfraUtil::verificarTempoProcessamento();
  487 +
  488 + $this->logar($strTitulo);
  489 + }
  490 +
  491 + /**
  492 + * Finaliza o script informando o tempo de execução.
  493 + *
  494 + * @return null
  495 + */
  496 + protected function finalizar() {
  497 +
  498 + $this->logar('TEMPO TOTAL DE EXECUCAO: ' . InfraUtil::verificarTempoProcessamento($this->numSeg) . ' s');
  499 +
  500 + $this->objDebug->setBolLigado(false);
  501 + $this->objDebug->setBolDebugInfra(false);
  502 + $this->objDebug->setBolEcho(false);
  503 +
  504 + print PHP_EOL;
  505 + die();
  506 + }
  507 +
  508 + /**
  509 + * Método criado em função de um bug com a InfraRN na linha 69, onde usamos
  510 + * uma instância do banco do SIP e a versão esta no banco SEI, essa verificação
  511 + * e lançamento de uma excessão pelos bancos terem nome diferentes tava o
  512 + * atualizado
  513 + *
  514 + * @todo Migrar para classe PenMetaBD
  515 + * @return null
  516 + */
  517 + protected function setVersao($strRegexVersao, $objInfraBanco = null) {
  518 +
  519 + InfraDebug::getInstance()->gravarInfra(sprintf('[%s->%s]', get_class($this), __FUNCTION__));
  520 +
  521 +
  522 + if ($this->getVersao($objInfraBanco)) {
  523 +
  524 + $sql = sprintf("UPDATE infra_parametro SET valor = '%s' WHERE nome = '%s'", $strRegexVersao, $this->sei_versao);
  525 + } else {
  526 +
  527 + $sql = sprintf("INSERT INTO infra_parametro(nome, valor) VALUES('%s', '%s')", $this->sei_versao, $strRegexVersao);
  528 + }
  529 +
  530 + if (empty($objInfraBanco)) {
  531 +
  532 + $objInfraBanco = $this->inicializarObjInfraIBanco();
  533 + }
  534 +
  535 + $objInfraBanco->executarSql($sql);
  536 +
  537 + return $strRegexVersao;
  538 + }
  539 +
  540 + /**
  541 + * Retorna a versão atual do modulo, se já foi instalado
  542 + *
  543 + * @todo Migrar para classe PenMetaBD
  544 + * @param InfraBanco $objInfraBanco Conexão com o banco SEI ou SIP
  545 + * @return string
  546 + */
  547 + protected function getVersao($objInfraBanco = null) {
  548 +
  549 + InfraDebug::getInstance()->gravarInfra(sprintf('[%s->%s]', get_class($this), __FUNCTION__));
  550 +
  551 + $sql = sprintf("SELECT valor FROM infra_parametro WHERE nome = '%s'", $this->sei_versao);
  552 +
  553 + if (empty($objInfraBanco)) {
  554 +
  555 + $objInfraBanco = $this->inicializarObjInfraIBanco();
  556 + }
  557 +
  558 + $arrResultado = $objInfraBanco->consultarSql($sql);
  559 +
  560 + if (empty($arrResultado)) {
  561 + return null;
  562 + }
  563 +
  564 + $arrLinha = current($arrResultado);
  565 +
  566 + return $arrLinha['valor'];
  567 + }
  568 +
  569 + /**
  570 + * Verifica se o número da versão é valido
  571 + *
  572 + * @param string $strVersao Versão a ser instalada
  573 + * @return bool
  574 + */
  575 + protected function isVersaoValida($strVersao = self::VER_NONE) {
  576 +
  577 + if (empty($strVersao)) {
  578 + return false;
  579 + }
  580 +
  581 + // Remove os caracteres não númericos
  582 + $strVersao = preg_replace('/\D+/', '', $strVersao);
  583 +
  584 + // Tem que no mínimo 3 digitos
  585 + if (strlen($strVersao) < 3) {
  586 + return false;
  587 + }
  588 +
  589 + return is_numeric($strVersao) ? true : false;
  590 + }
  591 +
  592 + /**
  593 + * Verifica se um paramêtro existe, caso sim retorna o seu valor, senão
  594 + * retorna o default especificado.
  595 + *
  596 + * @param string $strChave Nome do paramêtro
  597 + * @param string $strParam String a ser formatada com o valor do paramêtro
  598 + * @param string $strParamDefault String que retorna caso o valor do
  599 + * paramêtro não exista
  600 + * @param bool $bolAlgumFiltroUsado Ponteiro de controle para verificar se
  601 + * pelo menos um paramêtro foi encontrado
  602 + * @return string
  603 + */
  604 + private function getStrArg($strChave = '', $strParam = '', $strParamDefault = '', &$bolAlgumFiltroUsado) {
  605 +
  606 + if (array_key_exists($strChave, $this->arrArgs)) {
  607 + $bolAlgumFiltroUsado = true;
  608 + return sprintf($strParam, str_pad($this->arrArgs[$strChave], 3, '0', STR_PAD_LEFT));
  609 + }
  610 + return $strParamDefault;
  611 + }
  612 +
  613 + /**
  614 + * Retorna a última versão disponivel. Verifica as constantes que iniciam
  615 + * com VER_
  616 + */
  617 + private function getUltimaVersao() {
  618 +
  619 + $objReflection = new ReflectionClass(__CLASS__);
  620 + $arrVersao = array_flip(preg_grep('/^VER\_/', array_flip($objReflection->getConstants())));
  621 + sort($arrVersao);
  622 + return array_pop($arrVersao);
  623 + }
  624 +
  625 + /**
  626 + * Encontra os métodos com notação para instalar a versão selecionada
  627 + *
  628 + * @return string Número da versão
  629 + */
  630 + protected function executarControlado() {
  631 +
  632 + $this->inicializarObjMetaBanco()
  633 + ->isDriverSuportado()
  634 + ->isDriverPermissao();
  635 + //->isVersaoSuportada(SEI_VERSAO, $this->versaoMinRequirida);
  636 +
  637 + $arrMetodo = array();
  638 +
  639 + // Retorna a última versão disponibilizada pelo script. Sempre tenta atualizar
  640 + // para versão mais antiga
  641 + $strVersaoInstalar = $this->getUltimaVersao();
  642 +
  643 + //throw new InfraException($strVersaoInstalar);
  644 + $objInfraBanco = $this->inicializarObjInfraIBanco();
  645 + // Versão atual
  646 + $strPenVersao = $this->getVersao($objInfraBanco);
  647 + if (!$this->isVersaoValida($strPenVersao)) {
  648 + // Não instalado
  649 + $strPenVersao = $this->setVersao(self::VER_NONE, $objInfraBanco);
  650 + }
  651 +
  652 + $numPenVersao = substr($strPenVersao, -1);
  653 + $numVersaoInstalar = intval(substr($strVersaoInstalar, -1));
  654 +
  655 + $bolAlgumFiltroUsado = false;
  656 + $strRegexRelease = $this->getStrArg('release', '(R%s)', '(R[0-9]{1,3})?', $bolAlgumFiltroUsado);
  657 + $strRegexSprint = $this->getStrArg('sprint', '(S%s)', '(S[0-9]{1,3})?', $bolAlgumFiltroUsado);
  658 + $strRegexItem = $this->getStrArg('user-story', '(US%s)', '(US|IW[0-9]{1,3})?', $bolAlgumFiltroUsado);
  659 + $strRegexItem = $this->getStrArg('item-worker', '(IW%s)', $strRegexItem, $bolAlgumFiltroUsado);
  660 +
  661 + // Instalar todas atualizações
  662 + if ($bolAlgumFiltroUsado === false) {
  663 +
  664 + $strRegexVersao = sprintf('[%d-%d]', ($numPenVersao + 1), $numVersaoInstalar);
  665 + }
  666 + // Instalar somente a solicitada
  667 + else {
  668 + // Caso algum paramêtro seja adicionado não deve passar para próxima versão
  669 + $strVersaoInstalar = $strPenVersao;
  670 + $strRegexVersao = intval(substr($strPenVersao, -1) + 1);
  671 + }
  672 +
  673 + // instalarV[0-9]{1,2}[0-9](R[0-9]{1,3})?(S[0-9]{1,3})?(US|IW[0-9]{1,4})?
  674 + $strRegex = sprintf('/^instalarV[0-9][0-9]%s%s%s%s/i', $strRegexVersao, $strRegexRelease, $strRegexSprint, $strRegexItem
  675 + );
  676 +
  677 + // Tenta encontrar métodos que iniciem com instalar
  678 + $arrMetodo = (array) preg_grep($strRegex, get_class_methods($this));
  679 +
  680 + if (empty($arrMetodo)) {
  681 +
  682 + throw new InfraException(sprintf('NENHUMA ATUALIZACAO FOI ENCONTRADA SUPERIOR A VERSAO %s DO MODULO PEN', $strPenVersao));
  683 + } else {
  684 +
  685 + foreach ($arrMetodo as $strMetodo) {
  686 +
  687 + $this->{$strMetodo}();
  688 + }
  689 + }
  690 + $this->setVersao($strVersaoInstalar, $objInfraBanco);
  691 +
  692 + return $strVersaoInstalar;
  693 + }
  694 +
  695 + /**
  696 + * Método que inicia o processo
  697 + */
  698 + public function atualizarVersao() {
  699 +
  700 + $this->inicializar('INICIANDO ATUALIZACAO DO MODULO PEN NO SEI VERSAO ' . SEI_VERSAO);
  701 +
  702 + try {
  703 +
  704 + $strRegexVersao = $this->executar();
  705 + $this->logar('ATUALIZADA VERSAO: ' . $strRegexVersao);
  706 + } catch (InfraException $e) {
  707 +
  708 + $this->logar('Erro: ' . $e->getStrDescricao());
  709 + } catch (\Exception $e) {
  710 +
  711 + $this->logar('Erro: ' . $e->getMessage());
  712 + }
  713 +
  714 + $this->finalizar();
  715 + }
  716 +
  717 + /**
  718 + * Construtor
  719 + *
  720 + * @param array $arrArgs Argumentos enviados pelo script
  721 + */
  722 + public function __construct($arrArgs = array()) {
  723 +
  724 + ini_set('max_execution_time', '0');
  725 + ini_set('memory_limit', '-1');
  726 + @ini_set('zlib.output_compression', '0');
  727 + @ini_set('implicit_flush', '1');
  728 + ob_implicit_flush();
  729 +
  730 + $this->arrArgs = $arrArgs;
  731 +
  732 + $this->inicializarObjMetaBanco();
  733 +
  734 + $this->objDebug = InfraDebug::getInstance();
  735 + $this->objDebug->setBolLigado(true);
  736 + $this->objDebug->setBolDebugInfra(true);
  737 + $this->objDebug->setBolEcho(true);
  738 + $this->objDebug->limpar();
  739 + }
  740 +
  741 +}
  742 +
  743 +class PenAtualizarSipRN extends PenAtualizadorRN {
  744 +
  745 + protected $versaoMinRequirida = '1.30.0';
  746 + protected $sei_versao = 'PEN_VERSAO_MODULO_SIP';
  747 + private $arrRecurso = array();
  748 + private $arrMenu = array();
  749 +
  750 + /**
  751 + * Retorna/Cria a conexão com o banco de dados
  752 + *
  753 + * @return InfraIBanco
  754 + */
  755 + protected function inicializarObjInfraIBanco() {
  756 + if (empty($this->objBanco)) {
  757 +
  758 + $this->objBanco = BancoSip::getInstance();
  759 + }
  760 + return $this->objBanco;
  761 + }
  762 +
  763 + /**
  764 + * Retorna o ID do sistema
  765 + *
  766 + * @return int
  767 + */
  768 + protected function getNumIdSistema($strSigla = 'SIP') {
  769 +
  770 + $objDTO = new SistemaDTO();
  771 + $objDTO->setStrSigla($strSigla);
  772 + $objDTO->setNumMaxRegistrosRetorno(1);
  773 + $objDTO->retNumIdSistema();
  774 +
  775 + $objRN = new SistemaRN();
  776 + $objDTO = $objRN->consultar($objDTO);
  777 +
  778 + return (empty($objDTO)) ? '0' : $objDTO->getNumIdSistema();
  779 + }
  780 +
  781 + /**
  782 + *
  783 + * @return int Código do Menu
  784 + */
  785 + protected function getNumIdMenu($strMenu = 'Principal', $numIdSistema = 0) {
  786 +
  787 + $objDTO = new MenuDTO();
  788 + $objDTO->setNumIdSistema($numIdSistema);
  789 + $objDTO->setStrNome($strMenu);
  790 + $objDTO->setNumMaxRegistrosRetorno(1);
  791 + $objDTO->retNumIdMenu();
  792 +
  793 + $objRN = new MenuRN();
  794 + $objDTO = $objRN->consultar($objDTO);
  795 +
  796 + if (empty($objDTO)) {
  797 + throw new InfraException('Menu ' . $strMenu . ' não encontrado.');
  798 + }
  799 +
  800 + return $objDTO->getNumIdMenu();
  801 + }
  802 +
  803 + /**
  804 + *
  805 + * @return int Código do Recurso gerado
  806 + */
  807 + protected function criarRecurso($strNome = '', $strDescricao = null, $numIdSistema = 0) {
  808 +
  809 + $objDTO = new RecursoDTO();
  810 + $objDTO->setNumIdSistema($numIdSistema);
  811 + $objDTO->setStrNome($strNome);
  812 + $objDTO->setNumMaxRegistrosRetorno(1);
  813 + $objDTO->retNumIdRecurso();
  814 +
  815 + $objBD = new RecursoBD($this->getObjInfraIBanco());
  816 + $objDTO = $objBD->consultar($objDTO);
  817 +
  818 + if (empty($objDTO)) {
  819 +
  820 + $objDTO = new RecursoDTO();
  821 + $objDTO->setNumIdRecurso(null);
  822 + $objDTO->setStrDescricao($strDescricao);
  823 + $objDTO->setNumIdSistema($numIdSistema);
  824 + $objDTO->setStrNome($strNome);
  825 + $objDTO->setStrCaminho('controlador.php?acao=' . $strNome);
  826 + $objDTO->setStrSinAtivo('S');
  827 +
  828 + $objDTO = $objBD->cadastrar($objDTO);
  829 + }
  830 +
  831 + $this->arrRecurso[] = $objDTO->getNumIdRecurso();
  832 +
  833 + return $objDTO->getNumIdRecurso();
  834 + }
  835 +
  836 + /**
  837 + * Cria um menu
  838 + *
  839 + * @return int
  840 + */
  841 + protected function criarMenu($strRotulo = '', $numSequencia = 10, $numIdItemMenuPai = null, $numIdMenu = null, $numIdRecurso = null, $numIdSistema = 0) {
  842 +
  843 + $objDTO = new ItemMenuDTO();
  844 + $objDTO->setNumIdItemMenuPai($numIdItemMenuPai);
  845 + $objDTO->setNumIdSistema($numIdSistema);
  846 + $objDTO->setStrRotulo($strRotulo);
  847 + $objDTO->setNumIdRecurso($numIdRecurso);
  848 + $objDTO->setNumMaxRegistrosRetorno(1);
  849 + $objDTO->retNumIdItemMenu();
  850 +
  851 + $objBD = new ItemMenuBD($this->inicializarObjInfraIBanco());
  852 + $objDTO = $objBD->consultar($objDTO);
  853 +
  854 + if (empty($objDTO)) {
  855 +
  856 + $objDTO = new ItemMenuDTO();
  857 + $objDTO->setNumIdMenu($numIdMenu);
  858 + $objDTO->setNumIdMenuPai($numIdMenu);
  859 + $objDTO->setNumIdItemMenu(null);
  860 + $objDTO->setNumIdItemMenuPai($numIdItemMenuPai);
  861 + $objDTO->setNumIdSistema($numIdSistema);
  862 + $objDTO->setNumIdRecurso($numIdRecurso);
  863 + $objDTO->setStrRotulo($strRotulo);
  864 + $objDTO->setStrDescricao(null);
  865 + $objDTO->setNumSequencia($numSequencia);
  866 + $objDTO->setStrSinNovaJanela('N');
  867 + $objDTO->setStrSinAtivo('S');
  868 +
  869 + $objDTO = $objBD->cadastrar($objDTO);
  870 + }
  871 +
  872 + if (!empty($numIdRecurso)) {
  873 +
  874 + $this->arrMenu[] = array($objDTO->getNumIdItemMenu(), $numIdMenu, $numIdRecurso);
  875 + }
  876 +
  877 + return $objDTO->getNumIdItemMenu();
  878 + }
  879 +
  880 + public function addRecursosToPerfil($numIdPerfil, $numIdSistema) {
  881 +
  882 + if (!empty($this->arrRecurso)) {
  883 +
  884 + $objDTO = new RelPerfilRecursoDTO();
  885 + $objBD = new RelPerfilRecursoBD($this->inicializarObjInfraIBanco());
  886 +
  887 + foreach ($this->arrRecurso as $numIdRecurso) {
  888 +
  889 + $objDTO->setNumIdSistema($numIdSistema);
  890 + $objDTO->setNumIdPerfil($numIdPerfil);
  891 + $objDTO->setNumIdRecurso($numIdRecurso);
  892 +
  893 + if ($objBD->contar($objDTO) == 0) {
  894 + $objBD->cadastrar($objDTO);
  895 + }
  896 + }
  897 + }
  898 + }
  899 +
  900 + public function addMenusToPerfil($numIdPerfil, $numIdSistema) {
  901 +
  902 + if (!empty($this->arrMenu)) {
  903 +
  904 + $objDTO = new RelPerfilItemMenuDTO();
  905 + $objBD = new RelPerfilItemMenuBD($this->inicializarObjInfraIBanco());
  906 +
  907 + foreach ($this->arrMenu as $array) {
  908 +
  909 + list($numIdItemMenu, $numIdMenu, $numIdRecurso) = $array;
  910 +
  911 + $objDTO->setNumIdPerfil($numIdPerfil);
  912 + $objDTO->setNumIdSistema($numIdSistema);
  913 + $objDTO->setNumIdRecurso($numIdRecurso);
  914 + $objDTO->setNumIdMenu($numIdMenu);
  915 + $objDTO->setNumIdItemMenu($numIdItemMenu);
  916 +
  917 + if ($objBD->contar($objDTO) == 0) {
  918 + $objBD->cadastrar($objDTO);
  919 + }
  920 + }
  921 + }
  922 + }
  923 +
  924 + public function atribuirPerfil($numIdSistema) {
  925 +
  926 + $objDTO = new PerfilDTO();
  927 + $objBD = new PerfilBD($this->inicializarObjInfraIBanco());
  928 + $objRN = $this;
  929 +
  930 + // Vincula a um perfil os recursos e menus adicionados nos métodos criarMenu e criarReturso
  931 + $fnCadastrar = function($strNome, $numIdSistema) use($objDTO, $objBD, $objRN) {
  932 +
  933 + $objDTO->unSetTodos();
  934 + $objDTO->setNumIdSistema($numIdSistema);
  935 + $objDTO->setStrNome($strNome, InfraDTO::$OPER_LIKE);
  936 + $objDTO->setNumMaxRegistrosRetorno(1);
  937 + $objDTO->retNumIdPerfil();
  938 +
  939 + $objPerfilDTO = $objBD->consultar($objDTO);
  940 +
  941 + if (!empty($objPerfilDTO)) {
  942 + $objRN->addRecursosToPerfil($objPerfilDTO->getNumIdPerfil(), $numIdSistema);
  943 + $objRN->addMenusToPerfil($objPerfilDTO->getNumIdPerfil(), $numIdSistema);
  944 + }
  945 + };
  946 +
  947 + $fnCadastrar('ADMINISTRADOR', $numIdSistema);
  948 + $fnCadastrar('BASICO', $numIdSistema);
  949 + }
  950 +
  951 + /**
  952 + * Instala/Atualiza os módulo PEN para versão 1.0
  953 + */
  954 + protected function instalarV001() {
  955 +
  956 + $numIdSistema = $this->getNumIdSistema('SEI');
  957 + $numIdMenu = $this->getNumIdMenu('Principal', $numIdSistema);
  958 +
  959 + //----------------------------------------------------------------------
  960 + // Expedir procedimento
  961 + //----------------------------------------------------------------------
  962 + $this->criarRecurso('pen_procedimento_expedir', 'Expedir Procedimento', $numIdSistema);
  963 + $this->criarRecurso('apensados_selecionar_expedir_procedimento', 'Processos Apensados', $numIdSistema);
  964 + $numIdRecurso = $this->criarRecurso('pen_procedimento_expedido_listar', 'Processos Expedidos', $numIdSistema);
  965 + $this->criarMenu('Processos Expedidos', 55, null, $numIdMenu, $numIdRecurso, $numIdSistema);
  966 + //----------------------------------------------------------------------
  967 + // Mapeamento de documentos enviados
  968 + //----------------------------------------------------------------------
  969 + $this->criarRecurso('pen_map_tipo_doc_enviado_visualizar', 'Visualização de mapeamento de documentos enviados', $numIdSistema);
  970 +
  971 + // Acha o menu existente de Tipos de Documento
  972 + $objItemMenuDTO = new ItemMenuDTO();
  973 + $objItemMenuDTO->setNumIdSistema($numIdSistema);
  974 + $objItemMenuDTO->setNumIdMenu($numIdMenu);
  975 + $objItemMenuDTO->setStrRotulo('Tipos de Documento');
  976 + $objItemMenuDTO->setNumMaxRegistrosRetorno(1);
  977 + $objItemMenuDTO->retNumIdItemMenu();
  978 +
  979 + $objItemMenuBD = new ItemMenuBD($this->inicializarObjInfraIBanco());
  980 + $objItemMenuDTO = $objItemMenuBD->consultar($objItemMenuDTO);
  981 +
  982 + if (empty($objItemMenuDTO)) {
  983 + throw new InfraException('Menu "Tipo de Documentos" não foi localizado');
  984 + }
  985 +
  986 + $numIdItemMenuPai = $objItemMenuDTO->getNumIdItemMenu();
  987 +
  988 + // Gera o submenu Mapeamento
  989 + $_numIdItemMenuPai = $this->criarMenu('Mapeamento', 50, $numIdItemMenuPai, $numIdMenu, null, $numIdSistema);
  990 +
  991 + // Gera o submenu Mapeamento > Envio
  992 + $numIdItemMenuPai = $this->criarMenu('Envio', 10, $_numIdItemMenuPai, $numIdMenu, null, $numIdSistema);
  993 +
  994 + // Gera o submenu Mapeamento > Envio > Cadastrar
  995 + $numIdRecurso = $this->criarRecurso('pen_map_tipo_doc_enviado_cadastrar', 'Cadastro de mapeamento de documentos enviados', $numIdSistema);
  996 + $this->criarMenu('Cadastrar', 10, $numIdItemMenuPai, $numIdMenu, $numIdRecurso, $numIdSistema);
  997 +
  998 + // Gera o submenu Mapeamento > Envio > Listar
  999 + $numIdRecurso = $this->criarRecurso('pen_map_tipo_doc_enviado_listar', 'Listagem de mapeamento de documentos enviados', $numIdSistema);
  1000 + $this->criarMenu('Listar', 20, $numIdItemMenuPai, $numIdMenu, $numIdRecurso, $numIdSistema);
  1001 +
  1002 + // Gera o submenu Mapeamento > Recebimento
  1003 + $numIdItemMenuPai = $this->criarMenu('Recebimento', 20, $_numIdItemMenuPai, $numIdMenu, null, $numIdSistema);
  1004 +
  1005 + // Gera o submenu Mapeamento > Recebimento > Cadastrar
  1006 + $numIdRecurso = $this->criarRecurso('pen_map_tipo_doc_recebido_cadastrar', 'Cadastro de mapeamento de documentos recebidos', $numIdSistema);
  1007 + $this->criarMenu('Cadastrar', 10, $numIdItemMenuPai, $numIdMenu, $numIdRecurso, $numIdSistema);
  1008 +
  1009 + // Gera o submenu Mapeamento > Recebimento > Listar
  1010 + $numIdRecurso = $this->criarRecurso('pen_map_tipo_doc_recebido_listar', 'Listagem de mapeamento de documentos recebidos', $numIdSistema);
  1011 + $this->criarMenu('Listar', 20, $numIdItemMenuPai, $numIdMenu, $numIdRecurso, $numIdSistema);
  1012 +
  1013 + //Atribui as permissões aos recursos e menus
  1014 + $this->atribuirPerfil($numIdSistema);
  1015 + }
  1016 +
  1017 + protected function instalarV003R003S003IW001() {
  1018 +
  1019 +
  1020 + $objBD = new ItemMenuBD($this->inicializarObjInfraIBanco());
  1021 +
  1022 + //----------------------------------------------------------------------
  1023 + // Achar o root
  1024 +
  1025 + $numIdSistema = $this->getNumIdSistema('SEI');
  1026 + $numIdMenu = $this->getNumIdMenu('Principal', $numIdSistema);
  1027 +
  1028 + $objDTO = new ItemMenuDTO();
  1029 + $objDTO->setNumIdSistema($numIdSistema);
  1030 + $objDTO->setNumIdMenu($numIdMenu);
  1031 + $objDTO->setStrRotulo('Administração');
  1032 + $objDTO->setNumMaxRegistrosRetorno(1);
  1033 + $objDTO->retNumIdItemMenu();
  1034 +
  1035 + $objDTO = $objBD->consultar($objDTO);
  1036 +
  1037 + if (empty($objDTO)) {
  1038 + throw new InfraException('Menu "Administração" não foi localizado');
  1039 + }
  1040 +
  1041 + $numIdItemMenuRoot = $objDTO->getNumIdItemMenu();
  1042 + //----------------------------------------------------------------------
  1043 + // Acha o nodo do mapeamento
  1044 +
  1045 + $objItemMenuDTO = new ItemMenuDTO();
  1046 + $objItemMenuDTO->setNumIdSistema($numIdSistema);
  1047 + $objItemMenuDTO->setNumIdMenu($numIdMenu);
  1048 + $objItemMenuDTO->setStrRotulo('Mapeamento');
  1049 + $objItemMenuDTO->setNumSequencia(50);
  1050 + $objItemMenuDTO->setNumMaxRegistrosRetorno(1);
  1051 + $objItemMenuDTO->retTodos();
  1052 +
  1053 + $objItemMenuDTO = $objBD->consultar($objItemMenuDTO);
  1054 + if (!empty($objItemMenuDTO)) {
  1055 +
  1056 + $numIdItemMenuMapeamento = $objItemMenuDTO->getNumIdItemMenu();
  1057 +
  1058 + $objDTO = new ItemMenuDTO();
  1059 + $objDTO->setNumIdSistema($numIdSistema);
  1060 + $objDTO->setNumIdMenu($numIdMenu);
  1061 + $objDTO->setNumIdItemMenuPai($numIdItemMenuMapeamento);
  1062 + $objDTO->retTodos();
  1063 +
  1064 + $arrObjDTO = $objBD->listar($objDTO);
  1065 +
  1066 + if (!empty($arrObjDTO)) {
  1067 +
  1068 + $numIdItemMenuPai = $this->criarMenu('Processo Eletrônico Nacional', 0, $numIdItemMenuRoot, $numIdMenu, null, $numIdSistema);
  1069 + $numIdItemMenuPai = $this->criarMenu('Mapeamento de Tipos de Documento', 10, $numIdItemMenuPai, $numIdMenu, null, $numIdSistema);
  1070 +
  1071 + foreach ($arrObjDTO as $objDTO) {
  1072 +
  1073 + $objDTO->setNumIdItemMenuPai($numIdItemMenuPai);
  1074 +
  1075 + $objBD->alterar($objDTO);
  1076 + }
  1077 +
  1078 + $objBD->excluir($objItemMenuDTO);
  1079 + }
  1080 + }
  1081 + }
  1082 +
  1083 +}
  1084 +
  1085 +class PenConsoleRN extends InfraRN {
  1086 +
  1087 + protected $objRN;
  1088 + protected $strAction;
  1089 + protected $arrTokens = array();
  1090 + protected $objInfraBanco;
  1091 +
  1092 + public function __construct($objRN = null, $tokens = array()) {
  1093 +
  1094 + if(!is_null($objRN)) {
  1095 +
  1096 + parent::__construct();
  1097 +
  1098 + if(!is_object($objRN)) {
  1099 + throw new InfraException('Requerido objeto Infra');
  1100 + }
  1101 +
  1102 + if(get_parent_class($objRN) !== 'InfraRN') {
  1103 + throw new InfraException('Requerido objeto Infra que seja extendido de InfraRN');
  1104 + }
  1105 +
  1106 + $this->objRN = $objRN;
  1107 + }
  1108 +
  1109 + if(empty($tokens)) {
  1110 + $tokens = $_SERVER['argv'];
  1111 + }
  1112 +
  1113 + $this->criarTokens($tokens);
  1114 + }
  1115 +
  1116 + /**
  1117 + * Inicializador o banco de dados
  1118 + */
  1119 + protected function inicializarObjInfraIBanco() {
  1120 + if(empty($this->objInfraBanco)){
  1121 + $this->objInfraBanco = BancoSEI::getInstance();
  1122 + }
  1123 + return $this->objInfraBanco;
  1124 + }
  1125 +
  1126 + /**
  1127 + * Processa os parâmetros passados ao script pelo cli
  1128 + *
  1129 + * @param array $arguments
  1130 + * @return null
  1131 + */
  1132 + protected function criarTokens($arguments = array()){
  1133 +
  1134 + if(empty($arguments)) {
  1135 + throw new InfraException('Script não pode ser executado pela web');
  1136 + }
  1137 +
  1138 + $strScript = array_shift($arguments);
  1139 +
  1140 + if(!empty($this->objRN)) {
  1141 +
  1142 + $strAction = array_shift($arguments);
  1143 +
  1144 + if(substr($strAction, 0, 2) == '--') {
  1145 + throw new InfraException('O primeiro paramêtro deve ser uma action da RN');
  1146 + }
  1147 +
  1148 + $this->strAction = $strAction;
  1149 + }
  1150 +
  1151 + foreach($arguments as $key => $argument) {
  1152 +
  1153 + if(substr($argument, 0, 2) === '--'){
  1154 +
  1155 + $string = preg_replace('/^--/', '', $argument);
  1156 + $array = explode('=', $string);
  1157 +
  1158 + $key = array_shift($array);
  1159 + $value = (count($array) > 0) ? array_shift($array) : true;
  1160 +
  1161 + $this->arrTokens[$key] = $value;
  1162 + }
  1163 + }
  1164 + }
  1165 +
  1166 + /**
  1167 + * Retorna os parâmetros
  1168 + */
  1169 + public function getTokens(){
  1170 + return $this->arrTokens;
  1171 + }
22 1172  
  1173 + public function run(){
  1174 +
  1175 + if(empty($this->objRN)) {
  1176 + throw new InfraException('Nenhuma RN foi adicionada ao console');
  1177 + }
  1178 +
  1179 + if(!method_exists($this->objRN, $this->strAction)) {
  1180 +
  1181 + throw new InfraException(sprintf('Nenhuma ação "%s" foi encontrada em %s '.PHP_EOL.$this->objRN->ajuda(), $this->strAction, get_class($this->objRN)));
  1182 + }
  1183 +
  1184 + if(array_key_exists('ajuda', $this->arrTokens)) {
  1185 +
  1186 + print $this->objRN->ajuda();
  1187 + return true;
  1188 + }
  1189 +
  1190 + return call_user_func(array($this->objRN, $this->strAction), $this->getTokens());
  1191 + }
  1192 +
  1193 + public static function format($strMensagem = '', $strFonte = '', $bolBold = false){
  1194 +
  1195 + $strBold = ($bolBold !== false) ? '1' : '0';
  1196 +
  1197 + //$strMensagem = escapeshellarg($strMensagem);
  1198 +
  1199 + if(!empty($strFonte)) {
  1200 +
  1201 + switch($strFonte){
  1202 +
  1203 + case 'green':
  1204 + $strMensagem = "\033[".$strBold.";32m".$strMensagem;
  1205 + break;
  1206 +
  1207 + case 'red':
  1208 + $strMensagem = "\033[".$strBold.";31m".$strMensagem;
  1209 + break;
  1210 +
  1211 + case 'blue':
  1212 + $strMensagem = "\033[".$strBold.";34m".$strMensagem;
  1213 + break;
  1214 +
  1215 + case 'yellow':
  1216 + $strMensagem = "\033[".$strBold.";33m".$strMensagem;
  1217 + break;
  1218 +
  1219 + }
  1220 + }
  1221 + return static::resetAfter($strMensagem);
  1222 + }
  1223 +
  1224 + public static function resetAfter($strMensagem = ''){
  1225 +
  1226 + return $strMensagem. "\033[0m";
  1227 + }
  1228 +}
  1229 +
  1230 +try {
  1231 +
23 1232 $objPenConsoleRN = new PenConsoleRN();
24 1233 $arrArgs = $objPenConsoleRN->getTokens();
25   -
  1234 +
26 1235 $objAtualizarRN = new PenAtualizarSipRN($arrArgs);
27 1236 $objAtualizarRN->atualizarVersao();
28   -
  1237 +
29 1238 exit(0);
30   -}
31   -catch(Exception $e) {
32   -
  1239 +} catch (Exception $e) {
  1240 +
33 1241 print InfraException::inspecionar($e);
34   -
  1242 +
35 1243 try {
36 1244 LogSEI::getInstance()->gravar(InfraException::inspecionar($e));
37 1245 } catch (Exception $e) {
38 1246  
39 1247 }
40   -
  1248 +
41 1249 exit(1);
42 1250 }
43 1251  
44 1252 print PHP_EOL;
45   -
46   -/**
47   - # Apagar modulo PEN no SEI pelo MySQL
48   -
49   - # Apagar modulo PEN no SIP pelo MySQL
50   - SET FOREIGN_KEY_CHECKS = 1;
51   -
52   - DELETE FROM sip.recurso WHERE nome IN(
53   - 'pen_procedimento_expedir',
54   - 'pen_procedimento_expedido_listar',
55   - 'pen_map_tipo_doc_enviado_visualizar',
56   - 'pen_map_tipo_doc_enviado_cadastrar',
57   - 'pen_map_tipo_doc_enviado_listar',
58   - 'pen_map_tipo_doc_recebido_cadastrar',
59   - 'pen_map_tipo_doc_recebido_listar'
60   - );
61   - SET FOREIGN_KEY_CHECKS = 0;
62   -
63   - */
64 1253 \ No newline at end of file
... ...
verificar-servicos.sh
1 1 #!/bin/bash
2 2  
3   -if $(service gearmand status | grep -qv "running") ; then
4   - service gearmand start;
5   - LOG="Servico gearman foi iniciado"
  3 +PATH=/usr/bin:/sbin:/bin:/usr/sbin
  4 +export PATH
  5 +
  6 +if $(service gearmand status | grep -qv "running") ; then
  7 + service gearmand start;
  8 + LOG="Servico gearman foi iniciado"
6 9 fi
7 10  
8   -if $(service supervisord status | grep -qv "running") ; then
9   - service supervisord start;
10   - LOG="Servico supervisor foi iniciado"
  11 +if $(service supervisord status | grep -qv "running") ; then
  12 + service supervisord start;
  13 + LOG="Servico supervisor foi iniciado"
11 14 else
12 15  
13   - COMMAND=$(ps -C php -f | grep -o "PendenciasTramiteRN.php");
14   -
15   - if [ -z "$COMMAND" ]
16   - then
17   - service supervisord restart;
18   - LOG="Servico supervisor foi reiniciado"
19   - fi
20   -
21   - COMMAND=$(ps -C php -f | grep -o "ProcessarPendenciasRN.php");
22   -
23   - if [ -z "$COMMAND" ]
24   - then
25   - service supervisord restart;
26   - LOG="Servico supervisor foi reiniciado"
27   - fi
  16 + COMMAND=$(ps -C php -f | grep -o "PendenciasTramiteRN.php");
  17 +
  18 + if [ -z "$COMMAND" ]
  19 + then
  20 + service supervisord restart;
  21 + LOG="Servico supervisor foi reiniciado"
  22 + fi
  23 +
  24 + COMMAND=$(ps -C php -f | grep -o "ProcessarPendenciasRN.php");
  25 +
  26 + if [ -z "$COMMAND" ]
  27 + then
  28 + service supervisord restart;
  29 + LOG="Servico supervisor foi reiniciado"
  30 + fi
28 31 fi
29 32  
30 33 if [ -n "$LOG" ]
31 34 then
32   - /usr/bin/php console.php log --msg="$LOG" > /dev/null
  35 + #/usr/bin/php console.php log --msg="$LOG" > /dev/null
  36 + echo $LOG
33 37 fi
34   -
35   -
... ...