CACIC_Library.pas 86.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 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097
{*------------------------------------------------------------------------------
   Package of both methods/properties to be used by CACIC Clients

   @version CACIC_Library 2009-01-07 23:00 harpiain
   @package CACIC_Agente
   @subpackage CACIC_Library
   @author Adriano dos Santos Vieira <harpiain at gmail.com>
   @copyright Copyright (C) Adriano dos Santos Vieira. All rights reserved.
   @license GNU/GPL, see LICENSE.php
   CACIC_Library is free software and parts of it may contain or be derived from
   the GNU General Public License or other free or open source software license.
   See COPYRIGHT.php for copyright notices and details.

   CACIC_Library - Coding style
   for Constants
      - characters always in uppercase
      - use underscore for long name
      e.g.
        const CACIC_VERSION = '2.4.0';

   for Variables
      - characters always in lowercase
      - start with "g" character for global
      - start with "v" character for local
      - start with "p" character for methods parameters
      - start with "P" character for pointers
      - use underscore for better read
      e.g.
        var g_global : string;
        var v_local  : string;

   for Objects
      - start with "o" character
      e.g.
        oCacicObject : TCACIC_Common;

   for Methods
      - start with lowercase word
      - next words start with capital letter
      e.g.
        function getLocalFolderName() : string;
        procedure setLocalFolderName( pPath: string );
-------------------------------------------------------------------------------}
unit CACIC_Library;

interface

uses	Windows,
      Classes,
      SysUtils,
      StrUtils,
      MD5,
      DCPcrypt2,
      DCPrijndael,
      DCPbase64,
      ActiveX,
      PJVersionInfo,
      Registry,
      IniFiles,
      Tlhelp32,
      ComObj,
      ShellAPI,
      WinSvc,
      Variants;

type

{ ------------------------------------------------------------------------------
  Tipo de dados para obter informacoes extendidas dos Sistema Operacional
  ver MSDN: http://msdn.microsoft.com/en-us/library/ms724833(VS.85).aspx
-------------------------------------------------------------------------------}
  TOSVersionInfoEx = packed record
    dwOSVersionInfoSize: DWORD;
    dwMajorVersion: DWORD;
    dwMinorVersion: DWORD;
    dwBuildNumber: DWORD;
    dwPlatformId: DWORD;
    szCSDVersion: array[0..127] of AnsiChar;
    wServicePackMajor: WORD;
    wServicePackMinor: WORD;
    wSuiteMask: WORD;
    wProductType: Byte;
    wReserved: Byte;
  end;

{*------------------------------------------------------------------------------
 Classe para obter informações do sistema windows
-------------------------------------------------------------------------------}
   TCACIC_Windows = class
       private
       protected
         g_strAcao    :string;
         g_local_folder_name: string;
         /// Mantem a identificação do sistema operacional
         g_osVersionInfo: TOSVersionInfo;
         /// Mantem a identificação extendida do sistema operacional
         g_osVersionInfoEx: TOSVersionInfoEx;
         /// TRUE se houver informação extendida do SO, FALSE caso contrário
         g_osVersionInfoExtended: boolean;
       public
         function  explode(p_String, p_Separador : String)                                                                              : TStrings; virtual; abstract;
         function  getBitPlatform()                                                                                                     : string;
         function  getBoolToString(pBoolQuestion : boolean)                                                                             : string;   virtual; abstract;
         function  getHomeDrive()                                                                                                       : string;
         function  getLocalFolderName()                                                                                                 : string;
         function  getVersionFromHCR(pStrToProcess : String)                                                                            : string;
         function  getVersionInfo(pStrFileName: string)                                                                                 : string;
         function  getWindowsStrId()                                                                                                    : string;
         function  getWinDir()                                                                                                          : string;
         function  implode(const pTStrArray: TStrings; const pStrSeparator: string)                                                     : string;  virtual; abstract;
         function  isWindowsAdmin()                                                                                                     : boolean;
         function  isWindowsGEVista()                                                                                                   : boolean;
         function  isWindowsGEXP()                                                                                                      : boolean;
         function  isWindowsNT()                                                                                                        : boolean;
         function  isWindowsNTPlataform()                                                                                               : boolean;
         function  isWindowsVista()                                                                                                     : boolean;
         function  isWindowsXP()                                                                                                        : boolean;
         function  isWindows2000()                                                                                                      : boolean;
         function  isWindows9xME()                                                                                                      : boolean;
         function  verFmt(const MS, LS: DWORD)                                                                                          : string;
         procedure writeDebugLog(pStrDebugMessage:string);                                                                                          virtual; abstract;
         procedure writeExceptionLog(pStrExceptionMessage, pStrExceptionClassName : String; pStrAddedMessage : String = '');                        virtual; abstract;
   end;

{*------------------------------------------------------------------------------
 Classe geral da biblioteca
-------------------------------------------------------------------------------}
    TCACIC = class(TCACIC_Windows)
       constructor Create();
       destructor Destroy; override;
       private
       protected
         g_web_manager_address,
         g_web_services_folder_name,
         g_main_program_name,
         g_main_program_hash,
         g_details_to_debugging     : string;
         g_boolCipher               : boolean;

       public
         Windows : TCACIC_Windows; /// objeto de informacoes de windows
         function  checkIfFileDateIsToday(pStrFileName : String)                                                            : Boolean;
         function  countOccurences(const strSubText, strText: string)                                                       : Integer;
         function  createOneProcess(pStrCmd: string; pBoolWait: boolean; pWordShowWindow : word = SW_HIDE; waitMilliseconds : cardinal = INFINITE)                  : Boolean;
         function  capitalize (CONST s: STRING)                                                                             : String;
         function  checkModule(pStrModuleFileName, pStrModuleHashCode : String)                                             : String;
         function  deCrypt(pStrCipheredText : String; pBoolShowInLog : boolean = true; pBoolForceDecrypt : boolean = false) : String;
         function  deleteFileOrFolder(pStrFileOrFolderName : string)                                                        : Boolean;
         function  enCrypt(pStrPlainText : String; pBoolShowInLog : boolean = true; pBoolForceEncrypt : boolean = false)    : String;
         function  explode(p_String, p_Separador : String)                                                                  : TStrings; override;
         function  fixFolderAtHomeDrive(pStrFolderName : String)                                                            : String;
         function  fixWebAddress(pStrWebAddress : String)                                                                   : String;
         function  getBlockSize()                                                                                           : Integer;
         function  getBoolCipher()                                                                                          : Boolean;
         function  getBoolToString(pBoolQuestion : boolean)                                                                 : String;   override;
         function  getCipherKey()                                                                                           : String;
         function  getDetailsToDebugging()                                                                                  : String;
         function  getFileSize(pStrFileNameToExamine: string; boolShowInKBytes: Boolean)                                    : String;
         function  getInfFileName()                                                                                         : String;
         function  getFileHash(pStrFileName : String)                                                                       : String;
         function  getFolderDate(var p_FolderName: string)                                                                  : TDateTime;
         function  getIV()                                                                                                  : String;
         function  getKeySize()                                                                                             : Integer;
         function  getMainProgramName()                                                                                     : String;
         function  getMainProgramHash()                                                                                     : String;
         function  getParam(pStrParamName : string)                                                                         : String;
         function  getRootKey(strRootKey: String)                                                                           : HKEY;
         function  getSeparatorKey()                                                                                        : String;
         function  getTagsFromValues(pStrSource : String; pStrTags : String = '[]')                                         : TStrings;
         function  getValueFromFile(pStrSectionName, pStrKeyName, pStrFileName : String; pBoolShowInDebug : boolean = true) : String;
         function  getValueFromTags(pStrTagLabel, pStrSource : String; pStrTags : String = '[]')                            : String;
         function  getValueRegistryKey(p_KeyName : String)                                                                  : Variant;
         function  getWebManagerAddress()                                                                                   : String;
         function  getWebServicesFolderName()                                                                               : String;
         function  implode(const pTStrArray: TStrings; const pStrSeparator: string)                                         : String;   override;
         function  isAppRunning(pStrAppName: PAnsiChar )                                                                    : Boolean;
         function  isInDebugMode(pStrDetailName : String = '')                                                              : Boolean;
         function  listParams                                                                                               : String;
         function  padWithZeros(const str : string; size : integer)                                                         : String;
         function  removeSpecialsCharacters(p_Text : String)                                                                : String;
         function  removeZerosFimString(Texto : String)                                                                     : String;
         function  replaceInvalidHTTPChars(p_String : String)                                                               : String;
         function  replacePseudoTagsWithCorrectChars(pStrString : String)                                                   : String;
         function  setValueRegistryKey(p_KeyName: String; p_Data: Variant)                                                  : Variant;
         function  trimEspacosExcedentes(p_str: string)                                                                     : String;
         procedure addApplicationToFirewall(p_EntryName:string;p_ApplicationPathAndExe:string; p_Enabled : boolean);
         procedure criaTXT(p_Dir, p_File : String; pStrTextToWrite : String = '');
         procedure killProcess(p_HWindowHandle: HWND);
         procedure killTask(p_ExeFileName: string);
         procedure replaceEnvironmentVariables(var pStrText : String; pStrTag : String = '%');
         procedure setBoolCipher(p_boolCipher : boolean);
         procedure setDetailsToDebugging(pStrDetailsToDebugging: String);         
         procedure setLocalFolderName(pStrLocalFolderName: string = 'Cacic');
         procedure setMainProgramName(p_main_program_name: string);
         procedure setMainProgramHash(p_main_program_hash: string);
         procedure setValueToFile(pStrSectionName, pStrKeyName, pStrValue, pStrFileName : String);
         procedure setValueToTags(pStrTagLabel, pStrTagValue : String; var pStrSource : String; pStrTags : String = '[]');
         procedure setWebManagerAddress(pStrWebManagerAddress: string);
         procedure setWebServicesFolderName(pStrWebServicesFolderName: string);
         procedure writeDailyLog(pStrLogMessage : String; pStrFileNameSuffix : String = '');
         procedure writeDebugLog(pStrDebugMessage : String); override;
         procedure writeExceptionLog(pStrExceptionMessage, pStrExceptionClassName : String; pStrAddedMessage : String = ''); override;

         function serviceGetType(sMachine, sService: PChar): DWORD;
         function serviceStart(sMachine,sService : string ) : boolean;
         function ServiceGetStatus(sMachine, sService: PChar): DWORD;
   end;

