Mapa.pas 36.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
(**
---------------------------------------------------------------------------------------------------------------------------------------------------------------
Copyright 2000, 2001, 2002, 2003, 2004, 2005 Dataprev - Empresa de Tecnologia e Informações da Previdência Social, Brasil

Este arquivo é parte do programa CACIC - Configurador Automático e Coletor de Informações Computacionais

O CACIC é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como
publicada pela Fundação do Software Livre (FSF); na versão 2 da Licença, ou (na sua opinião) qualquer versão.

Este programa é distribuido na esperança que possa ser  util, mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer
MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para maiores detalhes.

Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título "LICENCA.txt", junto com este programa, se não, escreva para a Fundação do Software
Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
---------------------------------------------------------------------------------------------------------------------------------------------------------------
*)

unit Mapa;

interface

uses
  Windows,
  SysUtils,    // Deve ser colocado após o Windows acima, nunca antes
  StrUtils,
  StdCtrls,
  Controls,
  Classes,
  Forms,
  ExtCtrls,
  Graphics,
  Dialogs,
  CACIC_Library,
  CACIC_Comm,
  CACIC_WMI,
  ComCtrls,
  Commctrl,
  ShellAPI,
  Types,
  IdIPWatch,
  Registry,
  Math,
  IdBaseComponent,
  IdComponent,
  Mask,
  ComObj,
  ldapsend,
  MultiMon;

function IsUserAnAdmin() : boolean; external shell32;

var strCollectsPatrimonioLast,
    strConfigsPatrimonioCombos,
    strFieldsAndValuesToRequest,
    strIdUON1,
    strFrmAtual,
    strShowOrHide               : string;
    textFileAguarde             : TextFile;
    boolFinalizando             : boolean;
    objCacic                    : TCACIC;
    Fechar                      : boolean;
    Dummy                       : integer;
    OldValue                    : LongBool;
    formSecondMonitor           : TForm;

type
  TfrmMapaCacic = class(TForm)
    edWebManagerAddress: TLabel;
    lbWebManagerAddress: TLabel;
    pnVersao: TPanel;
    timerMessageBoxShowOrHide: TTimer;
    timerMessageShowTime: TTimer;
    timerProcessos: TTimer;
    gbLeiaComAtencao: TGroupBox;
    lbLeiaComAtencao: TLabel;
    gbInformacoesSobreComputador: TGroupBox;
    lbEtiqueta2: TLabel;
    lbEtiqueta3: TLabel;
    lbEtiqueta4: TLabel;
    lbEtiqueta9: TLabel;
    lbEtiqueta10: TLabel;
    lbEtiqueta1: TLabel;
    lbEtiqueta5: TLabel;
    edTeInfoPatrimonio4: TEdit;
    edTeInfoPatrimonio3: TEdit;
    btCombosUpdate: TButton;
    edTeInfoPatrimonio2: TEdit;
    edTeInfoPatrimonio9: TEdit;
    edTeInfoPatrimonio1: TEdit;
    edTeInfoPatrimonio5: TEdit;
    bgTermoResponsabilidade: TGroupBox;
    rdConcordaTermos: TRadioButton;
    btGravarInformacoes: TButton;
    lbEtiqueta7: TLabel;
    edTeInfoPatrimonio6: TEdit;
    lbEtiqueta6: TLabel;
    edTeInfoPatrimonio7: TEdit;
    btKonamiCode: TPanel;
    edTeInfoPatrimonio10: TEdit;
    
    procedure FormCreate(Sender: TObject);
    procedure AtualizaPatrimonio(Sender: TObject);
    procedure mapa;
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormActivate(Sender: TObject);
    procedure btCombosUpdateClick(Sender: TObject);
    procedure timerProcessosTimer(Sender: TObject);
    procedure rdConcordaTermosClick(Sender: TObject);
    procedure EstadoBarraTarefa(EstadoBarra: Boolean);

    function getLastValue(S : String; separador, separador2 : string): string; 
    function LDAPName: string;
    function NomeComputador : String;
    function getConfigs : String;
//    function SetCpfUser : String;
//    function SetPatrimonioPC : String;
//    function FormatarCpf(strCpfUser : String) : String;
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure btKonamiCodeClick(Sender: TObject);


  private
    strTeInfoPatrimonio1,
    strTeInfoPatrimonio2,
    strTeInfoPatrimonio3,
    strTeInfoPatrimonio4,
    strTeInfoPatrimonio5,
    strTeInfoPatrimonio6,
    strTeInfoPatrimonio7,
    strTeInfoPatrimonio8,
    strTeInfoPatrimonio9,
    strTeInfoPatrimonio10,
    strTeInfoPatrimonioTel     : String;
    psswd : String;
    foco : boolean;

    procedure FormSetFocus(VerificaFoco: Boolean);
    procedure MontaInterface;
    procedure RecuperaValoresAnteriores;
    procedure Sair;

  public
    boolAcessoOK                : boolean;
    strId_usuario,
    strChkSisInfFileName,
    strGerColsInfFileName       : String;

    procedure Finalizar;

  end;

const SENHA = 'uuddlrlrba';

var frmMapaCacic: TfrmMapaCacic;

