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

library MirandaNGHistoryToDB;

{$I Global.inc}

uses
  madExcept,
  madLinkDisAsm,
  madListHardware,
  madListProcesses,
  madListModules,
  m_api,
  Windows,
  SysUtils,
  XMLIntf,
  XMLDoc,
  ShellApi,
  WideStrUtils,
  JclStringConversions,
  Contacts in 'Contacts.pas',
  Database in 'Database.pas',
  Menu in 'Menu.pas',
  About in 'About.pas',
  MsgExport in 'MsgExport.pas' {ExportForm},
  Global in 'Global.pas',
  FSMonitor in 'FSMonitor.pas',
  MapStream in 'MapStream.pas';

// use it to make plugin unicode-aware
{$DEFINE UNICODE}

// tell Miranda about this plugin ExVersion
function MirandaPluginInfoEx(mirandaVersion:DWORD): PPLUGININFOEX; cdecl;
begin
  PluginInfo.cbSize:= SizeOf(TPLUGININFOEX);
  PluginInfo.shortName:= htdPluginShortName;
  PluginInfo.version:= htdVersion;
  PluginInfo.description:= htdDescription_EN;
  PluginInfo.author:= htdAuthor_EN;
  PluginInfo.authorEmail:= htdAuthorEmail;
  PluginInfo.copyright:= htdCopyright_EN;
  PluginInfo.homepage:= htdHomePageURL;
  PluginInfo.flags:= UNICODE_AWARE;
  PluginInfo.uuid:= MIID_HISTORYTODBDLL;
  Result := @PluginInfo;
end;

var
  {$ifdef REPLDEFHISTMOD}
  PluginInterfaces: array[0..1] of TGUID;
  {$else}
  PluginInterfaces: array[0..0] of TGUID;
  {$endif REPLDEFHISTMOD}

  PluginStatus: Boolean = False;
  StartExport: Boolean = False;
  StartUpdate: Boolean = False;
  DefaultINICopy: Boolean = False;

  HookModulesLoad,
  HookBuildMenu,
  HookContactMenu,
  HookSystemHistoryMenu,
  {$ifdef REPLDEFHISTMOD}
  HookShowMainHistory,
  {$endif REPLDEFHISTMOD}
  HookEventAdded,
  //HookTTBLoaded,
  HookShowHistoryAPI,
  HookShowContactHistoryAPI,
  HookShowVersionAPI: THandle;
  //hTTBButton: THandle = 0;
  DialogMainWindow: HWND = 0;

const
  hLangpack: THANDLE = 0;

function OnModulesLoad(awParam:WPARAM; alParam:LPARAM): Integer; cdecl; forward;
function OnBuildContactMenu(awParam: WPARAM; alParam: LPARAM): Integer; cdecl; forward;
function OnEventAdded(wParam: WPARAM; lParam: LPARAM): Integer; cdecl; forward;
//function OnTTBLoaded(awParam: WPARAM; alParam: LPARAM): Integer; cdecl; forward;
function OpenHistoryWindow(wParam:WPARAM;lParam:LPARAM): Integer; cdecl; forward;

// tell Miranda about supported interfaces
function MirandaPluginInterfaces:PMUUID; cdecl;
begin
  {$ifdef REPLDEFHISTMOD}
  PluginInterfaces[0]:=MIID_UIHISTORY;
  PluginInterfaces[1]:=MIID_LAST;
  {$else}
  PluginInterfaces[0]:=MIID_LAST;
  {$endif REPLDEFHISTMOD}
  Result := @PluginInterfaces;
end;

{ Ïîêàçûâàåì èñòîðèþ êîíòàêòà }
function OpenHistoryWindow(wParam: WPARAM; lParam: LPARAM): Integer; cdecl;
var
  ContactProto, ContactID, ContactName: AnsiString;
  MyContactName, MyContactID: AnsiString;
  ProtoType: Integer;
  WinName: String;
begin
  Result := 0;
  ContactProto := GetContactProto(wParam);
  ContactID := GetContactID(wParam, ContactProto);
  ContactName := GetContactDisplayName(wParam, '', True);
  MyContactName := GetMyContactDisplayName(ContactProto);
  MyContactID := GetMyContactID(ContactProto);
  if ContactID = '' then
    ContactID := TranslateW('Unknown Contact');
  if ContactName = '' then
    ContactName := TranslateW('Unknown Contact');
  if MyContactID = '' then
    MyContactID := TranslateW('Unknown Contact');
  if MyContactName = '' then
    MyContactName := TranslateW('Unknown Contact');
  // Äîï. ïðîâåðêà ïðîòîêîëà
  if ContactProto = MyAccount then
    ContactProto := 'ICQ';
  if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ôóíêöèÿ PluginContactMenuCommand: ' + 'Contact ID: ' + ContactID + ' | Contact Name: ' + ContactName + ' | Proto: ' + ContactProto + ' | My Contact ID: ' + MyContactID + ' | My Contact Name: ' + MyContactName, 2);
  // Òèï èñòîðèè
  ProtoType := StrContactProtoToInt(ContactProto);
  // Ïîêàçûâàåì ïîñëåäíèå N ñîîáùåíèé ïåðåïèñêè
  WinName := 'HistoryToDBViewer for ' + htdIMClientName + ' ('+MyAccount+')';
  if SearchMainWindow(pWideChar(WinName)) then
  begin
    // Ôîðìàò êîìàíäû:
    //   äëÿ èñòîðèè êîíòàêòà:
    //     008|0|UserID|UserName|ProtocolType
    //   äëÿ èñòîðèè ÷àòà:
    //     008|2|ChatName
    OnSendMessageToOneComponent(WinName, '008|0|'+ContactID+'|'+ContactName+'|'+IntToStr(ProtoType));
    if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ïðîöåäóðà PluginContactMenuCommand: Îòïðàâëÿåì çàïðîñ - 008|0|'+ContactID+'|'+ContactName+'|'+IntToStr(ProtoType), 2);
  end
  else
  begin
    if FileExists(PluginPath + 'HistoryToDBViewer.exe') then
    begin
      if MatchStrings(LowerCase(ContactProto), 'skype*') then // Skype
      begin
        // Ñòàâèì ïðèçíàê òèïà èñòîðèè (Èñòîðèÿ ÷àò-ñîîáùåíèé)
        Glogal_History_Type := 2;
        if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ïðîöåäóðà PluginContactMenuCommand: Çàïóñêàåì ' + PluginPath + 'HistoryToDBViewer.exe' + ' "'+PluginPath+'" "'+ProfilePath+'" '+IntToStr(Glogal_History_Type)+' "'+MyContactID+'" "'+MyContactName+'" "'+ContactName+'"', 2);
        ShellExecute(0, 'open', PWideChar(PluginPath + 'HistoryToDBViewer.exe'), PWideChar(' "'+PluginPath+'" "'+ProfilePath+'" '+IntToStr(Glogal_History_Type)+' "'+MyContactID+'" "'+MyContactName+'" "'+ContactName+'"'), nil, SW_SHOWNORMAL);
      end
      else
      begin
        // Ñòàâèì ïðèçíàê òèïà èñòîðèè (Èñòîðèÿ IM-ñîîáùåíèé)
        Glogal_History_Type := 0;
        if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ïðîöåäóðà PluginContactMenuCommand: Çàïóñêàåì ' + PluginPath + 'HistoryToDBViewer.exe' + ' "'+PluginPath+'" "'+ProfilePath+'" '+IntToStr(Glogal_History_Type)+' "'+MyContactID+'" "'+MyContactName+'" "'+ContactID+'" "'+ContactName+'" '+IntToStr(ProtoType), 2);
        ShellExecute(0, 'open', PWideChar(PluginPath + 'HistoryToDBViewer.exe'), PWideChar(' "'+PluginPath+'" "'+ProfilePath+'" '+IntToStr(Glogal_History_Type)+' "'+MyContactID+'" "'+MyContactName+'" "'+ContactID+'" "'+ContactName+'" '+IntToStr(ProtoType)), nil, SW_SHOWNORMAL);
      end;
    end
    else
      MsgInf(htdPluginShortName, Format(GetLangStr('ERR_NO_FOUND_VIEWER'), [PluginPath + 'HistoryToDBViewer.exe']));
  end;
