/**
  * Exclui um objeto oid do Banco de dados
  * @param integer $iOid
  *
  * Caso de Uso: Ao excluir um registro de uma tabela e eo campo for do tipo oid,
  * Deve-se excluir o objeto do banco utilizando este método
  */
 public static function exclusao($iOid)
 {
     $lTransacaoInterna = false;
     global $conn;
     if (!db_utils::inTransaction()) {
         throw new Exception("Sem transação Ativa.");
     }
     return pg_lo_unlink($conn, $iOid);
 }
 function __construct()
 {
     /**
      * Declaramos as variáveis da classe de acordo com o que está configurado no arquivo config.mail.php
      */
     include_once 'libs/config.mail.php';
     $this->sUserMail = $sUser;
     $this->sPassMail = $sPass;
     $this->sHostMail = $sHost;
     $this->sPortMail = (int) $sPort;
     $this->sClass = (int) $sClass;
     $oConfigDBpref = db_utils::getDao("configdbpref");
     $rsConfigDBpref = $oConfigDBpref->sql_record($oConfigDBpref->sql_query_file(db_getsession('DB_instit'), "w13_emailadmin"));
     $this->sEmailFrom = db_utils::fieldsMemory($rsConfigDBpref, 0)->w13_emailadmin;
 }
function db_rodape()
{
    require_once "libs/db_utils.php";
    require_once "libs/JSON.php";
    $oJSON = new Services_JSON();
    $sRodape = "<center>";
    $oDaoDBConfig = db_utils::getDao("db_config");
    $oInstituicao = $oDaoDBConfig->getParametrosInstituicao();
    if (!empty($oInstituicao->uf)) {
        $oEstados = $oJSON->decode(file_get_contents('imagens/estados/estados.json'));
        $sSiglaEstado = strtolower($oInstituicao->uf);
        if (!empty($oEstados->{$sSiglaEstado})) {
            $oEstado = $oEstados->{$sSiglaEstado};
            if (file_exists($oEstado->sCaminhoImagem)) {
                $sRodape .= "\t<a target='_blank' href='{$oEstado->sUrl}' style='margin-right:20px;text-decoration:none;'>           ";
                $sRodape .= "  \t<img src='{$oEstado->sCaminhoImagem}' title='{$oEstado->sTextoAlternativo}' width='37' height='18'> ";
                $sRodape .= " </a>                         ";
            }
        }
    }
    if (file_exists('imagens/gov_br.jpg')) {
        $sRodape .= "\t<a target='_blank'  href='http://www.brasil.gov.br' style='margin-right:20px;text-decoration:none;'>                            ";
        $sRodape .= "\t\t<img src='imagens/gov_br.jpg' width='69' height='18'>                                                                         ";
        $sRodape .= "  </a>                                                                                                                           ";
    }
    if (file_exists('imagens/adobe.gif')) {
        $sRodape .= "\t<a target='_blank'  href='http://www.adobe.com/products/acrobat/readstep2.html' style='margin-right:20px;text-decoration:none;'>";
        $sRodape .= "\t\t<img src='imagens/adobe.gif'>                                                                                                 ";
        $sRodape .= "\t</a>                                                                                                                            ";
    }
    $sRodape .= "  <font style='margin-right:20px;'>                                                                                              ";
    $sRodape .= "\t\t<br /><br />                                                                                                                  ";
    $sRodape .= "\t\tcopyright " . date('Y') . " &copy;                                                                                            ";
    $sRodape .= "\t  <a target='_blank' href='http://www.dbseller.com.br'>www.dbseller.com.br </a>                                                 ";
    $sRodape .= "  </font>                                                                                                                        ";
    $sRodape .= "</center>                                                                                                                        ";
    echo $sRodape;
}
 /**
  * No construtor já será gerado os abjetos apartir do layout informado
  *
  * @param integer $iLayoutTxt  Código do Cadastro de Layout
  * @param string  $sArquivo    Caminho do Arquivo
  * @param boolean $lUsaSeparador  true para utilizar separador (se houver), ou seja,
  * fazer o explode pelo separador nas linhas. false para não utilizar separador.
  * @param boolean $lProcessarArquivo  true para processar o arquivo diretamente default true
  */
 function __construct($iLayoutTxt = '', $sArquivo = '', $lUsaSeparador = false, $lProcessarArquivo = true, $lUsaChr = false)
 {
     if (trim($iLayoutTxt) == '') {
         throw new Exception('Código do Layout não informado!');
     }
     if (trim($sArquivo) == '') {
         throw new Exception('Caminho do arquivo não informado!');
     }
     $clLayoutTxt = db_utils::getDao("db_layouttxt");
     $this->sCaminhoArquivo = $sArquivo;
     /**
      *  Consulta as propriedades de cada campo das linhas do layout informado 
      */
     $sCamposDadosLayout = " ( select trim(db52_default)                     ";
     $sCamposDadosLayout .= "\t\t\tfrom db_layoutcampos                  \t\t\t";
     $sCamposDadosLayout .= "\t\t where db52_layoutlinha = db51_codigo\t\t\t\t\t";
     $sCamposDadosLayout .= "\t\t\t and db52_ident is true ) as identificador, ";
     $sCamposDadosLayout .= "\tdb52_nome       as nome_campo,         \t\t\t\t\t";
     $sCamposDadosLayout .= " db52_descr      as descricao_campo,             ";
     $sCamposDadosLayout .= "\tdb52_posicao    as posicao_campo,    \t\t\t\t\t\t";
     $sCamposDadosLayout .= "\tdb52_tamanho    as tamanho_campo, \t\t\t\t\t\t\t";
     $sCamposDadosLayout .= "\tdb51_separador  as separador_campo,\t\t\t\t\t\t\t";
     $sCamposDadosLayout .= " db52_obs        as observacao_campo,             ";
     $sCamposDadosLayout .= "\tdb52_ident      as campo_identificador      \t\t";
     $sOrderByDadosLayout = " db51_tipolinha, ";
     $sOrderByDadosLayout .= " identificador,  ";
     $sOrderByDadosLayout .= " db52_posicao    ";
     $sSqlDadosLayout = $clLayoutTxt->sql_query_campos($iLayoutTxt, $sCamposDadosLayout, $sOrderByDadosLayout);
     $rsDadosLayout = $clLayoutTxt->sql_record($sSqlDadosLayout);
     $iLinhasLayout = $clLayoutTxt->numrows;
     if ($iLinhasLayout > 0) {
         /**
          * Para o caso de utilizar separadores para determinar os campos dentro das linhas
          * preciso saber o índice do vetor explodido no separador. Como os dados vêm ordenados
          * pelo tipo de linha e pela posição dentro do tipo de linha, então, a ordem
          * para cada campo dentro de cada tipo de linha já está correta. O índice começa em 0
          * porque os arrays no PHP começam em 0 também.
          * Ex.: 
          * linha: 123|456|78
          * separador: |
          * array explodido: {123, 456, 78}
          * valor da posição 1: 456
          */
         $iIndice = 0;
         /**
          * Variável que identifica a mudança de um tipo de linha para outro
          */
         $sIdentificadorAtual = '';
         for ($iInd = 0; $iInd < $iLinhasLayout; $iInd++) {
             $oDadosLayout = db_utils::fieldsMemory($rsDadosLayout, $iInd);
             /**
              * Verifico se mudou o tipo de linha. Se mudou, zero o índice do campo.
              */
             if ($sIdentificadorAtual != $oDadosLayout->identificador) {
                 $iIndice = 0;
                 $sIdentificadorAtual = $oDadosLayout->identificador;
             }
             /**
              *  Cria um array contendo as propriedades necessárias para 
              *  a localização do campo dentro da linha do arquivo
              */
             $this->aPropriedadesCampos[$oDadosLayout->identificador][$oDadosLayout->nome_campo] = array($oDadosLayout->posicao_campo, $oDadosLayout->tamanho_campo, $oDadosLayout->separador_campo, $iIndice, $oDadosLayout->nome_campo, $oDadosLayout->campo_identificador == 't' ? true : false, $oDadosLayout->descricao_campo, $oDadosLayout->observacao_campo);
             $iTamanhoIdent = strlen($oDadosLayout->identificador);
             $iIndice++;
         }
     }
     if ($lProcessarArquivo) {
         $this->processarArquivo($iTamanhoIdent, $lUsaSeparador, false, $lUsaChr);
     }
 }
function MensagemCarne($exerc, $arretipo, $dtbase, $matric, $arrematric = "w_arrematric as arrematric")
{
    $mensagem = "";
    // Verifica Debitos Vencidos
    $sql = "  select arrecad.k00_tipo, ";
    $sql .= "         arretipo.k03_tipo, ";
    $sql .= "         count(distinct arrecad.k00_numpar) as qtdatraso ";
    $sql .= "    from arrecad ";
    $sql .= "         inner join arretipo on arretipo.k00_tipo = arrecad.k00_tipo ";
    $sql .= "   where arrecad.k00_numpre in (select k00_numpre from {$arrematric}) ";
    $sql .= "     and arrecad.k00_dtvenc < '{$dtbase}' ";
    $sql .= "group by arrecad.k00_tipo, ";
    $sql .= "         arretipo.k03_tipo ";
    $sql .= "order by 3 desc ";
    // ordena pela qtd parcelas em atraso em ordem descendente
    //die($sql);
    $resDebitos = db_query($sql);
    $rowsDebitos = pg_numrows($resDebitos);
    for ($iDeb = 0; $iDeb < $rowsDebitos; $iDeb++) {
        $oDebito = db_utils::fieldsmemory($resDebitos, $iDeb);
        if ($oDebito->qtdatraso >= 2) {
            // se tem duas ou mais parcelas em aberto...
            $mensagem = "AVISO DE SUSPENSÃO DO FORNECIMENTO DE ÁGUA: Fica o usuário avisado que a não regularização dos débitos do imóvel no prazo de 30 (trinta) dias, a contar do vencimento da segunda parcela em atraso, acarretará na suspensão do fornecimento de água (art. 40, V, §2º da Lei n.º 11.445/07).";
            break;
        } else {
            // Verifica o CADTIPO
            switch ($oDebito->k03_tipo) {
                // Divida Ativa
                case 5:
                case 18:
                    if (empty($mensagem)) {
                        $mensagem = "Imovel possui Divida Ativa";
                    } else {
                        $mensagem .= " / Divida Ativa";
                    }
                    break;
                    // Parcelamento
                // Parcelamento
                case 6:
                case 13:
                    if (empty($mensagem)) {
                        $mensagem = "Imovel possui Parcelamento em Atraso";
                    } else {
                        $mensagem .= " / Parcelamento em Atraso";
                    }
                    break;
                    // Saneamento Básico (Agua Exercicio)
                // Saneamento Básico (Agua Exercicio)
                case 20:
                    if (empty($mensagem)) {
                        $mensagem = "Imovel possui Debito no Exercicio";
                    } else {
                        $mensagem .= " / Debito no Exercicio ";
                    }
                    break;
                    // Outros Débitos
                // Outros Débitos
                default:
                    if (empty($mensagem)) {
                        $mensagem = "Imovel possui Outros Debitos em Atraso";
                    } else {
                        $mensagem .= " / Outros Debitos em Atraso ";
                    }
                    break;
            }
        }
    }
    if (empty($mensagem)) {
        // se nao tem nada em aberto
        $mensagem = "Obrigado pela pontualidade!!!";
    }
    db_query("set enable_bitmapscan to off");
    return $mensagem;
}
 *  detalhes.                                                         
 *                                                                    
 *  Voce deve ter recebido uma copia da Licenca Publica Geral GNU     
 *  junto com este programa; se nao, escreva para a Free Software     
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA          
 *  02111-1307, USA.                                                  
 *  
 *  Copia da licenca no diretorio licenca/licenca_en.txt 
 *                                licenca/licenca_pt.txt 
 */