implementation

{$R *.dfm}


procedure TfrmMapaCacic.Sair;
Begin
    Application.Terminate;
End;

procedure TfrmMapaCacic.Finalizar;
Begin
  Visible                               := false;

  if FileExists(objCACIC.getLocalFolderName + '\temp\aguarde_MAPACACIC.txt') then
      objCACIC.deleteFileOrFolder(objCacic.getLocalFolderName +
                                  '\temp\aguarde_MAPACACIC.txt');
  objCacic.setValueToFile('Configs', 'Patrimonio', 'false', strGercolsInfFileName);
  Application.ProcessMessages;

  Sair;
End;

procedure TfrmMapaCacic.rdConcordaTermosClick(Sender: TObject);
begin
  btGravarInformacoes.Enabled:= true;
end;

//------------------------------------------------------------------------------
//------------------FUNÇÃO PARA RETORNAR O NOME DO COMPUTADOR.------------------
//------------------------------------------------------------------------------

Function TfrmMapaCacic.NomeComputador : String;
var
  lpBuffer : PChar;
  nSize : DWord;
const Buff_Size = MAX_COMPUTERNAME_LENGTH + 1;
begin
  nSize := Buff_Size;
  lpBuffer := StrAlloc(Buff_Size);
  GetComputerName(lpBuffer,nSize);
  Result := String(lpBuffer);
  StrDispose(lpBuffer);
end;

//------------------------------------------------------------------------------
//----------------------FUNÇÃO PARA RETORNAR O PATRIMONIO-----------------------
//------------------------------------------------------------------------------

//function TfrmMapaCacic.SetPatrimonioPC : String;
//var
//  strPatrimonioPc,
//  strNomePC        : String;
//begin
//  Result:='';
//  strNomePC:=NomeComputador;
//
//  if (pos('-',strNomePC) > 0) then
//    strPatrimonioPc:=copy(strNomePC, 0, (pos('-', strNomePC)-1));
//  Result:=strPatrimonioPC;
//end;

//------------------------------------------------------------------------------
//--------------------FUNÇÃO PARA FORMATAR O CPF--------------------------------
//------------------------------------------------------------------------------

//function TfrmMapaCacic.FormatarCpf(strCpfUser : String) : String;
//var
//  strCpfFormatado : String;
//begin
//  Result:='';
//  strCpfFormatado:= Copy(strCpfUser, 1,3)
//
//            + '.' + Copy(strCpfUser, 4,3)
//
//            + '.' + Copy(strCpfUser, 7,3)
//
//            + '-' + Copy(strCpfUser, 10,2);
//  Result:=strCpfFormatado;
//
//end;
//------------------------------------------------------------------------------
//--------------------FUNÇÃO PARA RETORNAR O CPF DO USUARIO---------------------
//------------------------------------------------------------------------------

//function TfrmMapaCacic.SetCpfUser : String;
//var
//  strCpfUser,
//  strUser        : String;
//begin
//  Result:='';
//  strUser:=strTeInfoPatrimonio3;
//
//  if (pos('-',strUser) > 0) then
//    strCpfUser:=copy(strUser, 0, (pos('-', strUser)-1));
//
//  Result:=strCpfUser;
//end;

//------------------------------------------------------------------------------
//--------------------FUNÇÃO PARA RETORNAR O ULTIMO VALOR-----------------------
//-----------------------APÓS O SEPARADOR SELECIONADO---------------------------
//------------------------------------------------------------------------------

function TfrmMapaCacic.getLastValue(S : String; separador, separador2 : string): string;
  var
  conta, tamanho_separador, tamanho_separador2 : integer;         // variáveis auxiliares
  resultado : TStringList; // variáveis auxiliares
  Saux, index : string;           // variáveis auxiliares
