summaryrefslogtreecommitdiff
path: root/plugins/MirandaNGHistoryToDB/Global.pas
blob: fc4cc4c4bb1558beba5a519c61af7fd33bb36e6f (plain)
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
{ ############################################################################ }
{ #                                                                          # }
{ #  MirandaNG HistoryToDB Plugin v2.5                                       # }
{ #                                                                          # }
{ #  License: GPLv3                                                          # }
{ #                                                                          # }
{ #  Author: Grigorev Michael (icq: 161867489, email: sleuthhound@gmail.com) # }
{ #                                                                          # }
{ ############################################################################ }

unit Global;

interface

uses
  Windows, SysUtils, IniFiles, Messages, XMLIntf, XMLDoc,
  FSMonitor, DCPcrypt2, DCPblockciphers, DCPsha1, DCPdes, DCPmd5, ActiveX, MapStream;

type
  TCopyDataType = (cdtString = 0, cdtImage = 1, cdtRecord = 2);
  TCopyDataStruct = packed record
    dwData: DWORD;
    cbData: DWORD;
    lpData: Pointer;
  end;
  //TByteArr = Array of Byte;
  TArrayOfString = Array of String;

const
  htdPluginShortName = 'MirandaNGHistoryToDB';
  htdDescription_RU  = 'Õðàíåíèå èñòîðèè ñîîáùåíèé â áàçå äàííûõ.';
  htdDescription_EN  = 'Storing the history in the database.';
  htdAuthor_EN       = 'Michael Grigorev';
  htdAuthor_RU       = 'Michael Grigorev';
  htdAuthorEmail     = 'sleuthhound@gmail.com';
  htdCopyright_EN    = '(c) 2011-2013 Michael Grigorev';
  htdCopyright_RU    = '(c) 2011-2013 Michael Grigorev';
  htdHomePageURL  = 'http://www.im-history.ru/';
  htdVerMajor     = {MAJOR_VER}2{/MAJOR_VER};
  htdVerMinor     = {MINOR_VER}5{/MINOR_VER};
  htdVerRelease   = {SUB_VER}0{/SUB_VER};
  htdVerBuild     = {BUILD}0{/BUILD};
  htdVersion      = htdVerMajor shl 24 + htdVerMinor shl 16 + htdVerRelease shl 8 + htdVerBuild;
  {$IFDEF WIN32}
  htdPlatform     = 'x86';
  {$ELSE}
  htdPlatform     = 'x64';
  {$ENDIF}
  htdDBName       = 'MirandaNGHistoryToDB';
  htdIMClientName = 'MirandaNG';
  {htdFLUpdateURL    = 'http://addons.miranda-im.org/feed.php?dlfile=0';
  htdFLVersionURL   = 'http://addons.miranda-im.org/details.php?action=viewfile&id=0';
  htdFLVersionPrefix= '<span class="fileNameHeader">'+htdPluginShortName+' ';
  htdUpdateURL      = 'http://www.im-history.ru/get.php?file=MirandaNGHistoryToDB';
  htdVersionURL     = 'http://www.im-history.ru/get.php?file=MirandaNGHistoryToDB-Version';
  htdVersionPrefix  = htdPluginShortName+' version ';
  htdChangelogURL = 'http://www.im-history.ru/changelog/miranda.html';}

  // Generate your own unique id for your plugin.
  // Do not use this UUID!
  // Use Shift+Ctrl+G or uuidgen.exe to generate the uuuid
  MIID_HISTORYTODBDLL:TGUID = '{1F83C057-C59F-483B-B82E-1AE5CA6138EB}';

  MS_MHTD_SHOWHISTORY: PAnsiChar = 'MirandaNGHistoryToDB/ShowHistory';
  MS_MHTD_GETVERSION: PAnsiChar = 'MirandaNGHistoryToDB/GetVersion';
  MS_MHTD_SHOWCONTACTHISTORY: PAnsiChar = 'MirandaNGHistoryToDB/ShowContactHistory';

  DefaultDBAddres = 'db01.im-history.ru';
  DefaultDBName = 'imhistory';
  ININame = 'HistoryToDB.ini';
  DefININame = 'DefaultUser.ini';
  MesLogName = 'HistoryToDBMes.sql';
  ErrLogName = 'HistoryToDBErr.log';
  ImportLogName = 'HistoryToDBImport.sql';
  ContactListName = 'ContactList.csv';
  ProtoListName = 'ProtoList.csv';
  DebugLogName = 'HistoryToDBDebug.log';
  MSG_LOG : WideString = 'insert into uin_%s values (null, %s, ''%s'', ''%s'', ''%s'', ''%s'', %s, ''%s'', ''%s'', ''%s'', null);';
  MSG_LOG_ORACLE : WideString = 'insert into uin_%s values (null, %s, ''%s'', ''%s'', ''%s'', ''%s'', %s, %s, ''%s'', ''%s'', null)';
  CHAT_MSG_LOG : WideString = 'insert into uin_chat_%s values (null, %s, ''%s'', ''%s'', ''%s'', ''%s'', %s, %s, %s, ''%s'', ''%s'', null);';
  CHAT_MSG_LOG_ORACLE : WideString = 'insert into uin_chat_%s values (null, %s, %s, ''%s'', ''%s'', ''%s'', %s, %s, %s, ''%s'', ''%s'', null)';
  // Íà÷àëüíàÿ äàòà (01/01/1970) Unix Timestamp äëÿ ôóíêöèé êîíâåðòàöèè
  UnixStartDate: TDateTime = 25569.0;
  // Êëþ÷ äëÿ øèôðîâàíèÿ ïîñûëîê ïðîãðàììàì HistoryToDBSync è HistoryToDBViewer
  EncryptKey = 'jsU6s2msoxghsKsn7';
  // Äëÿ ìóëüòèÿçûêîâîé ïîääåðæêè
  WM_LANGUAGECHANGED = WM_USER + 1;
  dirLangs = 'langs\';
  defaultLangFile = 'English.xml';
  ThankYouText_Rus = 'Àííà Íèêèôîðîâà çà àêòèâíîå òåñòèðîâàíèå ïëàãèíà.' + #13#10 +
                    'Êèðèëë Óêñóñîâ (UksusoFF) çà àêòèâíîå òåñòèðîâàíèå ïëàãèíà è íîâûå èäåè.' + #13#10 +
                    'Èãîðü Ãóðüÿíîâ çà àêòèâíîå òåñòèðîâàíèå ïëàãèíà.' + #13#10 +
                    'Âÿ÷åñëàâ Ñ. (HDHMETRO) çà àêòèâíîå òåñòèðîâàíèå ïëàãèíà.' + #13#10 +
                    'Providence çà àêòèâíîå òåñòèðîâàíèå ïëàãèíà è íîâûå èäåè.' + #13#10 +
                    'Cy6 çà ïîìîùü â ðåàëèçàöèè èìïîðòà èñòîðèè RnQ.';
  ThankYouText_Eng = 'Anna Nikiforova for active testing of plug-in.' + #13#10 +
                    'Kirill Uksusov (UksusoFF) for active testing of plug-in and new ideas.' + #13#10 +
                    'Igor Guryanov for active testing of plug-in.' + #13#10 +
                    'Vyacheslav S. (HDHMETRO) for active testing of plug-in.' + #13#10 +
                    'Providence for active testing of plug-in and new ideas.' + #13#10 +
                    'Cy6 for help in implementing the import history RnQ.';

var
  hppCodepage: Cardinal;
  hppVersionStr: AnsiString;
  MetaContactsEnabled: Boolean;
  MetaContactsProto: AnsiString;
  WriteErrLog, AniEvents, EnableHistoryEncryption, ShowPluginButton, AddSpecialContact, BlockSpamMsg: Boolean;
  EnableDebug, EnableCallBackDebug, ExPrivateChatName, GetContactList: Boolean;
  SyncMethod, SyncInterval, SyncMessageCount, MaxErrLogSize: Integer;
  DBType, DBName, DBUserName, DefaultLanguage: String;
  //Global_AccountUIN: WideString;
  //Global_AccountName: WideString;
  //Global_CurrentAccountUIN: WideString;
  //Global_CurrentAccountName: WideString;
  Global_CurrentAccountProtoID: Integer;
  Global_CurrentAccountProtoName, Global_CurrentAccountProtoAccount: WideString;
  Glogal_History_Type: Integer;
  //Global_ChatName: WideString;
  Global_AboutForm_Showing: Boolean;
  DllPath, DllName, ProfilePath, MyAccount: String;
  MessageCount: Integer;
  // Äëÿ ìóëüòèÿçûêîâîé ïîääåðæêè
  CoreLanguage: String;
  AboutFormHandle: HWND;
  ExportFormHandle: HWND;
  LangDoc: IXMLDocument;
  PluginPath: String = '';
  // Øèôðîâàíèå
  Cipher: TDCP_3des;
  Digest: Array[0..19] of Byte;
  Hash: TDCP_sha1;
  // Ëîã-ôàéëû
  TFMsgLog: TextFile;
  MsgLogOpened: Boolean;
  TFErrLog: TextFile;
  ErrLogOpened: Boolean;
  TFDebugLog: TextFile;
  DebugLogOpened: Boolean;
  TFContactListLog: TextFile;
  ContactListLogOpened: Boolean;
  TFProtoListLog: TextFile;
  ProtoListLogOpened: Boolean;
  TFImportLog: TextFile;
  ImportLogOpened: Boolean;
  ExportFormDestroy: Boolean;
  // MMF
  FMap: TMapStream;

function BoolToIntStr(Bool: Boolean): String;
function UnixToDateTime(USec: Longint): TDateTime;
function PrepareString(const Source : PWideChar) : WideString;
function MatchStrings(Source, Pattern: String): Boolean;
function ReadCustomINI(INIPath, CustomParams, DefaultParamsStr: String): String;
function EncryptMD5(Str: String): String;
function EncryptStr(const Str: String): String;
function SearchMainWindow(MainWindowName: pWideChar): Boolean;
function OpenLogFile(LogPath: String; LogType: Integer): Boolean;
function GetMyFileSize(const Path: String): Integer;
function ExtractFileNameEx(FileName: String; ShowExtension: Boolean): String;
function WideStringToString(const ws: WideString; codePage: Word): AnsiString;
function AnsiToWideString(const S: AnsiString; CodePage: Cardinal; InLength: Integer = -1): WideString;
function WideToAnsiString(const WS: WideString; CodePage: Cardinal; InLength: Integer = -1): AnsiString;
function Utf8ToWideChar(Dest: PWideChar; MaxDestChars: Integer; Source: PAnsiChar; SourceBytes: Integer; CodePage: Cardinal = CP_ACP): Integer;
function StrContactProtoToInt(Proto: AnsiString): Integer;
function UnixToLocalTime(tUnix :Longint): TDateTime;
function GetUserTempPath: WideString;
procedure IMDelay(Value: Cardinal);
procedure EncryptInit;
procedure EncryptFree;
procedure WriteInLog(LogPath: String; TextString: String; LogType: Integer);
procedure CloseLogFile(LogType: Integer);
procedure LoadINI(INIPath: String);
procedure OnSendMessageToAllComponent(Msg: String);
procedure OnSendMessageToOneComponent(WinName, Msg: String);
procedure WriteCustomINI(INIPath, CustomParams, ParamsStr: String);
procedure ProfileDirChangeCallBack(pInfo: TInfoCallBack);
// Äëÿ ìóëüòèÿçûêîâîé ïîääåðæêè
procedure CoreLanguageChanged;
procedure MsgDie(Caption, Msg: WideString);
procedure MsgInf(Caption, Msg: WideString);
function GetLangStr(StrID: String): WideString;

implementation

uses Menu;

function BoolToIntStr(Bool: Boolean): String;
begin
  if Bool then
    Result := '1'
  else
    Result := '0'
end;

// Ôóíêöèÿ êîíâåðòàöèè Unix Timestamp â DateTime
function UnixToDateTime(USec: Longint): TDateTime;
begin
  Result := (Usec / 86400) + UnixStartDate;
end;

// Ôóíêöèÿ äëÿ ýêðàíèðîâàíèÿ ñïåöñèìâîëîâ â ñòðîêå
function PrepareString(const Source : PWideChar) : WideString;
var
  SLen,i : Cardinal;
  WSTmp : WideString;
  WChar : WideChar;
begin
 Result := '';
 SLen := Length(WideString(Source));
 if (SLen>0) then
  begin
   for i:=1 to SLen do
    begin
     WChar:=WideString(Source)[i];
     case WChar of
      #$09 :{tab}  WSTmp:=WSTmp+'\t';
      #$0A :{line feed}  WSTmp:=WSTmp+'\n';
      #$0D :{carriage return}  WSTmp:=WSTmp+'\r';
      #$27 :{single quote mark aka apostrophe?} WSTmp:=WSTmp+WChar+WChar;
      #$22, {double quote mark aka inch sign?}
      #$5C, {backslash itself}
      #$60 :{another single quote mark} WSTmp:=WSTmp+'\'+WChar;
      else WSTmp := WSTmp + WChar;
     end;
    end;
   Result := WSTmp;
  end;
end;

// LogType = 0 - ñîîáùåíèÿ äîáàâëÿþòñÿ â ôàéë MesLogName
// LogType = 1 - îøèáêè äîáàâëÿþòñÿ â ôàéë ErrLogName
// LogType = 2 - ñîîáùåíèÿ äîáàâëÿþòñÿ â ôàéë DebugLogName
// LogType = 3 - ñîîáùåíèÿ äîáàâëÿþòñÿ â ôàéë ContactListName
// LogType = 4 - ñîîáùåíèÿ äîáàâëÿþòñÿ â ôàéë ProtoListName
// LogType = 5 - ñîîáùåíèÿ äîáàâëÿþòñÿ â ôàéë ImportLogName
function OpenLogFile(LogPath: String; LogType: Integer): Boolean;
var
  Path: WideString;
begin
  if LogType = 0 then
    Path := LogPath + MesLogName
  else if LogType = 1 then
  begin
    Path := LogPath + ErrLogName;
    if (LogType > 0) and (GetMyFileSize(Path) > MaxErrLogSize*1024) then
      DeleteFile(Path);
  end
  else if LogType = 2 then
    Path := LogPath + DebugLogName
  else if LogType = 3 then
  begin
    Path := LogPath + ContactListName;
    if FileExists(Path) then
    begin
      try
        DeleteFile(Path);
      except
      end;
    end;
  end
  else if LogType = 4 then
  begin
    Path := LogPath + ProtoListName;
    if FileExists(Path) then
    begin
      try
        DeleteFile(Path);
      except
      end;
    end;
  end
  else
    Path := LogPath + ImportLogName;
  {$I-}
  try
    if LogType = 0 then
      Assign(TFMsgLog, Path)
    else if LogType = 1 then
      Assign(TFErrLog, Path)
    else if LogType = 2 then
      Assign(TFDebugLog, Path)
    else if LogType = 3 then
      Assign(TFContactListLog, Path)
    else if LogType = 4 then
      Assign(TFProtoListLog, Path)
    else
      Assign(TFImportLog, Path);
    if FileExists(Path) then
    begin
      if LogType = 0 then
        Append(TFMsgLog)
      else if LogType = 1 then
        Append(TFErrLog)
      else if LogType = 2 then
        Append(TFDebugLog)
      else if LogType = 3 then
        Append(TFContactListLog)
      else if LogType = 4 then
        Append(TFProtoListLog)
      else
        Append(TFImportLog);
    end
    else
    begin
      if LogType = 0 then
        Rewrite(TFMsgLog)
      else if LogType = 1 then
        Rewrite(TFErrLog)
      else if LogType = 2 then
        Rewrite(TFDebugLog)
      else if LogType = 3 then
        Rewrite(TFContactListLog)
      else if LogType = 4 then
        Rewrite(TFProtoListLog)
      else
        Rewrite(TFImportLog);
    end;
    Result := True;
  except
    on e :
      Exception do
      begin
        CloseLogFile(LogType);
        Result := False;
        Exit;
      end;
  end;
  {$I+}
end;

// LogType = 0 - ñîîáùåíèÿ äîáàâëÿþòñÿ â ôàéë MesLogName
// LogType = 1 - îøèáêè äîáàâëÿþòñÿ â ôàéë ErrLogName
// LogType = 2 - ñîîáùåíèÿ äîáàâëÿþòñÿ â ôàéë DebugLogName
// LogType = 3 - ñîîáùåíèÿ äîáàâëÿþòñÿ â ôàéë ContactListName
// LogType = 4 - ñîîáùåíèÿ äîáàâëÿþòñÿ â ôàéë ProtoListName
procedure WriteInLog(LogPath: String; TextString: String; LogType: Integer);
var
  Path: WideString;
begin
  if LogType = 0 then
  begin
    if not MsgLogOpened then
      MsgLogOpened := OpenLogFile(LogPath, 0);
    Path := LogPath + MesLogName
  end
  else if LogType = 1 then
  begin
    if not ErrLogOpened then
      ErrLogOpened := OpenLogFile(LogPath, 1);
    Path := LogPath + ErrLogName;
    if (LogType > 0) and (GetMyFileSize(Path) > MaxErrLogSize*1024) then
    begin
      CloseLogFile(LogType);
      DeleteFile(Path);
      if not OpenLogFile(LogPath, LogType) then
        Exit;
    end;
  end
  else if LogType = 2 then
  begin
    if not DebugLogOpened then
      DebugLogOpened := OpenLogFile(LogPath, 2);
    Path := LogPath + DebugLogName;
  end
  else if LogType = 3 then
  begin
    if not ContactListLogOpened then
      ContactListLogOpened := OpenLogFile(LogPath, 3);
    Path := LogPath + ContactListName;
  end
  else if LogType = 4 then
  begin
    if not ProtoListLogOpened then
      ProtoListLogOpened := OpenLogFile(LogPath, 4);
    Path := LogPath + ProtoListName;
  end
  else
  begin
    if not ImportLogOpened then
      ImportLogOpened := OpenLogFile(LogPath, 5);
    Path := LogPath + ImportLogName;
  end;
  {$I-}
  try
    if LogType = 0 then
      WriteLn(TFMsgLog, TextString)
    else if LogType = 1 then
      WriteLn(TFErrLog, TextString)
    else if LogType = 2 then
      WriteLn(TFDebugLog, TextString)
    else if LogType = 3 then
      WriteLn(TFContactListLog, TextString)
    else if LogType = 4 then
      WriteLn(TFProtoListLog, TextString)
    else
      WriteLn(TFImportLog, TextString);
  except
    on e :
      Exception do
      begin
        CloseLogFile(LogType);
        Exit;
      end;
  end;
  if MsgLogOpened then
    CloseLogFile(0);
  {$I+}
end;

procedure CloseLogFile(LogType: Integer);
begin
  {$I-}
  if LogType = 0 then
  begin
    CloseFile(TFMsgLog);
    MsgLogOpened := False;
  end
  else if LogType = 1 then
  begin
    CloseFile(TFErrLog);
    ErrLogOpened := False;
  end
  else if LogType = 2 then
  begin
    CloseFile(TFDebugLog);
    DebugLogOpened := False;
  end
  else if LogType = 3 then
  begin
    CloseFile(TFContactListLog);
    ContactListLogOpened := False;
  end
  else if LogType = 4 then
  begin
    CloseFile(TFProtoListLog);
    ProtoListLogOpened := False;
  end
  else
  begin
    CloseFile(TFImportLog);
    ImportLogOpened := False;
  end;
  {$I+}
end;

// Åñëè ôàéë íå ñóùåñòâóåò, òî âìåñòî ðàçìåðà ôàéëà ôóíêöèÿ âåðí¸ò -1
function GetMyFileSize(const Path: String): Integer;
var
  FD: TWin32FindData;
  FH: THandle;
begin
  FH := FindFirstFile(PChar(Path), FD);
  Result := 0;
  if FH = INVALID_HANDLE_VALUE then
    Exit;
  Result := FD.nFileSizeLow;
  if ((FD.nFileSizeLow and $80000000) <> 0) or
     (FD.nFileSizeHigh <> 0) then
    Result := -1;
  //FindClose(FH);
end;

// Çàãðóæàåì íàñòðîéêè
procedure LoadINI(INIPath: String);
var
  Path: WideString;
  Temp: String;
  INI: TIniFile;
begin
  // Ïðîâåðÿåì íàëè÷èå êàòàëîãà
  if not DirectoryExists(INIPath) then
    CreateDir(INIPath);
  Path := INIPath + ININame;
  if FileExists(Path) then
  begin
   Ini := TIniFile.Create(Path);
   DBType := INI.ReadString('Main', 'DBType', 'mysql');  // mysql èëè postgresql
   DBUserName := INI.ReadString('Main', 'DBUserName', 'username');
   SyncMethod := INI.ReadInteger('Main', 'SyncMethod', 1);
   SyncInterval := INI.ReadInteger('Main', 'SyncInterval', 0);

   Temp := INI.ReadString('Main', 'WriteErrLog', '1');
   if Temp = '1' then WriteErrLog := True
   else WriteErrLog := False;

   Temp := INI.ReadString('Main', 'ShowAnimation', '1');
   if Temp = '1' then AniEvents := True
   else AniEvents := False;

   Temp := INI.ReadString('Main', 'EnableHistoryEncryption', '0');
   if Temp = '1' then EnableHistoryEncryption := True
   else EnableHistoryEncryption := False;

   Temp := INI.ReadString('Main', 'AddSpecialContact', '1');
   if Temp = '1' then AddSpecialContact := True
   else AddSpecialContact := False;

   DefaultLanguage := INI.ReadString('Main', 'DefaultLanguage', 'Russian');
   SyncMessageCount := INI.ReadInteger('Main', 'SyncMessageCount', 50);

   Temp := INI.ReadString('Main', 'ShowPluginButton', '1');
   if Temp = '1' then ShowPluginButton := True
   else ShowPluginButton := False;

   Temp := INI.ReadString('Main', 'BlockSpamMsg', '0');
   if Temp = '1' then BlockSpamMsg := True
   else BlockSpamMsg := False;

   Temp := INI.ReadString('Main', 'EnableExPrivateChatName', '0');
   if Temp = '1' then ExPrivateChatName := True
   else ExPrivateChatName := False;

   Temp := INI.ReadString('Main', 'EnableDebug', '0');
   if Temp = '1' then EnableDebug := True
   else EnableDebug := False;

   Temp := INI.ReadString('Main', 'EnableCallBackDebug', '0');
   if Temp = '1' then EnableCallBackDebug := True
   else EnableCallBackDebug := False;

   MaxErrLogSize := INI.ReadInteger('Main', 'MaxErrLogSize', 20);
  end
 else
  begin
    INI := TIniFile.Create(path);
    // Çíà÷åíèÿ ïî-óìîë÷àíèþ
    DBType := 'mysql';
    DBName := DefaultDBName;
    DBUserName := 'username';
    SyncMethod := 1;
    SyncInterval := 0;
    SyncMessageCount := 50;
    WriteErrLog := True;
    AniEvents := True;
    ShowPluginButton := True;
    EnableHistoryEncryption := False;
    AddSpecialContact := True;
    BlockSpamMsg := False;
    EnableDebug := False;
    EnableCallBackDebug := False;
    MaxErrLogSize := 20;
    // Ñîõðàíÿåì íàñòðîéêè
    INI.WriteString('Main', 'DBType', DBType);
    INI.WriteString('Main', 'DBAddress', DefaultDBAddres);
    INI.WriteString('Main', 'DBSchema', 'username');
    INI.WriteString('Main', 'DBPort', '3306');
    INI.WriteString('Main', 'DBName', DefaultDBName);
    INI.WriteString('Main', 'DBUserName', DBUserName);
    INI.WriteString('Main', 'DBPasswd', 'skGvQNyWUHcHohJS2+2r4A==');
    INI.WriteInteger('Main', 'SyncMethod', SyncMethod);
    INI.WriteInteger('Main', 'SyncInterval', SyncInterval);
    INI.WriteInteger('Main', 'SyncTimeCount', 40);
    INI.WriteInteger('Main', 'SyncMessageCount', SyncMessageCount);
    INI.WriteInteger('Main', 'NumLastHistoryMsg', 6);
    INI.WriteString('Main', 'WriteErrLog', BoolToIntStr(WriteErrLog));
    INI.WriteString('Main', 'ShowAnimation', BoolToIntStr(AniEvents));
    INI.WriteString('Main', 'EnableHistoryEncryption', BoolToIntStr(EnableHistoryEncryption));
    INI.WriteString('Main', 'DefaultLanguage', CoreLanguage);
    INI.WriteString('Main', 'HideHistorySyncIcon', '0');
    INI.WriteString('Main', 'ShowPluginButton', BoolToIntStr(ShowPluginButton));
    INI.WriteString('Main', 'AddSpecialContact', BoolToIntStr(AddSpecialContact));
    INI.WriteString('Main', 'BlockSpamMsg', BoolToIntStr(BlockSpamMsg));
    INI.WriteInteger('Main', 'MaxErrLogSize', MaxErrLogSize);
    INI.WriteString('Main', 'AlphaBlend', '0');
    INI.WriteString('Main', 'AlphaBlendValue', '255');
    INI.WriteString('Main', 'EnableDebug', '0');
    INI.WriteString('Main', 'EnableCallBackDebug', '0');
    INI.WriteString('Fonts', 'FontInTitle', '183|-11|Verdana|0|96|8|Y|N|N|N|');
    INI.WriteString('Fonts', 'FontOutTitle', '8404992|-11|Verdana|0|96|8|Y|N|N|N|');
    INI.WriteString('Fonts', 'FontInBody', '-16777208|-11|Verdana|0|96|8|N|N|N|N|');
    INI.WriteString('Fonts', 'FontOutBody', '-16777208|-11|Verdana|0|96|8|N|N|N|N|');
    INI.WriteString('Fonts', 'FontService', '16711680|-11|Verdana|0|96|8|Y|N|N|N|');
    INI.WriteString('Fonts', 'TitleParagraph', '4|4|');
    INI.WriteString('Fonts', 'MessagesParagraph', '2|2|');
    INI.WriteString('HotKey', 'GlobalHotKey', '0');
    INI.WriteString('HotKey', 'SyncHotKey', 'Ctrl+Alt+F12');
    INI.WriteString('HotKey', 'ExSearchHotKey', 'Ctrl+F3');
    INI.WriteString('HotKey', 'ExSearchNextHotKey', 'F3');
  end;
  INI.Free;
end;

{ Ïðîöåäóðà çàïèñè çíà÷åíèÿ ïàðàìåòðà â ôàéë íàñòðîåê }
procedure WriteCustomINI(INIPath, CustomParams, ParamsStr: String);
var
  Path: String;
  INI: TIniFile;
begin
  Path := INIPath + ININame;
  if FileExists(Path) then
  begin
    INI := TIniFile.Create(Path);
    try
      INI.WriteString('Main', CustomParams, ParamsStr);
    finally
      INI.Free;
    end;
  end
  else
  begin
    if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ïðîöåäóðà WriteCustomINI: ' + GetLangStr('SettingsErrSave'), 2);
    MsgDie(htdPluginShortName, GetLangStr('SettingsErrSave'));
  end;
end;

{ Ôóíêöèÿ ÷òåíèÿ çíà÷åíèÿ ïàðàìåòðà èç ôàéëà íàñòðîåê }
function ReadCustomINI(INIPath, CustomParams, DefaultParamsStr: String): String;
var
  Path: String;
  INI: TIniFile;
begin
  Path := INIPath + ININame;
  if FileExists(Path) then
  begin
    INI := TIniFile.Create(Path);
    try
      Result := INI.ReadString('Main', CustomParams, DefaultParamsStr);
    finally
      INI.Free;
    end;
  end
  else
  begin
    if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ïðîöåäóðà ReadCustomINI: ' + GetLangStr('SettingsErrRead'), 2);
    MsgDie(htdPluginShortName, GetLangStr('SettingsErrRead'));
  end;
end;

{ Ïðîöåäóðà äëÿ îòïðàâêè ñîîáùåíèé ïðîãðàììå }
{ Ñòàíäàðòíûå êîìàíäû:
  001  - Ïåðå÷èòàòü íàñòðîéêè èç ôàéëà HistoryToDB.ini
  002  - Ñèíõðîíèçàöèÿ èñòîðèè
  003  - Çàêðûòü âñå êîìïîíåíòû ïëàãèíà
  0040 - Ïîêàçàòü âñå îêíà ïëàãèíà (Ðåæèì AntiBoss)
  0041 - Ñêðûòü âñå îêíà ïëàãèíà (Ðåæèì AntiBoss)
  005  - Ïîêàçàòü îêíî íàñòðîåê
  0050 - Çàïóñòèòü ïåðåðàñ÷åò MD5-õåøåé
  0051 - Çàïóñòèòü ïåðåðàñ÷åò MD5-õåøåé è óäàëåíèÿ äóáëèêàòîâ
  0060 - Çàïóùåí èìïîðò èñòîðèè
  0061 - Èìïîðò èñòîðèè çàâåðøåí
  007  - Îáíîâèòü êîíòàêò-ëèñò â ÁÄ
  008  - Ïîêàçàòü èñòîðèþ êîíòàêòà/÷àòà
         Ôîðìàò êîìàíäû:
           äëÿ èñòîðèè êîíòàêòà:
             008|0|UserID|UserName|ProtocolType
           äëÿ èñòîðèè ÷àòà:
             008|2|ChatName
  009 - Ýêñòðåííî çàêðûòü âñå êîìïîíåíòû ïëàãèíà.
  010 - Ñòðîêà SQL-insert ïåðåäàíà â ïàìÿòü
}
procedure OnSendMessageToAllComponent(Msg: String);
var
  HToDB: HWND;
  copyDataStruct : TCopyDataStruct;
  EncryptMsg, WinName: String;
begin
  if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ôóíêöèÿ OnSendMessageToAllComponent: Îòïðàâêà çàïðîñà "' + Msg + '" âñåì êîìïîíåíòàì ïëàãèíà.', 2);
  EncryptMsg := EncryptStr(Msg);
  // Èùåì îêíî HistoryToDBViewer è ïîñûëàåì åìó êîìàíäó
  WinName := 'HistoryToDBViewer for ' + htdIMClientName + ' ('+MyAccount+')';
  HToDB := FindWindow(nil, pWideChar(WinName));
  if HToDB <> 0 then
  begin
    copyDataStruct.dwData := {$IFDEF WIN32}Integer{$ELSE}LongInt{$ENDIF}(cdtString);;
    copyDataStruct.cbData := Length(EncryptMsg) * SizeOf(Char);;
    copyDataStruct.lpData := PChar(EncryptMsg);
    SendMessage(HToDB, WM_COPYDATA, 0, {$IFDEF WIN32}Integer{$ELSE}LongInt{$ENDIF}(@copyDataStruct));
    if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ôóíêöèÿ OnSendMessageToAllComponent: Îòïðàâêà çàïðîñà "' + Msg + '" îêíó ' + WinName, 2);
  end;
  // Èùåì îêíî HistoryToDBSync è ïîñûëàåì åìó êîìàíäó
  WinName := 'HistoryToDBSync for ' + htdIMClientName + ' ('+MyAccount+')';
  HToDB := FindWindow(nil, pWideChar(WinName));
  if HToDB <> 0 then
  begin
    copyDataStruct.dwData := {$IFDEF WIN32}Integer{$ELSE}LongInt{$ENDIF}(cdtString);;
    copyDataStruct.cbData := Length(EncryptMsg) * SizeOf(Char);;
    copyDataStruct.lpData := PChar(EncryptMsg);
    SendMessage(HToDB, WM_COPYDATA, 0, {$IFDEF WIN32}Integer{$ELSE}LongInt{$ENDIF}(@copyDataStruct));
    if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ôóíêöèÿ OnSendMessageToAllComponent: Îòïðàâêà çàïðîñà "' + Msg + '" îêíó ' + WinName, 2);
  end;
  // Èùåì îêíî HistoryToDBImport è ïîñûëàåì åìó êîìàíäó
  WinName := 'HistoryToDBImport for ' + htdIMClientName + ' ('+MyAccount+')';
  HToDB := FindWindow(nil, pWideChar(WinName));
  if HToDB <> 0 then
  begin
    copyDataStruct.dwData := {$IFDEF WIN32}Integer{$ELSE}LongInt{$ENDIF}(cdtString);;
    copyDataStruct.cbData := Length(EncryptMsg) * SizeOf(Char);;
    copyDataStruct.lpData := PChar(EncryptMsg);
    SendMessage(HToDB, WM_COPYDATA, 0, {$IFDEF WIN32}Integer{$ELSE}LongInt{$ENDIF}(@copyDataStruct));
    if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ôóíêöèÿ OnSendMessageToAllComponent: Îòïðàâêà çàïðîñà "' + Msg + '" îêíó ' + WinName, 2);
  end;
  // Èùåì îêíî HistoryToDBUpdater è ïîñûëàåì åìó êîìàíäó
  WinName := 'HistoryToDBUpdater for ' + htdIMClientName + ' ('+MyAccount+')';
  HToDB := FindWindow(nil, pWideChar(WinName));
  if HToDB <> 0 then
  begin
    copyDataStruct.dwData := {$IFDEF WIN32}Integer{$ELSE}LongInt{$ENDIF}(cdtString);;
    copyDataStruct.cbData := Length(EncryptMsg) * SizeOf(Char);;
    copyDataStruct.lpData := PChar(EncryptMsg);
    SendMessage(HToDB, WM_COPYDATA, 0, {$IFDEF WIN32}Integer{$ELSE}LongInt{$ENDIF}(@copyDataStruct));
    if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ôóíêöèÿ OnSendMessageToAllComponent: Îòïðàâêà çàïðîñà "' + Msg + '" îêíó ' + WinName, 2);
  end;
end;

procedure OnSendMessageToOneComponent(WinName, Msg: String);
var
  HToDB: HWND;
  copyDataStruct : TCopyDataStruct;
  AppNameStr, EncryptMsg: String;
begin
  // Èùåì îêíî WinName è ïîñûëàåì åìó êîìàíäó
  HToDB := FindWindow(nil, pWideChar(WinName));
  if HToDB <> 0 then
  begin
    EncryptMsg := EncryptStr(Msg);
    copyDataStruct.dwData := {$IFDEF WIN32}Integer{$ELSE}LongInt{$ENDIF}(cdtString);
    copyDataStruct.cbData := Length(EncryptMsg) * SizeOf(Char);
    copyDataStruct.lpData := PChar(EncryptMsg);
    SendMessage(HToDB, WM_COPYDATA, 0, {$IFDEF WIN32}Integer{$ELSE}LongInt{$ENDIF}(@copyDataStruct));
    if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ôóíêöèÿ OnSendMessageToOneComponent: Îòïðàâêà çàïðîñà "' + Msg + '" îêíó ' + WinName, 2);
  end;
end;

{ Ïîèñê îêíà ïðîãðàììû }
function SearchMainWindow(MainWindowName: pWideChar): Boolean;
var
  HToDB: HWND;
begin
  // Èùåì îêíî
  HToDB := FindWindow(nil, MainWindowName);
  if HToDB <> 0 then
    Result := True
  else
    Result := False
end;

{Ôóíêöèÿ îñóùåñòâëÿåò ñðàâíåíèå äâóõ ñòðîê. Ïåðâàÿ ñòðîêà
ìîæåò áûòü ëþáîé, íî îíà íå äîëæíà ñîäåðæàòü ñèìâîëîâ ñîîòâåòñòâèÿ (* è ?).
Ñòðîêà ïîèñêà (èñêîìûé îáðàç) ìîæåò ñîäåðæàòü àáñîëþòíî ëþáûå ñèìâîëû.
Äëÿ ïðèìåðà: MatchStrings('David Stidolph','*St*') âîçâðàòèò True.
Àâòîð îðèãèíàëüíîãî C-êîäà Sean Stanley
Àâòîð ïîðòàöèè íà Delphi David Stidolph}
function MatchStrings(Source, Pattern: String): Boolean;
var
  pSource: array[0..255] of Char;
  pPattern: array[0..255] of Char;

  function MatchPattern(element, pattern: PChar): Boolean;

  function IsPatternWild(pattern: PChar): Boolean;
  begin
    Result := StrScan(pattern, '*') <> nil;
    if not Result then
      Result := StrScan(pattern, '?') <> nil;
  end;

  begin
    if 0 = StrComp(pattern, '*') then
      Result := True
    else if (element^ = Chr(0)) and (pattern^ <> Chr(0)) then
      Result := False
    else if element^ = Chr(0) then
      Result := True
    else
    begin
      case pattern^ of
        '*': if MatchPattern(element, @pattern[1]) then
            Result := True
          else
            Result := MatchPattern(@element[1], pattern);
        '?': Result := MatchPattern(@element[1], @pattern[1]);
      else
        if element^ = pattern^ then
          Result := MatchPattern(@element[1], @pattern[1])
        else
          Result := False;
      end;
    end;
  end;
begin
  StrPCopy(pSource, source);
  StrPCopy(pPattern, pattern);
  Result := MatchPattern(pSource, pPattern);
end;

// Äëÿ ìóëüòèÿçûêîâîé ïîääåðæêè
procedure MsgDie(Caption, Msg: WideString);
begin
  //{$IFDEF UNICODE}
  //MessageBoxW(GetForegroundWindow, PWideChar(Msg), PWideChar(Caption), MB_ICONERROR);
  //{$ELSE}
  //MessageBoxA(GetForegroundWindow, PAnsiChar(Msg), PAnsiChar(Caption), MB_ICONERROR);
  //{$ENDIF}
  MessageBox(GetForegroundWindow, PWideChar(Msg), PWideChar(Caption), MB_ICONERROR);
end;

// Äëÿ ìóëüòèÿçûêîâîé ïîääåðæêè
procedure MsgInf(Caption, Msg: WideString);
begin
  //{$IFDEF UNICODE}
  //MessageBoxW(GetForegroundWindow, PWideChar(Msg), PWideChar(Caption), MB_ICONINFORMATION);
  //{$ELSE}
  //MessageBoxA(GetForegroundWindow, PAnsiChar(Msg), PAnsiChar(Caption), MB_ICONINFORMATION);
  //{$ENDIF}
  MessageBox(GetForegroundWindow, PWideChar(Msg), PWideChar(Caption), MB_ICONINFORMATION);
end;

// Äëÿ ìóëüòèÿçûêîâîé ïîääåðæêè
function GetLangStr(StrID: String): WideString;
begin
  if (not Assigned(LangDoc)) or (not LangDoc.Active) then
  begin
    Result := '';
    Exit;
  end;
  if LangDoc.ChildNodes['strings'].ChildNodes.FindNode(StrID) <> nil then
    Result := LangDoc.ChildNodes['strings'].ChildNodes[StrID].Text
  else
    Result := 'String not found.';
end;

{ Îáðàáîò÷èê èçìåíåíèé ôàéëîâ â êàòàëîãå ïðîôèëÿ }
procedure ProfileDirChangeCallBack(pInfo: TInfoCallBack);
var
  SettingsFormRequest: String;
begin
  SettingsFormRequest := ReadCustomINI(ProfilePath, 'SettingsFormRequestSend', '0');
  if EnableCallBackDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ïðîöåäóðà ProfileDirChangeCallBack: Ïàðàìåòð SettingsFormRequestSend = ' + SettingsFormRequest + ' | FAction = ' + IntToStr(pInfo.FAction) + ' | FOldFileName = ' + pInfo.FOldFileName + ' | FNewFileName = ' + Trim(pInfo.FNewFileName), 2);
  if (pInfo.FAction = 3) and (Trim(pInfo.FNewFileName) = 'HistoryToDB.ini') and (SettingsFormRequest = '0') then
  begin
    IMDelay(500);
    LoadINI(ProfilePath);
    CoreLanguage := DefaultLanguage;
    if EnableCallBackDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ïðîöåäóðà ProfileDirChangeCallBack: Íàñòðîéêè HistoryToDB.ini ïåðå÷èòàíû. | Íîâûé ÿçûê ïðîãðàììû = ' + CoreLanguage, 2);
    // Èíèöèàëèçàöèÿ COM ñ ïîääåðæêîé ìíîãîïîòî÷íîñòè
    // ÕÇ çà÷åì ýòî íóæíî, íî åñëè ýòîãî íå äåëàòü, òî ïðè âûçîâå CoreLanguageChanged
    // âûëàçèò îøèáêà "Íå áûë ïðîèçâåäåí âûçîâ CoInitialize"
    // CoInitialize îáúÿâëåí â ìîäóëå ActiveX
    CoInitializeEx(nil, COINIT_MULTITHREADED);
    // Ïåðåçàãðóæÿåì ÿçûêîâîé ôàéë
    CoreLanguageChanged;
    // Îñâîáîæäåíèå COM (äâàæäû)
    CoUninitialize();
    CoUninitialize();
    // Ïåðåñòðàèâàåì ìåíþ
    RebuildMainMenu;
    // MMF
    if SyncMethod = 0 then
    begin
      if not Assigned(FMap) then
      begin
        if EnableCallBackDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ïðîöåäóðà ProfileDirChangeCallBack: Ñîçäàåì TMapStream', 2);
        FMap := TMapStream.CreateEx('HistoryToDB for QIP ('+MyAccount+')',MAXDWORD,2000);
      end;
    end
    else
    begin
      if Assigned(FMap) then
      begin
        FMap.Free;
        FMap := nil;
      end;
    end;
  end;
end;

// Ïîäñ÷åò MD5 ñòðîêè
function EncryptMD5(Str: String): String;
var
  Hash: TDCP_md5;
  Digest: Array[0..15] of Byte;
  I: Integer;
  P: String;
begin
  if Str <> '' then
  begin
    Hash:= TDCP_md5.Create(nil);
    try
      Hash.HashSize := 128;
      Hash.Init;
      Hash.UpdateStr(Str);
      Hash.Final(Digest);
      P := '';
      for I:= 0 to 15 do
        P:= P + IntToHex(Digest[I], 2);
    finally
      Hash.Free;
    end;
    Result := P;
  end
  else
    Result := 'MD5';
end;

// Èíèöèèðóåì êðèïòîâàíèå
procedure EncryptInit;
begin
  Hash:= TDCP_sha1.Create(nil);
  try
    Hash.Init;
    Hash.UpdateStr(EncryptKey);
    Hash.Final(Digest);
  finally
    Hash.Free;
  end;
  Cipher := TDCP_3des.Create(nil);
  try
    Cipher.Init(Digest,Sizeof(Digest)*8,nil);
  except
    on E: Exception do
      if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ïðîöåäóðà EncryptInit: ' + E.Message, 2);
  end;
end;

// Îñâîáîæäàåì ðåñóðñû
procedure EncryptFree;
begin
  if Assigned(Cipher) then
  begin
    Cipher.Burn;
    Cipher.Free;
  end;
end;

// Çàøèôðîâûâàåì ñòðîêó
function EncryptStr(const Str: String): String;
begin
  Result := '';
  if Str <> '' then
  begin
    Cipher.Reset;
    Result := Cipher.EncryptString(Str);
  end;
end;

{ Ôóíêöèÿ äëÿ ïîëó÷åíèÿ èìåíè ôàéëà èç ïóòè áåç èëè ñ åãî ðàñøèðåíèåì.
  Âîçâðàùàåò èìÿ ôàéëà, áåç èëè ñ åãî ðàñøèðåíèåì.
  Âõîäíûå ïàðàìåòðû:
  FileName - èìÿ ôàéëà, êîòîðîå íàäî îáðàáîòàòü
  ShowExtension - åñëè TRUE, òî ôóíêöèÿ âîçâðàòèò êîðîòêîå èìÿ ôàéëà
  (áåç ïîëíîãî ïóòè äîñòóïà ê íåìó), ñ ðàñøèðåíèåì ýòîãî ôàéëà, èíà÷å, âîçâðàòèò
  êîðîòêîå èìÿ ôàéëà, áåç ðàñøèðåíèÿ ýòîãî ôàéëà. }
function ExtractFileNameEx(FileName: String; ShowExtension: Boolean): String;
var
  I: Integer;
  S, S1: string;
begin
  I := Length(FileName);
  if I <> 0 then
  begin
    while (FileName[i] <> '\') and (i > 0) do
      i := i - 1;
    S := Copy(FileName, i + 1, Length(FileName) - i);
    i := Length(S);
    if i = 0 then
    begin
      Result := '';
      Exit;
    end;
    while (S[i] <> '.') and (i > 0) do
      i := i - 1;
    S1 := Copy(S, 1, i - 1);
    if s1 = '' then
      s1 := s;
    if ShowExtension = True then
      Result := s
    else
      Result := s1;
  end
  else
    Result := '';
end;

function WideStringToString(const ws: WideString; codePage: Word): AnsiString;
var
  l: integer;
begin
  if ws = '' then
    Result := ''
  else
  begin
    l := WideCharToMultiByte(codePage,
      WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR,
      @ws[1], -1, nil, 0, nil, nil);
    SetLength(Result, l - 1);
    if l > 1 then
      WideCharToMultiByte(codePage,
        WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR,
        @ws[1], -1, @Result[1], l - 1, nil, nil);
  end;
end;

function AnsiToWideString(const S: AnsiString; CodePage: Cardinal; InLength: Integer = -1): WideString;
var
  InputLength,
  OutputLength: Integer;
begin
  Result := '';
  if S = '' then
    exit;
  if Codepage = CP_UTF8 then
  begin
    Result := UTF8ToWideString(S); // CP_UTF8 not supported on Windows 95
  end
  else
  begin
    if InLength < 0 then
      InputLength := Length(S)
    else
      InputLength := InLength;
    OutputLength := MultiByteToWideChar(Codepage, 0, PAnsiChar(S), InputLength, nil, 0);
    SetLength(Result, OutputLength);
    MultiByteToWideChar(Codepage, MB_PRECOMPOSED, PAnsiChar(S), InputLength, PWideChar(Result),
      OutputLength);
  end;
end;

function WideToAnsiString(const WS: WideString; CodePage: Cardinal; InLength: Integer = -1): AnsiString;
var
  InputLength,
  OutputLength: Integer;
begin
  Result := '';
  if WS = '' then
    exit;
  if Codepage = CP_UTF8 then
    Result := UTF8Encode(WS) // CP_UTF8 not supported on Windows 95
  else
  begin
    if InLength < 0 then
      InputLength := Length(WS)
    else
      InputLength := InLength;
    OutputLength := WideCharToMultiByte(Codepage, 0, PWideChar(WS), InputLength, nil, 0,
      nil, nil);
    SetLength(Result, OutputLength);
    WideCharToMultiByte(Codepage, 0, PWideChar(WS), InputLength, PAnsiChar(Result),
      OutputLength, nil, nil);
  end;
end;

function StrContactProtoToInt(Proto: AnsiString): Integer;
var
  ProtoType: Integer;
begin
  { Ïðîòîêîëû
    0 - ICQ
    1 - Google Talk
    2 - MRA
    3 - Jabber
    4 - QIP.Ru
    5 - Facebook
    6 - VKontacte
    7 - Twitter
    8 - Social (LiveJournal)
    9 - AIM
    10 - IRC
    11 - MSN
    12 - YAHOO
    13 - GADU
    14 - SKYPE
    15 - MetaContacts
    16 - Unknown
  }
  if MatchStrings(LowerCase(Proto), 'icq*') then
    ProtoType := 0
  else if MatchStrings(LowerCase(Proto), 'google talk*') then
    ProtoType := 1
  else if MatchStrings(LowerCase(Proto), 'mrad*') then
    ProtoType := 15
  else if MatchStrings(LowerCase(Proto), 'mra*') then
    ProtoType := 2
  else if MatchStrings(LowerCase(Proto), 'jabber*') then
    ProtoType := 3
  else if (LowerCase(Proto) = 'qip.ru') then
    ProtoType := 4
  else if MatchStrings(LowerCase(Proto), 'facebook*') then
    ProtoType := 5
  else if MatchStrings(LowerCase(Proto), 'vkontakte*') then
    ProtoType := 6
  else if MatchStrings(LowerCase(Proto), 'âêîíòàêòå*') then
    ProtoType := 6
  else if MatchStrings(LowerCase(Proto), 'twitter*') then
    ProtoType := 7
  else if MatchStrings(LowerCase(Proto), 'livejournal*') then
    ProtoType := 8
  else if MatchStrings(LowerCase(Proto), 'aim*') then
    ProtoType := 9
  else if MatchStrings(LowerCase(Proto), 'irc*') then
    ProtoType := 10
  else if MatchStrings(LowerCase(Proto), 'msn*') then
    ProtoType := 11
  else if MatchStrings(LowerCase(Proto), 'yahoo*') then
    ProtoType := 12
  else if MatchStrings(LowerCase(Proto), 'gadu*') then
    ProtoType := 13
  else if MatchStrings(LowerCase(Proto), 'skype*') then
    ProtoType := 14
  else if MatchStrings(LowerCase(Proto), 'metacontacts*') then
    ProtoType := 15
  else
    ProtoType := 16;
  Result := ProtoType;
end;

{ Çàäåðæêà íå ãðóçÿùàÿ ïðîöåññîð }
procedure IMDelay(Value: Cardinal);
var
  F, N: Cardinal;
begin
  N := 0;
  while N <= (Value div 10) do
  begin
    SleepEx(1, True);
    //Application.ProcessMessages;
    Inc(N);
  end;
  F := GetTickCount;
  repeat
    //Application.ProcessMessages;
    N := GetTickCount;
  until (N - F >= (Value mod 10)) or (N < F);
end;

function Utf8ToWideChar(Dest: PWideChar; MaxDestChars: Integer; Source: PAnsiChar; SourceBytes: Integer; CodePage: Cardinal = CP_ACP): Integer;
const
  MB_ERR_INVALID_CHARS = 8;
var
  Src,SrcEnd: PAnsiChar;
  Dst,DstEnd: PWideChar;
begin
  if (Source = nil) or (SourceBytes <= 0) then
  begin
    Result := 0;
  end
  else if (Dest = nil) or (MaxDestChars <= 0) then
  begin
    Result := -1;
  end
  else
  begin
    Src := Source;
    SrcEnd := Source + SourceBytes;
    Dst := Dest;
    DstEnd := Dst + MaxDestChars;
    while (PAnsiChar(Src) < PAnsiChar(SrcEnd)) and (Dst < DstEnd) do
    begin
      if (Byte(Src[0]) and $80) = 0 then
      begin
        Dst[0] := WideChar(Src[0]);
        Inc(Src);
      end
      else if (Byte(Src[0]) and $E0) = $E0 then
      begin
        if Src + 2 >= SrcEnd then
          break;
        if (Src[1] = #0) or ((Byte(Src[1]) and $C0) <> $80) then
          break;
        if (Src[2] = #0) or ((Byte(Src[2]) and $C0) <> $80) then
          break;
        Dst[0] := WideChar(((Byte(Src[0]) and $0F) shl 12) + ((Byte(Src[1]) and $3F) shl 6) +
          ((Byte(Src[2]) and $3F)));
        Inc(Src, 3);
      end
      else if (Byte(Src[0]) and $E0) = $C0 then
      begin
        if Src + 1 >= SrcEnd then
          break;
        if (Src[1] = #0) or ((Byte(Src[1]) and $C0) <> $80) then
          break;
        Dst[0] := WideChar(((Byte(Src[0]) and $1F) shl 6) + ((Byte(Src[1]) and $3F)));
        Inc(Src, 2);
      end
      else
      begin
        if MultiByteToWideChar(CodePage, MB_ERR_INVALID_CHARS, Src, 1, Dst, 1) = 0 then
          Dst[0] := '?';
        Inc(Src);
      end;
      Inc(Dst);
    end;
    Dst[0] := #0;
    Inc(Dst);
    Result := Dst - Dest;
  end;
end;

// Êîíâåðòàöèÿ Unix Timestamp â Ëîêàëüíîå âðåìÿ ñ ó÷åòîì ïîÿñà è Ïåðåõîäà íà ëåòíåå âðåìÿ
function UnixToLocalTime(tUnix :Longint): TDateTime;
var
  TimeZone :TTimeZoneInformation;
  Bias     :Integer;
begin
  if (GetTimeZoneInformation(TimeZone) = TIME_ZONE_ID_DAYLIGHT) then
    Bias := TimeZone.Bias + TimeZone.DaylightBias
  else
    Bias := TimeZone.Bias + TimeZone.StandardBias;
  Result := EncodeDate(1970,1,1) - Bias / 1440 + tUnix / 86400;
end;

{ Ôóíêöèÿ äëÿ ìóëüòèÿçûêîâîé ïîääåðæêè }
procedure CoreLanguageChanged;
var
  LangFile: String;
begin
  if CoreLanguage = '' then
    Exit;
  try
    LangFile := PluginPath + dirLangs + CoreLanguage + '.xml';
    if FileExists(LangFile) then
      LangDoc.LoadFromFile(LangFile)
    else
    begin
      if FileExists(PluginPath + dirLangs + defaultLangFile) then
        LangDoc.LoadFromFile(PluginPath + dirLangs + defaultLangFile)
      else
      begin
        MsgDie(htdPluginShortName, 'Not found any language file!');
        Exit;
      end;
    end;
    SendMessage(AboutFormHandle, WM_LANGUAGECHANGED, 0, 0);
    SendMessage(ExportFormHandle, WM_LANGUAGECHANGED, 0, 0);
  except
    on E: Exception do
    begin
      if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Error on CoreLanguageChanged: ' + Trim(E.Message) + ' | CoreLanguage: ' + CoreLanguage, 2);
      MsgDie(htdPluginShortName, 'Error on CoreLanguageChanged: ' + E.Message + sLineBreak +
        'CoreLanguage: ' + CoreLanguage);
    end;
  end;
end;

{ Ôóíêöèÿ âîçâðàùàåò ïóòü äî ïîëüçîâàòåëüñêîé âðåìåííîé ïàïêè }
function GetUserTempPath: WideString;
var
  UserPath: WideString;
begin
  Result := '';
  SetLength(UserPath, MAX_PATH);
  GetTempPath(MAX_PATH, PChar(UserPath));
  GetLongPathName(PChar(UserPath), PChar(UserPath), MAX_PATH);
  SetLength(UserPath, StrLen(PChar(UserPath)));
  Result := UserPath;
end;

begin
  hppVersionStr := AnsiString(Format('%d.%d.%d.%d',[htdVerMajor,htdVerMinor,htdVerRelease,htdVerBuild]));
end.