end;

{ Ïîñòðîåíèå ìåíþ êîíòàêòà òîëüêî äëÿ îïðåäåëåííûõ ïðîòîêîëîâ }
function OnBuildContactMenu(awParam: WPARAM; alParam: LPARAM): Integer; cdecl;
var
  MenuItem: TCLISTMENUITEM;
  ContactProto, ContactID, ContactName: AnsiString;
begin
  Result := 0;
  ContactProto := GetContactProto(awParam);
  // Ìåíþ
  ZeroMemory(@MenuItem, SizeOf(MenuItem));
  MenuItem.cbSize := SizeOf(MenuItem);
  MenuItem.flags := CMIM_FLAGS;
  if (ContactProto = MyAccount) or
    MatchStrings(LowerCase(ContactProto), 'icq*') or
    MatchStrings(LowerCase(ContactProto), 'jabber*') or
    MatchStrings(LowerCase(ContactProto), 'aim*') or
    MatchStrings(LowerCase(ContactProto), 'irc*') or
    MatchStrings(LowerCase(ContactProto), 'msn*') or
    MatchStrings(LowerCase(ContactProto), 'yahoo*') or
    MatchStrings(LowerCase(ContactProto), 'gadu*') or
    MatchStrings(LowerCase(ContactProto), 'skype*') or
    MatchStrings(LowerCase(ContactProto), 'vkonta*') then
  begin // Ïîêàçûâàåì ïóíê â ìåíþ êîíòàêòà
    ContactID := GetContactID(awParam, ContactProto);
    ContactName := GetContactDisplayName(awParam, '', True);
    if ContactName = '' then
      ContactName := TranslateW('Unknown Contact');
    if ContactID = '' then
      ContactID := TranslateW('Unknown Contact');
    // Äîï. ïðîâåðêà ïðîòîêîëà
    if ContactProto = MyAccount then
      ContactProto := 'ICQ';
    MenuItem.flags := MenuItem.flags or CMIM_NAME;
    MenuItem.szName.a := pAnsiChar(AnsiString(Format(WideStringToString(GetLangStr('ShowContactHistory'), CP_ACP), [ContactName, ContactID])));
    CallService(MS_CLIST_MODIFYMENUITEM, HookContactMenu, lParam(@MenuItem));
    if EnableDebug then // Åñëè îòëàäêà
      WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ôóíêöèÿ OnBuildContactMenu: ' + 'Contact ID: ' + ContactID + ' | Contact Name: ' + ContactName + ' | Proto: ' + ContactProto, 2);
  end
  else // Èëè ñêðûâàåì
  begin
    MenuItem.flags := MenuItem.flags or CMIF_HIDDEN;
    CallService(MS_CLIST_MODIFYMENUITEM, HookContactMenu, lParam(@MenuItem));
    if EnableDebug then // Åñëè îòëàäêà
    begin
      ContactID := GetContactID(awParam, ContactProto);
      ContactName := GetContactDisplayName(awParam, '', True);
      if ContactName = '' then
        ContactName := TranslateW('Unknown Contact');
      if ContactID = '' then
        ContactID := TranslateW('Unknown Contact');
      // Äîï. ïðîâåðêà ïðîòîêîëà
      if ContactProto = MyAccount then
        ContactProto := 'ICQ';
      WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ôóíêöèÿ OnBuildContactMenu: ' + 'Contact ID: ' + ContactID + ' | Contact Name: ' + ContactName + ' | Proto: ' + ContactProto, 2);
    end;
  end;
end;

{ Ïåðåõâàò ñîáûòèé â áàçå Ìèðàíäû }
function OnEventAdded(wParam: WPARAM; lParam: LPARAM): Integer; cdecl;
var
  ContactProto, ContactID, ContactName: AnsiString;
  MyContactName, MyContactID: AnsiString;
  BlobSize, ProtoType: Integer;
  DBEventInfo: TDBEventInfo;
  msgA: PAnsiChar;
  msgW: PChar;
  msgLen, LenW: Cardinal;
  I: Integer;
  Msg_RcvrNick, Msg_RcvrAcc, Msg_SenderNick, Msg_SenderAcc, Msg_Text, MD5String: WideString;
  Date_Str, MsgStatus: String;
  InsertSQLData, EncInsertSQLData, WinName: String;
  ASize: Integer;
  hContact: THandle;