include "libs/db_conecta.php";
include "libs/db_stdlib.php";
include "libs/db_sql.php";
include "libs/db_utils.php";
parse_str($HTTP_SERVER_VARS["QUERY_STRING"]);
$oGet = db_utils::postmemory($_GET);
$cnpj = formataCpfCnpj($oGet->cnpj);
$sql = "select * from cgm where z01_cgccpf = '{$cnpj}'";
//die($sql);
$result = pg_query($sql);
$linha = pg_num_rows($result);
if ($linha > 0) {
    db_fieldsmemory($result, 0);
    echo " <script> \n          \tparent.document.form1.nomerazao.value = '{$z01_nome}';\n  \t     </script>";
}
/*else{
   $sql2= "select q21_nome from issplanit where q21_cnpj =  '$cnpj'";
   //die($sql2);
	 $result2=pg_query($sql2);
	 $linha2=pg_num_rows($result2);
		if ($linha2 > 0) {
 *  
 *  Copia da licenca no diretorio licenca/licenca_en.txt 
 *                                licenca/licenca_pt.txt 
 */
include "libs/db_conecta.php";
include "libs/db_stdlib.php";
include "libs/db_sql.php";
include "libs/db_utils.php";
validaUsuarioLogado();
$aRetorno = array();
parse_str(base64_decode($HTTP_SERVER_VARS["QUERY_STRING"]), $aRetorno);
$iMatric = $aRetorno['iMatric'];
$oRHPessoal = db_utils::getDao('rhpessoal');
$sSqlDadosServidor = "select *,\n                             substr((select * from  db_fxxx(rh02_regist,rh02_anousu,rh02_mesusu,rh02_instit)),210,25) as padraoatual\n\t\t\t\t\t\t\t\t\t\t\t  from rhpessoal\n\t\t\t\t\t\t\t\t\t\t\t       inner join rhpessoalmov    on rh02_anousu                        = " . db_anofolha() . " \n\t\t\t\t\t\t\t\t\t\t\t                                 and rh02_mesusu                        = " . db_mesfolha() . "\n\t\t\t\t\t\t\t\t\t\t\t                                 and rh02_regist                        = rh01_regist\n\t\t\t\t\t\t\t\t\t\t\t       left  join rhlota          on rhlota.r70_codigo                  = rhpessoalmov.rh02_lota\n\t\t\t\t\t\t\t\t\t\t\t                                 and rhlota.r70_instit                  = rhpessoalmov.rh02_instit\n\t\t\t\t\t\t\t\t\t\t\t       left  join rhpesbanco      on rh44_seqpes                        = rhpessoalmov.rh02_seqpes\n\t\t\t\t\t\t\t\t\t\t\t       inner join cgm             on cgm.z01_numcgm                     = rhpessoal.rh01_numcgm\n\t\t\t\t\t\t\t\t\t\t\t       left  join db_cgmruas      on db_cgmruas.z01_numcgm              = cgm.z01_numcgm\n\t\t\t\t\t\t\t\t\t\t\t       left  join ruas            on ruas.j14_codigo                    = db_cgmruas.j14_codigo\n\t\t\t\t\t\t\t\t\t\t\t       left  join ruastipo        on ruastipo.j88_codigo                = ruas.j14_tipo\n\t\t\t\t\t\t\t\t\t\t\t       inner join rhestcivil      on rhestcivil.rh08_estciv             = rhpessoal.rh01_estciv\n\t\t\t\t\t\t\t\t\t\t\t       left  join rhfuncao        on rhfuncao.rh37_funcao               = rhpessoal.rh01_funcao\n\t\t\t\t\t\t\t\t\t\t\t                                 and rhfuncao.rh37_instit               = rhpessoalmov.rh02_instit\n\t\t\t\t\t\t\t\t\t\t\t       left  join rhregime        on rhregime.rh30_codreg               = rhpessoalmov.rh02_codreg\n\t\t\t\t\t\t\t\t\t\t\t                                 and rhregime.rh30_instit               = rhpessoalmov.rh02_instit   \n\t\t\t\t\t\t\t\t\t\t\t       inner join rhinstrucao     on rhinstrucao.rh21_instru            = rhpessoal.rh01_instru\n\t\t\t\t\t\t\t\t\t\t\t       left  join rhpespadrao     on rhpespadrao.rh03_seqpes            = rhpessoalmov.rh02_seqpes \n\t\t\t\t\t\t\t\t\t\t\t       left  join rhpesrescisao   on rh02_seqpes = rh05_seqpes\n\t\t\t\t\t\t\t\t\t\t\t where rhpessoal.rh01_regist = {$iMatric}";
$rsDadosServidor = $oRHPessoal->sql_record($sSqlDadosServidor);
$oDadosServidor = db_utils::fieldsMemory($rsDadosServidor, 0);
?>
<html>
<head>
<title><?php 
echo $w01_titulo;
?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="config/estilos.css"        rel="stylesheet" type="text/css">
<link href="config/portalservidor.css" rel="stylesheet" type="text/css">

<script language="JavaScript" src="scripts/scripts.js"></script>
<script language="JavaScript" src="scripts/db_script.js"></script>
</head>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" bgcolor="<?php 
 function sql_record()
 {
     global $o70_anousu, $o70_codrec, $o57_fonte, $o57_descr, $janeiro, $fevereiro, $marco, $abril, $maio, $junho, $julho, $agosto, $setembro, $outubro, $novembro, $dezembro, $o70_valor, $adicional;
     global $prev_jan, $prev_fev, $prev_mar, $prev_abr, $prev_mai, $prev_jun, $prev_jul, $prev_ago, $prev_set, $prev_out, $prev_nov, $prev_dez;
     require_once "libs/db_utils.php";
     if ($this->sql == null) {
         $this->sql_query($this->receita);
     }
     //    echo($this->sql . "<br>");
     pg_exec("begin");
     pg_exec("create temporary table work_plano as " . $this->sql);
     pg_exec("create index work_plano_estrut on work_plano(o57_fonte)");
     $result = pg_query("select * from work_plano");
     for ($i = 0; $i < pg_numrows($result); $i++) {
         db_fieldsmemory($result, $i);
         $sSqlSaldoPrevisao = "SELECT mes,coalesce(o34_valor, 0) as valor, {$o70_codrec} as receita \n                                 from  generate_series(1,12) as mes";
         $sSqlSaldoPrevisao .= "       left join orcprevrec ";
         $sSqlSaldoPrevisao .= "       on mes = o34_mes and o34_anousu = {$this->anousu} and o34_codrec = {$o70_codrec}";
         $sSqlSaldoPrevisao .= "    order by mes";
         if ($this->lPrevisaoCronograma) {
             $sSqlSaldoPrevisao = "SELECT coalesce(valor, 0) as valor, {$o70_codrec} as receita, mes";
             $sSqlSaldoPrevisao .= "  from generate_series(1,12) as mes";
             $sSqlSaldoPrevisao .= "       left join (SELECT coalesce(o127_valor, 0) as valor, ";
             $sSqlSaldoPrevisao .= "                         o127_mes ";
             $sSqlSaldoPrevisao .= "                    from cronogramaperspectivareceita  ";
             $sSqlSaldoPrevisao .= "                         inner join orcreceita on o70_codrec  = o126_codrec  ";
             $sSqlSaldoPrevisao .= "                                              and o126_anousu = {$this->anousu}";
             $sSqlSaldoPrevisao .= "                   inner join cronogramametareceita on o127_cronogramaperspectivareceita = o126_sequencial";
             $sSqlSaldoPrevisao .= "                   where o126_codrec = {$o70_codrec} ";
             $sSqlSaldoPrevisao .= "                      ) as bases on mes = o127_mes ";
             $sSqlSaldoPrevisao .= "                                        order by mes ";
         }
         //die($sSqlSaldoPrevisao);
         $rsSaldoPrevisao = db_query($sSqlSaldoPrevisao);
         $aMeses = db_utils::getColectionByRecord($rsSaldoPrevisao);
         $aValorPrevMes = array();
         foreach ($aMeses as $oSaldoMes) {
             $aValorPrevMes[$oSaldoMes->mes] = $oSaldoMes->valor;
         }
         $prev_jan += $aValorPrevMes[1];
         $prev_fev += $aValorPrevMes[2];
         $prev_mar += $aValorPrevMes[3];
         $prev_abr += $aValorPrevMes[4];
         $prev_mai += $aValorPrevMes[5];
         $prev_jun += $aValorPrevMes[6];
         $prev_jul += $aValorPrevMes[7];
         $prev_ago += $aValorPrevMes[8];
         $prev_set += $aValorPrevMes[9];
         $prev_out += $aValorPrevMes[10];
         $prev_nov += $aValorPrevMes[11];
         $prev_dez += $aValorPrevMes[12];
         $estrutural = $o57_fonte;
         if ($this->lPrevisaoCronograma) {
             pg_query("update work_plano set \n          prev_jan  = prev_jan  +{$prev_jan},\n          prev_fev  = prev_fev  +{$prev_fev}+0.0,\n          prev_mar  = prev_mar  +{$prev_mar}+0.0,\n          prev_abr  = prev_abr  +{$prev_abr}+0.0,\n          prev_mai  = prev_mai  +{$prev_mai}+0.0,\n          prev_jun  = prev_jun  +{$prev_jun}+0.0,\n          prev_jul  = prev_jul  +{$prev_jul}+0.0,\n          prev_ago  = prev_ago  +{$prev_ago}+0.0,\n          prev_set  = prev_set  +{$prev_set}+0.0,\n          prev_out  = prev_out  +{$prev_out}+0.0,\n          prev_nov  = prev_nov  +{$prev_nov}+0.0,\n          prev_dez  = prev_dez  +{$prev_dez}+0.0          \n          \n          \n          where o70_codrec = {$o70_codrec}");
         }
         for ($ii = 1; $ii < 10; $ii++) {
             ///o zé colocou isso... 19042005
             if ($estrutural == "") {
                 continue;
             }
             $estrutural = db_le_mae_conplano($estrutural);
             $nivel = db_le_mae_conplano($estrutural, true);
             $result_estrut = pg_query("select o57_descr from work_plano where o57_fonte = '{$estrutural}'");
             // db_criatabela($result_estrut); exit;
             //if ($estrutural == '411229900000000'){
             //   echo ($estrutural." ->" .$o70_valor ." <br>");
             // }
             if (pg_numrows($result_estrut) == 0) {
                 $result_estrut = pg_query("select o57_descr from orcfontes where o57_anousu = " . $this->anousu . " and o57_fonte = '{$estrutural}'");
                 if (pg_numrows($result_estrut) == 0) {
                     echo "Conta não encontrada nas fontes de Receita Comando:" . "select o57_descr from orcfontes where o57_anousu = " . $this->anousu . " and o57_fonte = '{$estrutural}'";
                     exit;
                 }
                 db_fieldsmemory($result_estrut, 0);
                 $sInsert = "insert into work_plano values(\n          " . $this->anousu . ",\n          0,\n          0,\n          '{$estrutural}',\n          '{$o57_descr}',\n          {$o70_valor},\n          {$adicional},\n          {$janeiro},\n          {$fevereiro},\n          {$marco},\n          {$abril},\n          {$maio},\n          {$junho},\n          {$julho},\n          {$agosto},\n          {$setembro},\n          {$outubro},\n          {$novembro},\n          {$dezembro},\n          {$prev_jan},\n          {$prev_fev},\n          {$prev_mar},\n          {$prev_abr},\n          {$prev_mai},\n          {$prev_jun},\n          {$prev_jul},\n          {$prev_ago},\n          {$prev_set},\n          {$prev_out},\n          {$prev_nov},\n          {$prev_dez}\n          )\n          ";
                 $result_1 = pg_query($sInsert);
             } else {
                 pg_query("update work_plano set \n          o70_valor = o70_valor + {$o70_valor},\n          adicional= adicional  +{$adicional},\n          janeiro  = janeiro    +{$janeiro},\n          fevereiro= fevereiro  +{$fevereiro},\n          marco    = marco      +{$marco},\n          abril    = abril      +{$abril},\n          maio     = maio       +{$maio},\n          junho    = junho      +{$junho},\n          julho    = julho      +{$julho},\n          agosto   = agosto     +{$agosto},\n          setembro = setembro   +{$setembro},\n          outubro  = outubro    +{$outubro},\n          novembro = novembro   +{$novembro},\n          dezembro = dezembro   +{$dezembro},\n          prev_jan  = prev_jan  +{$prev_jan},\n          prev_fev  = prev_fev  +{$prev_fev}+0.0,\n          prev_mar  = prev_mar  +{$prev_mar}+0.0,\n          prev_abr  = prev_abr  +{$prev_abr}+0.0,\n          prev_mai  = prev_mai  +{$prev_mai}+0.0,\n          prev_jun  = prev_jun  +{$prev_jun}+0.0,\n          prev_jul  = prev_jul  +{$prev_jul}+0.0,\n          prev_ago  = prev_ago  +{$prev_ago}+0.0,\n          prev_set  = prev_set  +{$prev_set}+0.0,\n          prev_out  = prev_out  +{$prev_out}+0.0,\n          prev_nov  = prev_nov  +{$prev_nov}+0.0,\n          prev_dez  = prev_dez  +{$prev_dez}+0.0          \n          \n          \n          where o57_fonte = '{$estrutural}'");
             }
             /*
                     o70_valor = o70_valor+$o70_valor,
                     adicional= adicional+$adicional,
             */
             if ($nivel == 1) {
                 break;
             }
         }
     }
     //exit;
     $sql = " \n    SELECT O70_ANOUSU,O70_CODREC,o70_instit,O57_FONTE,O57_DESCR,round(O70_VALOR,2) as o70_valor,\n    round(adicional,2) as adicional,\n    round(JANEIRO,2 ) as JANEIRO,\n    round(FEVEREIRO,2) as FEVEREIRO,\n    round(MARCO,2  )  as MARCO,\n    round(ABRIL,2  )  as ABRIL,\n    round(MAIO, 2  )  as MAIO,\n    round(JUNHO,2  )  as JUNHO,\n    round(JULHO,2  )  as JULHO,\n    round(AGOSTO,2 )  as AGOSTO,\n    round(SETEMBRO,2)  as SETEMBRO,\n    round(OUTUBRO,2 )  as OUTUBRO,\n    round(NOVEMBRO,2)  as NOVEMBRO,\n    round(DEZEMBRO,2)  as DEZEMBRO,\n    prev_jan,\n    prev_fev,\n    prev_mar,\n    prev_abr,\n    prev_mai,\n    prev_jun,\n    prev_jul,\n    prev_ago,\n    prev_set,\n    prev_out,\n    prev_nov,\n    prev_dez\n    \n    from work_plano ";
     //--
     if ($this->estrut != null) {
         $sql .= "where O57_FONTE IN  " . $this->estrut;
     }
     $sql .= "order by o57_fonte ";
     $this->result = pg_query($sql);
     if ($this->anousu == 2010) {
         //db_criatabela($this->result);
     }
     if ($this->result != false) {
         $this->numrows = pg_numrows($this->result);
     } else {
         $this->numrows = 0;
     }
 }