// Declaração de constantes para a biblioteca
const CACIC_PROCESS_WAIT   = true; // aguardar fim do processo
      CACIC_PROCESS_NOWAIT = false; // não aguardar o fim do processo

// Some constants that are dependant on the cipher being used
// Assuming MCRYPT_RIJNDAEL_128 (i.e., 128bit blocksize, 256bit keysize)
const CACIC_KEYSIZE        = 32; // 32 bytes = 256 bits
      CACIC_BLOCKSIZE      = 16; // 16 bytes = 128 bits

// Chave AES. Recomenda-se que cada empresa altere a sua chave.
// Esta chave é passada como parâmetro para o Gerente de Coletas
const CACIC_CIPHERKEY      = 'CacicBrasil';
      CACIC_IV             = 'abcdefghijklmnop';
      CACIC_SEPARATORKEY   = '=CacicIsFree='; // Usada apenas para os arquivos de controle (.INF)

{
 Controle de prioridade de processo
 http://msdn.microsoft.com/en-us/library/ms683211(VS.85).aspx
}
const BELOW_NORMAL_PRIORITY_CLASS = $00004000;
  {$EXTERNALSYM BELOW_NORMAL_PRIORITY_CLASS}

var   P_OSVersionInfo: POSVersionInfo;

implementation

{*------------------------------------------------------------------------------
  Construtor para a classe

  Objetiva inicializar valores a serem usados pelos objetos da
  classe.
-------------------------------------------------------------------------------}
constructor TCACIC.Create();
begin
  FillChar(Self.g_osVersionInfoEx, SizeOf(Self.g_osVersionInfoEx), 0);
  {$TYPEDADDRESS OFF}
  P_OSVersionInfo := @Self.g_osVersionInfoEx;
  {$TYPEDADDRESS ON}

  Self.g_osVersionInfoEx.dwOSVersionInfoSize:= SizeOf(TOSVersionInfoEx);
  Self.g_osVersionInfoExtended := GetVersionEx(P_OSVersionInfo^);
  if (not Self.g_osVersionInfoExtended) then begin
     Self.g_osVersionInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
     GetVersionEx(Self.g_osVersionInfo);
  end;
  Self.Windows := TCACIC_Windows.Create();
end;

{*------------------------------------------------------------------------------
  Destrutor para a classe

  Objetiva finalizar valores usados pelos objetos da classe.
-------------------------------------------------------------------------------}
destructor TCACIC.Destroy();
begin
   Try
     P_OSVersionInfo:=nil;
     FreeMemory(P_OSVersionInfo);
   Except
   End;
   inherited;
end;

function TCACIC.getRootKey(strRootKey: String): HKEY;
begin
    /// Encontrar uma maneira mais elegante de fazer esses testes.
    if      Trim(strRootKey) = 'HKEY_LOCAL_MACHINE'   Then Result := HKEY_LOCAL_MACHINE
    else if Trim(strRootKey) = 'HKEY_CLASSES_ROOT'    Then Result := HKEY_CLASSES_ROOT
    else if Trim(strRootKey) = 'HKEY_CURRENT_USER'    Then Result := HKEY_CURRENT_USER
    else if Trim(strRootKey) = 'HKEY_USERS'           Then Result := HKEY_USERS
    else if Trim(strRootKey) = 'HKEY_CURRENT_CONFIG'  Then Result := HKEY_CURRENT_CONFIG
    else if Trim(strRootKey) = 'HKEY_DYN_DATA'        Then Result := HKEY_DYN_DATA;
end;