begin
  Result := 0;
  ZeroMemory(@DBEventInfo, SizeOf(DBEventInfo));
  DBEventInfo.cbSize := SizeOf(DBEventInfo);
  DBEventInfo.pBlob := nil;
  BlobSize := CallService(MS_DB_EVENT_GETBLOBSIZE, lParam, 0);
  GetMem(DBEventInfo.pBlob, BlobSize);
  DBEventInfo.cbBlob := BlobSize;
  if (CallService(MS_DB_EVENT_GET, lParam, Integer(@DBEventInfo)) = 0) and (DBEventInfo.eventType = EVENTTYPE_MESSAGE and EVENTTYPE_URL) then
  begin
    // Ïîëó÷àåì òåêñò ñîîáùåíèÿ
    msgA := PAnsiChar(DBEventInfo.pBlob);
    msgW := nil;
    msgLen := lstrlenA(PAnsiChar(DBEventInfo.pBlob)) + 1;
    if msgLen > DBEventInfo.cbBlob then
      msgLen := DBEventInfo.cbBlob;
    if Boolean(DBEventInfo.flags and DBEF_UTF) then
    begin
      SetLength(Msg_Text, msgLen);
      LenW := Utf8ToWideChar(PChar(Msg_Text), msgLen, msgA, msgLen - 1, CP_ACP);
      if Integer(LenW) > 0 then
        SetLength(Msg_Text, LenW - 1)
      else
        Msg_Text := AnsiToWideString(msgA, CP_ACP, msgLen - 1);
    end
    else
    begin
      LenW := 0;
      if DBEventInfo.cbBlob >= msgLen * SizeOf(Char) then
      begin
        msgW := PChar(msgA + msgLen);
        for i := 0 to ((DBEventInfo.cbBlob - msgLen) div SizeOf(Char)) - 1 do
          if msgW[i] = #0 then
          begin
            LenW := i;
            Break;
          end;
      end;
      if (LenW > 0) and (LenW < msgLen) then
        SetString(Msg_Text, msgW, LenW)
      else
        Msg_Text := AnsiToWideString(msgA, CP_ACP, msgLen - 1);
    end;
    // Òèï èñòîðèè
    hContact := wParam;
    ContactProto := GetContactProto(hContact);
    ProtoType := StrContactProtoToInt(ContactProto);
    // Åñëè ñîîáùåíèå îò ìåòàêîíòàêòà, òî íå ïèøåì åãî â ÁÄ
    // ò.ê. îíî îòïðàâëÿåòñÿ èòàê â ÁÄ ÷åðåç íóæíûé ïðîòîêîë
    if ProtoType = 15 then
      Exit;
    // Äàííûå ñîáåñåäíèêà
    ContactID := GetContactID(hContact, ContactProto);
    ContactName := GetContactDisplayName(hContact, '', True);
    // Ìîè äàííûå
    MyContactName := GetMyContactDisplayName(ContactProto);
    MyContactID := GetMyContactID(ContactProto);
    // Äîï. ïðîâåðêà ïðîòîêîëà
    if ContactProto = MyAccount then
      ContactProto := 'ICQ';
    ProtoType := StrContactProtoToInt(ContactProto);
    // End
    if ContactID = '' then
      ContactID := TranslateW('Unknown Contact');
    if ContactName = '' then
      ContactName := TranslateW('Unknown Contact');
    if MyContactID = '' then
      MyContactID := TranslateW('Unknown Contact');
    if MyContactName = '' then
      MyContactName := TranslateW('Unknown Contact');
    // Êîððåêòèðóåì MyContactID è ContactName åñëè ïðèõîäÿò è
    // îòïðàâëÿþòñÿ ñîîáùåíèÿ äëÿ Ìåòàêîíòàêòà
    {if (ProtoType = 15) and (MyContactID = TranslateW('Unknown Contact')) and (MyContactName <> TranslateW('Unknown Contact')) then
      MyContactID := MyContactName;
    if (ProtoType = 15) and (ContactName = TranslateW('Unknown Contact')) and (ContactID <> TranslateW('Unknown Contact')) then
      ContactName := ContactID;}
    // Ýêðàíèðîâàíèå, ïåðåêîäèðîâàíèå è ò.ï.
    Msg_SenderNick := PrepareString(pWideChar(AnsiToWideString(MyContactName, CP_ACP)));
    Msg_SenderAcc := PrepareString(pWideChar(AnsiToWideString(MyContactID, CP_ACP)));
    Msg_SenderNick := WideStringToUTF8(Msg_SenderNick);
    Msg_SenderAcc := WideStringToUTF8(Msg_SenderAcc);
    Msg_RcvrNick := PrepareString(pWideChar(AnsiToWideString(ContactName, CP_ACP)));
    Msg_RcvrAcc := PrepareString(pWideChar(AnsiToWideString(ContactID, CP_ACP)));
    Msg_RcvrNick := WideStringToUTF8(Msg_RcvrNick);
    Msg_RcvrAcc := WideStringToUTF8(Msg_RcvrAcc);
    Msg_Text := WideStringToUTF8(PrepareString(pWideChar(Msg_Text)));
    MD5String := Msg_RcvrAcc + FormatDateTime('YYYY-MM-DD HH:MM:SS', UnixToLocalTime(DBEventInfo.timestamp)) + Msg_Text;
    if (DBType = 'oracle') or (DBType = 'oracle-9i') then
      Date_Str := FormatDateTime('DD.MM.YYYY HH:MM:SS', UnixToLocalTime(DBEventInfo.timestamp))
    else
      Date_Str := FormatDateTime('YYYY-MM-DD HH:MM:SS', UnixToLocalTime(DBEventInfo.timestamp));
    if MatchStrings(LowerCase(ContactProto), 'skype*') then
    begin
      // Îïðåäåëÿåì íàïðàâëåíèå îòïðàâêè (ìû îòïðàâèëè èëè íàì ïðèñëàëè)
      if (DBEventInfo.flags and DBEF_SENT) = 0 then
        MsgStatus := '0'  // Âõîäÿùåå
      else
        MsgStatus := '1'; // Èñõîäÿùåå
      // Ëîã îòëàäêè
      if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ôóíêöèÿ OnEventAdded: ' + 'Contact ID: ' + ContactID + ' | Contact Name: ' + ContactName + ' | Proto: ' + ContactProto + ' | My Contact ID: ' + MyContactID + ' | My Contact Name: ' + MyContactName + ' | Contact Proto = ' + ContactProto + ' | MsgStatus = ' + MsgStatus + ' | DateTime = ' + FormatDateTime('DD.MM.YYYY HH:MM:SS', UnixToLocalTime(DBEventInfo.timestamp)) + ' | Message = ' + Msg_Text, 2);
      if (MatchStrings(DBType, 'oracle*')) then // Åñëè Oracle, òî ïèøåì SQL-ëîã â ôîðìàòå CHAT_MSG_LOG_ORACLE
        InsertSQLData := Format(CHAT_MSG_LOG_ORACLE, [DBUserName, MsgStatus, 'to_date('''+Date_Str+''', ''dd.mm.yyyy hh24:mi:ss'')', Msg_RcvrNick, 'Skype', Msg_RcvrNick+' ('+Msg_RcvrAcc+')', BoolToIntStr(True), BoolToIntStr(False), BoolToIntStr(False), Msg_Text, EncryptMD5(MD5String)])
      else
        InsertSQLData := Format(CHAT_MSG_LOG, [DBUserName, MsgStatus, Date_Str, Msg_RcvrNick, 'Skype', Msg_RcvrNick+' ('+Msg_RcvrAcc+')', BoolToIntStr(True), BoolToIntStr(False), BoolToIntStr(False), Msg_Text, EncryptMD5(MD5String)]);
    end
    else
    begin
      // Îïðåäåëÿåì íàïðàâëåíèå îòïðàâêè (ìû îòïðàâèëè èëè íàì ïðèñëàëè)
      if (DBEventInfo.flags and DBEF_SENT) = 0 then
        MsgStatus := '1'  // Âõîäÿùåå
      else
        MsgStatus := '0'; // Èñõîäÿùåå
      // Ëîã îòëàäêè
      if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ôóíêöèÿ OnEventAdded: ' + 'Contact ID: ' + ContactID + ' | Contact Name: ' + ContactName + ' | Proto: ' + ContactProto + ' | My Contact ID: ' + MyContactID + ' | My Contact Name: ' + MyContactName + ' | Contact Proto = ' + ContactProto + ' | MsgStatus = ' + MsgStatus + ' | DateTime = ' + FormatDateTime('DD.MM.YYYY HH:MM:SS', UnixToLocalTime(DBEventInfo.timestamp)) + ' | Message = ' + Msg_Text, 2);
      if (MatchStrings(DBType, 'oracle*')) then // Åñëè Oracle, òî ïèøåì SQL-ëîã â ôîðìàòå MSG_LOG_ORACLE
        InsertSQLData := Format(MSG_LOG_ORACLE, [DBUserName, IntToStr(ProtoType), Msg_SenderNick, Msg_SenderAcc, Msg_RcvrNick, Msg_RcvrAcc, MsgStatus, 'to_date('''+Date_Str+''', ''dd.mm.yyyy hh24:mi:ss'')', Msg_Text, EncryptMD5(MD5String)])
      else
        InsertSQLData := Format(MSG_LOG, [DBUserName, IntToStr(ProtoType), Msg_SenderNick, Msg_SenderAcc, Msg_RcvrNick, Msg_RcvrAcc, MsgStatus, Date_Str, Msg_Text, EncryptMD5(MD5String)]);
    end;
    // Ïîñûëàåì ñîîáùåíèå ÷åðåç MMF äëÿ Àâòîìàòè÷åñêîãî ðåæèìà ñèíõðîíèçàöèè
    if SyncMethod = 0 then
    begin
      WinName := 'HistoryToDBSync for ' + htdIMClientName + ' ('+MyAccount+')';
      if SearchMainWindow(pWideChar(WinName)) then
      begin
        EncInsertSQLData := EncryptStr(InsertSQLData);
        ASize := 2*Length(EncInsertSQLData);
        with FMap do
        begin
          Clear;
          WriteBuffer(@ASize,Sizeof(Integer));
          WriteBuffer(PChar(EncInsertSQLData),ASize);
        end;
        // Îòïðàâëÿåì ñèãíàë, ÷òî ñîîáùåíèå â ïàìÿòè
        OnSendMessageToOneComponent('HistoryToDBSync for ' + htdIMClientName + ' ('+MyAccount+')', '010');
      end
      else
        WriteInLog(ProfilePath, InsertSQLData, 0);
    end
    else // Äëÿ ðåæèìà ñèíõðîíèçàöèè ïî ðàñïèñàíèþ è ðó÷íîãî ïèøåì ñîîáùåíèÿ â SQL-ôàéë
      WriteInLog(ProfilePath, InsertSQLData, 0);
    // Åñëè ðåæèì ïî ðàñïèñàíèþ
    if SyncMethod = 2 then
    begin
      if (SyncInterval > 4) and (SyncInterval < 8) then
      begin
        Inc(MessageCount);
        if (SyncInterval = 5) and (MessageCount = 10) then
        begin
          OnSendMessageToAllComponent('002');
          MessageCount := 0;
        end;
        if (SyncInterval = 6) and (MessageCount = 20) then
        begin
          OnSendMessageToAllComponent('002');
          MessageCount := 0;
        end;
        if (SyncInterval = 7) and (MessageCount = 30) then
        begin
          OnSendMessageToAllComponent('002');
          MessageCount := 0;
        end;
      end;
      if SyncInterval = 9 then
      begin
        Inc(MessageCount);
        if MessageCount = SyncMessageCount then
        begin
          OnSendMessageToAllComponent('002');
          MessageCount := 0;
        end;
      end;
    end;
  end;
end;

{function OnTTBLoaded(awParam: WPARAM; alParam: LPARAM): Integer; cdecl;
var
  TTB: TTBButtonV2;
begin
  if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ôóíêöèÿ OnTTBLoaded', 2);
  if hTTBButton <> 0 then
  begin
    if ServiceExists(MS_TTB_REMOVEBUTTON)>0 then
    begin
      CallService(MS_TTB_REMOVEBUTTON, WPARAM(hTTBButton),0);
      hTTBButton := 0;
    end;
  end;
  if ShowPluginButton then
  begin
    if ServiceExists(MS_TTB_ADDBUTTON) > 0 then
    begin
      ZeroMemory(@TTB, SizeOf(TTB));
      TTB.cbSize        := SizeOf(TTB);
      TTB.pszServiceUp  := MHTD_SHOWSERVICE;
      TTB.pszServiceDown:= MHTD_SHOWSERVICE;
      TTB.hIconUp       := LoadImage(hInstance, 'ICON_0', IMAGE_ICON, 16, 16, 0);
      TTB.hIconDn       := ttb.hIconUp;
      TTB.dwFlags       := TTBBF_VISIBLE;
      TTB.name          := htdDBName;
      hTTBButton := CallService(MS_TTB_ADDBUTTON, WPARAM(@TTB), 0);
      if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ôóíêöèÿ OnTTBLoaded: Êíîïêà äîáàâëåíà.', 2);
    end;
  end;
  Result := 0;
end;}

{ Cåðâèñ MS_MHTD_SHOWHISTORY
  Ñìîòðè äåòàëè â m_historytodb.inc }
function HTDBShowHistory(wParam { 0 } : WPARAM; lParam { 0 } : LPARAM): int_ptr; cdecl;
var
  WinName: String;
begin
  Result := 0;
  // Èùåì îêíî HistoryToDBViewer
  WinName := 'HistoryToDBViewer';
  if not SearchMainWindow(pWideChar(WinName)) then // Åñëè HistoryToDBViewer íå íàéäåí, òî èùåì äðóãîå îêíî
  begin
    WinName := 'HistoryToDBViewer for ' + htdIMClientName + ' ('+MyAccount+')';
    if not SearchMainWindow(pWideChar(WinName)) then // Åñëè HistoryToDBViewer íå çàïóùåí, òî çàïóñêàåì
    begin
      if FileExists(PluginPath + 'HistoryToDBViewer.exe') then
      begin
        ShellExecute(0, 'open', PWideChar(PluginPath + 'HistoryToDBViewer.exe'), PWideChar(' "'+PluginPath+'" "'+ProfilePath+'"'), nil, SW_SHOWNORMAL);
      end
      else
        MsgInf(htdPluginShortName, Format(GetLangStr('ERR_NO_FOUND_VIEWER'), [PluginPath + 'HistoryToDBViewer.exe']));
    end
    else // Èíà÷å ïîñûëàåì çàïðîñ íà ïîêàç îêíà
      OnSendMessageToOneComponent(WinName, '0040');
  end
  else // Èíà÷å ïîñûëàåì çàïðîñ íà ïîêàç îêíà
    OnSendMessageToOneComponent(WinName, '0040');
end;

{ Cåðâèñ MS_MHTD_SHOWCONTACTHISTORY
  Ñìîòðè äåòàëè â m_historytodb.inc }
function HTDBShowContactHistory(wParam { hContact } : WPARAM; lParam { 0 } : LPARAM): int_ptr; cdecl;
begin
  Result := OpenHistoryWindow(wParam, 0);
end;

{ Cåðâèñ MS_MHTD_GETVERSION
  Ñìîòðè äåòàëè â m_historytodb.inc }
function HTDBGetVersion(wParam { 0 } : WPARAM; lParam { 0 } : LPARAM): int_ptr; cdecl;
begin
  Result := htdVersion;
end;

function OnModulesLoad(awParam{0}:WPARAM; alParam{0}:LPARAM):integer; cdecl;
var
  Mi: TCListMenuItem;
  //{$ifdef REPLDEFHISTMOD}
  Si: TCListMenuItem;
  //{$endif REPLDEFHISTMOD}
  AutoCoreLang, UpdTmpPath, WinName: String;
  I: Byte;
  MenuMainService: PAnsiChar;
  //IMUPD: TUpdate;
begin
  // Ëîã-ôàéëû çàêðûòû
  MsgLogOpened := False;
  ErrLogOpened := False;
  DebugLogOpened := False;
  ContactListLogOpened := False;
  ProtoListLogOpened := False;
  ImportLogOpened := False;
  // Èíèöèàëèçàöèÿ øèôðîâàíèÿ
  EncryptInit;
  // Îïðåäåëÿåì ëîêàëèçàöèþ
  if FileExists(ExtractFilePath(ParamStr(0))+'Langpack_russian.txt') then
    AutoCoreLang := 'Russian'
  else
    AutoCoreLang := 'English';
  // Çàïðîñ íà çàêðûòèå âñåõ êîìïîíåíòîâ ïëàãèíà åñëè îíè áûëè çàïóùåíû
  OnSendMessageToAllComponent('003');
  // Êîïèðóåì äåôîëòíûé ôàéë êîíôèãóðàöèè þçåðó â ïðîôèëü
  if FileExists(PluginPath + DefININame) then
  begin
    if FileExists(ProfilePath + ININame) then
      RenameFile(ProfilePath + ININame, ProfilePath + ININame + '.' + FormatDateTime('ddmmyyhhmmss', Now));
    if CopyFileEx(PChar(PluginPath + DefININame), PChar(ProfilePath + ININame), nil, nil, nil, COPY_FILE_FAIL_IF_EXISTS) then
    begin
      DefaultINICopy := True;
      if FileExists(ProfilePath + ININame) then
        DeleteFile(PluginPath + DefININame);
    end;
  end;
  // Çàäàåì âîïðîñû ïðè ïåðâîì çàïóñêå
  if (GetDBInt(htdDBName, 'FirstRun.FirstActivate', 0) = 0) or (DefaultINICopy) then
  begin
    if AutoCoreLang = 'Russian' then
    begin
      case MessageBox(DialogMainWindow, PWideChar('Âû âïåðâûå àêòèâèðîâàëè ïëàãèí ' + htdPluginShortName + '.' + #13 +
        'Äëÿ êîððåêòíîé ðàáîòû ïëàãèíà ïðîâåðüòå íàñòðîéêè ñîåäèíåíèÿ ñ áàçîé äàííûõ.' + #13 +
        'Âû õîòèòå íà÷àòü ýêñïîðò èñòîðèè?'), PWideChar(htdPluginShortName),36) of
        6: StartExport := True; // Äà
        7: StartExport := False; // Íåò
      end;
    end
    else
    begin
      case MessageBox(DialogMainWindow, PWideChar('The first time you activate the plugin ' + htdPluginShortName + '.' + #13 +
        'To work correctly, check your plug-in connection to the database.' + #13 +
        'Do you want to start exporting the history?'), PWideChar(htdPluginShortName),36) of
        6: StartExport := True; // Äà
        7: StartExport := False; // Íåò
      end;
    end;
  end;
  // Ïðîâåðÿåì çíà÷åíèÿ ôëàãà îáíîâëåíèÿ
  if GetDBInt(htdDBName, 'FirstRun.RunUpdateDoneV'+IntToStr(htdVersion), 0) = 0 then
  begin
    if AutoCoreLang = 'Russian' then
    begin
      //MsgInf(htdPluginShortName, 'Âû âïåðâûå àêòèâèðîâàëè ïëàãèí ' + htdPluginShortName + '.' + #13 + 'Äëÿ êîððåêòíîé ðàáîòû ïëàãèíà ïðîâåðüòå íàñòðîéêè ñîåäèíåíèÿ ñ áàçîé äàííûõ.' + #13 + 'Ñïàñèáî çà èñïîëüçîâàíèå ïëàãèíà ' + htdPluginShortName + '.')
      case MessageBox(DialogMainWindow, PWideChar('Âû âïåðâûå àêòèâèðîâàëè ïëàãèí ' + htdPluginShortName + '.' + #13 +
        'Äëÿ êîððåêòíîé ðàáîòû ïëàãèíà íåîáõîäèìî çàïóñòèòü ïðîöåññ îáíîâëåíèÿ ïëàãèíà ÷åðåç Èíòåðíåò.' + #13 +
        'Âû õîòèòå íà÷àòü ïðîöåññ îáíîâëåíèÿ?'), PWideChar(htdPluginShortName),36) of
        6: StartUpdate := True; // Äà
        7: StartUpdate := False; // Íåò
      end;
    end
    else
    begin
      //MsgInf(htdPluginShortName, 'The first time you activate the plugin ' + htdPluginShortName + '.' + #13 + 'To work correctly, check your plug-in connection to the database.' + #13 + 'Thank you for using the plugin ' + htdPluginShortName + '.');
      case MessageBox(DialogMainWindow, PWideChar('The first time you activate the plugin ' + htdPluginShortName + '.' + #13 +
        'To work correctly, the plugin must run the update plugin via the Internet.' + #13 +
        'Do you want to start the update process?'), PWideChar(htdPluginShortName),36) of
        6: StartUpdate := True; // Äà
        7: StartUpdate := False; // Íåò
      end;
    end;
  end;
  // Âûáîð ÿçûêà ïî óìîë÷àíèþ
  if AutoCoreLang <> DefaultLanguage then
  begin
    CoreLanguage := AutoCoreLang;
    WriteCustomINI(ProfilePath, 'DefaultLanguage', CoreLanguage);
  end
  else
    CoreLanguage := DefaultLanguage;
  // Çàãðóæàåì íàñòðîéêè ëîêàëèçàöèè
  LangDoc := NewXMLDocument();
  CoreLanguageChanged;
  // Çàïèñûâàåì òèïà IM êëèåíòà
  WriteCustomINI(ProfilePath, 'IMClientType', htdIMClientName);
  WriteCustomINI(ProfilePath, 'IMClientPlatformType', htdPlatform);
  // Çàïèñûâàåì îòñóòñòâèå çàïðîñà íà ÷òåíèå íàñòðîåê
  WriteCustomINI(ProfilePath, 'SettingsFormRequestSend', '0');
  // Ñîçäàåì îêíî About è Export
  if not Assigned(AboutForm) then
    AboutForm := TAboutForm.Create(nil);
  ExportFormDestroy := True;
  // API - Îòêðûòèå îêíà èñòîðèè
  HookShowHistoryAPI := CreateServiceFunction(MS_MHTD_SHOWHISTORY, @HTDBShowHistory);
  // API - Îòêðûòèå îêíà èñòîðèè óêàçàííîãî êîíòàêòà
  HookShowContactHistoryAPI := CreateServiceFunction(MS_MHTD_SHOWCONTACTHISTORY, @HTDBShowContactHistory);
  // API - Âåðñèÿ ïëàãèíà
  HookShowVersionAPI := CreateServiceFunction(MS_MHTD_GETVERSION, @HTDBGetVersion);
  // Èíèöèàëèçàöèÿ îñíîâíîãî ìåíþ
  MenuMainItemsInit;
  // Ñîçäàåì îñíîâíîå ìåíþ
  FillChar(Mi, SizeOf(Mi), 0);
  Mi.cbSize := SizeOf(Mi);
  Mi.szPopupName.a := '&' + htdPluginShortName;
  Mi.popupPosition := 500000;
  Mi.hIcon := LoadImage(hInstance,'ICON_0',IMAGE_ICON,16,16,0);
  Mi.flags := 0;
  for I := Low(MainMenuItems) to High(MainMenuItems) do
  begin
    if MainMenuItems[I].Icon = '' then
      Mi.hIcon := 0
    else
      Mi.hIcon := LoadImage(hInstance, pChar(MainMenuItems[I].Icon), IMAGE_ICON, 16, 16, 0);
    Mi.szName.a := pAnsiChar(AnsiString(MainMenuItems[I].Name));
    MenuMainService := pAnsiChar(AnsiString(Format('%s/MainMenuCommand%d', [htdPluginShortName, I])));
    //if EnableDebug then WriteInLog(ProfilePath, FormatDateTime('dd.mm.yy hh:mm:ss', Now) + ' - Ôóíêöèÿ Load: ' + 'MenuMainName = ' + MenuMainItems[I].Name + ' | MenuMainService = ' + MenuMainService, 2);
    MainMenuHandle[I] := CreateServiceFunctionParam(MenuMainService, @MainMenuItems[I].Proc, I);
    Mi.pszService := MenuMainService;
    Mi.Position := MainMenuItems[I].Position;
    MenuHandle[I] := CallService(MS_CLIST_ADDMAINMENUITEM, 0, Windows.LPARAM(@Mi));
  end;
  // Ñîçäàåì ñâîé ïóíêò â îñíîâíîì ìåíþ äëÿ ñèñòåìíîé èñòîðèè
  //{$ifdef REPLDEFHISTMOD}
  FillChar(Si, SizeOf(Si), 0);
  Si.cbSize := SizeOf(Si);
  Si.Position := 500060000;
  Si.szName.a := pAnsiChar(AnsiString(Format(WideStringToString(GetLangStr('IMButtonCaption'), CP_ACP), [htdPluginShortName])));
  Si.pszService := MS_MHTD_SHOWHISTORY;//MS_HISTORY_SHOWCONTACTHISTORY;
  Si.hIcon := LoadImage(hInstance,'ICON_0',IMAGE_ICON,16,16,0);
  HookSystemHistoryMenu := CallService(MS_CLIST_ADDMAINMENUITEM,0,LPARAM(@Si));
  //{$endif REPLDEFHISTMOD}
  // Ñîçäàåì ñâîé ïóíêò â ìåíþ êîíòàêòà
  CreateServiceFunction(htdPluginShortName+'/ContactMenuCommand', @OpenHistoryWindow);
  Mi.pszContactOwner := nil; // Âñå êîíòàêòû
  Mi.cbSize := SizeOf(Mi);
  Mi.position := 1000090000;
  Mi.flags := 0;
  Mi.hIcon := LoadImage(hInstance,'ICON_0',IMAGE_ICON,16,16,0);
  Mi.szName.a := pAnsiChar(WideStringToString(GetLangStr('ShowOneContactHistory'), CP_ACP));
  Mi.pszService := htdPluginShortName+'/ContactMenuCommand';
  HookContactMenu := CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, LPARAM(@Mi));
  // Õóê íà îòêðûòèå ìåíþ êîíòàêòà
  HookBuildMenu := HookEvent(ME_CLIST_PREBUILDCONTACTMENU, OnBuildContactMenu);
  // Õóê íà äîáàâëåíèå äàííûõ â ëîêàëüíóþ ÁÄ Ìèðàíäû
  HookEventAdded := HookEvent(ME_DB_EVENT_ADDED, OnEventAdded);
  // Îòêðûòèå îêíà èñòîðèè
 {$ifdef REPLDEFHISTMOD}
    HookShowMainHistory := CreateServiceFunction(MS_HISTORY_SHOWCONTACTHISTORY, @OpenHistoryWindow);
 {$endif REPLDEFHISTMOD}
  // Ïîääåðæêà TopToolBar
  //HookTTBLoaded := HookEvent(ME_TTB_MODULELOADED, OnTTBLoaded);
  // Register in updater
  {if Boolean(ServiceExists(MS_UPDATE_REGISTER)) then
  begin
    ZeroMemory(@IMUPD,SizeOf(IMUPD));
    IMUPD.cbSize := SizeOf(IMUPD);
    IMUPD.szComponentName := htdPluginShortName;
    IMUPD.pbVersion := @hppVersionStr[1];
    IMUPD.cpbVersion := Length(hppVersionStr);
    // File listing section
    //IMUPD.szUpdateURL = UPDATER_AUTOREGISTER;
    IMUPD.szUpdateURL := htdFLUpdateURL;
    IMUPD.szVersionURL := htdFLVersionURL;
    IMUPD.pbVersionPrefix := htdFLVersionPrefix;
    IMUPD.cpbVersionPrefix := Length(htdFLVersionPrefix);
    // Alpha-beta section
    IMUPD.szBetaUpdateURL := htdUpdateURL;
    IMUPD.szBetaVersionURL := htdVersionURL;
    IMUPD.pbBetaVersionPrefix := htdVersionPrefix;
    IMUPD.cpbBetaVersionPrefix := Length(htdVersionPrefix);
    IMUPD.szBetaChangelogURL := htdChangelogURL;
    CallService(MS_UPDATE_REGISTER, 0, LPARAM(@IMUPD));
  end;}
  { Çàïóñêàåì êîíòðîëü ôàéëà êîíôèãóðàöèè
  FILE_NOTIFY_CHANGE_FILE_NAME        = $00000001;//Èçìåíåíèå èìåíè ôàéëà
  FILE_NOTIFY_CHANGE_DIR_NAME         = $00000002;//Èçìåíåíèå èìåíè ïàïêè
  FILE_NOTIFY_CHANGE_ATTRIBUTES       = $00000004;//Èçìåíåíèå àòðèáóòîâ ôàéëà
  FILE_NOTIFY_CHANGE_SIZE             = $00000008;//Èçìåíåíèå ðàçìåðà ôàéëà
  FILE_NOTIFY_CHANGE_LAST_WRITE       = $00000010;//Èçìåíåíèå âðåìåíè ïîñëåäíåé çàïèñè
  FILE_NOTIFY_CHANGE_LAST_ACCESS      = $00000020;//Èçìåíåíèå âðåìåíè ïîñëåäíåãî äîñòóïà
  FILE_NOTIFY_CHANGE_CREATION         = $00000040;//Èçìåíåíèå âðåìåíè ñîçäàíèÿ
  FILE_NOTIFY_CHANGE_SECURITY         = $00000100;//Èçìåíåíèå ïðàâ äîñòóïà
  }
  StartWatch(ProfilePath, FILE_NOTIFY_CHANGE_LAST_WRITE, False, @ProfileDirChangeCallBack);
  // MMF
  if SyncMethod = 0 then
    FMap := TMapStream.CreateEx('HistoryToDB for ' + htdIMClientName + ' ('+MyAccount+')',MAXDWORD,2000);
  // Ïëàãèí çàãðóæåí
  PluginStatus := True;
  // Êîë. ñîîáùåíèé
  MessageCount := 0;
  // Ïèøåì äàííûå î ïåðâîì çàïóñêå â áàçó
  WriteDBInt(htdDBName, 'FirstRun.FirstActivate', 1);
  // Îáíîâëåíèå óòèëèòû HistoryToDBUpdater.exe èç âðåìåííîé ïàïêè
  UpdTmpPath := GetUserTempPath + 'IMHistory\';
  if FileExists(UpdTmpPath + 'HistoryToDBUpdater.exe') then
  begin
    // Èùåì îêíî HistoryToDBUpdater
    WinName := 'HistoryToDBUpdater';
    if not SearchMainWindow(pWideChar(WinName)) then // Åñëè HistoryToDBUpdater íå íàéäåí, òî èùåì äðóãîå îêíî
    begin
      WinName := 'HistoryToDBUpdater for ' + htdIMClientName + ' ('+MyAccount+')';
      if SearchMainWindow(pWideChar(WinName)) then // Åñëè HistoryToDBUpdater çàïóùåí, òî çàêðûâàåì åãî
        OnSendMessageToOneComponent(WinName, '009');
    end
    else // Èíà÷å ïîñûëàåì çàïðîñ
      OnSendMessageToOneComponent(WinName, '009');
    Sleep(800);
    // Óäàëÿåì ñòàðóþ óòèëèòó
    if DeleteFile(PluginPath + 'HistoryToDBUpdater.exe') then
    begin
      if CopyFileEx(PChar(UpdTmpPath + 'HistoryToDBUpdater.exe'), PChar(PluginPath + 'HistoryToDBUpdater.exe'), nil, nil, nil, COPY_FILE_FAIL_IF_EXISTS) then
      begin
        DeleteFile(UpdTmpPath + 'HistoryToDBUpdater.exe');
        if CoreLanguage = 'Russian' then
          MsgInf(htdPluginShortName, Format('Óòèëèòà îáíîâëåíèÿ %s óñïåøíî îáíîâëåíà.', ['HistoryToDBUpdater.exe']))
        else
          MsgInf(htdPluginShortName, Format('Update utility %s successfully updated.', ['HistoryToDBUpdater.exe']));
      end;
    end
    else
    begin
      DeleteFile(UpdTmpPath + 'HistoryToDBUpdater.exe');
      if CoreLanguage = 'Russian' then
        MsgDie(htdPluginShortName, Format('Îøèáêà îáíîâëåíèÿ óòèëèòû %s èç âðåìåííîé ïàïêè.', [PluginPath + 'HistoryToDBUpdater.exe']))
      else
        MsgDie(htdPluginShortName, Format('Error update utility %s', [PluginPath + 'HistoryToDBUpdater.exe']));
    end;
  end;
  // Îáíîâëåíèå óòèëèòû HistoryToDBUpdater.exe èç ïàïêè ïëàãèíà
  if FileExists(PluginPath + 'HistoryToDBUpdater.upd') then
  begin
    // Èùåì îêíî HistoryToDBUpdater
    WinName := 'HistoryToDBUpdater';
    if not SearchMainWindow(pWideChar(WinName)) then // Åñëè HistoryToDBUpdater íå íàéäåí, òî èùåì äðóãîå îêíî
    begin
      WinName := 'HistoryToDBUpdater for ' + htdIMClientName + ' ('+MyAccount+')';
      if SearchMainWindow(pWideChar(WinName)) then // Åñëè HistoryToDBUpdater çàïóùåí, òî çàêðûâàåì åãî
        OnSendMessageToOneComponent(WinName, '009');
    end
    else // Èíà÷å ïîñûëàåì çàïðîñ
      OnSendMessageToOneComponent(WinName, '009');
    Sleep(800);
    // Óäàëÿåì ñòàðóþ óòèëèòó
    if DeleteFile(PluginPath + 'HistoryToDBUpdater.exe') then
    begin
      if CopyFileEx(PChar(PluginPath + 'HistoryToDBUpdater.upd'), PChar(PluginPath + 'HistoryToDBUpdater.exe'), nil, nil, nil, COPY_FILE_FAIL_IF_EXISTS) then
      begin
        DeleteFile(PluginPath + 'HistoryToDBUpdater.upd');
        if CoreLanguage = 'Russian' then
          MsgInf(htdPluginShortName, Format('Óòèëèòà îáíîâëåíèÿ %s óñïåøíî îáíîâëåíà.', ['HistoryToDBUpdater.exe']))
        else
          MsgInf(htdPluginShortName, Format('Update utility %s successfully updated.', ['HistoryToDBUpdater.exe']));
      end;
    end
    else
    begin
      DeleteFile(PluginPath + 'HistoryToDBUpdater.upd');
      if CoreLanguage = 'Russian' then
        MsgDie(htdPluginShortName, Format('Îøèáêà îáíîâëåíèÿ óòèëèòû %s èç ïàïêè ïëàãèíîâ.', [PluginPath + 'HistoryToDBUpdater.exe']))
      else
        MsgDie(htdPluginShortName, Format('Error update utility %s', [PluginPath + 'HistoryToDBUpdater.exe']));
    end;
  end;
  // Çàïóñê îáíîâëåíèÿ
  if StartUpdate then
  begin
    if FileExists(PluginPath + 'HistoryToDBUpdater.exe') then
    begin
      // Ïèøåì äàííûå â áàçó
      WriteDBInt(htdDBName, 'FirstRun.RunUpdateDoneV'+IntToStr(htdVersion), 1);
      // Îòïðàâëåí çàïðîñ
      ShellExecute(0, 'open', PWideChar(PluginPath + 'HistoryToDBUpdater.exe'), PWideChar(' "'+ProfilePath+'"'), nil, SW_SHOWNORMAL);
    end
    else
      MsgInf(htdPluginShortName, Format(GetLangStr('ERR_NO_FOUND_UPDATER'), [PluginPath + 'HistoryToDBUpdater.exe']));
  end
  else
  begin
    // Ïðîâåðÿåì çíà÷åíèÿ ôëàãà îáíîâëåíèÿ
    if GetDBInt(htdDBName, 'FirstRun.RunUpdateDoneV'+IntToStr(htdVersion), 0) = 0 then
      WriteDBInt(htdDBName, 'FirstRun.RunUpdateDoneV'+IntToStr(htdVersion), 1); // Ïèøåì äàííûå â áàçó
  end;
  // Ïîêàçàòü îêíî ýêñïîðòà
  if StartExport then
  begin
    if ExportFormDestroy then
      ChildExport := TExportForm.Create(nil);
    if Assigned(ChildExport) then
    begin
      if not ChildExport.Showing then
        ChildExport.Show
      else
        ChildExport.BringFormToFront(ChildExport);
    end;
  end;
  // Åñëè íå çàïóñêàåì îáíîâëåíèå, òî çàïóñêàåì ïðîãðàììó ñèíõðîíèçàöèè HistoryToDBSync
  if not StartUpdate then
  begin
    if FileExists(PluginPath + 'HistoryToDBSync.exe') then
    begin
      WinName := 'HistoryToDBSync for ' + htdIMClientName + ' ('+MyAccount+')';
      if not SearchMainWindow(pWideChar(WinName)) then // Åñëè HistoryToDBSync for QIP íå çàïóùåí, òî çàïóñêàåì
        ShellExecute(0, 'open', PWideChar(PluginPath + 'HistoryToDBSync.exe'), PWideChar(' "'+PluginPath+'" "'+ProfilePath+'"'), nil, SW_SHOWNORMAL)
    end
    else
    begin
      if CoreLanguage = 'Russian' then
        MsgInf(htdPluginShortName, Format('Ïðîãðàììà ñèíõðîíèçàöèè èñòîðèè %s íå íàéäåíà.' + #13 + 'Çàïóñòèòå ïðîöåññ îáíîâëåíèÿ ïëàãèíà.', [PluginPath + 'HistoryToDBSync.exe']))
      else
        MsgInf(htdPluginShortName, Format('The history synchronization program %s not found.' + #13 + 'Begin the process of updating the plugin.', [PluginPath + 'HistoryToDBSync.exe']));
    end;
  end;
  Result := 0;
end;

function Load():Integer; cdecl;
var
  ProfileName, TmpProfilePath: String;
  Str: PAnsiChar;
begin
  CallService(MS_LANGPACK_REGISTER,WPARAM(@hLangpack),LPARAM(@PluginInfo));
  // Êîäîâàÿ ñòðàíèöà
  hppCodepage := CallService(MS_LANGPACK_GETCODEPAGE, 0, 0);
  if (hppCodepage = CALLSERVICE_NOTFOUND) or (hppCodepage = CP_ACP) then
    hppCodepage := GetACP();
  // Ïðîâåðêà íà ïîääåðæêó Ìåòà-êîíòàêòîâ
  MetaContactsEnabled := Boolean(ServiceExists(MS_MC_GETMOSTONLINECONTACT));
  if MetaContactsEnabled then
  begin
    Str := pAnsiChar(CallService(MS_MC_GETPROTOCOLNAME, 0, 0));
    if Assigned(Str) then
      MetaContactsProto := AnsiString(Str)
    else
      MetaContactsEnabled := False;
  end;
  // Ïóòü äî ïëàãèíîâ
  SetLength(DllPath, MAX_PATH);
  SetLength(DllPath, GetModuleFileNameW(hInstance, @DllPath[1], MAX_PATH));
  PluginPath := ExtractFilePath(DllPath);
  // Ïóòü äî äèðåêòîðèè ïðîôèëÿ (USERNAME\USERNAME.dat)
  SetLength(TmpProfilePath, MAX_PATH);
  CallService(MS_DB_GETPROFILEPATH, MAX_PATH, lParam(@TmpProfilePath[1]));
  SetLength(TmpProfilePath, StrLen(pAnsiChar(@TmpProfilePath[1])));
  TmpProfilePath := pAnsiChar(TmpProfilePath) + PathDelim;
  // Èìÿ ôàéëà ïðîôèëÿ
  SetLength(ProfileName, MAX_PATH);
  CallService(MS_DB_GETPROFILENAME, MAX_PATH, lParam(@ProfileName[1]));
  SetLength(ProfileName, StrLen(pAnsiChar(@ProfileName[1])));
  // Ïóòü äî ïðîôèëÿ USERNAME.dat
  TmpProfilePath := TmpProfilePath + ExtractFileNameEx(TmpProfilePath+pAnsiChar(ProfileName), False) + PathDelim;
  if DirectoryExists(TmpProfilePath) then
    ProfilePath := TmpProfilePath
  else
    ProfilePath := ExtractFilePath(DllPath);
  // Çàãðóæàåì íàñòðîéêè
  LoadINI(ProfilePath);
  // Çàïèñûâàåì Èìÿ ïðîôèëÿ, ïîòîì îíî èñïîëüçóåòñÿ äëÿ çàãîëîâêà ïðîãðàìì
  MyAccount := ExtractFileNameEx(pAnsiChar(ProfileName), False);
  WriteCustomINI(ProfilePath, 'MyAccount', MyAccount);
  // Èíèöèàëèçàöèÿ îñíîâíûõ ôóíêöèé
  HookModulesLoad := HookEvent(ME_SYSTEM_MODULESLOADED, OnModulesLoad);
  Result := 0;
end;

function Unload: int; cdecl;
var
  I: Byte;
begin
  Result := 0;
  if PluginStatus then
  begin
    // Îñòàíàâëèâàåì êîíòðîëü ôàéëà êîíôèãóðàöèè
    StopWatch;
    if Assigned(AboutForm) then FreeAndNil(AboutForm);
    if Assigned(ExportForm) then FreeAndNil(ExportForm);
    // Óäàëÿåì ìåíþ
    for I := Low(MainMenuHandle) to High(MainMenuHandle) do
    begin
      DestroyServiceFunction(MainMenuHandle[I]);
      DestroyServiceFunction(MenuHandle[I]);
    end;
    {$ifdef REPLDEFHISTMOD}
    DestroyServiceFunction(HookShowMainHistory);
    {$endif REPLDEFHISTMOD}
    DestroyServiceFunction(HookShowHistoryAPI);
    DestroyServiceFunction(HookShowContactHistoryAPI);
    DestroyServiceFunction(HookShowVersionAPI);
    //{$ifdef REPLDEFHISTMOD}
    UnhookEvent(HookSystemHistoryMenu);
    //{$endif REPLDEFHISTMOD}
    UnhookEvent(HookContactMenu);
    //UnhookEvent(HookTTBLoaded);
    UnhookEvent(HookEventAdded);
    UnhookEvent(HookBuildMenu);
    UnhookEvent(HookModulesLoad);
    // Çàïðîñ íà çàêðûòèå âñåõ êîìïîíåíòîâ ïëàãèíà
    OnSendMessageToAllComponent('003');
    // Çàêðûâàåì ëîã-ôàéëû
    if MsgLogOpened then
      CloseLogFile(0);
    if ErrLogOpened then
      CloseLogFile(1);
    if DebugLogOpened then
      CloseLogFile(2);
    if ContactListLogOpened then
      CloseLogFile(3);
    if ProtoListLogOpened then
      CloseLogFile(4);
    // Î÷èñòêà êëþ÷åé øèôðîâàíèÿ
    EncryptFree;
    // MMF
    if Assigned(FMap) then
      FMap.Free;
    // Îòêë. ÿçûêîâîé ïîääåðæêè
    LangDoc.Active := False;
  end;
end;

exports
  MirandaPluginInfoEx,
  MirandaPluginInterfaces,
  Load,
  Unload;

begin
end.