include "libs/db_stdlib.php";
include "libs/db_utils.php";
include "dbforms/db_funcoes.php";
include "classes/db_db_usuarios_classe.php";
include "classes/db_db_usuacgm_classe.php";
include "libs/db_sql.php";
include "classes/db_cgm_classe.php";
include "libs/smtp.class.php";
require_once "libs/db_encriptacao.php";
$cldb_usuarios = new cl_db_usuarios();
$cldb_usuacgm = new cl_db_usuacgm();
$clcgm = new cl_cgm();
parse_str(base64_decode($HTTP_SERVER_VARS["QUERY_STRING"]));
db_logs("", "", 0, "Pedido de Senha.");
$oGet = db_utils::postmemory($_GET);
$oPost = db_utils::postmemory($_POST);
$sMatric = $oGet->nummatricula;
$sNome = $oGet->nome;
$sCgcCpf = formataCpfBanco($oGet->numcpf);
$sDataNasc = formataDataNascBanco($oGet->datansc);
$sNomeMae = $oGet->nomemae;
$sEmailServ = $oGet->emailsrv;
$sPassword = Encriptacao::encriptaSenha($oPost->senhasrv);
$sHeader = $oGet->header;
$mostar = 1;
// pedido de senha e executado se chave == 't'
if (isset($oGet->chave) && $oGet->chave == 't') {
    $sql = " select rh01_regist,\n                  z01_numcgm,\n                  z01_nome,\n                  z01_cgccpf,\n                  z01_nasc,\n                  z01_mae,\n                  z01_email,\n                  email,\n                  senha,\n                  login\n             from rhpessoal\n                  inner join cgm on rh01_numcgm = z01_numcgm\n                  left join db_usuarios on db_usuarios.nome  =  cgm.z01_nome\n            where rh01_regist = '{$sMatric}'\n              and z01_nasc is not null\n              and z01_mae is not null limit 1 ";
    $result = db_query($sql);
    $total = pg_num_rows($result);
    if ($total == 0) {
 /**
  * Anulaçao do debito, já efetuando o processamento do cancelamento
  *
  * @param boolean $cancdebitosissplan se a anulação é de uma planilha de retencao;
  */
 function incluir_cancelamento($cancdebitosissplan = true)
 {
     // $cancdebitosissplan = Se grava na cancdebitosissplan...true: grava false: não grava
     //gravar na cancdebitos, cancdebitosreg, cancdebitosproc, cancdebitosprocreg
     $erro = false;
     // inclui cancdebitos
     $this->incluir(null);
     if ($this->erro_status == "0") {
         echo $this->erro_msg;
         $erro = true;
         //echo"<br>erro na cancdebitos".$this->erro_msg;
     }
     $codigo = $this->k20_codigo;
     if ($cancdebitosissplan == true) {
         // inclui cancdebitosissplan
         $clcancdebitosissplan = db_utils::getDao("cancdebitosissplan");
         $clcancdebitosissplan->q78_cancdebitos = $codigo;
         $clcancdebitosissplan->q78_issplan = $this->planilha;
         $clcancdebitosissplan->incluir(null);
         if ($clcancdebitosissplan->erro_status == "0") {
             $erro = true;
             $this->erro_msg = "planilha" . $clcancdebitosissplan->erro_msg;
             //echo "<br> não incluiu na cancdebitosissplan ".$this->erro_msg;
             $this->erro_status = "0";
         }
     }
     // inclui cancdebitosproc
     $clcancdebitosproc = db_utils::getDao("cancdebitosproc");
     $clcancdebitosproc->k23_data = $this->k20_data;
     $clcancdebitosproc->k23_hora = $this->k20_hora;
     $clcancdebitosproc->k23_usuario = $this->usuario;
     $clcancdebitosproc->k23_cancdebitostipo = 1;
     $clcancdebitosproc->k23_obs = $this->k21_obs;
     $clcancdebitosproc->incluir(null);
     if ($clcancdebitosproc->erro_status == "0") {
         $erro = true;
         $this->erro_msg = "deb prtoc" . $clcancdebitosproc->erro_msg;
         //echo "<br> não incluiu na cancdebitosproc ".$this->erro_msg;
         $this->erro_status = "0";
     }
     //echo "<br> cancdebitosproc = ".$clcancdebitosproc->k23_codigo;
     $clcancdebitosprocreg = db_utils::getDao("cancdebitosprocreg");
     $clcancdebitosreg = db_utils::getDao("cancdebitosreg");
     $sqlarrecad = "select k00_receit from arrecad where k00_numpre = " . $this->numpre . " and k00_numpar=" . $this->numpar;
     //echo "<br>".$sqlarrecad;
     $resultarrecad = db_query($sqlarrecad);
     $linhasarrecad = pg_num_rows($resultarrecad);
     if ($linhasarrecad > 0) {
         for ($i = 0; $i < $linhasarrecad; $i++) {
             $k00_receit = pg_result($resultarrecad, $i, "k00_receit");
             $clcancdebitosreg->k21_codigo = $codigo;
             $clcancdebitosreg->k21_numpre = $this->numpre;
             $clcancdebitosreg->k21_numpar = $this->numpar;
             $clcancdebitosreg->k21_receit = $k00_receit;
             $clcancdebitosreg->k21_data = $this->k20_data;
             $clcancdebitosreg->k21_hora = $this->k20_hora;
             $clcancdebitosreg->k21_obs = $this->k21_obs;
             $clcancdebitosreg->incluir(null);
             if ($clcancdebitosreg->erro_status == "0") {
                 $erro = true;
                 $this->erro_msg = "debitos registros" . $clcancdebitosreg->erro_msg;
                 //echo "<br> não incluiu na cancdebitosreg ".$this->erro_msg;
                 $this->erro_status = "0";
             }
             if ($erro == false) {
                 $resultdebito = debitos_numpre($this->numpre, 0, $this->tipo, strtotime(date("Y-m-d")), date("Y"));
                 $linhasdebito = pg_num_rows($resultdebito);
                 $vlrhis = pg_result($resultdebito, 0, "vlrhis");
                 $vlrcor = pg_result($resultdebito, 0, "vlrcor");
                 $vlrjuros = pg_result($resultdebito, 0, "vlrjuros");
                 $vlrmulta = pg_result($resultdebito, 0, "vlrmulta");
                 $vlrdesconto = pg_result($resultdebito, 0, "vlrdesconto");
                 $clcancdebitosprocreg->k24_codigo = $clcancdebitosproc->k23_codigo;
                 $clcancdebitosprocreg->k24_cancdebitosreg = $clcancdebitosreg->k21_sequencia;
                 $clcancdebitosprocreg->k24_vlrhis = $vlrhis;
                 $clcancdebitosprocreg->k24_vlrcor = $vlrcor;
                 $clcancdebitosprocreg->k24_juros = $vlrjuros;
                 $clcancdebitosprocreg->k24_multa = $vlrmulta;
                 $clcancdebitosprocreg->k24_desconto = $vlrdesconto;
                 $clcancdebitosprocreg->incluir(null);
                 if ($clcancdebitosprocreg->erro_status == "0") {
                     $erro = true;
                     $this->erro_msg = "regitors prco" . $clcancdebitosprocreg->erro_msg;
                     //echo "<br> não incluiu na cancdebitosprocreg ".$this->erro_msg;
                     $this->erro_status = "0";
                 }
             }
         }
     } else {
         $this->erro_msg = "Não encontrou registros no arrecad.";
     }
 }
     </tr>	
     <tr>
      <td width="50%" height="30" align="right">
        Matr&iacute;cula do Im&oacute;vel:&nbsp;
      </td>
      <td width="50%" height="30">
       <input name="matricula1" type="text" class="digitacgccpf" id="matricula1" size="10" maxlength="10">
      </td>
     </tr>    
<?php 
    /*
     *  Se o parametro de configuração do prefeitura on-line no dbportal, na tabela configdbpref, campo chamado w13_exigecpfcnpjmatricula
     *  estiver como true é para exibir os campos cnpj e cpf para o usuário do dbpref  
     */
    $rsParametro = $clconfigdbpref->sql_record($clconfigdbpref->sql_query_file($iInstit, "w13_exigecpfcnpjmatricula"));
    $oRetorno = db_utils::fieldsMemory($rsParametro, 0);
    if ($oRetorno->w13_exigecpfcnpjmatricula == "t") {
        ?>
     <tr>
      <td width="50%" height="30" align="right">
       CNPJ:&nbsp;
      </td>
      <td width="50%" height="30">
       <input name="cgc" type="text" class="digitacgccpf" id="cgc" size="18" maxlength="18" 
              onKeyPress="FormataCNPJ(this,event); return js_teclas(event);">
      </td>
     </tr>
     <tr>
      <td width="50%" height="30" align="right">
       CPF:&nbsp;
      </td>
 *  durante o processo.
 */
if (isset($inicial)) {
    $sSqlNumpresInicial = " select distinct     ";
    $sSqlNumpresInicial .= "        k00_numpre,  ";
    $sSqlNumpresInicial .= "        k00_numpar   ";
    $sSqlNumpresInicial .= "  from inicialnumpre ";
    $sSqlNumpresInicial .= "       inner join arrecad on arrecad.k00_numpre = inicialnumpre.v59_numpre ";
    $sSqlNumpresInicial .= " where v59_inicial in (" . $num_pres . ")                                     ";
    $num_pres = "";
    $rsSqlNumpresInicial = pg_query($sSqlNumpresInicial);
    $iLinhasNumpresInicial = pg_num_rows($rsSqlNumpresInicial);
    if ($iLinhasNumpresInicial > 0) {
        $sVirgula = "";
        for ($iRow = 0; $iRow < $iLinhasNumpresInicial; $iRow++) {
            $oDadosNumpre = db_utils::fieldsMemory($rsSqlNumpresInicial, $iRow);
            $sNumpre = "N" . $oDadosNumpre->k00_numpre;
            $sNumpar = "P" . $oDadosNumpre->k00_numpar;
            $sReceita = "R0";
            $num_pres .= $sVirgula . $sNumpre . $sNumpar . $sReceita;
            $sVirgula = ",";
        }
    }
}
$num_pres = explode(',', $num_pres);
if (!isset($emite_recibo_protocolo)) {
    pg_exec("BEGIN");
    $result = pg_exec("select nextval('numpref_k03_numpre_seq') as k03_numpre");
    db_fieldsmemory($result, 0);
    $result = pg_exec("select k00_codbco,k00_codage,k00_descr,k00_hist1,k00_hist2,k00_hist3,k00_hist4,k00_hist5,k00_hist6,k00_hist7,k00_hist8,k03_tipo,k00_tipoagrup from arretipo where k00_tipo = {$tipo}");
    if (pg_numrows($result) == 0) {
        }
        $rsReceitaSaldo = db_receitasaldo(11, 1, 3, true, "o70_instit = " . db_getsession("DB_instit"), $oParam->iAno, $sDataInicial, $sDataFinal);
        $oRetorno->itens = db_utils::getColectionByRecord($rsReceitaSaldo, true, false, true);
        break;
    case 'getDespesasByPeriodo':
        $sWhere = " o58_instit = " . db_getsession("DB_instit");
        if ($oParam->iOrgao != '') {
            $sWhere .= " and o58_orgao = {$oParam->iOrgao}";
        }
        $sDataInicial = "{$oParam->iAno}-{$oParam->iMes}-01";
        $sDataFinal = "{$oParam->iAno}-{$oParam->iMes}-" . cal_days_in_month(CAL_GREGORIAN, $oParam->iMes, $oParam->iAno);
        $iMesCorrente = date("m", db_getsession("DB_datausu"));
        $iAnoCorrente = date("Y", db_getsession("DB_datausu"));
        $iDiaCorrente = date("d", db_getsession("DB_datausu"));
        if ($iMesCorrente == $oParam->iMes && $iAnoCorrente == $oParam->iAno) {
            $sDataFinal = date("Y-m-d", mktime(0, 0, 0, $oParam->iMes, $iDiaCorrente - 2, $oParam->iAno));
        }
        $rsDotacaoSaldo = db_dotacaosaldo(8, 1, 4, true, $sWhere, $oParam->iAno, $sDataInicial, $sDataFinal, 8, 0, false);
        $oRetorno->itens = db_utils::getColectionByRecord($rsDotacaoSaldo, false, false, true);
        break;
    case "getOrgaosByAno":
        $sSqlOrgaos = "select distinct o40_orgao, o40_descr";
        $sSqlOrgaos .= "  from orcorgao ";
        $sSqlOrgaos .= " where o40_anousu = {$oParam->iAno}";
        $sSqlOrgaos .= "   and o40_instit = " . db_getsession("DB_instit");
        $sSqlOrgaos .= " order by o40_orgao";
        $rsOrgaos = db_query($sSqlOrgaos);
        $oRetorno->itens = db_utils::getColectionByRecord($rsOrgaos, false, false, true);
        break;
}
echo $oJson->encode($oRetorno);
  </tr>
</table>
<table align="center"  class="tableForm">
   <tr class="subTituloForm" align="center">
      <td>N° Matrícula</td>
      <td>Data Admissão</td>
      <td>Cargo</td>
      <td>Data Demissão</td>
      <td>Instituicao</td>
   </tr>
   <?php 
    $corFundo = "#FFFFFF";
    $corOver = "#ede67c";
    for ($x = 0; $x < $iRhCgmCont; $x++) {
        if ($iRhCgmCont > 0) {
            $oCgmCont = db_utils::fieldsMemory($rsRhCgmCont, $x);
        }
        if ($corFundo == "#FFFFFF") {
            $corFundo = "#FFFFFF";
        } else {
            $corFundo = "#FFFFFF";
        }
        $sUrl = base64_encode("id_usuario=" . $id_usuario . "&matricula=" . $oCgmCont->rh01_regist . "&instituicao=" . $oCgmCont->rh02_instit);
        ?>
    <tr bgcolor="<?php 
        echo $corFundo;
        ?>
"   onmouseover="bgColor='<?php 
        echo $corOver;
        ?>
'" onmouseout="bgColor='<?php 
include "classes/db_proctransfer_classe.php";
include "classes/db_proctransferproc_classe.php";
include "classes/db_proctransand_classe.php";
include "classes/db_proctransferintand_classe.php";
include "classes/db_proctransferint_classe.php";
include "classes/db_procandamint_classe.php";
include "classes/db_procandamintand_classe.php";
include "classes/db_arqproc_classe.php";
include "classes/db_arqandam_classe.php";
include "dbforms/db_funcoes.php";
include "classes/db_protparam_classe.php";
//se $db21_usasisagua = 't' utiliza o modulo agua
db_sel_instit(null, "db21_usasisagua");
db_postmemory($HTTP_SERVER_VARS);
db_postmemory($HTTP_POST_VARS);
$utils = new db_utils();
$oPOST = $utils->postMemory($_POST);
$clprotprocesso = new cl_protprocesso();
$clprocandam = new cl_procandam();
$clproctransfer = new cl_proctransfer();
$clproctransferproc = new cl_proctransferproc();
$clproctransand = new cl_proctransand();
$clproctransferintand = new cl_proctransferintand();
$clproctransferint = new cl_proctransferint();
$clprocandamint = new cl_procandamint();
$clprocandamintand = new cl_procandamintand();
$clarqproc = new cl_arqproc();
$clarqandam = new cl_arqandam();
$clprotparam = new cl_protparam();
$cod_procandamint = 0;
$arquiv = false;
    saude das lotacoes abaixo, deve imprimir os dados da instituicao prefeitura,
    somente para Marica.
 */
 if ($oDbConfig->codcli == 19985) {
     if ($oRendimento->r70_codigo == 222 || $oRendimento->r70_codigo == 223) {
         $sSqlDbConfig = " select ender,                                              ";
         $sSqlDbConfig .= "        cgc,                                                ";
         $sSqlDbConfig .= "        nomeinst,                                           ";
         $sSqlDbConfig .= "        munic,                                              ";
         $sSqlDbConfig .= "        telef                                               ";
         $sSqlDbConfig .= " from db_config                                             ";
         $sSqlDbConfig .= " where codigo = (select codigo from db_config where prefeitura = true) ";
         $rsSqlDbConfig = db_query($sSqlDbConfig);
         $iNumRowsDbConfig = pg_num_rows($rsSqlDbConfig);
         if ($iNumRowsDbConfig > 0) {
             $oDbConfig2 = db_utils::fieldsMemory($rsSqlDbConfig, 0);
             $prefeitura = db_translate($oDbConfig2->nomeinst);
             $enderpref = db_translate($oDbConfig2->ender);
             $municpref = db_translate($oDbConfig2->munic);
             $telefpref = $oDbConfig2->telef;
             $cgcpref = $oDbConfig2->cgc;
         }
     }
 }
 /*=============================================================================================*/
 /**
  * Informações de Cabeçalho
  */
 $pdf1->prefeitura = $prefeitura;
 $pdf1->enderpref = $enderpref;
 $pdf1->municpref = $municpref;
 /**
  * Método responsável por setar na sessão a estrutura da folha de pagamento.
  * EX.: C/ Suplementar ou S/Suplementar
  * 
  * @static
  * @access public
  * @param Integer $iInstituicao
  * @throws DBException
  */
 public static function declararEstruturaFolhaPagamento($iInstituicao)
 {
     $oDaoCfPess = new cl_cfpess();
     $sSqlSuplementar = $oDaoCfPess->sql_query_file(null, null, $iInstituicao, "distinct r11_suplementar::int");
     $rsSuplementar = db_query($sSqlSuplementar);
     if (!$rsSuplementar) {
         throw new DBException("Ocorreu um erro ao declarar a estrutura da folha de pagamento.");
     }
     $oDadosSuplementar = db_utils::fieldsMemory($rsSuplementar, 0);
     db_putsession("DB_COMPLEMENTAR", (bool) $oDadosSuplementar->r11_suplementar);
 }
Example #18
0
<?php

include 'dbapi/db_utils.php';
$host = "localhost";
$user = "******";
$password = "";
$database = "dbapi";
$dbutils = new db_utils($host, $user, $password, $database);
//Insert Data
$table = "test";
$columns = array("name");
$records = array("Victor");
$dbutils->insert_records($table, $columns, $records, true);
//BULK INSERT
$columns = array("name");
$records = array("Mwenda", "Marvik", "Victor");
$dbutils->bulk_insert_records($table, $columns, $records, true);
//UPDATE DATA
$where_columns = array("name");
$where_records = array("Mwenda");
$columns = array("name");
$records = array("Vicky");
$dbutils->update_record($table, $columns, $records, $where_columns, $where_records, true);
//DELETE_DATA
$columns = array("name");
$records = array("Marvik");
$dbutils->delete_record($table, $columns, $records, true);
//COMPLEX METHODS
//QUERY && FETCH ASSOC
$columns = array("name");
$records = array("Vic");
 function processaSimulacao()
 {
     $aRetorno = array();
     $oDaoCadVenc = db_utils::getDao("cadvenc");
     $oDadosTipoCalculo = $this->processaAtividadeTipoCalculo();
     foreach ($oDadosTipoCalculo as $oDadosCalculo) {
         $sMsgLog = "----------------------------------------------------------------------------------------------<br>";
         $sMsgLog .= "Processando Calculo ...: {$oDadosCalculo->iCalculo} - {$oDadosCalculo->sCalculoDescricao} <br><br>";
         $sMsgLog .= "Tipo de Calculo .......: {$oDadosCalculo->iTipoCalculo} - {$oDadosCalculo->sTipoCalculoDescricao} <br>";
         $sMsgLog .= "Vencimento ............: {$oDadosCalculo->iCodigoVencimento} <br>";
         $this->logCalculo($sMsgLog);
         //Processamos os calculos de variável
         if ($oDadosCalculo->sVariavel == 't') {
             $sMsgLog = "Processando calculo de ISSQN Variável <br>";
             $this->logCalculo($sMsgLog);
             $sSqlVencimentos = $oDaoCadVenc->sql_query($oDadosCalculo->iCodigoVencimento, null, "*", "q82_parc asc");
             $rsVencimentos = $oDaoCadVenc->sql_record($sSqlVencimentos);
             $iQuantidadeVencimentos = $oDaoCadVenc->numrows;
             if ($iQuantidadeVencimentos == 0) {
                 $sMsgLog = "[ Erro 10] - Erro ao buscar dados dos vemcimentos";
                 $this->logCalculo($sMsgLog);
                 throw new Exception($sMsgLog);
             }
             for ($iInd = 0; $iInd < $iQuantidadeVencimentos; $iInd++) {
                 $oDadosVencimento = db_utils::fieldsMemory($rsVencimentos, $iInd);
                 if (substr(str_replace("-", "", $oDadosVencimento->q82_venc), 0, 6) > substr(str_replace("-", "", $this->getDataInicioAtividade()), 0, 6)) {
                     $nValorParcela = $oDadosCalculo->nValorOrigem / $this->nValorInflator;
                     $iParcela = $oDadosVencimento->q82_parc;
                     $dVencimento = $oDadosVencimento->q82_venc;
                     $sMsgLog = "Parcela : {$iParcela} Vencimento : {$dVencimento} Valor: {$nValorParcela}<br>";
                     $this->logCalculo($sMsgLog);
                     $oRetornoCalculo = new stdClass();
                     $oRetornoCalculo->iTipoCalculo = $oDadosCalculo->iTipoCalculo;
                     $oRetornoCalculo->sDescricaoCalculo = $oDadosCalculo->sCalculoDescricao;
                     $oRetornoCalculo->iParcela = $iParcela;
                     $oRetornoCalculo->dVencimento = $dVencimento;
                     $oRetornoCalculo->nValor = $nValorParcela;
                     $aRetorno[] = $oRetornoCalculo;
                 } else {
                     $sMsgLog = "Parcela : {$oDadosVencimento->q82_parc} Vencimento : {$oDadosVencimento->q82_venc} ";
                     $sMsgLog .= "não calculada pois o ano/mes de vencimento é menor ou igual ao ano/mes do início da ativiade {$this->getDataInicioAtividade()} <br>";
                     $this->logCalculo($sMsgLog);
                 }
             }
             $sMsgLog = "FIM DO PROCESSAMENTO DO ISSQN VARIÁVEL";
             $this->logCalculo($sMsgLog);
         } else {
             $sMsgLog = "Processando calculo de ISSQN NÃO VARIÁVEL<br>";
             $this->logCalculo($sMsgLog);
             $bProcessaParcelaVencida = false;
             $bUltimoVencimento = false;
             $iQuantidadeVencimentoProcessar = 0;
             $iVencimentosProcessados = 0;
             $iDiasSomados = 0;
             $dUltimoDiaAno = $this->getAnoCalculo() . "-12-31";
             $sMktimeUltimoDiaAno = mktime(0, 0, 0, "12", "31", $this->getAnoCalculo());
             $sWhere = " cadvencdesc.q92_codigo = {$oDadosCalculo->iCodigoVencimento}                                               ";
             $sWhere .= " and ( case                                                                                                 ";
             $sWhere .= "         when cadvencdesc.q92_formacalcparcvenc = 1                                                         ";
             $sWhere .= "           then                                                                                             ";
             $sWhere .= "             case                                                                                           ";
             $sWhere .= "               when q82_venc >= '{$this->getDataInicioAtividade()}'                                         ";
             $sWhere .= "                 then true                                                                                  ";
             $sWhere .= "               else false                                                                                   ";
             $sWhere .= "             end                                                                                            ";
             $sWhere .= "         when cadvencdesc.q92_formacalcparcvenc = 3                                                         ";
             $sWhere .= "           then q82_venc >= '{$this->getDataCalculo()}' and q82_venc >= '{$this->getDataInicioAtividade()}' ";
             $sWhere .= "         else                                                                                               ";
             $sWhere .= "           case                                                                                             ";
             $sWhere .= "             when cadvenc.q82_calculaparcvenc is true                                                       ";
             $sWhere .= "               then true                                                                                    ";
             $sWhere .= "             else                                                                                           ";
             $sWhere .= "               q82_venc >= '{$this->getDataCalculo()}' and q82_venc >= '{$this->getDataInicioAtividade()}'  ";
             $sWhere .= "           end                                                                                              ";
             $sWhere .= "       end )                                                                                                ";
             $sSqlVerificaVencimentosProcessar = $oDaoCadVenc->sql_query(null, null, "count(*) as qtd", null, $sWhere);
             $rsVerificaVencimentosProcessar = $oDaoCadVenc->sql_record($sSqlVerificaVencimentosProcessar);
             $iQuantidadeVencimentoProcessar = db_utils::fieldsMemory($rsVerificaVencimentosProcessar, 0)->qtd;
             $sCampos = "max(cadvenc.q82_venc)                     as maiorvencimento,\n                    coalesce(max(cadvencdesc.q92_diasvcto),0) as dias,\n                    count(*)                                  as total";
             $sSqlComplementoVencimento = $oDaoCadVenc->sql_query($oDadosCalculo->iCodigoVencimento, null, $sCampos, null);
             $rsComplementoVencimento = $oDaoCadVenc->sql_record($sSqlComplementoVencimento);
             $dMaiorVencimento = db_utils::fieldsMemory($rsComplementoVencimento, 0)->maiorvencimento;
             $iDiasParaVencimento = db_utils::fieldsMemory($rsComplementoVencimento, 0)->dias;
             $iTotalVencimentos = db_utils::fieldsMemory($rsComplementoVencimento, 0)->total;
             $sSqlVencimentos = $oDaoCadVenc->sql_query($oDadosCalculo->iCodigoVencimento, null, "*", "q82_parc asc");
             $rsVencimentos = $oDaoCadVenc->sql_record($sSqlVencimentos);
             $iQuantidadeVencimentos = $oDaoCadVenc->numrows;
             if ($iQuantidadeVencimentos == 0) {
                 $sMsgLog = "[ Erro 10] - Erro ao buscar dados dos vemcimentos";
                 $this->logCalculo($sMsgLog);
                 throw new Exception($sMsgLog);
             }
             for ($iInd = 0; $iInd < $iQuantidadeVencimentos; $iInd++) {
                 $oDadosVencimento = db_utils::fieldsMemory($rsVencimentos, $iInd);
                 $sMsgLog = "Processando Vencimento {$oDadosVencimento->q82_venc} Parcela: {$oDadosVencimento->q82_parc} <br>";
                 $this->logCalculo($sMsgLog);
                 //Guardar o vencimento atual do cadvenc
                 $dVencimento = $oDadosVencimento->q82_venc;
                 if ($dVencimento == "") {
                     $dVencimento = $this->getDataCalculo();
                 }
                 $bProcessaParcela = true;
                 if ($iQuantidadeVencimentoProcessar == 0) {
                     if ($iDiasParaVencimento > 0) {
                         $aDataCalculo = explode("-", $this->getDataCalculo());
                         $dVencimento = date("Y-m-d", mktime(0, 0, 0, $aDataCalculo[1], $aDataCalculo[2] + $iDiasParaVencimento, $aDataCalculo[0]));
                     } else {
                         $dVencimento = $dUltimoDiaAno;
                     }
                     $sMsgLog = "Trocou o vencimento para : {$dVencimento}";
                     $this->logCalculo($sMsgLog);
                 }
                 /*
                  * Verificamos se será gerada parcela vencida
                  */
                 if ($oDadosVencimento->q92_formacalcparcvenc == 1) {
                     $bProcessaParcelaVencida = true;
                 } else {
                     if ($oDadosVencimento->q92_formacalcparcvenc == 3) {
                         if ($oDadosVencimento->q82_venc >= $this->getDataCalculo() && $oDadosVencimento->q82_venc <= $dUltimoDiaAno) {
                             $bProcessaParcelaVencida = true;
                         }
                     } else {
                         if ($oDadosVencimento->q82_calculaparcvenc == "t") {
                             $bProcessaParcelaVencida = true;
                         } else {
                             if ($oDadosVencimento->q82_venc >= $this->getDataCalculo() && $oDadosVencimento->q82_venc <= $dUltimoDiaAno) {
                                 $bProcessaParcelaVencida = true;
                             }
                         }
                     }
                 }
                 $aVencimento = explode("-", $dVencimento);
                 $sMktimeVencimento = mktime(0, 0, 0, $aVencimento[1], $aVencimento[2], $aVencimento[0]);
                 $aMaiorVencimento = explode("-", $dMaiorVencimento);
                 $sMktimeMaiorVencimento = mktime(0, 0, 0, $aMaiorVencimento[1], $aMaiorVencimento[2], $aMaiorVencimento[0]);
                 $aDataInicioAtividade = explode("-", $this->getDataInicioAtividade());
                 $sMktimeDataInicioAtividade = mktime(0, 0, 0, $aDataInicioAtividade[1], $aDataInicioAtividade[2], $aDataInicioAtividade[0]);
                 $aDataCalculo = explode("-", $this->getDataCalculo());
                 $sMktimeDataCalculo = mktime(0, 0, 0, $aDataCalculo[1], $aDataCalculo[2], $aDataCalculo[0]);
                 if ($sMktimeVencimento > $sMktimeMaiorVencimento) {
                     $sMsgLog = "Vencimento do cadastro de vencimentos maior que o maximo vencimento, pasando bUltVenc para true";
                     $this->logCalculo($sMsgLog);
                     $bUltimoVencimento = true;
                 }
                 if ($this->getAnoInicioAtividade() != $this->getAnoCalculo()) {
                     $sMsgLog = "Ano de inicio diferente do atual";
                     $this->logCalculo($sMsgLog);
                     $bProcessaParcela = true;
                 } else {
                     if ($sMktimeVencimento >= $sMktimeDataInicioAtividade || $dVencimento == "" || $iQuantidadeVencimentoProcessar == 0 || $bProcessaParcelaVencida == true) {
                         $bProcessaParcela = true;
                     } else {
                         $bProcessaParcela = false;
                     }
                 }
                 if ($sMktimeDataCalculo > $sMktimeVencimento && $bProcessaParcelaVencida == false) {
                     $sMsgLog = "Inicio maior que data de vencimento e processar parcelas vencidas NAO";
                     $this->logCalculo($sMsgLog);
                     $bProcessaParcela = false;
                 }
                 if ($sMktimeDataInicioAtividade > $sMktimeVencimento && $bUltimoVencimento == false && $iTotalVencimentos != $iVencimentosProcessados) {
                     $bProcessaParcela = false;
                 }
                 if ($bProcessaParcela == true) {
                     $iVencimentosProcessados++;
                     if ($iQuantidadeVencimentoProcessar == 0) {
                         $nPercentualParcela = 100;
                     } else {
                         if ($oDadosCalculo->sTipoProporcionalidade == "D") {
                             $dVencimentoCalculado = $dVencimento;
                             if ($bUltimoVencimento == true || $sMktimeVencimento == $sMktimeMaiorVencimento) {
                                 $dVencimentoCalculado = $dUltimoDiaAno;
                                 $dMaiorVencimento = $dVencimentoCalculado;
                                 $aMaiorVencimento = explode("-", $dMaiorVencimento);
                                 $sMktimeMaiorVencimento = mktime(0, 0, 0, $aMaiorVencimento[1], $aMaiorVencimento[2], $aMaiorVencimento[0]);
                             }
                             if ($this->getAnoInicioAtividade() < $this->getAnoCalculo()) {
                                 $dInicioAtividadeCalculado = $this->getAnoCalculo() . "-01-01";
                             } else {
                                 $dInicioAtividadeCalculado = $this->getDataInicioAtividade();
                             }
                             $aInicioAtividadeCalculado = explode("-", $dInicioAtividadeCalculado);
                             $sMktimeInicioAtividadeCalculado = mktime(0, 0, 0, $aInicioAtividadeCalculado[1], $aInicioAtividadeCalculado[2], $aInicioAtividadeCalculado[0]);
                             $iDiasInicio = date("d", $sMktimeUltimoDiaAno - $sMktimeDataInicioAtividade) + 1;
                             $iDiasVencimento = date("d", $sMktimeUltimoDiaAno - $sMktimeInicioAtividadeCalculado) + 1 - $iDiasSomados;
                             $iDiasSomados += $iDiasVencimento;
                             $nPercentualParcela = round(100 / $iDiasInicio * $iDiasVencimento, 2);
                         } else {
                             $nPercentualParcela = round(100 / $iQuantidadeVencimentos, 2);
                         }
                     }
                     if ($dVencimento == "" and $this->getAnoInicioAtividade() < $this->getAnoCalculo()) {
                         $dVencimento = $dUltimoDiaAno;
                         if ($iDiasParaVencimento > 0 && $this->getAnoInicioAtividade() == $this->getAnoCalculo()) {
                             $dVencimento = date("Y-m-d", mktime(0, 0, 0, $aDataCalculo[1], $aDataCalculo[2] + $iDiasParaVencimento, $aDataCalculo[0]));
                         }
                     }
                     $nValorParcela = round($oDadosCalculo->nValorIntegral * $nPercentualParcela / 100, 2);
                     $oRetornoCalculo = new stdClass();
                     $oRetornoCalculo->iTipoCalculo = $oDadosCalculo->iTipoCalculo;
                     $oRetornoCalculo->sDescricaoCalculo = $oDadosCalculo->sCalculoDescricao;
                     $oRetornoCalculo->iParcela = $iVencimentosProcessados;
                     $oRetornoCalculo->dVencimento = $dVencimento;
                     $oRetornoCalculo->nValor = $nValorParcela;
                     $aRetorno[] = $oRetornoCalculo;
                     if ($nPercentualParcela == 100) {
                         break;
                     }
                 }
             }
         }
     }
     return $aRetorno;
 }
 *  Copia da licenca no diretorio licenca/licenca_en.txt 
 *                                licenca/licenca_pt.txt 
 */
session_start();
include "libs/db_conecta.php";
include "libs/db_stdlib.php";
include "libs/db_sql.php";
include "libs/db_utils.php";
include "classes/db_confsite_classe.php";
include "classes/db_issbase_classe.php";
include "classes/db_cgm_classe.php";
include "classes/db_iptubase_classe.php";
parse_str(base64_decode($HTTP_SERVER_VARS["QUERY_STRING"]));
//postmemory($HTTP_POST_VARS,2);
$oPost = db_utils::postMemory($_POST, 0);
$oGet = db_utils::postMemory($_GET, 0);
$clissbase = new cl_issbase();
$cliptubase = new cl_iptubase();
db_mensagem("certidao_cab", "certidao_rod");
$db_verificaip = db_verifica_ip();
$instit = db_getsession("DB_instit");
$bForm = true;
$numcgm = "";
$sqlconf = "select db21_regracgmiptu, db21_regracgmiss from db_config where codigo = {$instit}";
$resconf = pg_query($sqlconf);
$iconf = pg_num_rows($resconf);
if ($iconf > 0) {
    db_fieldsmemory($resconf, 0);
}
$sQueryCndPorNome = "select * from configdbpref where w13_instit = {$instit}";
$resQueryCndPorNome = pg_query($sQueryCndPorNome);
 /**
  * Função que calcula o valor total da inicial
  *
  */
 function valorInicialAtualizado($iInicial, $dDtEmiss = null)
 {
     require_once "libs/db_sql.php";
     $nValor = 0;
     $sSqlCertidoesInicial = "select v51_inicial, \n    \t                                  v13_certid, \n    \t                                  v13_dtemis \n            \t                     from inicialcert\n            \t                    inner join certid   on v13_certid = v51_certidao \n    \t                            where v51_inicial = {$iInicial} ";
     $rsCertidoesInicial = db_query($sSqlCertidoesInicial);
     for ($iCertidoesInicial = 0; $iCertidoesInicial < pg_num_rows($rsCertidoesInicial); $iCertidoesInicial++) {
         $oCertidoesInicial = db_utils::fieldsMemory($rsCertidoesInicial, $iCertidoesInicial);
         if ($dDtEmiss == null) {
             $dDtEmiss = $oCertidoesInicial->v13_dtemis;
         }
         $sSqlParcelamentos = " select v14_parcel, ";
         $sSqlParcelamentos .= "        v07_numpre  ";
         $sSqlParcelamentos .= "   from certter";
         $sSqlParcelamentos .= "  inner join termo on v07_parcel = v14_parcel";
         $sSqlParcelamentos .= "  where v14_certid = {$oCertidoesInicial->v13_certid} ";
         $rsParcelamentos = db_query($sSqlParcelamentos);
         $iLinhasParcel = pg_num_rows($rsParcelamentos);
         for ($iIndParcel = 0; $iIndParcel < $iLinhasParcel; $iIndParcel++) {
             $oDadosParcel = db_utils::fieldsMemory($rsParcelamentos, $iIndParcel);
             $rsDadosDebitoCorrigido = debitos_numpre($oDadosParcel->v07_numpre, 0, 0, mktime(0, 0, 0, substr($dDtEmiss, 5, 2), substr($dDtEmiss, 8, 2), substr($dDtEmiss, 0, 4)), substr($dDtEmiss, 0, 4), 0);
             if ($rsDadosDebitoCorrigido != false) {
                 $iLinhasDebito = pg_num_rows($rsDadosDebitoCorrigido);
                 for ($iIndDebito = 0; $iIndDebito < $iLinhasDebito; $iIndDebito++) {
                     $nValor += db_utils::fieldsMemory($rsDadosDebitoCorrigido, $iIndDebito)->total;
                 }
             }
         }
         $sSqlDadosDebitos = " select distinct    ";
         $sSqlDadosDebitos .= "        k00_numpre, ";
         $sSqlDadosDebitos .= "        k00_numpar  ";
         $sSqlDadosDebitos .= "   from certdiv";
         $sSqlDadosDebitos .= "        inner join divida   on certdiv.v14_coddiv = divida.v01_coddiv";
         $sSqlDadosDebitos .= "        inner join arrecad  on arrecad.k00_numpre = divida.v01_numpre ";
         $sSqlDadosDebitos .= "                           and arrecad.k00_numpar = divida.v01_numpar";
         $sSqlDadosDebitos .= "  where v14_certid in ({$oCertidoesInicial->v13_certid})";
         $rsDadosDebitos = db_query($sSqlDadosDebitos);
         $iLinhasDadosDebitos = pg_num_rows($rsDadosDebitos);
         for ($iIndDadosDebitos = 0; $iIndDadosDebitos < $iLinhasDadosDebitos; $iIndDadosDebitos++) {
             $oDivida = db_utils::fieldsmemory($rsDadosDebitos, $iIndDadosDebitos);
             $rsDadosDebitoCorrigido = debitos_numpre($oDivida->k00_numpre, 0, 0, mktime(0, 0, 0, substr($dDtEmiss, 5, 2), substr($dDtEmiss, 8, 2), substr($dDtEmiss, 0, 4)), substr($dDtEmiss, 0, 4), $oDivida->k00_numpar);
             for ($iIndDebito = 0; $iIndDebito < pg_numrows($rsDadosDebitoCorrigido); $iIndDebito++) {
                 $nValor += db_utils::fieldsMemory($rsDadosDebitoCorrigido, $iIndDebito)->total;
             }
         }
     }
     return $nValor;
 }
$pdf1->logo = $logo;
$pdf1->prefeitura = $nomeinst;
$pdf1->enderpref = $ender . (isset($numero) ? ', ' . $numero : "");
$pdf1->cgcpref = $cgc;
$pdf1->municpref = $munic;
$pdf1->telefpref = $telef;
$pdf1->emailpref = $email;
$pdf1->ano = $ano;
$pdf1->mes = $mes;
$pdf1->mensagem = $msg;
$pdf1->qualarquivo = $qualarquivo;
$lin = 1;
for ($i = 0; $i < $num; $i++) {
    db_fieldsmemory($res, $i);
    $rsSeqContraCheque = db_query("select nextval('rhemitecontracheque_rh85_sequencial_seq') as sequencial");
    $oSeqContraCheque = db_utils::fieldsMemory($rsSeqContraCheque, 0);
    $iSequencial = str_pad($oSeqContraCheque->sequencial, 6, '0', STR_PAD_LEFT);
    $iMes = str_pad($mes, 2, '0', STR_PAD_LEFT);
    $iMatricula = str_pad($regist, 6, '0', STR_PAD_LEFT);
    $iMod1 = db_CalculaDV($iMatricula);
    $iMod2 = db_CalculaDV($iMatricula . $iMod1 . $iMes . $ano . $iSequencial);
    $iCodAutent = $iMatricula . $iMod1 . $iMes . $iMod2 . $ano . $iSequencial;
    $clrhemitecontracheque->rh85_sequencial = $iSequencial;
    $clrhemitecontracheque->rh85_regist = $regist;
    $clrhemitecontracheque->rh85_anousu = $ano;
    $clrhemitecontracheque->rh85_mesusu = $mes;
    $clrhemitecontracheque->rh85_sigla = substr($sigla, 0, 3);
    $clrhemitecontracheque->rh85_codautent = $iCodAutent;
    $clrhemitecontracheque->rh85_dataemissao = date('Y-m-d', db_getsession('DB_datausu'));
    $clrhemitecontracheque->rh85_horaemissao = db_hora();
    $clrhemitecontracheque->rh85_ip = $sIp;
 function __construct($iArretipo = null, $iTipoMod, $iInstit, $dDatahj, $sIp = null, $lNovoPdf = true, $oPdfUnico = null)
 {
     $this->lNovoPdf = $lNovoPdf;
     $this->oPdfUnico = $oPdfUnico;
     $sWhereModCarne = "   where k48_dataini  <= '{$dDatahj}' ";
     $sWhereModCarne .= "     and k48_datafim  >= '{$dDatahj}' ";
     $sWhereModCarne .= "     and k48_instit     = {$iInstit}  ";
     $sWhereModCarne .= "     and k48_cadtipomod = {$iTipoMod} ";
     $sSqlTipoExecessao = " select distinct k48_sequencial,                                                                               ";
     $sSqlTipoExecessao .= "        k49_tipo,                                                                                              ";
     $sSqlTipoExecessao .= "        k36_ip                                                                                                 ";
     $sSqlTipoExecessao .= "   from modcarnepadrao                                                                                         ";
     $sSqlTipoExecessao .= "        left  join modcarnepadraotipo on modcarnepadraotipo.k49_modcarnepadrao = modcarnepadrao.k48_sequencial ";
     $sSqlTipoExecessao .= "        left  join modcarneexcessao   on modcarneexcessao.k36_modcarnepadrao   = modcarnepadrao.k48_sequencial ";
     $sSqlTipoExecessao .= $sWhereModCarne;
     $rsConsultaTipoExcessao = db_query($sSqlTipoExecessao);
     $iNroLinhasTipoExcessao = pg_num_rows($rsConsultaTipoExcessao);
     $iCodModCarnePadrao = '';
     // Validação de Tipo e Excessão
     for ($iInd = 0; $iInd < $iNroLinhasTipoExcessao; $iInd++) {
         $oTipoExcessao = db_utils::fieldsMemory($rsConsultaTipoExcessao, $iInd);
         if ($oTipoExcessao->k49_tipo != '' || $oTipoExcessao->k36_ip != '') {
             if (!empty($iArretipo) && !empty($sIp)) {
                 if ($oTipoExcessao->k49_tipo != '' && $oTipoExcessao->k36_ip != '') {
                     if (trim($iArretipo) == trim($oTipoExcessao->k49_tipo) && $sIp == $oTipoExcessao->k36_ip) {
                         $iCodModCarnePadrao = $oTipoExcessao->k48_sequencial;
                     }
                 } else {
                     if ($oTipoExcessao->k36_ip != '') {
                         if ($sIp == $oTipoExcessao->k36_ip) {
                             $iCodModCarnePadrao = $oTipoExcessao->k48_sequencial;
                         }
                     } else {
                         if (trim($iArretipo) == trim($oTipoExcessao->k49_tipo)) {
                             $iCodModCarnePadrao = $oTipoExcessao->k48_sequencial;
                         }
                     }
                 }
             } else {
                 if (!empty($sIp)) {
                     if ($sIp == $oTipoExcessao->k36_ip) {
                         $iCodModCarnePadrao = $oTipoExcessao->k48_sequencial;
                     }
                 } else {
                     if (!empty($iArretipo)) {
                         if (trim($iArretipo) == trim($oTipoExcessao->k49_tipo) && $oTipoExcessao->k36_ip == "") {
                             $iCodModCarnePadrao = $oTipoExcessao->k48_sequencial;
                         }
                     } else {
                         $iCodModCarnePadrao = $oTipoExcessao->k48_sequencial;
                     }
                 }
             }
             // Caso não tenha retornado nenhum tipo ou excessão e a variável $iCodModCarnePadrao estiver vazia então é atribuído
             // a ela o código do molelo padrão
         } else {
             if (trim($iCodModCarnePadrao) == '') {
                 $iCodModCarnePadrao = $oTipoExcessao->k48_sequencial;
             }
         }
     }
     if ($iCodModCarnePadrao != "") {
         $sSql = "  select k48_sequencial,                                                                                         \t\t\t\t \t                  ";
         $sSql .= "  \t     k48_cadconvenio,                                                                                        \t\t\t\t \t                  ";
         $sSql .= "  \t     ar12_cadconveniomodalidade,                                                                                \t\t\t                  ";
         $sSql .= "  \t     m01_sequencial,                                                                                         \t\t\t\t \t                  ";
         $sSql .= "  \t     m02_sequencial,                                                                                         \t\t\t\t \t                  ";
         $sSql .= "  \t     k47_sequencial,                                                                                         \t\t\t\t\t                  ";
         $sSql .= "         k47_descr,                                                                                              \t\t\t\t\t                  ";
         $sSql .= "         k47_obs,                                                                                                \t\t\t\t \t                  ";
         $sSql .= "         k47_altura,                                                                                             \t\t\t\t \t                  ";
         $sSql .= "         k47_largura,                                                                                            \t\t\t\t \t                  ";
         $sSql .= "         k47_orientacao                                                                                          \t\t\t\t\t                  ";
         $sSql .= "    from modcarnepadrao\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t                                                  \t                  ";
         $sSql .= "  \t     inner join cadconvenio                on cadconvenio.ar11_sequencial                  = modcarnepadrao.k48_cadconvenio             ";
         $sSql .= "  \t     inner join cadtipoconvenio            on cadtipoconvenio.ar12_sequencial              = cadconvenio.ar11_cadtipoconvenio           ";
         $sSql .= "  \t     left  join conveniocobranca           on conveniocobranca.ar13_cadconvenio  \t         = cadconvenio.ar11_sequencial                ";
         $sSql .= "         left  join modcarnepadraocadmodcarne  on modcarnepadraocadmodcarne.m01_modcarnepadrao = modcarnepadrao.k48_sequencial \t            ";
         $sSql .= "         left  join cadmodcarne \t\t\t\t       on cadmodcarne.k47_sequencial\t                 = modcarnepadraocadmodcarne.m01_cadmodcarne \t";
         $sSql .= "         left  join modcarnepadraolayouttxt    on modcarnepadraolayouttxt.m02_modcarnepadrao   = modcarnepadrao.k48_sequencial \t            ";
         $sSql .= "         left  join db_layouttxt \t\t\t\t       on db_layouttxt.db50_codigo \t\t                 = modcarnepadraolayouttxt.m02_db_layouttxt \t";
         $sSql .= "   where k48_sequencial = {$iCodModCarnePadrao}                                                                                             ";
         $rsConsultaRegra = pg_query($sSql);
         $iNroLinhas = pg_num_rows($rsConsultaRegra);
         if ($iNroLinhas > 0) {
             $oModCarne = db_utils::fieldsMemory($rsConsultaRegra, 0);
             $this->iModCarnePadrao = $oModCarne->k48_sequencial;
             $this->iConvenio = $oModCarne->k48_cadconvenio;
             if (!empty($oModCarne->m01_sequencial)) {
                 $this->setObjPdf($oModCarne->k47_altura, $oModCarne->k47_largura, $oModCarne->k47_orientacao, $oModCarne->k47_sequencial);
             } else {
                 if (!empty($oModCarne->m02_sequencial)) {
                     $this->setObjLayout();
                 }
             }
             if (!empty($oModCarne->ar13_sequencial)) {
                 $this->iCodConvenioCobranca = $oModCarne->ar13_sequencial;
             } else {
                 $this->iCodConvenioCobranca = 0;
             }
             if ($oModCarne->ar12_cadconveniomodalidade == 1) {
                 $this->lArrecadacao = false;
                 $this->lCobranca = true;
             } else {
                 if ($oModCarne->ar12_cadconveniomodalidade == 2) {
                     $this->lArrecadacao = true;
                     $this->lCobranca = false;
                 }
             }
         } else {
             throw new Exception("Nenhum convênio encontrado! TipoMod:{$iTipoMod}, Tipo Débito: {$iArretipo}");
         }
     } else {
         throw new Exception("Nenhum modelo padrão encontrado! TipoMod:{$iTipoMod}, Tipo Débito: {$iArretipo}");
     }
 }
 if ($clcertidao->numrows > 0) {
     $oCertidao = db_utils::fieldsMemory($rsCertidao, 0);
     if ($sqlerro == false && $sStatus != 3) {
         $clcertvalonlinecert->w19_certidao = $oCertidao->p50_sequencial;
         $clcertvalonlinecert->w19_certidaovalidaonline = $clcertvalonline->w18_sequencial;
         $clcertvalonlinecert->incluir(null);
         if ($clcertvalonlinecert->erro_status == 0) {
             $sqlerro = true;
             $erro_msg = $clcertvalonlinecert->erro_msg;
         }
     }
 }
 if (isset($iLogin) && $iLogin != "") {
     $rsDbUsuarios = $cldbusuarios->sql_record($cldbusuarios->sql_query("", "id_usuario", "", "login = '******'"));
     if ($cldbusuarios->numrows > 0) {
         $oDbUsuario = db_utils::fieldsMemory($rsDbUsuarios, 0);
         if ($sqlerro == false && $sStatus != 3) {
             $clcertvalonlineusuario->w20_certidaovalidaonline = $clcertvalonline->w18_sequencial;
             $clcertvalonlineusuario->w20_id_usuario = $oDbUsuario->id_usuario;
             $clcertvalonlineusuario->incluir(null);
             if ($clcertvalonlineusuario->erro_status == 0) {
                 $sqlerro = true;
                 $erro_msg = $clcertvalonlineusuario->erro_msg;
             }
         }
     }
 }
 db_fim_transacao($sqlerro);
 if ($sqlerro == true) {
     db_msgbox($erro_msg);
 }
 *  
 *  Copia da licenca no diretorio licenca/licenca_en.txt 
 *                                licenca/licenca_pt.txt 
 */
session_start();
include "libs/db_conecta.php";
include "libs/db_stdlib.php";
include "libs/db_sql.php";
include "libs/db_utils.php";
include "classes/db_issbase_classe.php";
$sSqlAnos = "select distinct o70_anousu";
$sSqlAnos .= "  from orcreceita ";
$sSqlAnos .= " where o70_instit = " . db_getsession("DB_instit");
$sSqlAnos .= " order by o70_anousu";
$rsAnos = db_query($sSqlAnos);
$aAnos = db_utils::getColectionByRecord($rsAnos);
$aMes = array(1 => 'Janeiro', 2 => 'Fevereiro', 3 => 'Março', 4 => 'Abril', 5 => 'Maio', 6 => 'Junho', 7 => 'Julho', 8 => 'Agosto', 9 => 'Setembro', 10 => 'Outubro', 11 => 'Novembro', 12 => 'Dezembro');
?>
<html>
<head>
<title><?php 
echo $w01_titulo;
?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript" src="scripts/db_script.js"></script>
<script language="JavaScript" src="scripts/scripts.js"></script>
<script language="JavaScript" src="scripts/prototype.js"></script>
<script language="JavaScript" src="scripts/strings.js"></script>
<script>
</script>
$sCamposAtendimentoLocal .= "ov25_sequencial ||' - '|| ov25_descricao as local,";
$sCamposAtendimentoLocal .= "ov01_depart ||' - '|| descrdepto as departamento_inicial,";
$sCamposAtendimentoLocal .= "(select procarquiv.p67_dtarq ";
$sCamposAtendimentoLocal .= "   from arqproc ";
$sCamposAtendimentoLocal .= "        inner join procarquiv on p68_codarquiv = p67_codarquiv ";
$sCamposAtendimentoLocal .= " where  p68_codproc = p58_codproc) as data_arquivamento, ";
$sCamposAtendimentoLocal .= "p58_codproc as numero_processo";
$sWhereAtendimentoLocal = "ouvidoriaatendimento.ov01_sequencial = {$oGet->iAtendimento}";
$sSqlOuvAtend = $oDaoOuvidoriaAtend->sql_query_atendimento_processo(null, $sCamposAtendimentoLocal, null, $sWhereAtendimentoLocal);
$rsOuviAtendimento = $oDaoOuvidoriaAtend->sql_record($sSqlOuvAtend);
if ($oDaoOuvidoriaAtend->erro_status == "0") {
    db_msgbox("Não foi possível localizar o atendimento desejado.");
    db_redireciona("digitaconsultaouvidorianovo.php");
    exit;
}
$oAtendimento = db_utils::fieldsMemory($rsOuviAtendimento, 0);
$sDataArquivamento = "";
if ($oAtendimento->data_arquivamento != "") {
    $sDataArquivamento = db_formatar($oAtendimento->data_arquivamento, "d");
}
$oAtendimento->data_arquivamento = $sDataArquivamento;
$sNumeroProcesso = "";
if ($oAtendimento->numero_processo != "") {
    $sNumeroProcesso = $oAtendimento->numero_processo;
}
$oAtendimento->numero_processo = $sNumeroProcesso;
?>
<html>
<head>
	<title>Consulta Atendimento Ouvidoria</title>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
     if ($oParam->iProcesso != "") {
         $aWhere[] = "p58_codproc = {$oParam->iProcesso}";
     }
     if ($oParam->iAtendimento != "") {
         list($iNumeroAtendimento, $iAnoAtendimento) = explode("/", $oParam->iAtendimento);
         $aWhere[] = "ov01_numero = {$iNumeroAtendimento} and ov01_anousu = {$iAnoAtendimento}";
     }
     $sWhere = implode(" and ", $aWhere);
     $sSqlBuscaAtendimentos = $oDaoOuvidoriaAtendimento->sql_query_titular(null, $sCampos, null, $sWhere);
     $rsBuscaAtendimentos = $oDaoOuvidoriaAtendimento->sql_record($sSqlBuscaAtendimentos);
     if ($oDaoOuvidoriaAtendimento->numrows == 0) {
         throw new Exception("Não encontrado atendimentos para os filtros selecionados.");
     }
     $aResultados = array();
     for ($iAtendimento = 0; $iAtendimento < $oDaoOuvidoriaAtendimento->numrows; $iAtendimento++) {
         $oOuvidoriaAtendimento = db_utils::fieldsMemory($rsBuscaAtendimentos, $iAtendimento);
         $oAtendimento = new stdClass();
         $oAtendimento->iSeqAtendimento = $oOuvidoriaAtendimento->ov01_sequencial;
         $oAtendimento->iAtendimento = $oOuvidoriaAtendimento->ov01_numero;
         $oAtendimento->sDescricao = urlencode($oOuvidoriaAtendimento->p51_descr);
         $oAtendimento->sRequerente = urlencode($oOuvidoriaAtendimento->ov01_requerente);
         $oAtendimento->sDepartamento = urlencode($oOuvidoriaAtendimento->descrdepto);
         $oAtendimento->dtDataAtendimento = $oOuvidoriaAtendimento->ov01_dataatend;
         $oAtendimento->iProtocolo = $oOuvidoriaAtendimento->ov09_protprocesso;
         $oAtendimento->iCpfCnpj = $oOuvidoriaAtendimento->cpf_cnpj;
         $aResultados[] = $oAtendimento;
     }
     $_SESSION["aResultadosConsultaOuvidoria"] = $aResultados;
 }
 $oRetorno->status = 1;
 $oRetorno->aResultados = $_SESSION["aResultadosConsultaOuvidoria"];
}
$pdf->Cell(180, 3, "", "", 1, "L", 0);
$pdf->Cell(200, 4, "", "", 1, "C", 0);
$pdf->setX(5);
$pdf->SetFont('Arial', 'B', 9);
$pdf->Cell(200, 4, "Atividades", "LRBT", 1, "C", 0);
$pdf->setX(5);
$pdf->Cell(200, 4, "", "", 1, "C", 0);
if ($iLinhasConsultaAtividade > 0) {
    $pdf->setX(10);
    $pdf->SetFont('Arial', '', $titulo);
    $pdf->cell(15, 4, "Cod.", 0, 0, "C", 1);
    $pdf->cell(95, 4, "Atividade", 0, 0, "C", 1);
    $pdf->cell(10, 4, "Tipo", 0, 1, "C", 1);
    for ($iInd = 0; $iInd < $iLinhasConsultaAtividade; $iInd++) {
        $oDadosAtividade = db_utils::fieldsmemory($rsSimulacaoCalculoAtividade, $iInd);
        $sTipoAtividade = "S";
        if ($oDadosAtividade->q131_principal == "t") {
            $sTipoAtividade = "P";
        }
        $pdf->setX(10);
        $pdf->SetFont('Arial', '', $texto);
        $pdf->cell(15, 4, $oDadosAtividade->q131_atividade, 0, 0, "C", 0);
        $pdf->cell(95, 4, $oDadosAtividade->q03_descr, 0, 0, "L", 0);
        $pdf->cell(10, 4, $sTipoAtividade, 0, 1, "L", 0);
    }
} else {
    $pdf->cell(190, 4, "NÃO POSSUI ATIVIDADE", 0, 1, "C", 0);
}
$pdf->Cell(180, 3, "", "", 1, "L", 0);
$pdf->Cell(200, 4, "", "", 1, "C", 0);
 /**
  * Retorna objeto com as configurções do módulo issqn
  * @return mixed boolean|object
  */
 function getParametrosIssqn()
 {
     $sSql = $this->sql_query_file();
     $rsSql = db_query($sSql);
     if (!$rsSql) {
         $this->erro_status = "0";
         $this->erro_msg = "Erro ao Buscar Parametros do ISSQN.";
         return false;
     }
     $oParametrosISSQN = db_utils::fieldsMemory($rsSql, 0);
     return $oParametrosISSQN;
 }
 /**
  * Salva os Dados da Nota da Planilha de Retencao 
  * 
  * @access public
  * @return void
  */
 public function salvar()
 {
     if (!db_utils::inTransaction()) {
         throw new Exception("Erro [0] - Não Existe transação ativa");
     }
     $oDaoNotas = db_utils::getDao("issplanit");
     $oDaoNotas->q21_planilha = $this->getCodigoPlanilha();
     //$this->iCodigoPlanilha;
     $oDaoNotas->q21_dataop = $this->getDataOperacao()->getDate();
     //$this->getDatausu();
     $oDaoNotas->q21_horaop = $this->getHoraOperacao();
     //db_hora();
     $oDaoNotas->q21_tipolanc = $this->getTipoLancamento();
     //1;
     $oDaoNotas->q21_retido = $this->isRetido() ? 'true' : 'false';
     //"true";
     $oDaoNotas->q21_status = $this->getStatus();
     //1;
     $oDaoNotas->q21_situacao = $this->getSituacao();
     //"0";
     $oDaoNotas->q21_datanota = $this->getDataNota()->getDate();
     //$oNota->dtNota;
     $oDaoNotas->q21_cnpj = $this->getCNPJ();
     //$oNota->sCnpj;
     $oDaoNotas->q21_serie = $this->getSerie();
     //"";
     $oDaoNotas->q21_nome = $this->getNome();
     //substr($oNota->sNome,0,40);
     $oDaoNotas->q21_nota = $this->getNumeroNota();
     //$oNota->sNumeroNota;
     $oDaoNotas->q21_valorser = $this->getValorServico();
     //$oNota->nValor;
     $oDaoNotas->q21_valor = $this->getValorRetencao();
     //$oNota->nValorTotalRetencao;
     $oDaoNotas->q21_aliq = $this->getAliquota();
     //$oNota-nAliquota;
     $oDaoNotas->q21_valordeducao = $this->getValorDeducao();
     //"{$oNota->nValorDeducao}";
     $oDaoNotas->q21_valorbase = $this->getValorBase();
     //$oNota->nValorBase;
     $oDaoNotas->q21_valorimposto = $this->getValorImposto();
     //$oNota->nValorTotalRetencao;
     $oDaoNotas->q21_servico = $this->getDescricaoServico();
     //"Recolhimento de retencao";
     $oDaoNotas->q21_obs = $this->getObservacoes();
     //"";
     $oDaoNotas->incluir(null);
     if ($oDaoNotas->erro_status == 0) {
         throw new Exception("Erro ao incluir nota na planilha.\n{$oDaoNotas->erro_msg}");
     }
     if (!empty($this->iCodigoNotaLiquidacao)) {
         $oDaoIssPlanOp = db_utils::getDao("issplanitop");
         $oDaoIssPlanOp->q96_issplanit = $this->getCodigoPlanilha();
         $oDaoIssPlanOp->q96_pagordem = $this->getCodigoNotaLiquidacao();
         $oDaoIssPlanOp->incluir(null);
         if ($oDaoIssPlanOp->erro_status == 0) {
             throw new Exception("Erro ao incluir nota na planilha.");
         }
     }
     return true;
 }