function TCACIC.deleteFileOrFolder(pStrFileOrFolderName: String) : boolean;
var OS: TSHFileOpStruct;
begin
  Result := true;
  if Length(pStrFileOrFolderName) > 0 then
    begin
      FillChar(OS, sizeof(OS),0);
      OS.pFrom := PChar(pStrFileOrFolderName + #0);
      OS.wFunc := FO_DELETE;
      OS.fFlags := FOF_NOCONFIRMATION or FOF_SILENT;
      Result := (SHFileOperation(OS)=0);
    end
end;

{ Returns a count of the number of occurences of SubText in Text }
function TCACIC.CountOccurences(const strSubText, strText: string): Integer;
begin
  if (strSubText = '') OR (strText = '') OR (Pos(strSubText, strText) = 0) then
    Result := 0
  else
    Result := (Length(strText) - Length(StringReplace(strText, strSubText, '', [rfReplaceAll]))) div  Length(strSubText);
end;  { CountOccurences }

{*------------------------------------------------------------------------------------
 Transformar as variáveis de ambiente existentes no Texto em seus respectivos valores
-------------------------------------------------------------------------------------}
procedure TCACIC.replaceEnvironmentVariables(var pStrText : String; pStrTag : String = '%');
var intLoop            : integer;
    strVariableName    : String;
    tstrVariablesNames : TStrings;
begin
  // Somente trato as variáveis de ambiente se as tags estiverem em número par!
  if (countOccurences(pStrTag,pStrText) mod 2 = 0) then
    Begin
      tstrVariablesNames := explode(pStrText, pStrTag);
      intloop := 1;
      while (intLoop < tstrVariablesNames.Count) do
        Begin
          if strVariableName <> '' then
            strVariableName := strVariableName + ',';

          strVariableName := strVariableName + tstrVariablesNames[intLoop];
          inc(intLoop,2);
        End;

      tstrVariablesNames := explode(strVariableName,',');
      for intLoop := 0 to tstrVariablesNames.Count - 1 do
        pStrText := StringReplace(pStrText,pStrTag + tstrVariablesNames[intLoop] + pStrTag, GetEnvironmentVariable(tstrVariablesNames[intLoop]),[rfReplaceAll]);
    End;
  writeDebugLog('replaceEnvironmentVariables: Final: "' + pStrText + '"');
end;

{*------------------------------------------------------------------------------------
 Retornar o endereço Web devidamente formatado
-------------------------------------------------------------------------------------}
function TCACIC.fixWebAddress(pStrWebAddress : String): String;
Begin
  Result := '';
  if (pStrWebAddress <> '') then
    Begin
      Result := StringReplace(pStrWebAddress,'//'   ,'',[rfReplaceAll]);        // Substituo possíveis "//" por nada
      Result := StringReplace(Result          ,'http:','',[rfReplaceAll]);      // Substituo possível "http:" por nada
      Result := Result + '/';                                                   // Acrescento "/"
      Result := StringReplace(Result          ,'//'   ,'',[rfReplaceAll]);      // Substituo possíveis "//" por nada
      Result := Result + '/';                                                   // Acrescento "/'
      Result := 'http://' + StringReplace(Result, '//', '/', [rfReplaceAll]);   // Precedo com "http://"
    End;
End;


{*------------------------------------------------------------------------------------
Retornar para fixar um nome de pasta no HomeDrive
-------------------------------------------------------------------------------------}
function TCACIC.fixFolderAtHomeDrive(pStrFolderName : String) : String;
var tstrFolderName1,
    tstrFolderName2 : TStrings;
    intAUX : integer;
Begin
  Result := pStrFolderName;

  // Crio um array separado por ":" (Para o caso de ter sido informada a letra da unidade)
  //tstrLocalFolder1 := TStrings.Create;

  tstrFolderName1 := explode(StringReplace(pStrFolderName,'/','\',[rfReplaceAll]),':');

  if (tstrFolderName1.Count > 1) then
    Begin
      tstrFolderName2 := TStrings.Create;
      // Ignoro a letra informada...
      // Certifico-me de que as barras são invertidas... (erros acontecem)
      // Crio um array quebrado por "\"
      Result := tstrFolderName1[1];

      tstrFolderName2 := explode(Result,'\');

      // Inicializo retorno com a unidade raiz do Sistema Operacional
      // Concateno ao retorno as partes que formarão o caminho completo do CACIC
      Result := getHomeDrive;
      for intAux := 0 to (tstrFolderName2.Count-1) do
        if (tstrFolderName2[intAux] <> '') then
            Result := Result + tstrFolderName2[intAux];
      tstrFolderName2.Free;
    End
  else
    Result := getHomeDrive + pStrFolderName + '\';

  tstrFolderName1.Free;
End;

{*------------------------------------------------------------------------------------
  Retornar Boolean TRUE caso as informações de executável e hash-code estejam corretas
-------------------------------------------------------------------------------------}
function  TCACIC.checkModule(pStrModuleFileName, pStrModuleHashCode : String) : String;
Begin
  if (getFileHash(pStrModuleFileName) = pStrModuleHashCode) then
    Result := 'Ok!'
  else if FileExists(pStrModuleFileName) then
    Result := 'Módulo Corrompido!'
  else
    Result := 'Módulo Não Baixado!';
End;
function TCACIC.getFileSize(pStrFileNameToExamine: string; boolShowInKBytes: Boolean): string;
var
  SearchRec: TSearchRec;
  strPath: string;
  intRetval,
  intFileSize,
  intKbytes : Integer;
begin
  Try
    intKbytes := StrToInt(IfThen(boolShowInKBytes,'1024','1'));
    strPath := ExpandFileName(pStrFileNameToExamine);
    try
      intRetval := FindFirst(ExpandFileName(pStrFileNameToExamine), faAnyFile, SearchRec);
      if intRetval = 0 then
        intFileSize := SearchRec.Size
      else
        intFileSize := -1;
    finally
      SysUtils.FindClose(SearchRec);
    end;

    Result := IntToStr(intFileSize);
    if intFileSize > -1 then
      Result := IntToStr((StrToInt(Result) div intKbytes)) ;
  Except
  End;
end;

function TCACIC.getParam(pStrParamName : string) : String;
var strAuxParamName : String;
    intAuxLoop : integer;
Begin
  Result          := '';
  strAuxParamName := '/' + Trim(pStrParamName) + '=';
  intAuxLoop      := 1;
  while (intAuxLoop <= ParamCount) do
    Begin
      if (LowerCase(Copy(ParamStr(intAuxLoop),1,StrLen(PAnsiChar(strAuxParamName)))) = LowerCase(strAuxParamName)) then
        Result     := Copy(ParamStr(intAuxLoop),StrLen(PAnsiChar(strAuxParamName))+1,StrLen(PChar(ParamStr(intAuxLoop))));

      inc(intAuxLoop);
    End;
End;

function TCACIC.listParams : String;
var intAuxLoop : integer;
Begin
  Result := Concat('Nenhum Parâmetro Recebido na Chamada a "' + ParamStr(0) + '"' , chr(13) ,DupeString('=',100));
  if (ParamCount > 1) then
    Begin
      Result := Concat('Lista de Parâmetros Recebidos' , chr(13) , DupeString('-',50) , chr(13));
      for intAuxLoop := 1 to ParamCount - 1 do
        Result := Concat(Result,ParamStr(intAuxLoop),chr(13));
      Result := Concat(Result,DupeString('=',100),chr(13));
    End;
End;

function TCACIC.removeSpecialsCharacters(p_Text : String) : String;
var I : Integer;
    strAuxRSC : String;
Begin
   For I := 0 To Length(p_Text) Do
     if ord(p_Text[I]) in [32..126] Then
        strAuxRSC := strAuxRSC + p_Text[I]
     else
        strAuxRSC := strAuxRSC + ' ';  // Coloca um espaço onde houver caracteres especiais
   Result := strAuxRSC;
end;

function TCACIC.setValueRegistryKey(p_KeyName: String; p_Data: Variant): Variant;
var RegEditSet: TRegistry;
    RegDataType: TRegDataType;
    strRootKey, strKey, strValue : String;
    ListaAuxSet : TStrings;
    I : Integer;
begin
    ListaAuxSet := explode(p_KeyName, '\');
    strRootKey := ListaAuxSet[0];
    For I := 1 To ListaAuxSet.Count - 2 do
      strKey := strKey + ListaAuxSet[I] + '\';
    strValue := ListaAuxSet[ListaAuxSet.Count - 1];

    RegEditSet := TRegistry.Create;
    try
        RegEditSet.Access := KEY_WRITE;
        RegEditSet.Rootkey := GetRootKey(strRootKey);

        if RegEditSet.OpenKey(strKey, True) then
        Begin
            RegDataType := RegEditSet.GetDataType(strValue);
            if RegDataType = rdString then
              begin
                RegEditSet.WriteString(strValue, p_Data);
              end
            else if RegDataType = rdExpandString then
              begin
                RegEditSet.WriteExpandString(strValue, p_Data);
              end
            else if RegDataType = rdInteger then
              begin
                RegEditSet.WriteInteger(strValue, p_Data);
              end
            else
              begin
                RegEditSet.WriteString(strValue, p_Data);
              end;

        end;
    finally
      RegEditSet.CloseKey;
    end;
    ListaAuxSet.Free;
    RegEditSet.Free;
end;

function TCACIC.getValueRegistryKey(p_KeyName: String): Variant;
var RegEditGet: TRegistry;
    RegDataType: TRegDataType;
    strRootKey, strKey, strValue, s: String;
    ListaAuxGet : TStrings;
    DataSize, Len, I : Integer;
begin
    try
      Result := '';
      ListaAuxGet := explode(p_KeyName, '\');

      strRootKey := ListaAuxGet[0];
      For I := 1 To ListaAuxGet.Count - 2 Do strKey := strKey + ListaAuxGet[I] + '\';
      strValue := ListaAuxGet[ListaAuxGet.Count - 1];
      if (strValue = '(Padrão)') then
        strValue := ''; //Para os casos de se querer buscar o valor default (Padrão)

      RegEditGet := TRegistry.Create;

      RegEditGet.Access := KEY_READ;
      RegEditGet.Rootkey := GetRootKey(strRootKey);
      if RegEditGet.OpenKeyReadOnly(strKey) then //teste
      Begin
           RegDataType := RegEditGet.GetDataType(strValue);
           if (RegDataType = rdString) or (RegDataType = rdExpandString) then
              Result := RegEditGet.ReadString(strValue)
           else if RegDataType = rdInteger then
              Result := RegEditGet.ReadInteger(strValue)
           else if (RegDataType = rdBinary) or (RegDataType = rdUnknown) then
            Begin
              DataSize := RegEditGet.GetDataSize(strValue);
              if DataSize = -1 then
                exit;
              SetLength(s, DataSize);
              Len := RegEditGet.ReadBinaryData(strValue, PChar(s)^, DataSize);
              if Len <> DataSize then
                exit;
              Result := removeSpecialsCharacters(s);
            End
      end;
    finally
      RegEditGet.CloseKey;
      RegEditGet.Free;
      ListaAuxGet.Free;
    end;
end;

function TCACIC.getFolderDate(var p_FolderName: string): TDateTime;
var
  Rec: TSearchRec;
  Found: Integer;
  Date: TDateTime;
begin
  if (p_FolderName[Length(p_FolderName)] = '\') then
    p_FolderName := Copy(p_FolderName,1,Length(p_FolderName)-1);

  Result := 0;
  Found  := FindFirst(p_FolderName, faDirectory, Rec);
  try
    if Found = 0 then
    begin
      Date   := FileDateToDateTime(Rec.Time);
      Result := Date;
    end;
  finally
    sysutils.FindClose(Rec);
  end;
end;

Function TCACIC.removeZerosFimString(Texto : String) : String;
var I       : Integer;
    strAuxRZFS  : string;
Begin
   strAuxRZFS := '';
   if (Length(trim(Texto))>0) then
     For I := Length(Texto) downto 0 do
       if (ord(Texto[I])<>0) Then
         strAuxRZFS := Texto[I] + strAuxRZFS;
   Result := trim(strAuxRZFS);
end;

procedure TCACIC.criaTXT(p_Dir, p_File : String; pStrTextToWrite : String = '');
var v_TXT : TextFile;
begin
  AssignFile(v_TXT,p_Dir + '\' + p_File + '.txt'); {Associa o arquivo a uma variável do tipo TextFile}
  Rewrite (v_TXT);

  if (pStrTextToWrite <> '') then
    Begin
      Append(v_TXT);
      Writeln(v_TXT,pStrTextToWrite);
    End;

  Closefile(v_TXT);
end;
{
    function RetornaValorShareNT(pStrKey, pStrText : String) : String;
    var intPosKey,
        intLoop    : integer;
    Begin
      Result := '';
      intPosKey := pos(' ' + pStrKey + '=',pStrText);
      if (intPosKey > 0) then
        Begin
          intLoop   := length(pStrText);
          while (intLoop > intPosKey) do
            Begin
              if (copy(pStrText,intLoop,1) <> '=') then
                Result := copy(pStrText,intLoop,1) + Result
              else
                Begin
                  if (copy(pStrText,intLoop - length(pStrKey),length(pStrKey)) = pStrKey) then
                    exit
                  else
                    Begin
                      Result := '';
                      while (copy(pStrText,intLoop,1) <> ' ') do
                        dec(intLoop);
                    End;
                End;
              dec(intLoop);
            End;
        End;
    End;
}

// Função para recuperar valor delimitado por tags "[" e "]"
function TCACIC.getValueFromTags(pStrTagLabel, pStrSource : String; pStrTags : String = '[]'): String;
var strTagInicio,
    strTagFim,
    strSource : String;
begin
  Result       := '';
  strSource    := LowerCase(pStrSource);
  strTagInicio := copy(pStrTags,1,1)       + LowerCase(pStrTagLabel) + copy(pStrTags,2,1);
  strTagFim    := copy(pStrTags,1,1) + '/' + LowerCase(pStrTagLabel) + copy(pStrTags,2,1);

  if (pos(strTagInicio,strSource) > 0) and (pos(strTagFim,strSource) > 0) then
    Result := copy(pStrSource,pos(strTagInicio,strSource)+length(strTagInicio),pos(strTagFim,strSource) - pos(strTagInicio,strSource) - length(strTagInicio));

  writeDebugLog('getValueFromTags: "'+pStrTagLabel+'" => "' + Result + '"');
End;

// Função para obter nomes de tags existentes em pStrSource
function TCACIC.getTagsFromValues(pStrSource : String; pStrTags : String = '[]') : TStrings;
var intLoopTags  : integer;
    strTagsNames : String;
    tstrTags     : TStrings;
Begin
  tstrTags     := explode(pStrSource,copy(pStrTags,2,1));
  strTagsNames := '';
  for intLoopTags := 0 to tstrTags.Count -1 do
    Begin
      if (copy(tstrTags[intLoopTags],1,1) = copy(pStrTags,1,1)) and (copy(tstrTags[intLoopTags],2,1) <> '/') then
        Begin
          if (strTagsNames <> '') then
            strTagsNames := strTagsNames + ',';

          strTagsNames := strTagsNames + copy(tstrTags[intLoopTags],2,length(tstrTags[intLoopTags]));
        End;
    End;

  Result := explode(strTagsNames,',');
End;

// Procedure para atribuir valor delimitados por tags "[" e "]"
procedure TCACIC.setValueToTags(pStrTagLabel, pStrTagValue : String; var pStrSource : String; pStrTags : String = '[]');
var strAuxSVTT       : String;
begin
  strAuxSVTT := getValueFromTags(pStrTagLabel,pStrSource,pStrTags);
  pStrSource := StringReplace(pStrSource, copy(pStrTags,1,1) + pStrTagLabel + copy(pStrTags,2,1) + strAuxSVTT + copy(pStrTags,1,1) + '/' + pStrTagLabel + copy(pStrTags,2,1), '' , [rfReplaceAll]);
  pStrSource := pStrSource + copy(pStrTags,1,1) + pStrTagLabel + copy(pStrTags,2,1) + pStrTagValue + copy(pStrTags,1,1) + '/' + pStrTagLabel + copy(pStrTags,2,1);
End;


function TCACIC.getValueFromFile(pStrSectionName, pStrKeyName, pStrFileName : String; pBoolShowInDebug : boolean = true): String;
//Para buscar do Arquivo INF...
// Marreta devido a limitações do KERNEL w9x no tratamento de arquivos texto e suas seções
var textFileText    : TStringList;
    intFileLine,
    intSectionSize,
    intKeySize      : integer;
    strSectionName,
    strKeyName      : string;
begin
  if pBoolShowInDebug then // Para evitar EStackOverflow devido a requisição recursiva!
    Begin
      writeDebugLog('getValueFromFile: pStrSectionName: "' + pStrSectionName + '"');
      writeDebugLog('getValueFromFile: pStrKeyName: "'     + pStrKeyName     + '"');
      writeDebugLog('getValueFromFile: pStrFileName: "'    + pStrFileName    + '"');
    End;

  Result         := '';
  strSectionName := '[' + pStrSectionName + ']';
  intSectionSize := strLen(PChar(strSectionName));
  strKeyName     := pStrKeyName + '=';
  intKeySize     := strLen(PChar(strKeyName));
  textFileText   := TStringList.Create;
  intFileLine    := 0;
  if (FileExists(pStrFileName)) then
    Begin
      try
        textFileText.LoadFromFile(pStrFileName);
        While (intFileLine < textFileText.Count) Do
          Begin
            if (LowerCase(Trim(PChar(Copy(textFileText[intFileLine],1,intSectionSize)))) = LowerCase(Trim(PChar(strSectionName)))) then
               Begin
                  inc(intFileLine);
                  While (intFileLine < textFileText.Count) and (Trim(PChar(Copy(textFileText[intFileLine],1,1)))<>'[') Do
                    Begin
                      if (LowerCase(Trim(PChar(Copy(textFileText[intFileLine],1,intKeySize)))) = LowerCase(Trim(PChar(strKeyName)))) then
                          Begin
                            Result := PChar(Copy(textFileText[intFileLine],intKeySize + 1,strLen(PChar(textFileText[intFileLine]))-intKeySize));
                            intFileLine := textFileText.Count;
                          End;
                      inc(intFileLine);
                    End;
               End;
            inc(intFileLine);
          End;
      finally
        textFileText.Free;
      end;
    end
  else
    textFileText.Free;

  if pBoolShowInDebug then
    Begin
      writeDebugLog('getValueFromFile: Result: "' + Result + '"');
      writeDebugLog('getValueFromFile: ' + DupeString(':',100));
    End;
end;

// Para gravar no Arquivo INF...
procedure TCACIC.setValueToFile(pStrSectionName, pStrKeyName, pStrValue, pStrFileName : String);
var InfFile : TIniFile;
begin
  self.writeDebugLog('setValueToFile: pStrSectionName: "' + pStrSectionName + '"');
  self.writeDebugLog('setValueToFile: pStrKeyName: "'     + pStrKeyName     + '"');
  self.writeDebugLog('setValueToFile: pStrValue: "'       + pStrValue       + '"');
  self.writeDebugLog('setValueToFile: pStrFileName: "'    + pStrFileName    + '"');
  self.writeDebugLog('setValueToFile: ' + DupeString(':',100));
  if (FileGetAttr(pStrFileName) and faReadOnly) > 0 then
    FileSetAttr(pStrFileName, FileGetAttr(pStrFileName) xor faReadOnly);

  InfFile := TIniFile.Create(pStrFileName);
  InfFile.DeleteKey(pStrSectionName, pStrKeyName);
  InfFile.WriteString(pStrSectionName, pStrKeyName, pStrValue);
  InfFile.Free;
end;

{*------------------------------------------------------------------------------
  Insere exceção na FireWall nativa do MS-Windows

  @param p_EntryName             String  Nome da exceção
  @param p_ApplicationPathAndExe String  Caminho e nome da aplicação
  @param p_Enabled               Boolean Estado da exceção
-------------------------------------------------------------------------------}
procedure TCACIC.addApplicationToFirewall(p_EntryName:string;p_ApplicationPathAndExe:string; p_Enabled : boolean);
var   fwMgr,app:OleVariant;
      profile:OleVariant;
Const NET_FW_PROFILE_DOMAIN = 0;
      NET_FW_PROFILE_STANDARD = 1;
      NET_FW_IP_VERSION_ANY = 2;
      NET_FW_IP_PROTOCOL_UDP = 17;
      NET_FW_IP_PROTOCOL_TCP = 6;
      NET_FW_SCOPE_ALL = 0;
      NET_FW_SCOPE_LOCAL_SUBNET = 1;
begin
  Try
    if FileExists(p_EntryName) then
      Begin
        CoInitialize(nil);

        fwMgr := CreateOLEObject('HNetCfg.FwMgr');
        profile := fwMgr.LocalPolicy.CurrentProfile;
        app := CreateOLEObject('HNetCfg.FwAuthorizedApplication');
        app.ProcessImageFileName := p_ApplicationPathAndExe;
        app.Name := p_EntryName;
        app.Scope := NET_FW_SCOPE_ALL;
        app.IpVersion := NET_FW_IP_VERSION_ANY;
        app.Enabled := p_Enabled;
        profile.AuthorizedApplications.Add(app);

        CoUninitialize;
      End;
  Except
    on E : Exception do
      writeExceptionLog(E.Message,E.ClassName,'addApplicationToFirewall: EntryName="'+p_EntryName+'" ApplicationPathAndExe="'+p_ApplicationPathAndExe+'"');
  End;
end;

{*------------------------------------------------------------------------------
  Retorna string de valores separados pelo caracter indicado

  @param pTstrArray    TStrings contendo os valores
  @param pStrSeparator String   separadora de valores
-------------------------------------------------------------------------------}
Function TCACIC.implode(const pTStrArray: TStrings; const pStrSeparator: string): String;
var i: Integer;
begin
  Result := pTStrArray[0];
  for i := 0 to pTStrArray.Count - 1 do
    Result := Result + pStrSeparator + pTStrArray[i];
end;
{*------------------------------------------------------------------------------
  Retorna array de elementos com base em separador

  @param p_String    String contendo campos e valores separados por caracter ou string
  @param p_Separador String separadora de campos e valores
-------------------------------------------------------------------------------}
Function TCACIC.explode(p_String, p_Separador : String) : TStrings;
var strItem       : String;
    ListaAuxUTILS : TStrings;
    NumCaracteres,
    TamanhoSeparador,
    I : Integer;
Begin
    ListaAuxUTILS    := TStringList.Create;
    strItem          := '';
    NumCaracteres    := Length(p_String);
    TamanhoSeparador := Length(p_Separador);
    I                := 1;
    While I <= NumCaracteres Do
      Begin
        If (Copy(p_String,I,TamanhoSeparador) = p_Separador) or (I = NumCaracteres) Then
          Begin
            if (I = NumCaracteres) then strItem := strItem + p_String[I];
            ListaAuxUTILS.Add(trim(strItem));
            strItem := '';
            I := I + (TamanhoSeparador-1);
          end
        Else
            strItem := strItem + p_String[I];

        I := I + 1;
      End;
    Explode := ListaAuxUTILS;
end;

{*------------------------------------------------------------------------------
  Elimina espacos excedentes na string

  @param p_str String a excluir espacos
-------------------------------------------------------------------------------}
function TCACIC.trimEspacosExcedentes(p_str: String): String;
begin
  if(ansipos('  ', p_str ) <> 0 ) then
    repeat
      p_str := StringReplace( p_str, '  ', ' ', [rfReplaceAll] );
    until ( ansipos( '  ', p_str ) = 0 );

  Result := p_str;
end;

{*------------------------------------------------------------------------------
  Atribui valor booleano à variável indicadora do status da criptografia

  @param p_boolCipher Valor booleano para atribuição à variável para status da
                      criptografia.
-------------------------------------------------------------------------------}
procedure TCACIC.setBoolCipher(p_boolCipher : boolean);
Begin
  Self.g_boolCipher := p_boolCipher;
End;
{*------------------------------------------------------------------------------
  Obtém o status da criptografia (TRUE -> Ligada  /  FALSE -> Desligada)

  @return boolean contendo o status para a criptografia
-------------------------------------------------------------------------------}
function TCACIC.getBoolCipher() : boolean;
Begin
  Result := Self.g_boolCipher;
End;

{*------------------------------------------------------------------------------
  Atribui nomes de métodos para DEBUG

  @param pStrWhatToDebug Valor string para atribuição à variável de nomes de
                         functions e procedures para DEBUG.
-------------------------------------------------------------------------------}
procedure TCACIC.setDetailsToDebugging(pStrDetailsToDebugging: String);
Begin
  Self.g_details_to_debugging := pStrDetailsToDebugging;
End;
{*------------------------------------------------------------------------------
  Obtém os nomes das functions e procedures indicadas para DEBUG

  @return String contendo os nomes das functions e procedures para DEBUG
-------------------------------------------------------------------------------}
function TCACIC.getDetailsToDebugging() : String;
Begin
  Result := Self.g_details_to_debugging;
End;

{*------------------------------------------------------------------------------
  Atribui o nome da pasta do Gerente WEB

  @param p_web_manager_address Nome da Pasta do Gerente WEB
-------------------------------------------------------------------------------}
procedure TCACIC.setWebManagerAddress(pStrWebManagerAddress: string);
begin
  Self.g_web_manager_address := self.fixWebAddress(pStrWebManagerAddress);
end;

{*------------------------------------------------------------------------------
  Atribui o nome da pasta dos scripts de comunicação do Gerente WEB

  @param p_web_services_folder_name Nome da Pasta dos scripts de comunicação do Gerente WEB
-------------------------------------------------------------------------------}
procedure TCACIC.setWebServicesFolderName(pStrWebServicesFolderName: string);
begin
  Self.g_web_services_folder_name := pStrWebServicesFolderName;
end;

{*------------------------------------------------------------------------------
  Obtém o nome da pasta do Gerente WEB

  @return String Nome da Pasta do Gerente WEB
-------------------------------------------------------------------------------}
function TCACIC.getWebManagerAddress() : string;
begin
  Result := Self.g_web_manager_address;
end;

{*------------------------------------------------------------------------------
  Obtém o nome da pasta dos scripts de comunicação do Gerente WEB

  @return String Nome da Pasta dos scripts de comunicação do Gerente WEB
-------------------------------------------------------------------------------}
function TCACIC.getWebServicesFolderName() : string;
begin
  Result := IfThen(Self.g_web_services_folder_name <> '', Self.g_web_services_folder_name , 'ws/');
end;

{*------------------------------------------------------------------------------
  Atribui o caminho físico de instalação do agente cacic

  @param p_local_folder_name Caminho físico de instalação do agente cacic
-------------------------------------------------------------------------------}
procedure TCACIC.setLocalFolderName(pStrLocalFolderName: string = 'Cacic');
begin
  Self.g_local_folder_name := self.fixFolderAtHomeDrive(pStrLocalFolderName);

  // DEBUG - Escrevendo lista de parâmetros recebidos
  writeDebugLog('setLocalFolderName: "' + Self.g_local_folder_name + '"');
  writeDebugLog('setLocalFolderName: ' + listParams);
end;

{*------------------------------------------------------------------------------
  Atribui o nome do programa principal do CACIC

  @param p_main_program_name Nome do programa principal do CACIC
-------------------------------------------------------------------------------}
procedure TCACIC.setMainProgramName(p_main_program_name: string);
begin
  Self.g_main_program_name := p_main_program_name;
end;

{*------------------------------------------------------------------------------
  Atribui o código hash do programa principal do CACIC

  @param p_main_program_hash Código hash do programa principal do CACIC
-------------------------------------------------------------------------------}
procedure TCACIC.setMainProgramHash(p_main_program_hash: string);
begin
  Self.g_main_program_hash := p_main_program_hash;
end;
{*------------------------------------------------------------------------------
  Obtém o nome do programa principal do CACIC

  @return String  Nome do programa principal do CACIC
-------------------------------------------------------------------------------}
function TCACIC.getMainProgramName() : String;
begin
  Result := Self.g_main_program_name;
end;
{*------------------------------------------------------------------------------
  Obtém o hash-code do programa principal do CACIC

  @return String  Hash-Code do programa principal do CACIC
-------------------------------------------------------------------------------}
function TCACIC.getMainProgramHash() : String;
begin
  Result := Self.g_main_program_hash;
end;

{*------------------------------------------------------------------------------
  Verifica se a aplicação está em execução

  @param pStrAppName Nome da aplicação a ser verificada
  @return TRUE se em execução, FALSE caso contrário
-------------------------------------------------------------------------------}
function TCACIC.isAppRunning( pStrAppName: PAnsiChar ): boolean;
var MutexHandle: THandle;
begin
   MutexHandle := CreateMutex(nil, TRUE, pStrAppName);
   Result := ((MutexHandle = 0) OR (GetLastError = ERROR_ALREADY_EXISTS));
end;

{*------------------------------------------------------------------------------
  Verifica quais programas do sistema estão em modo de debug

  @return Boolean contendo status do DEBUG
-------------------------------------------------------------------------------}
function TCACIC.isInDebugMode(pStrDetailName : String = '') : boolean;
var strTeDebugging : String;
begin
  Result := checkIfFileDateIsToday(getLocalFolderName + 'Temp\Debugging');
  if Result and FileExists(getLocalFolderName + 'Temp\Debugging\Debugging.conf') and (pStrDetailName <> '') then
    Begin
      strTeDebugging := getValueFromFile('Configs','TeDebugging',getLocalFolderName + 'Temp\Debugging\Debugging.conf',false);
      if (pos(ExtractFileName(ParamStr(0)) + '.' + pStrDetailName, strTeDebugging) = 0) and
         (pos(ExtractFileName(ParamStr(0)) + '.*'                , strTeDebugging) = 0) then
          Result := false;
    End;
end;

// Rotina obtida em http://www.swissdelphicenter.ch/torry/showcode.php?id=266
{For Windows 9x/ME/2000/XP }
procedure TCACIC.killTask(p_ExeFileName: string);
const
  PROCESS_TERMINATE = $0001;
var
  ContinueLoop: BOOL;
  FSnapshotHandle: THandle;
  FProcessEntry32: TProcessEntry32;
  intAuxKillTask : integer;
begin
  FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
  ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);

  while Integer(ContinueLoop) <> 0 do
  begin
    if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =
      UpperCase(p_ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile) =
      UpperCase(p_ExeFileName))) then
      intAuxKillTask := Integer(TerminateProcess(
                        OpenProcess(PROCESS_TERMINATE,
                                    BOOL(0),
                                    FProcessEntry32.th32ProcessID),
                                    0));
     ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
  end;
  CloseHandle(FSnapshotHandle);
end;

// Rotina obtida em http://www.swissdelphicenter.ch/torry/showcode.php?id=266
{ For Windows NT/2000/XP }
procedure TCACIC.KillProcess(p_HWindowHandle: HWND);
var
  hprocessID: INTEGER;
  processHandle: THandle;
  DWResult: DWORD;
begin
  SendMessageTimeout(p_HWindowHandle, WM_DDE_TERMINATE, 0, 0,
    SMTO_ABORTIFHUNG or SMTO_NORMAL, 5000, DWResult);

  if isWindow(p_HWindowHandle) then
  begin
    // PostMessage(hWindowHandle, WM_QUIT, 0, 0);

    { Get the process identifier for the window}
    GetWindowThreadProcessID(p_HWindowHandle, @hprocessID);
    if hprocessID <> 0 then
    begin
      { Get the process handle }
      processHandle := OpenProcess(PROCESS_TERMINATE or PROCESS_QUERY_INFORMATION,
        False, hprocessID);
      if processHandle <> 0 then
      begin
        { Terminate the process }
        TerminateProcess(processHandle, 0);
        CloseHandle(ProcessHandle);
      end;
    end;
  end;
end;

function TCACIC.serviceStart(sMachine,sService : string ) : boolean;
var
  schm,schs   : SC_Handle;
  ss     : TServiceStatus;
  psTemp : PChar;
  dwChkP : DWord;
begin
  ss.dwCurrentState := 0;
  schm := OpenSCManager(PChar(sMachine),Nil,SC_MANAGER_CONNECT);
  if(schm > 0)then
  begin
    schs := OpenService(schm,PChar(sService),SERVICE_START or SERVICE_QUERY_STATUS);
    if(schs > 0)then
    begin
      psTemp := Nil;
      if(StartService(schs,0,psTemp))then
      begin
        if(QueryServiceStatus(schs,ss))then
        begin
          while(SERVICE_RUNNING <> ss.dwCurrentState)do
          begin
            dwChkP := ss.dwCheckPoint;
            Sleep(ss.dwWaitHint);
            if(not QueryServiceStatus(schs,ss))then
            begin
              break;
            end;
            if(ss.dwCheckPoint < dwChkP)then
            begin
              break;
            end;
          end;
        end;
      end;
      CloseServiceHandle(schs);
    end;
    CloseServiceHandle(schm);
  end;
  Result := SERVICE_RUNNING = ss.dwCurrentState;
end;

procedure TCACIC.writeDebugLog(pStrDebugMessage : String);
Begin
  if isInDebugMode(copy(pStrDebugMessage,1,pos(':',pStrDebugMessage)-1)) then
      writeDailyLog('[DEBUG] - v.' + getVersionInfo(ParamStr(0)) + ' - ' + pStrDebugMessage,'Debugs');
End;

function TCACIC.checkIfFileDateIsToday(pStrFileName : String) : boolean;
var strFileDate,
    strTodayDate : String;
Begin
  DateTimeToString(strTodayDate, 'yyyymmdd', date);

  if FileExists(pStrFileName) then
    DateTimeToString(strFileDate, 'yyyymmdd', FileDateToDateTime(Fileage(pStrFileName)))
  else if DirectoryExists(pStrFileName) then
    DateTimeToString(strFileDate, 'yyyymmdd', GetFolderDate(pStrFileName));

  Result := (strTodayDate = strFileDate);
End;

procedure TCACIC.writeDailyLog(pStrLogMessage : String; pStrFileNameSuffix : String = '');
var DailyLogFile   : TextFile;
    strLogFileName,
    strDateTimeAux : string;
    strAUXDEBUG : String;
begin
   try
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
      if (getLocalFolderName <> '') then
        Begin
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
          strDateTimeAux := FormatDateTime('dd/mm hh:nn:ss ', Now);
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
          if not DirectoryExists(getLocalFolderName + 'Logs') then
            ForceDirectories(getLocalFolderName + 'Logs');
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
          strLogFileName := getLocalFolderName + 'Logs\' + ChangeFileExt(UpperCase(ExtractFileName(ParamStr(0))),'.log');
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
          if (pStrFileNameSuffix <> '') then
            strLogFileName := StringReplace(strLogFileName,'.log','_' + pStrFileNameSuffix + '.log',[rfReplaceAll]);
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
          FileSetAttr (strLogFileName,0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
          AssignFile(DailyLogFile,strLogFileName); {Associa o arquivo a uma variável do tipo TextFile}
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
          {$IOChecks off}
          Reset(DailyLogFile); {Abre o arquivo texto}
          {$IOChecks on}
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
          if (IOResult <> 0) or                    // Arquivo de log diário não existe
             not checkIfFileDateIsToday(strLogFileName) then // Arquivo de log diário não tem data atual
            Begin
              Rewrite (DailyLogFile); // Recriação do arquivo de log diário
              Append(DailyLogFile);
              Writeln(DailyLogFile,'===========================================> Inicio de Log para ' + UpperCase(ExtractFileName(ParamStr(0))) + ' <===========================================');
            End;
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
          Append(DailyLogFile);
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
          Writeln(DailyLogFile,strDateTimeAux + pStrLogMessage); {Escreve uma linha com a mensagem}
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
          CloseFile(DailyLogFile); {Fecha o arquivo de log diário}
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
          if (pStrFileNameSuffix = '') and isInDebugMode then // Caso esteja em modo DEBUG e seja uma mensagem para o log diário, escrevo também a mensagem no log de DEBUG.
            Begin
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
              strLogFileName := getLocalFolderName + 'Logs\' + ChangeFileExt(UpperCase(ExtractFileName(ParamStr(0))),'_Debugs.log');
              FileSetAttr (strLogFileName,0); // Retira os atributos do arquivo para evitar o erro FILE ACCESS DENIED em máquinas 2000
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
              AssignFile(DailyLogFile,strLogFileName); {Associa o arquivo a uma variável do tipo TextFile}
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
              {$IOChecks off}
              Reset(DailyLogFile); {Abre o arquivo texto}
              {$IOChecks on}
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
              if (IOResult <> 0) or                    // Arquivo de log não existe
                 not checkIfFileDateIsToday(strLogFileName) then // Arquivo de log não tem data atual
                Begin
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
                  Rewrite (DailyLogFile); // Recriação do arquivo de log diário
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
                  Append(DailyLogFile);
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
                  Writeln(DailyLogFile,'===========================================> Inicio de DEBUG para ' + UpperCase(ExtractFileName(ParamStr(0))) + ' <===========================================');
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
                End;
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
              Append(DailyLogFile);
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
              Writeln(DailyLogFile,strDateTimeAux + pStrLogMessage); {Escreve uma linha com a mensagem}
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
              CloseFile(DailyLogFile); {Fecha o arquivo de log diário}
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
            End;

          if (trim(g_strAcao)='') then g_strAcao := pStrLogMessage;
   strAUXDEBUG := 'WriteDailyLog - DEBUG #1';
        End;
   except
      on E : Exception do
        writeExceptionLog(E.Message,E.ClassName,strAUXDEBUG);
   end;
end;

{*------------------------------------------------------------------------------
  Cria um arquivo texto contendo informações de exceções
-------------------------------------------------------------------------------}
procedure TCACIC.writeExceptionLog(pStrExceptionMessage, pStrExceptionClassName : String; pStrAddedMessage : String = '');
Begin
  writeDailyLog('[EXCEPTION] - v.' + getVersionInfo(ParamStr(0)) + chr(13) + 'Erro: '      + pStrExceptionMessage   + chr(13) +
                                                                             'Classe: '    + pStrExceptionClassName + chr(13) +
                                                                             'Mensagem: '  + pStrAddedMessage       + chr(13) +
                                                                             DupeString('-',100),'Exceptions');
End;
{*------------------------------------------------------------------------------
  Executa commandos, substitui o WinExec

  @autor: Marcos Dell Antonio
  @param p_cmd        Comando a ser executado
  @param p_wait       TRUE se deve aguardar término da excução, FALSE caso contrário
-------------------------------------------------------------------------------}
{function TCACIC_Windows.createSampleProcess(p_cmd: string; p_wait: boolean ): boolean;
begin
end;
}
{*------------------------------------------------------------------------------
  Executa commandos, substitui o WinExec

  @autor: Marcos Dell Antonio
  @param p_cmd        Comando a ser executado
  @param p_wait       TRUE se deve aguardar término da excução, FALSE caso contrário
  @param p_showWindow Constante que define o tipo de exibição da janela do aplicativo
-------------------------------------------------------------------------------}
function TCACIC.createOneProcess(pStrCmd: string; pBoolWait: boolean; pWordShowWindow : word = SW_HIDE; waitMilliseconds : cardinal = INFINITE): boolean;
var
  SUInfo: TStartupInfo;
  ProcInfo: TProcessInformation;
begin
  FillChar(SUInfo, SizeOf(SUInfo), #0);
  SUInfo.cb      := SizeOf(SUInfo);
  SUInfo.dwFlags := STARTF_USESHOWWINDOW;
  SUInfo.wShowWindow := pWordShowWindow;

  writeDebugLog('createOneProcess: ' + DupeString('*',100));
  writeDebugLog('createOneProcess: pStrCmd   => "' + pStrCmd                    + '"');
  writeDebugLog('createOneProcess: pBoolWait => "' + getBoolToString(pBoolWait) + '"');
  writeDebugLog('createOneProcess: ' + DupeString('*',100));
  try
    Result := CreateProcess(nil,
                            PChar(pStrCmd),
                            nil,
                            nil,
                            false,
                            NORMAL_PRIORITY_CLASS,
                            nil,
                            nil,
                            SUInfo,
                            ProcInfo);
    if (Result) then
    begin
      if(pBoolWait) then begin
         WaitForSingleObject(ProcInfo.hProcess, waitMilliseconds);
         CloseHandle(ProcInfo.hProcess);
         CloseHandle(ProcInfo.hThread);
      end;
    end;
  Except
  on E : Exception do
  begin
    writeExceptionLog(E.Message,E.ClassName,'createOnePcrocces: Falha ao criar processo');
  end;

  end;
end;

{*------------------------------------------------------------------------------
  Para cálculo de HASH de determinado arquivo.

  @autor: Anderson Peterle
  @param p_strFileName - Nome do arquivo para extração do HashCode
-------------------------------------------------------------------------------}
function TCACIC.getFileHash(pStrFileName : String) : String;
Begin
  Result := 'Arquivo "' + pStrFileName + '" Inexistente!';
  if (FileExists(pStrFileName)) then
    Result := MD5Print(MD5File(pStrFileName));
End;


{*------------------------------------------------------------------------------
  Obter a chave para criptografia simétrica

  @return String contendo a chave simétrica
-------------------------------------------------------------------------------}
function TCACIC.getCipherKey(): string;
begin
   Result := CACIC_CIPHERKEY;
end;

{*------------------------------------------------------------------------------
  Obter o vetor de inicialização para criptografia

  @return String contendo o vetor de inicialização
-------------------------------------------------------------------------------}
function TCACIC.getIV(): string;
begin
   Result := CACIC_IV;
end;

{*------------------------------------------------------------------------------
  Obter o valor para tamanho da chave de criptografia

  @return Integer contendo o tamanho para chave de criptografia
-------------------------------------------------------------------------------}
function TCACIC.getKeySize(): Integer;
begin
   Result := CACIC_KEYSIZE;
end;

{*------------------------------------------------------------------------------
  Obter o valor para tamanho do bloco de criptografia

  @return Integer contendo o tamanho para bloco de criptografia
-------------------------------------------------------------------------------}
function TCACIC.getBlockSize(): Integer;
begin
   Result := CACIC_BLOCKSIZE;
end;

{*------------------------------------------------------------------------------
  Obter o nome do arquivo de configurações

  @return String contendo o nome do arquivo de configurações
-------------------------------------------------------------------------------}
function TCACIC.getInfFileName(): string;
begin
   Result := ChangeFileExt( UpperCase(ExtractFileName(ParamStr(0))),'.inf');
end;


{*------------------------------------------------------------------------------
  Obter o separador para criação de listas locais

  @return String contendo o separador de campos e valores
-------------------------------------------------------------------------------}
function TCACIC.getSeparatorKey(): string;
begin
   Result := CACIC_SEPARATORKEY;
end;

{*------------------------------------------------------------------------------
  Substituir alguns valores inválidos ao tráfego HTTP

  @return String contendo o string com valores inválidos substituidos por válidos
------------------------------------------------------------------------------}
function TCACIC.replaceInvalidHTTPChars(p_String : String) : String;
var v_strNewString : String;
begin
  Try
    v_strNewString := StringReplace(p_String      ,'+' ,'[[MAIS]]'    ,[rfReplaceAll]);
    v_strNewString := StringReplace(v_strNewString,' ' ,'[[ESPACE]]'  ,[rfReplaceAll]);
    v_strNewString := StringReplace(v_strNewString,'"' ,'[[AD]]'      ,[rfReplaceAll]);
    v_strNewString := StringReplace(v_strNewString,'''','[[AS]]'      ,[rfReplaceAll]);
    v_strNewString := StringReplace(v_strNewString,'\' ,'[[BarrInv]]' ,[rfReplaceAll]);

    Result := v_strNewString;
  Except
    on E : Exception do
       Begin
         writeExceptionLog(E.Message,E.ClassName,'TCACIC.replaceInvalidHTTPChars');
         Result := 'ERROR - Check TCACIC.replaceInvalidHTTPChars Function';
       End;
  End;
end;

{*------------------------------------------------------------------------------
  Repor valores substituidos durante tráfego HTTP

  @return String contendo o string com valores substituidos
------------------------------------------------------------------------------}
function TCACIC.replacePseudoTagsWithCorrectChars(pStrString : String) : String;
var v_strNewString : String;
begin
  Try
    v_strNewString := StringReplace(pStrString    ,'[[MAIS]]'   ,'+' ,[rfReplaceAll]);
    v_strNewString := StringReplace(v_strNewString,'[[ESPACE]]' ,' ' ,[rfReplaceAll]);
    v_strNewString := StringReplace(v_strNewString,'[[AD]]'     ,'"' ,[rfReplaceAll]);
    v_strNewString := StringReplace(v_strNewString,'[[AS]]'     ,'''',[rfReplaceAll]);
    v_strNewString := StringReplace(v_strNewString,'[[BarrInv]]','\' ,[rfReplaceAll]);

    Result := v_strNewString;
  Except
    on E : Exception do
       Begin
         writeExceptionLog(E.Message,E.ClassName,'TCACIC.replacePseudoTagsWithCorrectValuesChars');
         Result := 'ERROR - Check TCACIC.replacePseudoTagsWithCorrectValuesChars Function';
       End;
  End;
end;

{*------------------------------------------------------------------------------
  Obter a capitalização de uma string

  @return String contendo capitalizado
-------------------------------------------------------------------------------}
function TCACIC.capitalize (const s: String): String;
var flag: BOOLEAN;
    i : Byte;
    t,strAuxCapitalize : string;
Begin
  flag := TRUE;
  t := '';
  strAuxCapitalize := LowerCase(s);
  For i := 1 TO LENGTH(strAuxCapitalize) DO
    Begin
      If flag Then
        AppendStr(t, UpCase(strAuxCapitalize[i]))
      Else
        AppendStr(t, strAuxCapitalize[i]);
      flag := (strAuxCapitalize[i] = ' ')
    End;
  Result := t;
End {Capitalize};

// Encrypt a string and return the Base64 encoded result
function TCACIC.enCrypt(pStrPlainText : String; pBoolShowInLog : boolean = true; pBoolForceEncrypt : boolean = false) : String;
var l_Cipher : TDCP_rijndael;
    l_Data,
    l_Key,
    l_IV     : string;
begin
  Try
    if self.g_boolCipher or pBoolForceEncrypt then
      Begin
        // Pad Key, IV and Data with zeros as appropriate
        l_Key   := PadWithZeros(CACIC_CIPHERKEY, CACIC_KEYSIZE);
        l_IV    := PadWithZeros(CACIC_IV       , CACIC_BLOCKSIZE);
        l_Data  := PadWithZeros(pStrPlainText  , CACIC_BLOCKSIZE);

        // Create the cipher and initialise according to the key length
        l_Cipher := TDCP_rijndael.Create(nil);

        if      Length(CACIC_CIPHERKEY) <= 16 then
          l_Cipher.Init(l_Key[1],128,@l_IV[1])
        else if Length(CACIC_CIPHERKEY) <= 24 then
          l_Cipher.Init(l_Key[1],192,@l_IV[1])
        else
          l_Cipher.Init(l_Key[1],256,@l_IV[1]);

        // Encrypt the data
        l_Cipher.EncryptCBC(l_Data[1],l_Data[1],Length(l_Data));

        // Free the cipher and clear sensitive information
        l_Cipher.Free;

        FillChar(l_Key[1],Length(l_Key),0);

        // Return the Base64 encoded result
        Result := Base64EncodeStr(l_Data);
        Result := Result + '__CRYPTED__';
      End
    Else
      // Return the original value
      Result := pStrPlainText;
  Except
    on E : Exception do
       Begin
         writeExceptionLog(E.Message,E.ClassName,'TCACIC.enCrypt');
          Result := 'ERROR - Check TCACIC.enCrypt Function';
        End;
  End;
end;

function TCACIC.deCrypt(pStrCipheredText : String; pBoolShowInLog : boolean = true; pBoolForceDecrypt : boolean = false) : String;
var
  l_Cipher : TDCP_rijndael;
  l_Data,
  l_Key,
  l_IV : string;
begin
  Try

    if (RightStr(pStrCipheredText,11) = '__CRYPTED__') and (self.g_boolCipher or pBoolForceDecrypt) then
      Begin
        // Pad Key and IV with zeros as appropriate
        l_Key := PadWithZeros(CACIC_CIPHERKEY , CACIC_KEYSIZE);
        l_IV  := PadWithZeros(CACIC_IV        , CACIC_BLOCKSIZE);

        l_Data := StringReplace(pStrCipheredText,'__CRYPTED__','',[rfReplaceAll]);

        // Decode the Base64 encoded string
        l_Data := Base64DecodeStr(trim(replacePseudoTagsWithCorrectChars(l_Data)));

        // Create the cipher and initialise according to the key length
        l_Cipher := TDCP_rijndael.Create(nil);

        if      Length(CACIC_CIPHERKEY) <= 16 then
          l_Cipher.Init(l_Key[1],128,@l_IV[1])
        else if Length(CACIC_CIPHERKEY) <= 24 then
          l_Cipher.Init(l_Key[1],192,@l_IV[1])
        else
          l_Cipher.Init(l_Key[1],256,@l_IV[1]);

        // Decrypt the data
        l_Cipher.DecryptCBC(l_Data[1],l_Data[1],Length(l_Data));

        // Free the cipher and clear sensitive information
        l_Cipher.Free;

        FillChar(l_Key[1],Length(l_Key),0);

        // Return the result (unCrypted)
        Result := trim(l_Data);
      End
    Else
      // Return the original value
      Result := pStrCipheredText
  Except
    on E : Exception do
       Begin
         writeExceptionLog(E.Message,E.ClassName,'TCACIC.deCrypt');
         Result :='ERROR - Check TCACIC.deCrypt Function';
       End;
  End;
end;

// Pad a string with zeros so that it is a multiple of size
function TCACIC.padWithZeros(const str : string; size : integer) : string;
var origsize, i : integer;
begin
  Result := str;
  origsize := Length(Result);
  if ((origsize mod size) <> 0) or (origsize = 0) then
  begin
    SetLength(Result,((origsize div size)+1)*size);
    for i := origsize+1 to Length(Result) do
      Result[i] := #0;
  end;
end;

{*------------------------------------------------------------------------------
  Retorna "False" ou "True" para uma questão lógica
-------------------------------------------------------------------------------}
function TCACIC.getBoolToString(pBoolQuestion : boolean) : string;
const arrBool : array[boolean] of String = ('False','True');
begin
  Result := arrBool[pBoolQuestion];
end;

{*===========================================================================================================
                                        TCACIC_WINDOWS Methods
=============================================================================================================}
{*------------------------------------------------------------------------------
  Retorna a versão a partir de uma CLSID
  Anderson PETERLE - 31JAN2013
-------------------------------------------------------------------------------}
function TCACIC_Windows.getVersionFromHCR(pStrToProcess : String): string;
var regRegistry : TRegistry;
    intLen,
    intPos      : Integer;
    strCLSID    : String;
begin
  Result      := '';

  intPos    := Pos('{',pStrToProcess);
  strCLSID    := copy(pStrToProcess,intPos,length(pStrToProcess));
  intPos    := Pos('}',strCLSID);
  strCLSID    := copy(strCLSID,1,intPos);

  regRegistry := TRegistry.Create;

  with regRegistry do
    begin
      try
        RootKey := HKEY_CLASSES_ROOT;
        try
          if OpenKeyReadOnly('CLSID\' + strCLSID + '\InprocServer32') OR
             OpenKeyReadOnly('CLSID\' + strCLSID + '\LocalServer32')  THEN
            Result := GetVersionInfo(ReadString(''));
        finally
          CloseKey;
          intLen := Length(Result);

          if intLen >= 2 then
            begin
              if(Result[intLen] = '"') then
                Delete(Result, intLen, 1);

              if(Result[1] = '"') then
                Delete(Result, 1, 1);
            end;
        end;
      finally
      end;
    end;

  // Caso a busca acima resulte em VAZIO, alternativamente verifico a partir de estrutura 64Bits
  if (Result = '') then
    Begin
      with regRegistry do
        begin
          try
            RootKey := HKEY_CLASSES_ROOT;
            try
              if OpenKeyReadOnly('Wow6432Node\CLSID\' + strCLSID + '\InprocServer32') OR
                 OpenKeyReadOnly('Wow6432Node\CLSID\' + strCLSID + '\LocalServer32')  THEN
                Result := GetVersionInfo(ReadString(''));
            finally
              CloseKey;
              intLen := Length(Result);

              if intLen >= 2 then
                begin
                  if(Result[intLen] = '"') then
                    Delete(Result, intLen, 1);

                  if(Result[1] = '"') then
                    Delete(Result, 1, 1);
                end;
            end;
          finally
          end;
        end;
    End;

  regRegistry.Free;
end;

{*------------------------------------------------------------------------------
 Format the version number from the given DWORDs containing the info
-------------------------------------------------------------------------------}
function TCACIC_Windows.verFmt(const MS, LS: DWORD): string;
begin
  Result := Format('%d.%d.%d.%d',[HiWord(MS), LoWord(MS), HiWord(LS), LoWord(LS)]);
end;

{*------------------------------------------------------------------------------
  Retorna a pasta de instalação do MS-Windows
-------------------------------------------------------------------------------}
function TCACIC_Windows.getVersionInfo(pStrFileName: string):string;
var PJVersionInfo1: TPJVersionInfo;
begin
  PJVersionInfo1 := TPJVersionInfo.Create(nil);
  PJVersionInfo1.FileName := PChar(pStrFileName);

  Result := VerFmt(PJVersionInfo1.FixedFileInfo.dwFileVersionMS, PJVersionInfo1.FixedFileInfo.dwFileVersionLS);
  PJVersionInfo1.Free;
end;

{*------------------------------------------------------------------------------
  Retorna a pasta de instalação do MS-Windows
-------------------------------------------------------------------------------}
function TCACIC_Windows.getWinDir : string;
var
  WinPath: array[0..MAX_PATH + 1] of char;
begin
  GetWindowsDirectory(WinPath,MAX_PATH);
  Result := StrPas(WinPath)+'\';
end;

{*------------------------------------------------------------------------------
  Retorna a unidade de instalação do MS-Windows
-------------------------------------------------------------------------------}
function TCACIC_Windows.getHomeDrive() : string;
begin
  Result := MidStr(getWinDir,1,3); //x:\
end;

{*------------------------------------------------------------------------------
  Obter o caminho fisico de instalacao do agente cacic

  @return String contendo o caminho físico
-------------------------------------------------------------------------------}
function TCACIC_Windows.getLocalFolderName(): string;
begin
   Result :=  Self.g_local_folder_name ;
end;

{*------------------------------------------------------------------------------
  Verifica se é Windows Vista ou superior

  @return TRUE se Windows Vista ou superior, FALSE caso contrário
  @see isWindowsNTPlataform, isWindows9xME, isWindowsNT, isWindows2000
  @see isWindowsXP, isWindowsVista, isWindowsGEVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindowsGEVista() : boolean;
begin
   Result := false;
   if(Self.g_osVersionInfoExtended) then begin
      if((g_osVersionInfoEx.dwMajorVersion >= 6) and (g_osVersionInfoEx.dwMinorVersion >= 0)) then
         Result := true;
   end
   else
      if((g_osVersionInfo.dwMajorVersion >= 6) and (g_osVersionInfo.dwMinorVersion >= 0)) then
         Result := true;
end;

{*------------------------------------------------------------------------------
  Verifica se é Windows Vista

  @return TRUE se Windows Vista, FALSE caso contrário
  @see isWindowsNTPlataform, isWindows9xME, isWindowsNT, isWindows2000
  @see isWindowsXP, isWindowsVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindowsVista() : boolean;
begin
   Result := false;
   if(Self.g_osVersionInfoExtended) then begin
     if((g_osVersionInfoEx.dwMajorVersion = 6) and (g_osVersionInfoEx.dwMinorVersion = 0)) then
        Result := true;
   end
   else
     if((g_osVersionInfo.dwMajorVersion = 6) and (g_osVersionInfo.dwMinorVersion = 0)) then
        Result := true;
end;

{*------------------------------------------------------------------------------
  Verifica se é Windows XP ou superior

  @return TRUE se Windows XP ou superior, FALSE caso contrário
  @see isWindowsNTPlataform, isWindows9xME, isWindowsNT, isWindows2000
  @see isWindowsXP, isWindowsVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindowsGEXP() : boolean;
begin
   Result := false;
   if(Self.g_osVersionInfoExtended) then begin
     if((g_osVersionInfoEx.dwMajorVersion >= 5) and (g_osVersionInfoEx.dwMinorVersion >= 1)) then
        Result := true;
   end
   else
     if((g_osVersionInfo.dwMajorVersion >= 5) and (g_osVersionInfo.dwMinorVersion >= 1)) then
        Result := true;

end;

{*------------------------------------------------------------------------------
  Verifica se é Windows XP

  @return TRUE se Windows XP, FALSE caso contrário
  @see isWindowsNTPlataform, isWindows9xME, isWindowsNT, isWindows2000
  @see isWindowsXP, isWindowsVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindowsXP() : boolean;
begin
   Result := false;
   if(Self.g_osVersionInfoExtended) then begin
     if((g_osVersionInfoEx.dwMajorVersion = 5) and (g_osVersionInfoEx.dwMinorVersion = 1)) then
        Result := true;
   end
   else
     if((g_osVersionInfo.dwMajorVersion = 5) and (g_osVersionInfo.dwMinorVersion = 1)) then
        Result := true;

end;

{*------------------------------------------------------------------------------
  Verifica se é Windows 2000

  @return TRUE se Windows 2000, FALSE caso contrário
  @see isWindowsNTPlataform, isWindows9xME, isWindowsNT, isWindows2000
  @see isWindowsXP, isWindowsVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindows2000() : boolean;
begin
   Result := false;
   if(Self.g_osVersionInfoExtended) then begin
     if((g_osVersionInfoEx.dwMajorVersion = 5) and (g_osVersionInfoEx.dwMinorVersion = 0)) then
        Result := true;
   end
   else
     if((g_osVersionInfo.dwMajorVersion = 5) and (g_osVersionInfo.dwMinorVersion = 0)) then
        Result := true;

end;

{*------------------------------------------------------------------------------
  Verifica se é Windows NT

  @return TRUE se Windows NT, FALSE caso contrário
  @see isWindowsNTPlataform, isWindows9xME, isWindowsNT, isWindows2000
  @see isWindowsXP, isWindowsVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindowsNT() : boolean;
begin
   Result := false;
   if(Self.g_osVersionInfoExtended) then begin
      if((g_osVersionInfoEx.dwMajorVersion = 4) and (g_osVersionInfoEx.dwMinorVersion = 0)) then
         Result := true;
   end
   else
      if((g_osVersionInfo.dwMajorVersion = 4) and (g_osVersionInfo.dwMinorVersion = 0)) then
         Result := true;
end;

{*------------------------------------------------------------------------------
  Verifica se a plataforma do sistema é de windows 9x ou ME

  @return TRUE se plataforma de Windows 9x/ME, FALSE caso contrário
  @see isWindowsNTPlataform, isWindows9xME, isWindowsNT, isWindows2000
  @see isWindowsXP, isWindowsVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindows9xME() : boolean;
begin
  if (Self.g_osVersionInfoExtended) then
     Result := (Self.g_osVersionInfoEx.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS)
  else
     Result := (Self.g_osVersionInfo.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS);

end;

{*------------------------------------------------------------------------------
  Obter identificação extensa do sistema operacional

  @return String de identificação do sistema operacional
  @example 1.4.10.A
-------------------------------------------------------------------------------}
function TCACIC_Windows.getWindowsStrId() : string;
begin
  Result := 'S.O.unknown';

  try
	  if (Self.g_osVersionInfoExtended) then
      Begin
  		  if(Self.isWindows9xME) then
          Begin
     			  Result := IntToStr(Self.g_osVersionInfoEx.dwPlatformId)   + '.' +
	     	              IntToStr(Self.g_osVersionInfoEx.dwMajorVersion) + '.' +
		                  IntToStr(Self.g_osVersionInfoEx.dwMinorVersion) + ifThen(trim(Self.g_osVersionInfoEx.szCSDVersion)='','','.' + trim(Self.g_osVersionInfoEx.szCSDVersion))
          End
		    else
          Begin
  			    Result := IntToStr(Self.g_osVersionInfoEx.dwPlatformId)   + '.' +
	  			            IntToStr(Self.g_osVersionInfoEx.dwMajorVersion) + '.' +
		  		            IntToStr(Self.g_osVersionInfoEx.dwMinorVersion) + '.' +
			  	            IntToStr(Self.g_osVersionInfoEx.wProductType)   + '.' +
				              IntToStr(Self.g_osVersionInfoEx.wSuiteMask);
          End
      End
	  else
      Begin
  		  Result := IntToStr(Self.g_osVersionInfo.dwPlatformId)   + '.' +
	  			        IntToStr(Self.g_osVersionInfo.dwMajorVersion) + '.' +
		  		        IntToStr(Self.g_osVersionInfo.dwMinorVersion) + ifThen(trim(Self.g_osVersionInfo.szCSDVersion)='','','.'+trim(Self.g_osVersionInfo.szCSDVersion));
      End;
  except
    on E : Exception do
      writeExceptionLog(E.Message,E.ClassName,'getWindowsStrId');
  end;

  Result := Result + getBitPlatform;

end;

{*------------------------------------------------------------------------------
  Returns String with bit platform information

  @return String
  @example .64
-------------------------------------------------------------------------------}
function TCACIC_Windows.getBitPlatform() : String;
  // Type of IsWow64Process API fn
  type
    TIsWow64Process = function(Handle: Windows.THandle; var Res: Windows.BOOL): Windows.BOOL; stdcall;
  var
    IsWow64Result: Windows.BOOL; // Result from IsWow64Process
    IsWow64Process: TIsWow64Process; // IsWow64Process fn reference
    boolIsWow64 : boolean;
begin
  Result := '';
  // Try to load required function from kernel32
  IsWow64Process := Windows.GetProcAddress(Windows.GetModuleHandle('kernel32'), 'IsWow64Process');
  if Assigned(IsWow64Process) then
    Begin
      if IsWow64Process(Windows.GetCurrentProcess, IsWow64Result) then
        Begin
          boolIsWow64 := IsWow64Result;
          if boolIsWow64 then
            Result := '.64'
          else
            Result := '.32';
        End;
//      else
//        Result := 'IsWow64 call failed';
    End;
//  else
//    s := 'IsWow64Process not present in kernel32.dll';

end;


{*------------------------------------------------------------------------------
  Verifica se a plataforma do sistema é de Windows NT

  @return TRUE se plataforma de Windows NT, FALSE caso contrário
  @see isWindows9xME, isWindowsVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindowsNTPlataform() : boolean;
begin
  if(Self.g_osVersionInfoExtended)
    then Result := (Self.g_osVersionInfoEx.dwPlatformId = VER_PLATFORM_WIN32_NT)
    else Result := (Self.g_osVersionInfo.dwPlatformId = VER_PLATFORM_WIN32_NT);

end;

{*------------------------------------------------------------------------------
  Verifica se é administrador do sistema operacional se em plataforma NT

  @return TRUE se administrador do sistema, FALSE caso contrário
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindowsAdmin(): Boolean;

const
   constSECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5));
   constSECURITY_BUILTIN_DOMAIN_RID = $00000020;
   constDOMAIN_ALIAS_RID_ADMINS = $00000220;

var
   hAccessToken: THandle;
   ptgGroups: PTokenGroups;
   dwInfoBufferSize: DWORD;
   psidAdministrators: PSID;
   x: Integer;
   bSuccess: BOOL;

begin
  if (not Self.isWindowsNTPlataform()) then // Se nao NT (ex: Win95/98)
       // Se nao eh NT nao tem ''admin''
       Result   := True
  else begin
	  Result   := False;
	  bSuccess := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, hAccessToken);
	  if not bSuccess then begin
  		 if GetLastError = ERROR_NO_TOKEN then
	        bSuccess := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, hAccessToken);
	  end;
	  if bSuccess then begin
		GetMem(ptgGroups, 1024);
		bSuccess := GetTokenInformation(hAccessToken, TokenGroups, ptgGroups, 1024, dwInfoBufferSize);
		CloseHandle(hAccessToken);
		if bSuccess then begin
		  AllocateAndInitializeSid(constSECURITY_NT_AUTHORITY, 2,
								   constSECURITY_BUILTIN_DOMAIN_RID,
								   constDOMAIN_ALIAS_RID_ADMINS,
								   0, 0, 0, 0, 0, 0, psidAdministrators);
		  {$R-}
		  for x := 0 to ptgGroups.GroupCount - 1 do
          if EqualSid(psidAdministrators, ptgGroups.Groups[x].Sid) then begin
			       Result := True;
			       Break;
			    end;
		  {$R+}
		  FreeSid(psidAdministrators);
		end;
		FreeMemory(ptgGroups);
	  end;
  end;
end;

function TCACIC.ServiceGetType(sMachine, sService: PChar): DWORD;
  {*******************************************}
  {*** Parameters: ***}
  {*** sService: specifies the name of the service to open
  {*** sMachine: specifies the name of the target computer
  {*** ***}
  {*** Return Values: ***}

var
  SCManHandle, SvcHandle: SC_Handle;
  SS: TServiceStatus;
  dwStat: DWORD;
begin
  dwStat := 0;
  // Open service manager handle.
  writeDebugLog('ServiceGetStatus: Executando OpenSCManager.SC_MANAGER_CONNECT');
  SCManHandle := OpenSCManager(sMachine, nil, SC_MANAGER_CONNECT);
  if (SCManHandle > 0) then
  begin
    writeDebugLog('ServiceGetStatus: Executando OpenService.SERVICE_QUERY_STATUS');
    SvcHandle := OpenService(SCManHandle, sService, SERVICE_ALL_ACCESS);
    // if Service installed
    if (SvcHandle > 0) then
    begin
      writeDebugLog('ServiceGetStatus: O serviço "'+ sService +'" já está instalado.');
      // SS structure holds the service status (TServiceStatus);
      if (QueryServiceStatus(SvcHandle, SS)) then
        dwStat := ss.dwServiceType;
      if dwStat <> 272 then
      begin
        ChangeServiceConfig(SvcHandle,
                            272,  //iterative
                            SERVICE_NO_CHANGE,
                            SERVICE_NO_CHANGE,
                            nil,
                            nil,
                            nil,
                            nil,
                            nil,
                            nil,
                            nil);
      end;

      if (QueryServiceStatus(SvcHandle, SS)) then
        dwStat := ss.dwServiceType;
      CloseServiceHandle(SvcHandle);
    end;
    CloseServiceHandle(SCManHandle);
  end;
  Result := dwStat;
end;

function TCACIC.ServiceGetStatus(sMachine, sService: PChar): DWORD;
  {*******************************************}
  {*** Parameters: ***}
  {*** sService: specifies the name of the service to open
  {*** sMachine: specifies the name of the target computer
  {*** ***}
  {*** Return Values: ***}
  {*** -1 = Error opening service ***}
  {*** 1 = SERVICE_STOPPED ***}
  {*** 2 = SERVICE_START_PENDING ***}
  {*** 3 = SERVICE_STOP_PENDING ***}
  {*** 4 = SERVICE_RUNNING ***}
  {*** 5 = SERVICE_CONTINUE_PENDING ***}
  {*** 6 = SERVICE_PAUSE_PENDING ***}
  {*** 7 = SERVICE_PAUSED ***}
  {******************************************}
var
  SCManHandle, SvcHandle: SC_Handle;
  SS: TServiceStatus;
  dwStat: DWORD;
begin
  dwStat := 0;
  // Open service manager handle.
  writeDebugLog('ServiceGetStatus: Executando OpenSCManager.SC_MANAGER_CONNECT');
  SCManHandle := OpenSCManager(sMachine, nil, SC_MANAGER_CONNECT);
  if (SCManHandle > 0) then
  begin
    writeDebugLog('ServiceGetStatus: Executando OpenService.SERVICE_QUERY_STATUS');
    SvcHandle := OpenService(SCManHandle, sService, SERVICE_QUERY_STATUS);
    // if Service installed
    if (SvcHandle > 0) then
    begin
      writeDebugLog('ServiceGetStatus: O serviço "'+ sService +'" já está instalado.');
      // SS structure holds the service status (TServiceStatus);
      if (QueryServiceStatus(SvcHandle, SS)) then
        dwStat := ss.dwCurrentState;

      CloseServiceHandle(SvcHandle);
    end;
    CloseServiceHandle(SCManHandle);
  end;
  Result := dwStat;
end;

end.