begin
    resultado := TStringList.Create;   // inicializa variavel
    tamanho_separador:= Length(separador);
    tamanho_separador2:= Length(separador2);
    index:=copy(separador2, 1, pos(#$D#$A, separador2)-1);
    conta := pos(separador,S)+tamanho_separador;         // pega posição do separador
    if conta <> 0 then begin           // verifica se existe o separador caso contrario trata apenas //como uma única linha
        while trim(S) <> '' do begin   // enquanto S não for nulo executa
            Saux := copy(S,1,conta-1); // Variável Saux recebe primeiro valor
            delete(S,1,conta);         // deleta primeiro valor
            if conta = 0 then begin    // se não ouver mais separador Saux equivale ao resto da //linha
                Saux := S;
                S := '';
            end;
            if pos(separador2, Saux)>0 then begin
              delete(Saux, 1, tamanho_separador2);
              resultado.values[index]:=
                copy(Saux,1,pos(#$D#$A, Saux));
              break;
            end;
            resultado.add(Saux);           // adiciona linhas na string lista
            conta := pos(separador,S);     //pega posição do separador
        end;
    end
    else begin
        Saux := S;
        resultado.Add(Saux);
    end;
    Result := trim(resultado.values[index]); // retorna resultado como uma lista indexada
end;

//------------------------------------------------------------------------------
//--------------------FUNÇÃO PARA PEGAR CONFIGURAÇÕES NO GERENTE----------------
//------------------------------------------------------------------------------

function TfrmMapaCacic.getConfigs : String;
var
   teste : string;
Begin
  btCombosUpdate.Enabled := false;
  objCACIC.writeDailyLog('getConfigs: Invocando getConfigs...');
  Result := Comm(objCacic.getWebManagerAddress + objCacic.getWebServicesFolderName + 'get/config', strFieldsAndValuesToRequest, objCacic.getLocalFolderName);

  objCacic.setBoolCipher(not objCacic.isInDebugMode);
  objCacic.writeDebugLog('FormActivate: Retorno de getConfigs: "'+Result+'"');

  if (Result <> '0') then
    Begin
      objCACIC.writeDailyLog('getConfigs: Comunicação realizada com sucesso!');
      objCacic.setValueToFile('Configs' ,'servidor_autenticacao', objCacic.getValueFromTags('dados_ldap'                  , Result), strGerColsInfFileName);
      objCacic.setValueToFile('Configs' ,'Patrimonio_Combos'    , objCacic.getValueFromTags('Configs_Patrimonio_Combos'   , Result), strGerColsInfFileName);
      objCacic.setValueToFile('Configs' ,'Patrimonio_Interface' , objCacic.getValueFromTags('Configs_Patrimonio_Interface', Result), strGerColsInfFileName);
    End
  else
    begin
      objCACIC.writeDailyLog('Não foi possível realizar a conexão!');
    end;
  btCombosUpdate.Enabled := true;
End;

//------------------------------------------------------------------------------
//--------------------PROCEDIMENTO UTILIZADO PARA PEGAR AS ULTIMAS--------------
//----------------------INFORMAÇÕES ENVIADAS PELO MAPACACIC---------------------

procedure TfrmMapaCacic.RecuperaValoresAnteriores;
var strCollectsPatrimonioLast : String;
begin
  objCACIC.writeDailyLog('RecuperaValoresAnteriores: Início.');
  btCombosUpdate.Enabled := false;

  strCollectsPatrimonioLast := objCacic.deCrypt( objCacic.GetValueFromFile
                                                ('Collects','col_patr_last',
                                                 strGerColsInfFileName));

  if (strCollectsPatrimonioLast <> '') then
    Begin

      if (strTeInfoPatrimonio1='') then
        strTeInfoPatrimonio1 := objCacic.getValueFromTags('IDPatrimonio',
                                                          strCollectsPatrimonioLast);
      if (strTeInfoPatrimonio2='') then
        strTeInfoPatrimonio2 := objCacic.getValueFromTags('PatrimonioMonitor1',
                                                          strCollectsPatrimonioLast);
      if (strTeInfoPatrimonio3='') then
        strTeInfoPatrimonio3 := objCacic.getValueFromTags('PatrimonioMonitor2',
                                                          strCollectsPatrimonioLast);
      if (strTeInfoPatrimonio4='') then
        strTeInfoPatrimonio4 := objCacic.getValueFromTags('UserLogado',
                                                          strCollectsPatrimonioLast);
      if (strTeInfoPatrimonio5='') then
        strTeInfoPatrimonio5 := objCacic.getValueFromTags('UserName',
                                                          strCollectsPatrimonioLast);
      if (strTeInfoPatrimonio6='') then
        strTeInfoPatrimonio6 := objCacic.getValueFromTags('Coordenacao_Setor',
                                                          strCollectsPatrimonioLast);
      if (strTeInfoPatrimonio7='') then
        strTeInfoPatrimonio7 := objCacic.getValueFromTags('Sala',
                                                          strCollectsPatrimonioLast);
      if (strTeInfoPatrimonioTel='') then
        strTeInfoPatrimonioTel := objCacic.getValueFromTags('Tel',
                                                          strCollectsPatrimonioLast);
      if (strTeInfoPatrimonio8='') then
        strTeInfoPatrimonio8 := objCacic.getValueFromTags('Ramal',
                                                          strCollectsPatrimonioLast);
      if (strTeInfoPatrimonio9='') then
        strTeInfoPatrimonio9 := objCacic.getValueFromTags('ComputerName',
                                                          strCollectsPatrimonioLast);
      if (strTeInfoPatrimonio10='') then
        strTeInfoPatrimonio10 := objCacic.getValueFromTags('IPComputer',
                                                          strCollectsPatrimonioLast);
    End;
  btCombosUpdate.Enabled := true;
  Application.ProcessMessages;
  objCACIC.writeDailyLog('RecuperaValoresAnteriores: Fim.');
end;

procedure TfrmMapaCacic.AtualizaPatrimonio(Sender: TObject);
var strColetaAtual,
    strRetorno: String;
begin
if edTeInfoPatrimonio5.text <> '' then
  begin
    btGravarInformacoes.Enabled := false;
    btGravarInformacoes.Caption := 'Enviando informações...';
    objCACIC.writeDailyLog('Preparando para o envio das informações...');
    strFieldsAndValuesToRequest := 'CollectType=' + objCacic.replaceInvalidHTTPChars(objCacic.enCrypt('col_patr')) ;

    strColetaAtual := StringReplace('[IDPatrimonio]'         + edTeInfoPatrimonio1.Text   + '[/IDPatrimonio]'       +
                                    '[PatrimonioMonitor1]'   + edTeInfoPatrimonio2.Text   + '[/PatrimonioMonitor1]' +
                                    '[PatrimonioMonitor2]'   + edTeInfoPatrimonio3.Text   + '[/PatrimonioMonitor2]' +
                                    '[UserLogado]'           + edTeInfoPatrimonio4.Text   + '[/UserLogado]'         +
                                    '[UserName]'             + edTeInfoPatrimonio5.Text   + '[/UserName]'           +
                                    '[Coordenacao_Setor]'    + edTeInfoPatrimonio6.Text   + '[/Coordenacao_Setor]'  +
                                    '[Sala]'                 + edTeInfoPatrimonio7.Text   + '[/Sala]'               +
                                    '[ComputerName]'         + edTeInfoPatrimonio9.text   + '[/ComputerName]'       +
                                    '[IPComputer]'           + edTeInfoPatrimonio10.text  + '[/IPComputer]'
                                    , ',','[[COMMA]]',[rfReplaceAll]);

    strFieldsAndValuesToRequest := strFieldsAndValuesToRequest + ',Patrimonio='  +
                                   objCacic.replaceInvalidHTTPChars(objCacic.enCrypt(strColetaAtual));

    strRetorno := Comm(objCacic.getWebManagerAddress + objCacic.getWebServicesFolderName +
                        'gercols/set/collects', strFieldsAndValuesToRequest, objCacic.getLocalFolderName);

    objCacic.setBoolCipher(not objCacic.isInDebugMode);

    if (strRetorno = '0') then
    begin
       btGravarInformacoes.caption := 'Problema ao enviar informações...';
       Application.messagebox(Pchar('Atenção!'+ #13#10 + 'Problema ao enviar as informações!'
               + #13#10 + 'Se o problema persistir contate o adminsitrador.'), 'Erro!',MB_ICONERROR + mb_ok);
    end
    else
    Begin
        objCACIC.writeDailyLog('Envio realizado com sucesso.');
        btGravarInformacoes.Caption := 'Informações enviadas com sucesso...';
        objCacic.setValueToFile('Collects','col_patr_last' ,
                                objCacic.enCrypt(strColetaAtual), strGerColsInfFileName);
    End;
    objCacic.writeDebugLog(#13#10 + 'AtualizaPatrimonio: Dados Enviados ao Servidor!');
    Application.ProcessMessages;
    Finalizar;
  end
  else
    Application.messagebox(Pchar('Por favor, é necessário digitar seu nome!'), 'Atenção!',MB_ICONEXCLAMATION + mb_ok);
end;


procedure TfrmMapaCacic.MontaInterface;
var strConfigsPatrimonioInterface,
    termosPatrimonio,
    strNomeLDAP : String;
    count : integer;
Begin
    count := 0;
    btCombosUpdate.Enabled := false;

    strConfigsPatrimonioInterface := objCacic.deCrypt(objCacic.getValueFromFile
                                                      ('Configs','Patrimonio_Interface',
                                                      strGerColsInfFileName));
    termosPatrimonio := objCacic.getValueFromFile('Configs', 'termos_patrimonio', strGercolsInfFileName);

//-------------------------PATRIMONIO DA MAQUINA--------------------------------
{   edTePatrimonioPc.Text                     := SetPatrimonioPc;
   if edTePatrimonioPc.Text <> '' then
   Begin
      lbEtiquetaPatrimonioPc.Visible         := true;
      edTePatrimonioPc.Visible               := true;
   end;}
    edTeInfoPatrimonio1.Text        := strTeInfoPatrimonio1;
    edTeInfoPatrimonio1.Visible     := true;
    lbEtiqueta1.Visible             := true;

//   objCacic.writeDebugLog('MontaInterface: in_exibir_etiqueta2 -> "'     +
//                          objCacic.getValueFromTags('in_exibir_etiqueta2',
//                                                   strConfigsPatrimonioInterface)+'"');

//   if (trim(objCacic.getValueFromTags('in_exibir_etiqueta2', strConfigsPatrimonioInterface)) = 'S') then
//   begin
      //lbEtiqueta3.Caption         := objCacic.getValueFromTags('te_etiqueta2', strConfigsPatrimonioInterface);
       lbEtiqueta2.Visible          := true;
       edTeInfoPatrimonio2.Text     := strTeInfoPatrimonio2;
       edTeInfoPatrimonio2.visible  := True;
//   end;

//   objCacic.writeDebugLog('MontaInterface: in_exibir_etiqueta3 -> "'     +
//                          objCacic.getValueFromTags('in_exibir_etiqueta3',
//                                                   strConfigsPatrimonioInterface)+'"');

//   if (trim(objCacic.getValueFromTags('in_exibir_etiqueta3', strConfigsPatrimonioInterface)) = 'S') then
//   begin
      //lbEtiqueta3.Caption         := objCacic.getValueFromTags('te_etiqueta3', strConfigsPatrimonioInterface);
       lbEtiqueta3.Visible          := true;
       edTeInfoPatrimonio3.Text     := strTeInfoPatrimonio3;
       edTeInfoPatrimonio3.visible  := True;
//   end;

//-----------------------------USUARIO LOGADO-----------------------------------

//    edTeInfoUserLogado.Text                   := getUserLogon;
    strTeInfoPatrimonio4 := '';
    while(strTeInfoPatrimonio4 = '') and (count < 600) do
    begin
      strTeInfoPatrimonio4    := objCACIC.getValueFromTags('UserName',fetchWMIvalues('Win32_ComputerSystem',objCACIC.getLocalFolderName,'UserName'));
      strTeInfoPatrimonio4    := copy(strTeInfoPatrimonio4, pos('\', strTeInfoPatrimonio4)+1, length(strTeInfoPatrimonio4));
      edTeInfoPatrimonio4.Text:= strTeInfoPatrimonio4;
      sleep(1000);
      count := count + 1;
    end;

    if edTeInfoPatrimonio4.Text <> '' then
    begin
       lbEtiqueta4.Visible          := true;
       edTeInfoPatrimonio4.Visible  := true;
    end;

    //-------------------------------NOME USUARIO-----------------------------------
    strNomeLDAP := getLastValue(LDAPName, 'Attribute:', 'cn'+#$D#$A);


    if (strNomeLDAP <> '') and (strNomeLDAP <> 'Results: 0') then
    begin
       edTeInfoPatrimonio5.Text     := strNomeLDAP;
       edTeInfoPatrimonio5.Visible  := true;
       lbEtiqueta5.Visible          := true;
       lbEtiqueta5.ShowHint         := true;
       lbEtiqueta5.hint             := 'Nome do usuário logado.';
    end
    else
    begin
       edTeInfoPatrimonio5.Visible  := true;
       edTeInfoPatrimonio5.Enabled  := true;
       lbEtiqueta5.Visible          := true;
       lbEtiqueta5.ShowHint         := true;
       lbEtiqueta5.hint             := 'Digite seu nome, não foi possível recuperá-lo.';
       objCacic.writeDailyLog('Não foi possível pegar nome do ldap');
    end;

//   objCacic.writeDebugLog('MontaInterface: in_exibir_etiqueta6 -> "'     +
//                          objCacic.getValueFromTags('in_exibir_etiqueta6',
//                                                    strConfigsPatrimonioInterface)+'"');

//   if (trim(objCacic.getValueFromTags('in_exibir_etiqueta6', strConfigsPatrimonioInterface)) = 'S') then
//   begin
      //lbEtiqueta6.Caption         := objCacic.getValueFromTags('te_etiqueta6', strConfigsPatrimonioInterface);
      lbEtiqueta6.Visible           := true;
      edTeInfoPatrimonio6.Hint      := objCacic.getValueFromTags('te_help_etiqueta6', strConfigsPatrimonioInterface);
      edTeInfoPatrimonio6.Text      := strTeInfoPatrimonio6;
      edTeInfoPatrimonio6.visible   := True;
//   end;

//   objCacic.writeDebugLog('MontaInterface: in_exibir_etiqueta7 -> "'     +
//                          objCacic.getValueFromTags('in_exibir_etiqueta7',
//                                                    strConfigsPatrimonioInterface)+'"');

//   if (trim(objCacic.getValueFromTags('in_exibir_etiqueta7', strConfigsPatrimonioInterface)) = 'S') then
//   begin
      //lbEtiqueta7.Caption         := objCacic.getValueFromTags('te_etiqueta7', strConfigsPatrimonioInterface);
      lbEtiqueta7.Visible           := true;
      edTeInfoPatrimonio7.Hint      := objCacic.getValueFromTags('te_help_etiqueta7', strConfigsPatrimonioInterface);
      edTeInfoPatrimonio7.Text      := strTeInfoPatrimonio7;
      edTeInfoPatrimonio7.visible   := True;
//   end;

//-----------------------NOME DO COMPUTADOR PARA O EDTEXT-----------------------
    edTeInfoPatrimonio9.Text               := NomeComputador;
    if edTeInfoPatrimonio9.Text <> '' then
    begin
       lbEtiqueta9.Visible          := true;
       edTeInfoPatrimonio9.Visible  := true;
    end;
    lbEtiqueta9.Visible             := true;
    edTeInfoPatrimonio9.Visible     := true;

//-----------------------PUXA O IP DA MÁQUINA PARA O EDTEXT-------------------------------------
    strTeInfoPatrimonio10            := fetchWMIvalues('Win32_NetworkAdapterConfiguration', objCACIC.getLocalFolderName);
    edTeInfoPatrimonio10.Text        := objCACIC.getValueFromTags('IPAddress',strTeInfoPatrimonio10);
    if edTeInfoPatrimonio10.Text <> '' then
    begin
       lbEtiqueta10.Visible          := true;
       edTeInfoPatrimonio10.Visible  := true;
    end;

    if termosPatrimonio <> '' then
      rdConcordaTermos.Caption := termosPatrimonio;

    btGravarInformacoes.Visible := true;
    btCombosUpdate.Enabled      := true;
    Application.ProcessMessages;
    objCACIC.writeDailyLog('Interface criada com sucesso.');
end;

procedure TfrmMapaCacic.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  If Not fechar Then //se a variavel de fechamento fecha estiver falsa
    Action := caNone // nao realizará  nenhuma operação
  Else
  begin
    Action := caFree;
    formSecondMonitor:=nil;
    objCacic.writeDebugLog('FormClose: ' + Sender.ClassName);
    Finalizar;
  end;
end;


procedure TfrmMapaCacic.mapa;
begin
  Try
    RecuperaValoresAnteriores;
    MontaInterface;
  Except
    on E:Exception do
       Begin
         Application.messagebox(Pchar('Problemas ao gerar formulário.'), 'Erro!',MB_ICONERROR + mb_ok);
//         EstadoBarraTarefa(TRUE);
         objCacic.writeExceptionLog(E.Message,e.ClassName);
         Finalizar;
       End;
  End;
End;

procedure TfrmMapaCacic.FormCreate(Sender: TObject);

begin
  psswd := '';
  KeyPreview := true;
  frmMapaCacic.boolAcessoOK := true;
//Definido TRUE, se não, mesmo que o foco seja falso, a aplicação não é fechada quando quiser.
  Fechar:=TRUE;
  foco:=true; //DEFINIDO COMO TRUE PARA QUE A JANELA NÃO SEJA FECHADA

  
  Try
    strFrmAtual  := 'Principal';
    objCacic     := TCACIC.Create();

    objCacic.setBoolCipher(true);
    objCacic.setLocalFolderName('Cacic');
    objCacic.setWebServicesFolderName('/ws');

    if IsUserAnAdmin then
    begin
      strChkSisInfFileName := objCacic.getWinDir + 'chksis.inf';

      if not (objCacic.GetValueFromFile('Configs','LocalFolderName',
                                         strChkSisInfFileName) = '') then

      Begin

        objCacic.setLocalFolderName(objCacic.GetValueFromFile
                                    ('Configs', 'LocalFolderName',
                                     strChkSisInfFileName));

        objCacic.setWebServicesFolderName(objCacic.GetValueFromFile
                                          ('Configs','WebServicesFolderName',
                                            strChkSisInfFileName));

        objCacic.setWebManagerAddress(objCacic.GetValueFromFile
                                      ('Configs','WebManagerAddress',
                                        strChkSisInfFileName));


        strGerColsInfFileName := objCacic.getLocalFolderName + 'GerCols.inf';

        // A existência e bloqueio do arquivo abaixo evitará que o Agente Principal entre em ação

        AssignFile(textFileAguarde,objCacic.getLocalFolderName +
                   '\temp\aguarde_MAPACACIC.txt'); //Associa o arquivo a uma variável do tipo TextFile

        {$IOChecks off}

        reset(textFileAguarde);

        {$IOChecks on}
        if (IOResult <> 0) then // Arquivo não existe, será recriado.
            rewrite (textFileAguarde); //Abre o arquivo texto

        Append(textFileAguarde);
        Writeln(textFileAguarde,'Apenas um pseudo-cookie para o Agente Principal esperar o término de MapaCACIC');
        Append(textFileAguarde);

        frmMapaCacic.edWebManagerAddress.Caption := objCacic.GetValueFromFile('Configs','WebManagerAddress', strChkSisInfFileName);

        objCacic.writeDebugLog('FormActivate: Versão do MapaCacic...: '    +
                                pnVersao.Caption);
        ObjCacic.writeDebugLog('FormActivate: Hash-Code do MapaCacic: '    +
                                objCacic.getFileHash(ParamStr(0)));

        // Povoamento com dados de configurações da interface patrimonial
        // Solicita ao servidor as configurações para a Coleta de Informações de Patrimônio
        objCacic.writeDebugLog('FormActivate: Requisitando informações de patrimônio da estação...');

        if getConfigs <> '0' then
        begin
          if (objCACIC.getValueFromFile('Configs',
                                        'Patrimonio',
                                        strGerColsInfFileName) = 'true') then
          begin
            objCACIC.writeDailyLog('Iniciando formulário.');
            mapa;
            FormSetFocus(foco)
          end
          else
          begin
            objCACIC.writeDailyLog('Modulo desabilitado.');
            Finalizar;
          end;
        end
        else
        begin
           objCACIC.writeDailyLog('Falha ao pegar informações!.');
           Finalizar;
        end;
      end
      else
      Begin
        frmMapaCacic.boolAcessoOK := false;
        objCACIC.writeDailyLog('Atenção! É necessário reinstalar o CACIC nesta estação. A estrutura encontra-se corrompida.');
        Finalizar;
      End;
    end
    else
    Begin // Se NT/2000/XP/...
      Application.messagebox(Pchar('ATENÇÃO! Essa aplicação requer execução com nível administrativo.'), 'Erro!',MB_ICONERROR + mb_ok);
      objCacic.writeDailyLog('SEM PRIVILÉGIOS: Necessário ser administrador "local" ou de Domínio!');
      Finalizar;
    End;
    Except
      on E:Exception do
        Begin
          objCacic.writeExceptionLog(E.Message,e.ClassName + 'Erro ao criar formulario.');
          objCACIC.writeDailyLog('Erro ao criar formulario.');
          Finalizar;
      End; //on E:Exception do
    end;
end;


procedure TfrmMapaCacic.FormActivate(Sender: TObject);

begin
  pnVersao.Caption := 'Versão: ' + objCacic.getVersionInfo(ParamStr(0));
  strFrmAtual := 'Principal';
  //ESCONDE APLICAÇÃO DA TASKBAR -- DEVE SER COLOCADA NO OnActivate
  Application.MainFormOnTaskBar:=FALSE;
  ShowWindow(Application.Handle, SW_HIDE);
end;

procedure TfrmMapaCacic.btCombosUpdateClick(Sender: TObject);
begin

  getConfigs;
  RecuperaValoresAnteriores;
  MontaInterface;

end;

procedure TfrmMapaCacic.btKonamiCodeClick(Sender: TObject);
begin
  finalizar;
end;

//------------------------------------------------------------------------------
//PROCEDURE CRIADO PARA DEIXAR O FORM FULLSCREEN E FOCADO, SEM QUE SEJA POSSÍVEL
//FECHAR OU ALTERNAR ENTRE OUTRAS JANELAS ATÉ QUE ATUALIZE O PATRIMONIO.
procedure TfrmMapaCacic.FormSetFocus(VerificaFoco: Boolean);
var
  r : TRect;
begin
  if VerificaFoco then
  begin
    Fechar                    := False;
    BorderIcons               := BorderIcons - [biSystemMenu] - [biMinimize] - [biMaximize];
    BorderStyle               := bsNone;
    FormStyle                 := fsStayOnTop;
    Position                  := poOwnerFormCenter;
    timerProcessos.Enabled    := True;
    SystemParametersInfo(SPI_GETWORKAREA, 0, @r,0);
    SetBounds(r.Left, r.Top, r.Right-r.Left, r.Bottom-r.Top);
    Top := Screen.WorkAreaTop;
    Left := Screen.WorkAreaLeft;
    Width := Screen.WorkAreaWidth;
    Height := Screen.Height;
    {    if Screen.MonitorCount>1 then
    begin
      formSecondMonitor := TForm.Create(nil);
      for i := 0 to Screen.MonitorCount - 1 do
      begin
        if not Screen.Monitors[i].Primary then
          formSecondMonitor.WindowState := wsNormal;
          formSecondMonitor.BorderStyle := bsNone;
          formSecondMonitor.Width := Screen.Monitors[i].Width;
          formSecondMonitor.Height := Screen.Monitors[i].Height;
          formSecondMonitor.top := Screen.Monitors[i].top;
          formSecondMonitor.left := Screen.Monitors[i].left;
          formSecondMonitor.Enabled := true;
          formSecondMonitor.Visible:=true;
      end;
    end;
       }

//  EstadoBarraTarefa(FALSE);

  end;

end;

//CODE PRA FECHAR O MAPA SEM PRESSIONAR NADA. (up + up + down + down + <- + -> + <- + -> + B + A)
procedure TfrmMapaCacic.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);

begin
  case Key of
    VK_Left : psswd:=psswd+'l';
    VK_Right : psswd:=psswd+'r';
    VK_Up : psswd:=psswd+'u';
    VK_Down : psswd:=psswd+'d';
    65 : psswd:=psswd+'a';
    66 : psswd:=psswd+'b';
    else
      psswd:='';
  end;
  if psswd = SENHA then begin
    FormStyle                 := fsNormal;
    MessageDlg('KONAMICODE ACTIVATED!',mtWarning, [mbOK], 0);
    btKonamiCode.Left    := width-btKonamiCode.Width;
    btKonamiCode.visible := true;
    btKonamiCode.enabled := true;
  end;
end;


//------------------------------------------------------------------------------
//----------------ESCONDE BARRA DE TAREFAS--------------------------------------
//------------------------------------------------------------------------------

procedure TfrmMapaCacic.EstadoBarraTarefa(EstadoBarra: Boolean);

var wndHandle : THandle;
    wndClass  : array[0..50] of Char;

begin

  StrPCopy(@wndClass[0],'Shell_TrayWnd');
  wndHandle := FindWindow(@wndClass[0], nil);

  If EstadoBarra=True Then
    ShowWindow(wndHandle, SW_RESTORE) {Mostra a barra de tarefas}

  Else
    ShowWindow(wndHandle, SW_HIDE); {Esconde a barra de tarefas}

end;

//------------------------------------------------------------------------------
//-----------------BEGIN-----RETIRA PROCESSO DO GERENCIADOR---------------------
//------------------------------------------------------------------------------

procedure TfrmMapaCacic.timerProcessosTimer(Sender: TObject);
var
  dwSize,dwNumBytes,PID,hProc: Cardinal;
  PLocalShared,PSysShared: PlvItem;
  h: THandle;
  iCount,i: integer;
  szTemp: string;
begin
  //Pega o Handle da ListView
  h:=FindWindow('#32770',nil);
  h:=FindWindowEx(h,0,'#32770',nil);
  h:=FindWindowEx(h,0,'SysListView32',nil);

  //Pega o número de itens da ListView
  iCount:=SendMessage(h, LVM_GETITEMCOUNT,0,0);
  for i:=0 to iCount-1 do
    begin
    //Define o tamanho de cada item da ListView
    dwSize:=sizeof(LV_ITEM) + sizeof(CHAR) * MAX_PATH;

    //Abre um espaço na memória do NOSSO programa para o PLocalShared
    PLocalShared:=VirtualAlloc(nil, dwSize, MEM_RESERVE + MEM_COMMIT, PAGE_READWRITE);

    //Pega o PID do processo taskmgr
    GetWindowThreadProcessId(h,@PID);

    //Abre o processo taskmgr
    hProc:=OpenProcess(PROCESS_ALL_ACCESS,false,PID);

    //Abre um espaço na memória do taskmgr para o PSysShared
    PSysShared:=VirtualAllocEx(hProc, nil, dwSize, MEM_RESERVE OR MEM_COMMIT, PAGE_READWRITE);

    //Define as propriedades do PLocalShared
    PLocalShared.mask:=LVIF_TEXT;
    PLocalShared.iItem:=0;
    PLocalShared.iSubItem:=0;
    PLocalShared.pszText:=LPTSTR(dword(PSysShared) + sizeof(LV_ITEM));
    PLocalShared.cchTextMax:=20;

    //Escreve PLocalShared no espaço de memória que abriu no taskmgr
    WriteProcessMemory(hProc,PSysShared,PLocalShared,1024,dwNumBytes);

    //Pega o texto to item i e passa pro PSysShared
    SendMessage(h,LVM_GETITEMTEXT,i,LPARAM(PSysShared));

    //Passa o PSysShared para o PLocalShared
    ReadProcessMemory(hProc,PSysShared,PLocalShared,1024,dwNumBytes);

    //Passa o texto do Item para szTemp
    szTemp:=pchar(dword(PLocalShared)+sizeof(LV_ITEM));

    //Se esse texto contiver a string proc deleta o item
    if LowerCase(szTemp) = 'mapacacic.exe' then
      ListView_DeleteItem(h,i);

    //Libera os espaços de memória utilizados
    VirtualFree(pLocalShared, 0, MEM_RELEASE);
    VirtualFreeEx(hProc, pSysShared, 0, MEM_RELEASE);

    //Fecha o handle do processo
    CloseHandle(hProc);
  end;
end;

function TfrmMapaCacic.LDAPName: string;
var
  retorno: TStringList;
  i: integer;
  host, username, psswd, base, strDadosLDAP, aux, identificador : string;
  ldap: TLDAPsend;

begin
  result            := '';

//  PEGANDO OS DADOS DO POR MEIO DO GET/CONFIGS, ONDE SERÁ GRAVADO NO GERCOLS.INF
  strDadosLDAP := objCacic.deCrypt(objCacic.getValueFromFile('Configs','servidor_autenticacao',strGerColsInfFileName));
  if strDadosLDAP<>'' then
  begin
    ldap              := TLDAPsend.Create;
    retorno           := TStringList.Create;

    host         := objCacic.getValueFromTags('ip', strDadosLDAP);
    username     := objCacic.getValueFromTags('usuario', strDadosLDAP);
    psswd        := objCacic.getValueFromTags('senha', strDadosLDAP);
    base         := objCacic.getValueFromTags('base', strDadosLDAP);
    identificador:= objCacic.getValueFromTags('identificador', strDadosLDAP);
    for i := 0 to 2 do //Até 2 porque são no máxio 3 identificadores que serão passados.
    begin
      aux:=objCacic.getValueFromTags('retorno'+IntToStr(i+1), strDadosLDAP);
      if aux<>'' then
        retorno.Add(aux);
    end;
    if (host<>'') and (base<>'') and (retorno.count<>0) and (username<>'') then
    begin
      try
        try
         objCACIC.writeDailyLog('Nome Usuário: Estabelecendo conexão.');
         ldap.TargetHost := host;
         ldap.UserName   := username;
         ldap.Password   := psswd;
         ldap.Timeout    := 5000;
         if ldap.Login and ldap.Bind then    //Loga no LDAP e autentica no LDAP com Usuário e senha repassado. (BindSasl é mais seguro que Bind)
         begin
          ldap.Search(base, False, identificador+ '=' + strTeInfoPatrimonio4, retorno); //Faz a pesquisa, com o CPF repassado.
          result := LDAPResultdump(ldap.SearchResult);
          objCACIC.writeDailyLog('Nome Usuário: Conexão estabelecida, pesquisa realizada.');
          ldap.Logout;
         end;
        finally
         ldap.Free;
         retorno.Free;
        end;
      Except
        on E:Exception do
           Begin
             objCacic.writeExceptionLog(E.Message,e.ClassName);
             objCACIC.writeDailyLog('Nome Usuário: Falha ao tentar recuperar o nome.');
           End; //on E:Exception do
      end; // Try
    end; // if (host<>'') or (base<>'') or (retorno.count=0) then
  end  //if strDadosLDAP<>'' then
  else
    objCACIC.writeDailyLog('Nome Usuário: Dados do servidor de autenticação inexistentes.');
end;




end.